diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..d3c3021b41e440c7d53e877afe1e0a29d56adfeb --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml index a538f9f69e1f03b4ac05ded3d2abf8c6b2afc240..e3022c49a8c684c35f027b4663a0bc00e9c2e09a 100644 --- a/.github/workflows/regression.yml +++ b/.github/workflows/regression.yml @@ -15,22 +15,83 @@ concurrency: group: regression-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +# Every action is pinned to a full commit SHA (resolved with +# `gh api repos///git/ref/tags/`); the trailing comment names +# the release so Dependabot can propose updates. jobs: + lint-and-contracts: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Check out source + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install CPU PyTorch, project and lint tooling + run: | + python -m pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cpu + python -m pip install . 'ruff==0.15.16' + + - name: Start an agent from the installed wheel + working-directory: ${{ runner.temp }} + run: | + python - <<'PY' + from synapse.agent import IntegratedAgent + from synapse.config import SynapseConfig, tidal_checkpoint_path + from synapse.frontier.spec import MODULE_IDS + + assert tidal_checkpoint_path().is_file() + assert len(MODULE_IDS) == 18 + IntegratedAgent(SynapseConfig(nodes_per_source=16)) + PY + + - name: Ruff lint check + run: ruff check synapse tests scripts + + - name: JavaScript syntax check + run: node --check synapse/web/app.js + + - name: Pre-NEUROWEAVE compatibility manifest check + run: python scripts/neuroweave_compat_manifest.py --check + + - name: Pre-Frontier compatibility manifest check + run: >- + python scripts/neuroweave_compat_manifest.py + --manifest docs/compatibility/manifest-pre-frontier.json + --baseline-tag sonapse-pre-frontier-baseline + --check + pytest: runs-on: ubuntu-latest timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + # torch 2.11.0+cpu manylinux_2_28_x86_64 wheels exist for cp310, cp312 and cp313 + # (https://download.pytorch.org/whl/cpu/torch/, checked 2026-11-20). + python-version: ['3.10', '3.12', '3.13'] env: OMP_NUM_THREADS: '1' MKL_NUM_THREADS: '1' OPENBLAS_NUM_THREADS: '1' steps: - name: Check out source - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false - - name: Set up Python - uses: actions/setup-python@v5 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: - python-version: '3.12' + python-version: ${{ matrix.python-version }} cache: pip cache-dependency-path: pyproject.toml @@ -40,13 +101,17 @@ jobs: - name: Install project and test dependencies run: python -m pip install -e '.[test,connectomes,yaml]' + - name: Install NIR for the interchange round-trip test + if: matrix.python-version == '3.12' + run: python -m pip install 'nir==1.0.8' 'h5py==3.14.0' + - name: Run full regression suite - run: python -m pytest -q --junitxml=pytest-results.xml + run: python -m pytest -q --junitxml=pytest-results-${{ matrix.python-version }}.xml - name: Upload test report if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: pytest-results - path: pytest-results.xml + name: pytest-results-py${{ matrix.python-version }} + path: pytest-results-${{ matrix.python-version }}.xml if-no-files-found: ignore diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3c123c56d35429709c90a0b9b6acd42b71f0abf --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,20 @@ +# Hooks are frozen to full commit SHAs (resolved with `gh api .../git/ref/tags/`). +# Ruff reads the same [tool.ruff] selection from pyproject.toml as CI. +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: 22f0422809455ec89ffdcf5a00170ba816e42ddb # frozen: v0.15.16 + hooks: + - id: ruff-check + exclude: ^synapse/_vendor/ + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.0 + hooks: + - id: check-yaml + - id: check-json + exclude: ^(docs/results/|synapse/_vendor/) + # Whitespace fixers are limited to the configuration/metadata file types this + # change introduces, so they never rewrite existing Python, Markdown or data files. + - id: end-of-file-fixer + files: \.(cff|ya?ml)$ + - id: trailing-whitespace + files: \.(cff|ya?ml)$ diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..d7c7b38cf9d4a47495116a5225ba12a767b4ff1f --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,25 @@ +cff-version: 1.2.0 +title: "Sonapse-LAB / SYNAPSE: a CPU-first connectome research workbench" +message: "If you use Sonapse-LAB or SYNAPSE in your research, please cite it using the metadata below." +type: software +authors: + - given-names: Kai + family-names: Piper + alias: kai9987kai +abstract: >- + Integrated connectome, weight-programming and bounded recursive-self-improvement + research workbench with opt-in NEUROWEAVE and Frontier extensions, sealed experiment + receipts and additive compatibility manifests. Synthetic research software; no claim + of biological fidelity or general intelligence. +license: Apache-2.0 +version: 0.3.0 +date-released: "2026-11-19" +repository-code: "https://github.com/kai9987kai/Sonapse-LAB" +url: "https://huggingface.co/Kai9987kai/Sonapse-LAB" +keywords: + - computational-neuroscience + - connectomics + - neuromorphic-computing + - reinforcement-learning + - spiking-neural-networks + - reproducibility diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..d7f217c95a4c41cf05eadb08c4de64cb5e775dc1 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include CITATION.cff +global-exclude *.pyc *.pyo diff --git a/README.md b/README.md index a90793f663a6042e6fd7a96cca0af03c9944866f..0b85cf6bdb68bc48c5e6a684f52e56a452d99c12 100644 --- a/README.md +++ b/README.md @@ -389,6 +389,23 @@ The runtime provides toggleable research implementations of recent frontier tech All options are configurable in `SynapseConfig`, controllable via the web workbench HUD and settings, and fully preserved across mid-episode state checkpoints. +## Frontier Pack + +Sonapse 0.3.0 includes 18 experimental modules covering neural dynamics, memory, +connectivity, sparse learning, experiment design and model interchange. List the +modules and experiments, then run the Hodgkin–Huxley cable reference check: + +```bash +python -m synapse.cli frontier catalog +python -m synapse.cli frontier experiment --id hh_cable --quick +``` + +Ordinary agent runs leave the pack disabled. Max Mode enables read-only observers. +The workbench also has an isolated lab for stepping observers and running experiments. +Each experiment produces a receipt with its checks or comparisons and a digest. +The results describe synthetic models. See the [module catalog](docs/frontier/README.md) +for individual controls, results and limitations. + ## Upstream Lineage & Research Grounding SYNAPSE unifies innovations from: @@ -411,7 +428,7 @@ It is **off by default**: All results are `synthetic_abstraction`: not biological validation, not emotions, not FPGA hardware. What it includes: -- 45 mechanisms (two are declared only) +- 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. - 16 sensory channels with scalar-only privacy rules - 24 experiments with sealed receipts - package, standalone HTML and FPGA-mapping exports diff --git a/docs/ENGINEERING.md b/docs/ENGINEERING.md new file mode 100644 index 0000000000000000000000000000000000000000..4ba68babae23107ef68f5d4fccad5768e1bbd99d --- /dev/null +++ b/docs/ENGINEERING.md @@ -0,0 +1,226 @@ +# Engineering notes (v0.3.0) + +Toolchain, local checks, CI, security posture and the additive-compatibility contract for +**Sonapse-LAB / SYNAPSE 0.3.0**. Everything here describes configuration in this repository or a run made +locally on 2026-11-20 (Windows 11 on ARM64, Python 3.12.10, ruff 0.15.16, Node v24). GitHub Actions did not run +as part of writing this page, so no CI result is claimed. + +The 0.3.0 engineering changes are additive. They add metadata, tooling, documentation, a theme selector and +accessibility attributes; they do not change simulation, training, checkpoint or HTTP behaviour. + +## 1. Toolchain + +| Item | Where | Value | +|---|---|---| +| Version | `pyproject.toml`, `synapse/__init__.py` | `0.3.0`; `python -m synapse --version` prints `synapse-connectome-lab 0.3.0` | +| Python | `requires-python` | `>=3.10`; CI matrix `3.10`, `3.12`, `3.13` | +| Build backend | `[build-system]` | `setuptools>=77` (PEP 639 `license = "Apache-2.0"` + `license-files`) | +| Runtime deps | `[project] dependencies` | `torch>=2.4`, `numpy>=1.26`, `scipy>=1.11` (unchanged) | +| Extras | `[project.optional-dependencies]` | `test`, `connectomes`, `yaml` (unchanged) | +| Dev group | `[dependency-groups]` (PEP 735) | `pytest>=8`, `ruff>=0.8`, `pip-audit>=2.7`, `hypothesis>=6` | +| Citation | `CITATION.cff` | CFF 1.2.0; validated locally against the CFF 1.2.0 JSON schema | + +Install the `dev` group with any installer that implements PEP 735, or install the four packages directly: + +```bash +python -m pip install "pytest>=8" "ruff>=0.8" "pip-audit>=2.7" "hypothesis>=6" +``` + +Package metadata was built locally with `setuptools.build_meta.prepare_metadata_for_build_wheel` (setuptools 81): +it reports `Metadata-Version: 2.4`, `License-Expression: Apache-2.0`, `License-File: LICENSE`, the keywords, +classifiers and both `Project-URL` entries. + +The distribution includes the Tidal checkpoint in `share/synapse-connectome-lab/`. The agent uses the +checkout or configured `SYNAPSE_HOME/artifacts/tidal_core.pt` first. For a wheel install it can also locate +the bundled checkpoint. Both distribution formats exclude generated Python bytecode. + +## 2. Local checks + +Run tests single-threaded, as CI does: + +```bash +OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 python -m pytest -q +``` + +Static checks (the same commands as the `lint-and-contracts` CI job): + +```bash +ruff check synapse tests scripts +node --check synapse/web/app.js +python scripts/neuroweave_compat_manifest.py --check +python scripts/neuroweave_compat_manifest.py --manifest docs/compatibility/manifest-pre-frontier.json \ + --baseline-tag sonapse-pre-frontier-baseline --check +``` + +`tests/test_compat_manifest_tool.py` covers the manifest tool, both manifests, version consistency +(`pyproject.toml`, `synapse.__version__`, `CITATION.cff`, `--version`), the action SHA pins and the static +theme/accessibility checks in section 7. + +### Pre-commit + +`.pre-commit-config.yaml` pins both hook repositories to full commit SHAs: + +| Repository | Tag | Commit | Hooks | +|---|---|---|---| +| `astral-sh/ruff-pre-commit` | v0.15.16 | `22f0422809455ec89ffdcf5a00170ba816e42ddb` | `ruff-check` (reads `[tool.ruff]` from `pyproject.toml`) | +| `pre-commit/pre-commit-hooks` | v6.0.0 | `3e8a8703264a2f4a69428a0aa4dcb512790b2c8c` | `check-yaml`, `check-json`, `end-of-file-fixer`, `trailing-whitespace` | + +`check-json` excludes `docs/results/` and `synapse/_vendor/`. The whitespace fixers only touch `*.cff`, `*.yml` and +`*.yaml`, so they never rewrite existing Python, Markdown or data files. The hook ids were confirmed in each +repository's `.pre-commit-hooks.yaml` at the pinned commit. The JSON, YAML and whitespace hooks were emulated +locally over all tracked and new files (0 failures); `pre-commit` itself was not installed or run. + +## 3. Lint policy + +`[tool.ruff]`: `target-version = "py310"`, `line-length = 140`, `extend-exclude = ["synapse/_vendor"]`. The enforced +selection covers correctness rules, including undefined names in runtime code and annotations. + +```toml +select = [ + "E9", "F63", "F7", "F50", "F52", "F601", "F602", "F621", "F622", "F821", "F822", "F823", "F901", + "W605", "PLE", + "B002", "B003", "B004", "B011", "B012", "B013", "B014", "B015", "B016", "B019", "B020", + "B021", "B022", "B025", "B026", "B029", "B030", "B031", "B032", "B033", "B034", "B035", "B039", +] +``` + +`ruff check synapse tests scripts` printed `All checks passed!` on 2026-11-20. With `target-version = "py310"`, +ruff also reports syntax that needs a newer interpreter (for example `except*` or PEP 701 f-strings) under `E9`; +a local probe file confirmed this. That keeps the Python 3.10 CI leg honest. + +### Broader rule set (future work, not enforced) + +`ruff check --select=F,E,W,B,UP --statistics synapse tests scripts` (same `pyproject.toml` settings), measured +2026-11-20 with ruff 0.15.16 while other work was still landing in the tree: **5,522 findings**, 3,209 of them +auto-fixable. The largest groups: + +| Rule | Count | Meaning | +|---|---:|---| +| `UP006` | 1,709 | `typing.List`/`Dict` annotations instead of built-in generics | +| `F401` | 797 | unused import | +| `UP035` | 630 | deprecated `typing` import | +| `E501` | 567 | line longer than 140 | +| `E702` | 494 | several statements on one line (semicolon) | +| `UP045` | 334 | `Optional[X]` instead of `X \| None` | +| `E701` | 289 | several statements on one line (colon) | +| `W293` | 285 | whitespace on a blank line | +| `B905` | 186 | `zip()` without `strict=` | +| `F841` | 55 | unused local variable | +| `B007` | 54 | unused loop variable | +| `UP037` | 45 | quoted annotation | +| `B023` | 15 | closure uses a loop variable | +| `F821` | 5 | undefined name | +| `B006` | 4 | mutable default argument | + +The release review resolved all five `F821` findings and enabled the rule in CI. The `B023` and `B006` +findings remain candidates for review. + +## 4. Continuous integration (`.github/workflows/regression.yml`) + +Triggers, permissions (`contents: read`) and concurrency are unchanged. Every action is pinned to a full commit +SHA, resolved on 2026-11-20 with `gh api repos///git/ref/tags/` (all three tags are lightweight +tags that point directly at commits, so no dereferencing was needed): + +| Action | Tag | Commit | +|---|---|---| +| `actions/checkout` | v4.4.0 | `11d5960a326750d5838078e36cf38b85af677262` | +| `actions/setup-python` | v5.6.0 | `a26af69be951a213d495a4c3e4e4022e16d87065` | +| `actions/upload-artifact` | v4.6.2 | `ea165f8d65b6e75b540449e92b4886f43607fa02` | + +The major versions match the previously used `@v4`/`@v5`/`@v4` references. Checkout uses +`persist-credentials: false`. + +Jobs: + +1. **`lint-and-contracts`** (Python 3.12, `timeout-minutes: 15`): installs CPU `torch==2.11.0`, the project and + `ruff==0.15.16`, starts a 16-node-per-source agent from the installed wheel outside the checkout, then runs + `ruff check synapse tests scripts`, `node --check synapse/web/app.js` (Node from the + runner image), the pre-NEUROWEAVE manifest check and the pre-Frontier manifest check. +2. **`pytest`** (`timeout-minutes: 60`, `fail-fast: false`, matrix `3.10`, `3.12`, `3.13`): same steps as before + (CPU `torch==2.11.0`, `pip install -e '.[test,connectomes,yaml]'`, `python -m pytest -q` with one BLAS/OpenMP + thread), with a per-version JUnit report artifact. Python 3.12 also installs `nir==1.0.8` and + `h5py==3.14.0` to exercise the HDF5 interchange path. The other legs exercise the JSON fallback. + +`torch-2.11.0+cpu` `manylinux_2_28_x86_64` wheels for `cp310`, `cp312` and `cp313` were listed at + when checked on 2026-11-20, so no matrix entry was dropped. + +`.github/dependabot.yml` checks `pip` and `github-actions` weekly (at most 5 open PRs each). The version comment +after each SHA lets Dependabot propose pin updates. + +## 5. Security posture + +These controls exist in the code (paths are relative to the repository root): + +- **HTTP workbench** (`synapse/server.py`): responses carry `Content-Security-Policy: default-src 'self'; + script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data:; connect-src 'self'`, + `X-Content-Type-Options: nosniff` and `Cache-Control: no-store`. `POST` requires a loopback host and same + origin, `Content-Type: application/json`, and a body of 1 byte to 1 MiB (`MAX_BODY`); JSON with `NaN` or + `Infinity` is rejected and responses are serialised with `allow_nan=False`. +- **Checkpoints**: `synapse/stateio.py` loads archives with `torch.load(..., map_location='cpu', weights_only=True)`. + Weight archives in `synapse/experiments.py` and connectome caches in `synapse/connectome_assets.py` use + `np.load(..., allow_pickle=False)`. +- **Known exception**: `synapse/capabilities.py` (bundled MaleCNS type table under `synapse/_vendor`) and + `synapse/connectome_compiler.py` (default bundled dataset, or a caller-supplied `data_path`) call + `np.load(..., allow_pickle=True)`. Only pass trusted files there; removing the pickle requirement is open work. +- **Read-only package inspection**: `NeuroWeaveWorkbenchAPI.inspect` in `synapse/neuroweave/workbench_api.py` accepts + at most `MAX_INSPECT_BYTES = 1_000_000` bytes of package text and returns `read_only: true` and + `live_state_changed: false`. +- **No raw media**: the NEUROWEAVE workbench API and package reader reject raw frame/audio keys + (`RAW_MEDIA_KEYS` in `synapse/neuroweave/workbench_api.py` and `synapse/neuroweave/package.py`); the sensory + endpoints take bounded derived summaries. +- **Offline exports**: standalone HTML exports (`synapse/portable_export.py`, `synapse/neuroweave/standalone.py`) + set a `default-src 'none'` CSP meta tag. +- **Frontier modules**: `docs/frontier/CONTRACT.md` requires `import_state` to validate fully before mutating. + +## 6. Additive compatibility contract + +Two manifests record the public surface of a baseline tag. A later tree passes `--check` when every recorded +item is still present and every recorded config default is equal; new items may be added freely. + +| Manifest | Baseline tag | Commit | +|---|---|---| +| `docs/neuroweave/compatibility-manifest.json` (default) | `sonapse-pre-neuroweave-baseline` | `6f2761b` | +| `docs/compatibility/manifest-pre-frontier.json` | `sonapse-pre-frontier-baseline` | `b9d8270` | + +Recorded sections: `config_defaults`, `cli_commands`, `cli_flags`, `http_routes`, `web_dom_ids`, +`checkpoint_namespaces`, `test_modules`, `max_mode_enabled_features`. + +`scripts/neuroweave_compat_manifest.py`: + +- `--check` / `--write` with no other flags behave as before (default manifest and tag). +- `--manifest PATH` selects another manifest (relative paths resolve against the repository root). +- `--baseline-tag TAG` labels a written manifest; with `--check` the manifest must also record that tag. +- `--root DIR` collects from another tree, such as a worktree of the baseline tag (run in a fresh interpreter). +- Route discovery scans `/api/...` string literals in every `synapse/**/*.py` except `synapse/_vendor`; CLI + discovery reads `synapse/cli.py` plus `synapse/neuroweave/cli_commands.py` and `synapse/frontier/cli_commands.py` + when they exist. Discovery only adds items to the current surface, so it cannot make an older manifest fail. + +The pre-Frontier manifest was generated from a temporary worktree of `sonapse-pre-frontier-baseline`. +Regenerating it on 2026-11-20 with the current script produced a byte-identical file: + +```bash +git worktree add /pre-frontier-wt sonapse-pre-frontier-baseline +python scripts/neuroweave_compat_manifest.py --write --root /pre-frontier-wt \ + --manifest docs/compatibility/manifest-pre-frontier.json --baseline-tag sonapse-pre-frontier-baseline +git worktree remove --force /pre-frontier-wt +``` + +## 7. Workbench theme and accessibility + +- **Theme selector** (sidebar, `#theme-select`): Dark (default), Light, System. Dark leaves `` without a + `data-theme` attribute, so a first visit with nothing stored renders exactly as before. Light and System set + `data-theme`; the `prefers-color-scheme` media query applies only under `data-theme="system"`. The choice is + stored under `synapse_theme_v1` in `localStorage`, and every storage call is wrapped in `try`/`catch`. + Canvases and the chat console stay dark in every theme because their drawing code assumes a dark background. +- **Contrast**: the test computes WCAG 2.x contrast for every light-theme text colour against every light surface, + with translucent fills composited over the page and panel colours. The lowest measured pair is 4.66:1 (teal + `#0b6e5b` on the composited tag fill `#e2dfdb`). White on accent fills is at least 6.18:1, omnibus buttons + on their inline tints are at least 6.16:1, and the dark chat console's colours are at least 4.80:1. +- **Accessibility**: a skip link to the focusable `

`, `:focus-visible` outlines for links, `summary` + and programmatic focus targets (buttons and form fields already had them), `aria-current="page"` on the active + nav button (set inside the existing tab handler), `aria-label`s that contain the visible text on + pictograph-prefixed controls, and `role="status"`/`aria-live="polite"` on status lines that lacked a live region. +- **Manual check** (2026-11-20, built-in browser, `python -m synapse --nodes 16 serve`): a first load with + nothing stored was dark with no `data-theme`; Light persisted across a reload; with OS light emulation, System + switched to the light palette while Dark stayed dark; choosing Dark cleared the stored value; switching tabs + moved `aria-current`; the skip link moved focus to `#title`. The console showed no errors. diff --git a/docs/compatibility/manifest-pre-frontier.json b/docs/compatibility/manifest-pre-frontier.json new file mode 100644 index 0000000000000000000000000000000000000000..e28272655627c74c24c92babe0f3d59b404d4d13 --- /dev/null +++ b/docs/compatibility/manifest-pre-frontier.json @@ -0,0 +1,1140 @@ +{ + "baseline_commit": "b9d8270", + "baseline_commit_full": "b9d82707c4575fc4147765357487cc092b518736", + "baseline_tag": "sonapse-pre-frontier-baseline", + "checkpoint_namespaces": [ + "active_inference", + "aether_bridge", + "apical_engine", + "archimedes_engine", + "auditory_encoder_state", + "comm_fabric", + "criticality_homeostat", + "cross_graft_engine", + "dendritic_ltc", + "dpo_engine", + "dsag_v1", + "dvgem_memory", + "event_backend", + "fatigue_controller", + "glymphatic_engine", + "graft_bus", + "grafted_diffusion", + "graph_diffusion", + "holographic_vsa", + "hyperbolic_manifold", + "knowledge_pool", + "kuramoto_engine", + "memory_carrier_nexus", + "metaplasticity_bcm", + "mixed_affect", + "multitimescale", + "neural_graft", + "neurowave_x2", + "neuroweave_v1", + "oscillatory_coherence", + "overflow_mini_brain", + "phase_protocol", + "programmed_prior_status", + "recurrent_planner", + "relational_memory", + "selective_ssm", + "source_provenance", + "spectral_reservoir", + "spiking_engine", + "synthetic_glands", + "tether_coordinator", + "thermodynamics", + "torch_rng", + "transfer_entropy", + "wave_solver", + "wpac" + ], + "cli_commands": [ + "ablate", + "ablation", + "adaptation-verify", + "astrocyte", + "atlas", + "autoprogram", + "benchmarks", + "capabilities", + "causal-growth", + "checkpoint-migration", + "coconut-think", + "connectome", + "connectome-assay", + "connectome-datasets", + "connectome-inventory", + "continual-backprop", + "controlled-study", + "curriculum-verify", + "diffusion-repair", + "dpo-align", + "dsag", + "ecology", + "efficiency", + "evidence", + "experiment", + "experiments", + "export", + "fast-memory", + "flagship", + "flagship-milestone", + "free_energy", + "frontier-innovations", + "frontier-v2", + "homeostasis", + "hyperprogram", + "import-legacy", + "inspect", + "lesion", + "live-rsi", + "manifest-check", + "manifold", + "mechanisms", + "meta-plasticity", + "metamorphic", + "mimomix", + "motifs", + "multi-connectome", + "multistep-plan", + "neural-comm", + "neurogenesis", + "neurowave-x2", + "neuroweave", + "omnibus", + "patch", + "planning-study", + "planning-verify", + "pretrain", + "reusable-skills", + "rsi-verify", + "scale-neurons", + "self-model-audit", + "sequence-search", + "serve", + "sleep-train", + "smoke", + "spectral", + "spiking", + "status", + "study", + "tool-arena", + "topology", + "transplant", + "uncertainty-calibrate", + "unified-eval", + "validate", + "verify", + "world-model-cem", + "world4d" + ], + "cli_flags": [ + "--active-training", + "--agent-nodes", + "--assay-trials", + "--batch-size", + "--budget", + "--candidates", + "--cem-horizon", + "--checkpoint", + "--compute-threads", + "--config", + "--connectome-mode", + "--csv", + "--diagnostic-episodes", + "--donor-task", + "--dsag", + "--dsag-config", + "--dsag-gain", + "--edits", + "--episodes", + "--eval-episodes", + "--eval-task", + "--feature", + "--fpga", + "--frontier-all", + "--frozen", + "--gain", + "--generations", + "--horizon", + "--horizons", + "--host", + "--html", + "--id", + "--input-dim", + "--landscapes", + "--mechanisms", + "--milestone-steps", + "--min-gain", + "--name", + "--neural-graft", + "--neurons", + "--neuroweave", + "--neuroweave-config", + "--nodes", + "--nodes-per-source", + "--out", + "--output", + "--pairs", + "--patch-type", + "--payload", + "--ponder", + "--port", + "--programmed-connectome", + "--query", + "--query-steps", + "--quick", + "--receipt", + "--repair-iters", + "--save", + "--save-report", + "--seed", + "--seeds", + "--seeds-per-landscape", + "--sleep-steps", + "--steps", + "--steps-per-stage", + "--steps-per-task", + "--study-nodes", + "--support-steps", + "--synapse-agent", + "--target", + "--targets", + "--task", + "--task-horizon", + "--tasks", + "--test-task", + "--think-depth", + "--topology", + "--total-neurons", + "--training-steps", + "--updates", + "--workers" + ], + "config_defaults": { + "active_inference_planner": false, + "active_training": false, + "aether_bridge_control": "none", + "aether_bridge_gamma": 0.0, + "aether_bridge_modes": 16, + "aether_graft_bridge": false, + "affective_core": false, + "apical_amplification": false, + "archimedes_buoyancy": false, + "causal_world_model": false, + "cognition_interval": 8, + "compute_threads": 1, + "connectome_mode": "proxy", + "connectome_sources": [ + "flywire", + "manc", + "optic-lobe" + ], + "continual_backprop": false, + "criticality_homeostat": false, + "cross_connectome_graft": false, + "cross_model_exchange": false, + "dendritic_ltc": false, + "dormant_lifecycle": true, + "dsag": null, + "dvgem_memory": false, + "event_driven_backend": false, + "evo_compat": false, + "experience_horizon": 1, + "experience_planning": false, + "experimental_cognition": false, + "fast_weight_memory": false, + "frontier_all": false, + "glymphatic_clearance": false, + "graft_batch_size": 64, + "graft_bus_enabled": false, + "graft_updates": 2, + "grafted_diffusion": false, + "graph_diffusion": false, + "holographic_vsa": false, + "hyperbolic_manifold": false, + "latent_reasoning": false, + "live_chat": false, + "live_microphone": false, + "memory_carrier_nexus": false, + "meta_plasticity": false, + "metaplasticity_bcm": false, + "microsteps": 2, + "multitimescale_learning": false, + "neural_comm_dim": 16, + "neural_comm_drop_rate": 0.0, + "neural_comm_enabled": false, + "neural_comm_every": 1, + "neural_comm_latency_steps": 0, + "neural_comm_max_aux_current": 0.5, + "neural_comm_max_bits": 128, + "neural_comm_max_messages": 4, + "neural_comm_mode": "continuous", + "neural_comm_precision_bits": 4, + "neural_comm_topology": "hybrid_causal", + "neural_graft": false, + "neural_pulses": false, + "neuroendocrine": false, + "neurowave_enabled": false, + "neurowave_x2_dendritic": false, + "neurowave_x2_development": false, + "neurowave_x2_development_level": 0, + "neurowave_x2_dimension": 16, + "neurowave_x2_enabled": false, + "neurowave_x2_gamma": 0.0, + "neurowave_x2_phase": true, + "neurowave_x2_plasticity": false, + "neurowave_x2_precision_bits": 32, + "neurowave_x2_protocol": "adaptive", + "neurowave_x2_spectral_basis": "hybrid", + "neurowave_x2_spectral_modes": 8, + "neuroweave": null, + "nodes_per_source": 100, + "oscillatory_coherence": false, + "overflow_mini_brain": false, + "planner_algorithm": "experience_mpc", + "programmed_connectome": false, + "quantum_kuramoto": false, + "readout": "absolute", + "relational_memory": false, + "seed": 7, + "selective_state_space": false, + "self_model": false, + "shared_knowledge": false, + "sleep_replay": false, + "spectral_reservoir": false, + "spiking_neuromorphic": false, + "structural_learning": true, + "surprise_memory": true, + "synthetic_glands": false, + "task": "forage", + "tether_coordinator": false, + "thermodynamics": false, + "total_neurons": null, + "transfer_entropy": false, + "value_guided_planning": false, + "verifiable_dpo": false, + "verifier_rsi": false, + "virtual_ecology_v2": false + }, + "contract": "additive-only: every recorded item must remain present; defaults must stay equal", + "http_routes": [ + "/api/", + "/api/ablation-engine/run", + "/api/aether_bridge/status", + "/api/apical/status", + "/api/apical_reservoir_hyperbolic", + "/api/archimedes/status", + "/api/atlas", + "/api/audio", + "/api/audio/push", + "/api/audio/toggle", + "/api/autoprogram", + "/api/benchmark-suite/catalog", + "/api/benchmark-suite/run", + "/api/capabilities", + "/api/causal-world/run", + "/api/causal_9arm", + "/api/chat", + "/api/checkpoint-migration/run", + "/api/checkpoints", + "/api/connectome/fusion/couple", + "/api/connectome/fusion/summary", + "/api/connectome/pac", + "/api/connectome/pac/enable", + "/api/connectome/stdp", + "/api/connectome/stdp/enable", + "/api/connectomes", + "/api/connectomes/fusion", + "/api/connectomes/fusion/couple", + "/api/connectomes/fusion/summary", + "/api/connectomes/inventory", + "/api/continual_backprop/status", + "/api/controlled_study", + "/api/criticality_vsa", + "/api/cross_graft/status", + "/api/diffusion_dpo", + "/api/dormant/status", + "/api/dsag/status", + "/api/dvgem_tether", + "/api/ecology", + "/api/ecology/allostasis", + "/api/ecology/allostasis/enable", + "/api/ecology/epigenetics", + "/api/ecology/epigenetics/enable", + "/api/ecology/evolution", + "/api/ecology/soundscape", + "/api/ecology/stats", + "/api/ecology/step", + "/api/ecology/tournament/cataclysm", + "/api/ecology/tournament/run", + "/api/ecology/tournament/status", + "/api/ecology/vocalize", + "/api/event-driven/run", + "/api/evo/candidates", + "/api/evo/transact", + "/api/experience/mode", + "/api/experience/preview", + "/api/export", + "/api/export/status/", + "/api/exports/", + "/api/fast_weight/status", + "/api/flagship", + "/api/frontier/innovations", + "/api/frontier/v2_innovations", + "/api/frontier_v4_assay", + "/api/glymphatic/status", + "/api/graft_bus/status", + "/api/hyperbolic/status", + "/api/hyperprogram", + "/api/invoke", + "/api/jobs", + "/api/jobs/cancel", + "/api/knowledge", + "/api/kuramoto/status", + "/api/load", + "/api/memory_carrier/status", + "/api/meta-plasticity/run", + "/api/metamorphic", + "/api/motif-discovery/run", + "/api/multimodal/synesthesia", + "/api/multimodal/synesthesia/burst", + "/api/neural-comm/bench", + "/api/neural-comm/config", + "/api/neural-comm/status", + "/api/neuroendocrine", + "/api/neuroweave/", + "/api/neuroweave/catalog", + "/api/neuroweave/configure", + "/api/neuroweave/ecology", + "/api/neuroweave/experiment", + "/api/neuroweave/export", + "/api/neuroweave/inspect", + "/api/neuroweave/ledger", + "/api/neuroweave/ledger/lab", + "/api/neuroweave/lesion", + "/api/neuroweave/observatory", + "/api/neuroweave/observatory/lab", + "/api/neuroweave/sensory", + "/api/neuroweave/sequence-search", + "/api/neuroweave/status", + "/api/neuroweave/step", + "/api/neuroweave/topology", + "/api/observatory/activity", + "/api/observatory/structure", + "/api/omnibus/reset", + "/api/omnibus/run", + "/api/omnibus/status", + "/api/omnibus/step", + "/api/pac/status", + "/api/patch/apply", + "/api/patch/evaluate", + "/api/patch/make", + "/api/patch/preview", + "/api/patch/rollback", + "/api/planning-study/receipt/", + "/api/pulses", + "/api/pulses/trigger", + "/api/reconsolidation/status", + "/api/relational-memory/run", + "/api/reservoir/status", + "/api/reset", + "/api/reusable_skills", + "/api/rsi/live", + "/api/save", + "/api/self_model/status", + "/api/sim-worker/control", + "/api/sim-worker/status", + "/api/sleep/consolidation/status", + "/api/sleep/dream_cycle", + "/api/sleep/reconsolidation", + "/api/sleep/reconsolidation/reactivate", + "/api/sleep/state", + "/api/sleep_replay", + "/api/soundscape", + "/api/spectral", + "/api/spiking/status", + "/api/state", + "/api/stdp/status", + "/api/step", + "/api/studies", + "/api/supermix/status", + "/api/supermix_archimedes_nexus_assay", + "/api/synesthesia", + "/api/tandem/max", + "/api/tandem/start", + "/api/tandem/status", + "/api/tensors", + "/api/tool-arena/status", + "/api/training/config", + "/api/training/intensive", + "/api/training/pretrain", + "/api/training/status", + "/api/transplant", + "/api/uncertainty/status", + "/api/verifier-rsi/run", + "/api/world4d/status" + ], + "max_mode_enabled_features": [ + "active_inference_planner", + "active_training", + "aether_graft_bridge", + "affective_core", + "apical_amplification", + "archimedes_buoyancy", + "causal_world_model", + "continual_backprop", + "criticality_homeostat", + "cross_connectome_graft", + "cross_model_exchange", + "dendritic_ltc", + "dormant_lifecycle", + "dsag_v1.axo_branches", + "dsag_v1.dual_soma", + "dsag_v1.enabled", + "dsag_v1.phase_gate_enabled", + "dsag_v1.plasticity_enabled", + "dsag_v1.richer_messages", + "dsag_v1.structural_growth_enabled", + "dvgem_memory", + "event_driven_backend", + "evo_compat", + "experience_planning", + "experimental_cognition", + "fast_weight_memory", + "frontier_all", + "glymphatic_clearance", + "graft_bus_enabled", + "grafted_diffusion", + "graph_diffusion", + "holographic_vsa", + "hyperbolic_manifold", + "latent_reasoning", + "live_chat", + "live_microphone", + "memory_carrier_nexus", + "meta_plasticity", + "metaplasticity_bcm", + "multitimescale_learning", + "neural_comm_enabled", + "neural_graft", + "neural_pulses", + "neuroendocrine", + "neurowave_enabled", + "neurowave_x2_dendritic", + "neurowave_x2_development", + "neurowave_x2_enabled", + "neurowave_x2_phase", + "neurowave_x2_plasticity", + "neuroweave_v1", + "neuroweave_v1.adaptive_conduction", + "neuroweave_v1.adaptive_routing", + "neuroweave_v1.affective_modulation", + "neuroweave_v1.associative_memory", + "neuroweave_v1.astrocyte_regulation", + "neuroweave_v1.axonal_branches", + "neuroweave_v1.context_attention", + "neuroweave_v1.counterfactual_prediction", + "neuroweave_v1.cross_modal_memory", + "neuroweave_v1.dendritic_compartments", + "neuroweave_v1.efference_self_model", + "neuroweave_v1.expert_routing", + "neuroweave_v1.extended_somas", + "neuroweave_v1.fast_weights", + "neuroweave_v1.flyhash_projection", + "neuroweave_v1.hierarchical_prediction", + "neuroweave_v1.hierarchical_temporal_memory", + "neuroweave_v1.homeostatic_governor", + "neuroweave_v1.membrane_dynamics", + "neuroweave_v1.memory_ecology", + "neuroweave_v1.meta_plasticity", + "neuroweave_v1.micro_collective", + "neuroweave_v1.multi_region_routing", + "neuroweave_v1.multi_soma", + "neuroweave_v1.multimodal_sensory", + "neuroweave_v1.neurogenesis", + "neuroweave_v1.neuromodulator_field", + "neuroweave_v1.predictive_coding", + "neuroweave_v1.predictive_ensemble", + "neuroweave_v1.predictive_replay", + "neuroweave_v1.q88_state", + "neuroweave_v1.quantised_synapses", + "neuroweave_v1.receptor_heterogeneity", + "neuroweave_v1.representation_fusion", + "neuroweave_v1.reward_plasticity", + "neuroweave_v1.sleep_consolidation", + "neuroweave_v1.sparse_code", + "neuroweave_v1.specialist_graft", + "neuroweave_v1.stdp", + "neuroweave_v1.structural_encoder", + "neuroweave_v1.structural_plasticity", + "neuroweave_v1.synaptic_delays", + "neuroweave_v1.tiled_execution", + "neuroweave_v1.transmitter_inference", + "neuroweave_v1.uncertainty_gating", + "oscillatory_coherence", + "overflow_mini_brain", + "programmed_connectome", + "quantum_kuramoto", + "relational_memory", + "selective_state_space", + "self_model", + "shared_knowledge", + "sleep_replay", + "spectral_reservoir", + "spiking_neuromorphic", + "structural_learning", + "surprise_memory", + "synthetic_glands", + "tether_coordinator", + "thermodynamics", + "transfer_entropy", + "value_guided_planning", + "verifiable_dpo", + "verifier_rsi", + "virtual_ecology_v2" + ], + "schema": "sonapse-compatibility-manifest-v1", + "test_modules": [ + "test_12000_neurons_and_multi_connectome_fusion.py", + "test_9000_neurons_and_backward_compatibility.py", + "test_active_training.py", + "test_adaptation_study.py", + "test_advanced_frontier_features.py", + "test_aether_graft_master_integration.py", + "test_agent.py", + "test_antigravity_contract_regressions.py", + "test_apical_reservoir_hyperbolic.py", + "test_astrocyte.py", + "test_auto_programmer.py", + "test_bioacoustic_soundscape_and_cross_coupling.py", + "test_capabilities.py", + "test_causal_circuit_evolution.py", + "test_causal_mediation.py", + "test_circuit_atlas.py", + "test_cli.py", + "test_cli_evidence_labels.py", + "test_complex_environments.py", + "test_compute_budget.py", + "test_connectome_assets.py", + "test_connectome_authenticity.py", + "test_connectome_compiler.py", + "test_continual_probe.py", + "test_controlled_study.py", + "test_cross_graft_master.py", + "test_curriculum.py", + "test_dales_law.py", + "test_darwinian_tournament_and_web_audio.py", + "test_deep_research_upgrades.py", + "test_dsag.py", + "test_efficiency.py", + "test_evidence_engine.py", + "test_evidence_sleep_regressions.py", + "test_experience.py", + "test_experience_integration.py", + "test_experience_planner.py", + "test_experience_workbench.py", + "test_flagship.py", + "test_frontier_v2_innovations.py", + "test_frontier_v4_innovations.py", + "test_genome.py", + "test_graft_bus_and_aether_bridge.py", + "test_hypernetwork.py", + "test_hypernetwork_trainer.py", + "test_imagination_and_symbolic.py", + "test_kai_supermix_nexus.py", + "test_learning.py", + "test_live_programming.py", + "test_live_training_integration.py", + "test_manifold_alignment.py", + "test_max_mode_memory.py", + "test_measured_evo_and_live_audio.py", + "test_memory_consolidation_and_shy.py", + "test_metabolic.py", + "test_metamorphic.py", + "test_motivation_and_adaptive.py", + "test_multi_connectome_scaling.py", + "test_multimodal_live_and_virtual_ecology.py", + "test_neural_graft.py", + "test_neural_pulses_and_graph_waves.py", + "test_neuroendocrine_affective.py", + "test_neurogenesis_ranking_equivalence.py", + "test_neuromodulation.py", + "test_neuron_count.py", + "test_neurowave_x2_ablations.py", + "test_neurowave_x2_checkpoint.py", + "test_neurowave_x2_hybrid_basis.py", + "test_neurowave_x2_optimizer_migration.py", + "test_neurowave_x2_packets.py", + "test_neurowave_x2_phase.py", + "test_neurowave_x2_promotion.py", + "test_neurowave_x2_reference.py", + "test_neurowave_x2_regression.py", + "test_neurowave_x2_replay.py", + "test_neurowave_x2_resources.py", + "test_neurowave_x2_selector.py", + "test_neurowave_x2_spectral.py", + "test_neurowave_x2_stress.py", + "test_neurowave_x2_topology.py", + "test_neurowave_x2_transaction.py", + "test_neurowave_x2_transport.py", + "test_neuroweave_cli.py", + "test_neuroweave_core.py", + "test_neuroweave_ecology.py", + "test_neuroweave_engine.py", + "test_neuroweave_hardware_package.py", + "test_neuroweave_integration.py", + "test_neuroweave_lab.py", + "test_neuroweave_micro_memory.py", + "test_neuroweave_modulation_sensory.py", + "test_neuroweave_prediction_packets.py", + "test_neuroweave_review_fixes.py", + "test_neuroweave_sequence_search.py", + "test_neuroweave_server.py", + "test_neuroweave_standalone.py", + "test_observatory.py", + "test_omnibus_mode.py", + "test_pac_waves_epigenetics_synesthesia.py", + "test_parallel_pretraining.py", + "test_patches.py", + "test_planner_review_regressions.py", + "test_planning_study.py", + "test_planning_workbench.py", + "test_portable_export.py", + "test_predictive_coding.py", + "test_recursive_learning.py", + "test_research_fabric_and_plasticity.py", + "test_reusable_skills.py", + "test_rsi.py", + "test_runtime.py", + "test_runtime_contracts.py", + "test_sail_upgrades.py", + "test_sancf_and_frontier_master.py", + "test_self_model_efference.py", + "test_server.py", + "test_server_lock_isolation.py", + "test_shared_knowledge_and_exchange.py", + "test_sleep_replay_and_dreams.py", + "test_spatial_and_memory.py", + "test_spectral.py", + "test_spiking.py", + "test_stateio.py", + "test_stdp_allostasis_reconsolidation.py", + "test_structural_plasticity.py", + "test_study_isolation_regressions.py", + "test_supermix_advancements.py", + "test_surprise_memory.py", + "test_tandem_max_and_innovations.py", + "test_training_jobs.py", + "test_transfer.py", + "test_transplantation.py", + "test_uncertainty_calibration.py", + "test_uncertainty_guard.py", + "test_virtual_ecology.py", + "test_vision_and_objects.py", + "test_workbench_canvas_and_features.py" + ], + "web_dom_ids": [ + "aether-graft-badge", + "aether-graft-canvas", + "aether-graft-hud", + "allostasis-enable-btn", + "apical-badge", + "apical-canvas", + "apical-hud", + "applypatch", + "archimedes-badge", + "archimedes-canvas", + "archimedes-hud", + "atlas", + "atlasresult", + "audio-cochlea-badge", + "audio-harmonic-btn", + "audio-live-toggle-btn", + "audio-mic-badge", + "audio-mic-btn", + "audio-status-badge", + "audio-toggle-btn", + "auditory-canvas", + "auditory-hud", + "autoprogram", + "autorepairresult", + "bcm-badge", + "bcm-hud", + "benchmark-badge", + "benchmark-hud", + "benchmark-suite-out", + "btn-causal-assay", + "btn-checkpoint-migration", + "btn-meta-plasticity", + "btn-neurowave-modes", + "btn-omnibus-run", + "btn-run-ablation", + "btn-run-benchmarks", + "btn-run-tool-arena", + "btn-sancf-bench", + "btn-tandem-max", + "btn-tandem-max-toolbar", + "capabilities", + "capname", + "cappayload", + "capresult", + "capschema", + "capsweepresult", + "carrier-badge", + "carrier-canvas", + "carrier-hud", + "catalog", + "causal-9arm-btn", + "causal-assay-out", + "causal-entropy-canvas", + "causal9armresult", + "chat-input", + "chat-send-btn", + "chat-stream", + "checkpointlist", + "checkpointname", + "checkpointresult", + "checkpoints", + "cognition-hud", + "config", + "config-max-preset", + "connection", + "controlled-study-btn", + "controlledstudyresult", + "criticality-badge", + "criticality-canvas", + "criticality-hud", + "criticality-vsa-btn", + "criticalityvsaresult", + "cross-graft-badge", + "cross-graft-canvas", + "cross-graft-hud", + "darwinian-badge", + "darwinian-cataclysm-btn", + "darwinian-run-btn", + "dendritic-badge", + "dendritic-canvas", + "dendritic-hud", + "description", + "diffusion-dpo", + "diffusiondporesult", + "dormant-badge", + "dormant-hud", + "dsag-badge", + "dsag-canvas", + "dsag-hud", + "dvgem-badge", + "dvgem-hud", + "dvgem-tether-btn", + "dvgemtetherresult", + "ecology-badge", + "ecology-canvas", + "ecology-evo-toggle-btn", + "ecology-hud", + "ecology-predator-btn", + "ecology-seed-btn", + "ecology-sleep-btn", + "ecology-transact-btn", + "edits", + "epigenetics-enable-btn", + "error", + "evaluatepatch", + "experience-algorithm", + "experience-apply", + "experience-details", + "experience-horizon", + "experience-mode", + "experience-preview", + "experience-summary", + "experience-value-guided", + "experiments", + "export-simulation", + "export-status", + "exportpatch", + "flagship", + "flagshipresult", + "gauges", + "glands-badge", + "glands-canvas", + "glands-hud", + "glymphatic-badge", + "glymphatic-canvas", + "glymphatic-hud", + "graph", + "graph-activity", + "graph-autorotate", + "graph-camera-reset", + "graph-cluster-halos", + "graph-edges", + "graph-grafts", + "graph-legend", + "graph-neurowave", + "graph-nodes", + "graph-role", + "graph-selection", + "graph-source", + "graph-streamlines", + "graph-summary", + "graph-tooltip", + "graph-view-2d", + "graph-view-3d", + "hyperapply", + "hyperbolic-badge", + "hyperbolic-canvas", + "hyperbolic-hud", + "hyperprogram", + "hyperresult", + "importpatch", + "invoke", + "jobs", + "kuramoto-badge", + "kuramoto-canvas", + "kuramoto-hud", + "learn", + "learning-contract", + "lineage", + "load", + "makepatch", + "manifold", + "manifoldresult", + "metamorphic", + "metamorphicresult", + "metrics", + "mimomix-badge", + "neuroplasticity-result", + "neurowave-badge", + "neurowave-canvas", + "neurowave-hud", + "neuroweave", + "nwl-affect", + "nwl-auto", + "nwl-axon", + "nwl-channels", + "nwl-conn-canvas", + "nwl-controls", + "nwl-eco-canvas", + "nwl-eco-config", + "nwl-eco-refresh", + "nwl-eco-run", + "nwl-eco-steps", + "nwl-eco-summary", + "nwl-exp-background", + "nwl-exp-quick", + "nwl-exp-run", + "nwl-exp-seeds", + "nwl-exp-select", + "nwl-exp-status", + "nwl-exp-steps", + "nwl-expert-load", + "nwl-export-csv", + "nwl-export-fpga", + "nwl-export-html", + "nwl-export-json", + "nwl-export-package", + "nwl-export-source", + "nwl-external-channel", + "nwl-external-send", + "nwl-external-value", + "nwl-import-file", + "nwl-inspect-out", + "nwl-lab-out", + "nwl-ledger-body", + "nwl-ledger-refresh", + "nwl-ledger-summary", + "nwl-lesion-run", + "nwl-loss", + "nwl-mech-apply", + "nwl-mech-list", + "nwl-mech-none", + "nwl-mic-start", + "nwl-mic-stop", + "nwl-modes-apply", + "nwl-modulators", + "nwl-panel-environment", + "nwl-panel-lab", + "nwl-panel-learning", + "nwl-panel-neural", + "nwl-panel-neuromod", + "nwl-panel-sensory", + "nwl-panel-studio", + "nwl-plasticity", + "nwl-receptors", + "nwl-refresh", + "nwl-region-bars", + "nwl-results-body", + "nwl-sensory-out", + "nwl-sensory-pe", + "nwl-sensory-status", + "nwl-sequence-body", + "nwl-sequence-details", + "nwl-sequence-run", + "nwl-sequence-status", + "nwl-soma", + "nwl-source", + "nwl-status", + "nwl-step-count", + "nwl-step-run", + "nwl-studio-status", + "nwl-topology-run", + "nwl-webcam-start", + "nwl-webcam-stop", + "nwl-webcam-video", + "omnibus-badge", + "omnibus-hud", + "oscillatory-badge", + "oscillatory-canvas", + "oscillatory-hud", + "overflow-badge", + "overflow-hud", + "overview", + "pac-badge", + "pac-enable-btn", + "pac-synesthesia-hud", + "pac-waves-canvas", + "packet", + "patches", + "patchresult", + "pause", + "plan-actions", + "plan-candidates", + "plan-details", + "plan-preview", + "plan-reason", + "plan-step", + "planning-receipt-load", + "planning-receipt-name", + "planning-receipt-result", + "planning-receipt-status", + "plasticity-badge", + "plasticity-hud", + "predictive", + "previewpatch", + "pulses-badge", + "pulses-canvas", + "pulses-hud", + "quicktask", + "reconsolidation-reactivate-btn", + "refreshcheckpoints", + "reservoir-badge", + "reservoir-canvas", + "reservoir-hud", + "rollback", + "rsi-live", + "rsi-receipt", + "rsi-status", + "run", + "runstatus", + "sancf-badge", + "sancf-bench-out", + "sancf-hud", + "save", + "search", + "self-model-badge", + "self-model-hud", + "signals", + "simspeed", + "simsteps", + "skills-refresh", + "skills-result", + "sleep-badge", + "sleep-canvas", + "sleep-hud", + "snapshot", + "soundscape-badge", + "soundscape-canvas", + "soundscape-cross-couple-btn", + "soundscape-forager-call-btn", + "soundscape-hud", + "soundscape-sentinel-alarm-btn", + "source-details", + "source-inventory", + "speciation-canvas", + "speciation-hud", + "spectral", + "spectralresult", + "spiking-badge", + "spiking-canvas", + "spiking-hud", + "startstudy", + "stdp-allostasis-canvas", + "stdp-allostasis-hud", + "stdp-badge", + "stdp-enable-btn", + "step", + "studyconfig", + "studyresult", + "surfaces", + "sweep-capabilities", + "synesthesia-burst-btn", + "tandem-banner", + "tandem-receipt-out", + "tandem-section-pills", + "tandem-status-pill", + "tandem-summary", + "task-aware-route", + "task-aware-status", + "task-aware-support", + "te-badge", + "te-hud", + "telemetry", + "teleop-arm", + "teleop-fwd", + "teleop-grip", + "teleop-left", + "teleop-right", + "tensors", + "tether-badge", + "tether-hud", + "thermo-badge", + "thermo-hud", + "thrust-governor", + "title", + "tool-arena-out", + "train", + "training-active", + "training-apply", + "training-badge", + "training-batch", + "training-cancel", + "training-compute", + "training-intensive", + "training-job-progress", + "training-job-status", + "training-metrics", + "training-pretrain", + "training-prior", + "training-receipt", + "training-threads", + "training-workers", + "transplant", + "transplantresult", + "trigger-threat-btn", + "uncertainty-badge", + "uncertainty-hud", + "vitals-hud", + "vsa-badge", + "vsa-canvas", + "vsa-hud", + "world", + "world-clear-trail", + "world-goals", + "world-legend", + "world-retina-cam", + "world-summary", + "world-terrain-mesh", + "world-tooltip", + "world-trails", + "world-view-iso", + "world-view-top", + "world-wind-streamlines", + "world4d-badge", + "world4d-hud", + "worldtask", + "wpac-badge", + "wpac-canvas", + "wpac-hud" + ] +} diff --git a/docs/frontier/CONTRACT.md b/docs/frontier/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..3429cf901943f4d86acebfaf4335495111db6f6d --- /dev/null +++ b/docs/frontier/CONTRACT.md @@ -0,0 +1,94 @@ +# Frontier pack: module contract (v1) + +The frontier pack (`synapse/frontier/`) adds experimental modules inspired by +2024–2026 research and by sibling `kai9987kai` projects. This contract fixes the +rules every module follows so the pack stays additive, testable and honest. + +Read with: `synapse/frontier/spec.py` (module registry and `FrontierSpecV1`), +`synapse/frontier/extension.py` (engine-extension interface v1) and +`synapse/frontier/harness.py` (shared experiment harness). + +## Non-negotiable rules + +1. **Additive and default-off.** No existing Sonapse or NEUROWEAVE default, + API, route, DOM id, CLI flag, checkpoint format or test changes behaviour. + `scripts/neuroweave_compat_manifest.py --check` keeps passing. +2. **Live observers are read-only.** An observer receives a *copy* of activity + and never writes into the brain, graft bus, actor or any shared RNG. +3. **Influence only by explicit attachment.** A module may change computation + only as an extension attached to a NEUROWEAVE engine (lab experiments), as a + standalone model in its own experiment, or through an explicitly selected + opt-in option. +4. **Deterministic.** All randomness from `numpy.random.default_rng(seed + offset)` + or a seeded `torch.Generator`; never the global RNGs. Torch code sets + `torch.manual_seed` only inside its own local generator usage and must not + change global torch state (use `torch.Generator` objects; restore + `torch.get_num_threads()` if changed). +5. **Bounded and finite.** Every buffer has a fixed maximum size; every state + value is finite; inputs are validated (`ValueError` on bad input) before any + state changes. `import_state` validates fully before mutating. +6. **Honest evidence.** Receipts carry `evidence_tier: 'synthetic_abstraction'`. + Module titles name the idea a module is *inspired by*; never claim to + reproduce a paper's results, biological validity, consciousness, emotion, + or measured hardware performance. Every citation is verified (title, + authors, venue, month/year, URL) before it is written down. +7. **Dependencies.** NumPy, SciPy and PyTorch only (already required). Any + other package (for example `nir`) is optional: import lazily, degrade + gracefully, and test the fallback. + +## Module file API + +Each module lives in `synapse/frontier/.py` and exposes: + +- `MODULE_ID: str` — the id from `spec.MODULE_IDS`. +- `run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict` + returning a **sealed frontier receipt** (see below). `quick=True` must finish + in under ~20 s on one CPU thread; the default size should finish in a few + minutes at most. +- `EXPERIMENTS: dict[str, Callable[..., dict]]` mapping every experiment id the + module provides to its runner (same signature as `run_experiment`). The first + entry is `MODULE_ID: run_experiment`; extra ids start with `MODULE_ID + '_'`. + The frontier lab registry is built from these dictionaries. +- Observer modules (`spec.OBSERVER_MODULE_IDS`) also expose an observer class: + `__init__(self, n_units: int, *, seed: int = 7, history: int = 256, **params)`, + `observe(self, x: np.ndarray) -> None` (1-D, length `n_units`, finite), + `summary(self) -> dict` (JSON-safe, at most ~16 KB, no wall-clock), + `reset()`, `export_state() -> dict`, `import_state(state) -> None`. + Observer parameters come from `FrontierSpecV1` (`history`, `sync_pairs`, + `sae_features`, `sae_k`, `fc_window`). +- Engine extensions subclass `extension.EngineExtension` and follow its rules + (no engine reference kept, deep-copyable, frozen when `ctx['learn']` is false). + +## Receipts and verdicts + +Build receipts with `harness.base_receipt(experiment_id, kind, config)`, add +fields, and finish with `harness.seal(receipt)` (adds the SHA-256 digest; keys +containing `wallclock` are excluded from the digest). + +- **Comparison experiments** (`kind` other than `validation`) set + `verdict` in `('improved', 'no_detectable_difference', 'worse')` using + `harness.compare` (paired 95 % t interval over seeds; `improved` only when + the interval excludes zero) and, when the candidate adds capacity, + `harness.headline_verdict` against a capacity-matched control. Report the + basis in `verdict_basis`. Never declare `improved` from complexity alone. +- **Validation experiments** (`kind: 'validation'`, e.g. interchange export, + biophysical reference, statistical coverage checks) set `verdict` in + `('pass', 'fail')` with an explicit `checks` mapping of named booleans. +- Always include: `config` (enough to reproduce), parameter/state budgets where + models are compared, `estimated_*` cost fields kept apart from + `measured_wallclock_s`, and `notes` stating limits. + +## Tests + +One test file per implementation group, `tests/test_frontier_.py`, fast +(tiny sizes; well under a minute in total per file), covering: determinism +(same seed ⇒ same digest), bounds and finiteness, validation errors, state +round-trips, the module's core behaviour on a case with a known answer, and +`run_experiment(quick=True)` producing a sealed, verifiable receipt. + +## Documentation + +Each module gets `docs/frontier/modules/.md`: what it does (with the +key equations), the verified source citation(s), what is implemented and what is +not, how it connects to Sonapse, and the measured quick-mode result with its +date and settings. No claim without a test or a recorded measurement. diff --git a/docs/frontier/README.md b/docs/frontier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..64701b4d79bfb81ef44d4ba00c957b9c5589dd9c --- /dev/null +++ b/docs/frontier/README.md @@ -0,0 +1,52 @@ +# Sonapse Frontier Pack (`synapse/frontier/`) + +The **Frontier Pack** is an additive, default-off collection of experimental computational neuroscience, machine +learning, and methodology modules inspired by 2024–2026 research literature and by sibling `kai9987kai` repositories. + +Every module follows the contract in [`CONTRACT.md`](CONTRACT.md) and carries full verified bibliography and portfolio +provenance in [`REFERENCES.md`](REFERENCES.md): + +1. **Additive and default-off.** `SynapseConfig().frontier` defaults to `None` and is omitted from `to_dict()`. + No existing Sonapse or NEUROWEAVE default, route, DOM id, CLI flag, or checkpoint changes behaviour. +2. **Read-only live observers.** Modules marked `observer=True` can observe a deterministic unit subsample of live + brain activity (`FrontierObserverHub` in `synapse/frontier/runtime.py`) without ever writing back into the brain, + graft bus, actor, or shared RNGs. +3. **Capacity-matched experimental harness.** Comparison experiments run through `synapse/frontier/harness.py`, + reporting paired differences over seeds with a two-sided 95 % t confidence interval against both an unmodified + baseline and (whenever capacity is added) a capacity-matched control, sealed with a wall-clock-independent SHA-256 + digest (`FrontierLabReceiptV1`, `evidence_tier: 'synthetic_abstraction'`). + +--- + +## Module Catalog (`synapse/frontier/spec.py`) + +| Module ID | File | Kind | Live Observer | Engine Extension | Inspiration / Source | Documentation | +|---|---|---|---|---|---|---| +| `synchrony` | `synchrony.py` | `extension` | `SynchronyObserver` | `SynchronyExtension`, `NeuronLevelExtension` | Continuous Thought Machines (Darlow et al., NeurIPS 2025) | [`modules/synchrony.md`](modules/synchrony.md) | +| `continuum_memory` | `continuum_memory.py` | `extension` | — | `ContinuumMemoryExtension` | Nested Learning / HOPE & Titans (Behrouz et al., NeurIPS 2025) | [`modules/continuum_memory.md`](modules/continuum_memory.md) | +| `btsp_memory` | `btsp.py` | `extension` | — | `BTSPExtension` | One-shot binary-synapse BTSP (Wu & Maass, *Nat. Commun.* 2025) | [`modules/btsp_memory.md`](modules/btsp_memory.md) | +| `kuramoto_binding` | `kuramoto.py` | `extension` | `KuramotoObserver` | `KuramotoExtension` | Artificial Kuramoto Oscillatory Neurons (Miyato et al., ICLR 2025) | [`modules/kuramoto_binding.md`](modules/kuramoto_binding.md) | +| `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) | +| `dendritic_layer` | `dendritic.py` | `model` | — | — | Structured dendritic ANNs (Chavlis & Poirazi, *Nat. Commun.* 2025) | [`modules/dendritic_layer.md`](modules/dendritic_layer.md) | +| `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) | +| `rigl_sparse` | `rigl.py` | `tool` | — | — | RigL dynamic sparse training (Evci et al., ICML 2020) & `sonapse-evo` | [`modules/rigl_sparse.md`](modules/rigl_sparse.md) | +| `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) | +| `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) | +| `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) | +| `connectomics` | `connectomics.py` | `analysis` | `ConnectivityObserver` | — | Structural, functional, dynamic-FC, and ridge-VAR(1) effective connectivity (`SONAPSE-CONNECTOME`) | [`modules/connectomics.md`](modules/connectomics.md) | +| `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) | +| `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) | +| `nir_export` | `nir_export.py` | `tool` | — | — | Neuromorphic Intermediate Representation export (Pedersen et al., *Nat. Commun.* 2024) | [`modules/nir_export.md`](modules/nir_export.md) | +| `joint_failure` | `joint_failure.py` | `methodology` | — | — | Condition-indexed joint-failure voting panel selection (`FAULTLINE`) | [`modules/joint_failure.md`](modules/joint_failure.md) | +| `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) | +| `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) | + +--- + +## Integration Surfaces + +* **Config (`synapse/config.py`):** `SynapseConfig(frontier=FrontierSpecV1.max_preset())` (default `None`, omitted from `to_dict()`). +* **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'`). +* **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}`. +* **Workbench HTTP API (`synapse/frontier/workbench_api.py`):** `GET /api/frontier/{catalog,status,observers,observers/lab}` and `POST /api/frontier/{configure,step,experiment}`. +* **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. diff --git a/docs/frontier/REFERENCES.md b/docs/frontier/REFERENCES.md new file mode 100644 index 0000000000000000000000000000000000000000..9efb5a0e0b3c3245663ea4ef9b2b793b1cf13d52 --- /dev/null +++ b/docs/frontier/REFERENCES.md @@ -0,0 +1,176 @@ +# Frontier Pack: Verified References & Portfolio Provenance + +Every module in `synapse/frontier/` is a synthetic computational abstraction (`evidence_tier: 'synthetic_abstraction'`). +Module titles and docstrings name the research papers or sibling `kai9987kai` projects that inspired each mechanism; +they do not claim to reproduce published results or biological systems. + +All bibliographic details below (title, authors, venue, publication/preprint month & year, and URL/DOI) were verified +against publisher, arXiv, Project Euclid, PMC, or Crossref metadata on 2026-11-17 through 2026-11-19. + +--- + +## 1. Literature References (by Module) + +### `synchrony` (`synapse/frontier/synchrony.py`) + +* Luke Darlow, Ciaran Regan, Sebastian Risi, Jeffrey Seely, and Llion Jones (Sakana AI). + **Continuous Thought Machines.** *Advances in Neural Information Processing Systems (NeurIPS) 2025* (Spotlight). + Preprint: arXiv:2505.05522 (v1 8 May 2025; v4 3 October 2025), . + Reference code: . + +### `continuum_memory` (`synapse/frontier/continuum_memory.py`) + +* Ali Behrouz, Meisam Razaviyayn, Peilin Zhong, and Vahab Mirrokni. + **Nested Learning: The Illusion of Deep Learning Architectures.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*. + Preprint: arXiv:2512.24695 (December 2025), . +* Ali Behrouz, Peilin Zhong, and Vahab Mirrokni. + **Titans: Learning to Memorize at Test Time.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*. + Preprint: arXiv:2501.00663 (31 December 2024), . + +### `btsp_memory` (`synapse/frontier/btsp.py`) + +* Yujie Wu and Wolfgang Maass. + **A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides content addressable memory with binary synapses and one-shot learning.** + *Nature Communications* 16, 342 (published online 2 January 2025). + DOI [10.1038/s41467-024-55563-6](https://doi.org/10.1038/s41467-024-55563-6). +* David J. Willshaw, O. Peter Buneman, and Hugh C. Longuet-Higgins. + **Non-Holographic Associative Memory.** *Nature* 222(5197), 960–962 (7 June 1969). + DOI [10.1038/222960a0](https://doi.org/10.1038/222960a0). + +### `kuramoto_binding` (`synapse/frontier/kuramoto.py`) + +* Takeru Miyato, Sindy Löwe, Andreas Geiger, and Max Welling. + **Artificial Kuramoto Oscillatory Neurons.** *International Conference on Learning Representations (ICLR) 2025* (Oral, April 2025). + Preprint: arXiv:2410.13821 (v1 17 October 2024; v3 16 May 2025), . +* Murray Shanahan. + **Metastable chimera states in community-structured oscillator networks.** *Chaos* 20(1), 013108 (March 2010; published online 22 February 2010). + DOI [10.1063/1.3305451](https://doi.org/10.1063/1.3305451); arXiv:0908.3881. + +### `recursive_refiner` (`synapse/frontier/recursive_refiner.py`) + +* Alexia Jolicoeur-Martineau. + **Less is More: Recursive Reasoning with Tiny Networks.** + Preprint: arXiv:2510.04871 (October 2025), . +* Guan Wang, Jin Li, Yuhao Sun, Xing Chen, Changling Liu, Yue Wu, Meng Lu, Sen Song, and Yasin Abbasi Yadkori. + **Hierarchical Reasoning Model.** + Preprint: arXiv:2506.21734 (June 2025), . + +### `dendritic_layer` (`synapse/frontier/dendritic.py`) + +* Spyridon Chavlis and Panayiota Poirazi. + **Dendrites endow artificial neural networks with accurate, robust and parameter-efficient learning.** + *Nature Communications* 16, 943 (published 22 January 2025). + DOI [10.1038/s41467-025-56297-9](https://doi.org/10.1038/s41467-025-56297-9); PMC11754790; arXiv:2404.03708. + Reference code: . + +### `muon_optimizer` (`synapse/frontier/muon.py`) + +* Keller Jordan, Yuchen Jin, Vlado Boza, Jiacheng You, Franz Cesista, Laker Newhouse, and Jeremy Bernstein. + **Muon: An optimizer for hidden layers in neural networks.** Blog post (8 December 2024), + . +* 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). + **Muon is Scalable for LLM Training.** + Preprint: arXiv:2502.16982 (24 February 2025), . + +### `rigl_sparse` (`synapse/frontier/rigl.py`) + +* Utku Evci, Trevor Gale, Jacob Menick, Pablo Samuel Castro, and Erich Elsen. + **Rigging the Lottery: Making All Tickets Winners.** *Proceedings of the 37th International Conference on Machine Learning (ICML 2020)*, PMLR 119, 2943–2952 (July 2020). + Preprint: arXiv:1911.11134 (25 November 2019), . + +### `sparse_dictionary` (`synapse/frontier/sparse_dictionary.py`) + +* Leo Gao, Tom Dupré la Tour, Henk Tillman, Gabriel Goh, Rajan Troll, Alec Radford, Ilya Sutskever, Jan Leike, and Jeffrey Wu. + **Scaling and evaluating sparse autoencoders.** *International Conference on Learning Representations (ICLR) 2025*. + Preprint: arXiv:2406.04093 (6 June 2024), . +* Alireza Makhzani and Brendan Frey. + **k-Sparse Autoencoders.** *International Conference on Learning Representations (ICLR) 2014*. + Preprint: arXiv:1312.5663 (19 December 2013), . + +### `anytime_inference` (`synapse/frontier/anytime.py`) + +* Ian Waudby-Smith and Aaditya Ramdas. + **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). + DOI [10.1093/jrsssb/qkad009](https://doi.org/10.1093/jrsssb/qkad009); arXiv:2010.09686. +* Aaditya Ramdas, Peter Grünwald, Vladimir Vovk, and Glenn Shafer. + **Game-Theoretic Statistics and Safe Anytime-Valid Inference.** *Statistical Science* 38(4), 576–601 (November 2023). + DOI [10.1214/23-STS894](https://doi.org/10.1214/23-STS894); arXiv:2210.01948. + +### `experiment_design` (add-on) + +* Dennis V. Lindley. + **On a Measure of the Information Provided by an Experiment.** *The Annals of Mathematical Statistics* 27(4), 986–1005 (December 1956). + DOI [10.1214/aoms/1177728069](https://doi.org/10.1214/aoms/1177728069). +* Kathryn Chaloner and Isabella Verdinelli. + **Bayesian Experimental Design: A Review.** *Statistical Science* 10(3), 273–304 (August 1995). + DOI [10.1214/ss/1177009939](https://doi.org/10.1214/ss/1177009939). + +### `quality_diversity` (`synapse/frontier/quality_diversity.py`) + +* Jean-Baptiste Mouret and Jeff Clune. + **Illuminating search spaces by mapping elites.** + Preprint: arXiv:1504.04909 (20 April 2015), . +* Jenny Zhang, Shengran Hu, Cong Lu, Robert Lange, and Jeff Clune (Sakana AI / UBC). + **Darwin Gödel Machine: Open-Ended Evolution of Self-Improving Agents.** + Preprint: arXiv:2505.22954 (29 May 2025), . + +### `morphogenesis` (add-on) + +* Alexander Mordvintsev, Ettore Randazzo, Eyvind Niklasson, and Michael Levin. + **Growing Neural Cellular Automata.** *Distill* (11 February 2020). + DOI [10.23915/distill.00023](https://doi.org/10.23915/distill.00023), . +* Giovanni Pezzulo and Michael Levin. + **Re-membering the body: applications of computational neuroscience to the top-down control of regeneration of limbs and other complex organs.** + *Integrative Biology* 7(12), 1487–1517 (December 2015). + DOI [10.1039/c5ib00221d](https://doi.org/10.1039/c5ib00221d); PMC4700597. + +### `connectomics` (`synapse/frontier/connectomics.py`) + +* Christopher J. Honey, Olaf Sporns, Leila Cammoun, Xavier Gigandet, Jean-Philippe Thiran, Reto Meuli, and Patric Hagmann. + **Predicting human resting-state functional connectivity from structural connectivity.** *Proceedings of the National Academy of Sciences (PNAS)* 106(6), 2035–2040 (10 February 2009). + DOI [10.1073/pnas.0811168106](https://doi.org/10.1073/pnas.0811168106). +* Elena A. Allen, Eswar Damaraju, Sergey M. Plis, Erik B. Erhardt, Tom Eichele, and Vince D. Calhoun. + **Tracking Whole-Brain Connectivity Dynamics in the Resting State.** *Cerebral Cortex* 24(3), 663–676 (March 2014; published online 11 November 2012). + DOI [10.1093/cercor/bhs352](https://doi.org/10.1093/cercor/bhs352). +* Ernesto Estrada and Naomichi Hatano. + **Communicability in complex networks.** *Physical Review E* 77(3), 036111 (March 2008). + DOI [10.1103/PhysRevE.77.036111](https://doi.org/10.1103/PhysRevE.77.036111). + +### `causal_emergence` (`synapse/frontier/causal_emergence.py`) + +* Erik P. Hoel, Larissa Albantakis, and Giulio Tononi. + **Quantifying causal emergence shows that macro can beat micro.** *Proceedings of the National Academy of Sciences (PNAS)* 110(49), 19790–19795 (3 December 2013). + DOI [10.1073/pnas.1314922110](https://doi.org/10.1073/pnas.1314922110). +* Erik P. Hoel. + **When the Map Is Better Than the Territory.** *Entropy* 19(5), 188 (May 2017). + DOI [10.3390/e19050188](https://doi.org/10.3390/e19050188). + +### `hh_cable` (`synapse/frontier/hh_cable.py`) + +* Alan L. Hodgkin and Andrew F. Huxley. + **A quantitative description of membrane current and its application to conduction and excitation in nerve.** + *The Journal of Physiology* 117(4), 500–544 (28 August 1952). + DOI [10.1113/jphysiol.1952.sp004764](https://doi.org/10.1113/jphysiol.1952.sp004764); PMC1392413. + +### `nir_export` (`synapse/frontier/nir_export.py`) + +* Jens E. Pedersen, Steven Abreu, Melika Payvand, Sadique Sheik, Gregor Lenz, Felix Bauer, Yigit Demirag, et al. + **Neuromorphic intermediate representation: A unified instruction set for interoperable brain-inspired computing.** + *Nature Communications* 15, 8122 (17 September 2024). + DOI [10.1038/s41467-024-52259-9](https://doi.org/10.1038/s41467-024-52259-9). + Repository: . + +--- + +## 2. Portfolio Provenance (`kai9987kai` Sibling Repositories) + +| Frontier Module | Sibling Repository (`kai9987kai`) | Core Concept Adapted | +|---|---|---| +| `rigl_sparse` | `sonapse-evo` | Dynamic sparse topology pruning and gradient-magnitude regrowth at a fixed synapse budget | +| `experiment_design` | `COUNTERFORM`, `Mnemorph` | One-step expected downstream decision-risk acquisition with explicit abstention | +| `quality_diversity` | `SONAPSE-ORIGIN`, `sonapse-evo` | MAP-Elites illumination archive with verifier-gated admission and lineage tracking | +| `morphogenesis` | `morpheus`, `prometheus-alpha`, `GenesisEngine`, `MOLT` | Single-organizer developmental growth into a regional connectome and setpoint-guided regeneration after lesions | +| `connectomics` | `SONAPSE-CONNECTOME` | Separation of structural, functional (Pearson/Spearman/partial), dynamic-functional, and ridge-VAR(1) effective connectivity | +| `causal_emergence` | `GhostInTheMachine`, `SONAPSE-ORIGIN` | Effective information of micro vs coarse-grained transition probability matrices with determinism/degeneracy decomposition | +| `hh_cable` | `NeuroPulse-CableLab` | Multi-compartment Hodgkin–Huxley squid-axon cable integrator and electrophysiological assay protocol | +| `joint_failure` | `FAULTLINE` | Condition-indexed joint-failure signature accounting and worst-condition majority-vote panel selection | diff --git a/docs/frontier/modules/anytime_inference.md b/docs/frontier/modules/anytime_inference.md new file mode 100644 index 0000000000000000000000000000000000000000..da5c40a039d270fd533d0a01276cb4a5e75a9b8b --- /dev/null +++ b/docs/frontier/modules/anytime_inference.md @@ -0,0 +1,252 @@ +# `anytime_inference`: anytime-valid inference + +Module file: `synapse/frontier/anytime.py` · tests: `tests/test_frontier_methodology.py` · +experiment id: `anytime_inference` (kind `validation`, verdict `pass`/`fail`) · no live observer · +evidence tier: `synthetic_abstraction`. + +The module provides two betting-based tools that stay valid when you look at the data after every +observation and stop whenever you like: + +* a **confidence sequence** for the mean of a bounded stream; +* a two-sided **e-process** for a zero mean of bounded paired differences. + +Both are combined into `anytime_compare`, a paired comparison that returns the lab's verdict vocabulary. +The constructions are *inspired by* Waudby-Smith & Ramdas (2024), and the framing follows Ramdas, Grünwald, +Vovk & Shafer (2023). The module re-implements the constructions in NumPy and checks their guarantees in +seeded simulations. It reproduces none of the papers' experiments or figures. + +## What it computes + +### Betting confidence sequence (`betting_confidence_sequence`) + +Observations `x_t` in `[lo, hi]` are rescaled to `X_t = (x_t - lo) / (hi - lo)` in `[0, 1]`. For a candidate +mean `m` (paper Sec. 4.4, Eqs. 24-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)) +K±_t(m) = max{ theta K+_t(m), (1 - theta) K-_t(m) } (hedged capital, Eq. 24) +lam+_t(m) = min(lam_t, c / m) lam-_t(m) = min(lam_t, c / (1 - m)) (truncation, Eq. 25) +lam_t = sqrt( 2 log(2/alpha) / (sigma2_{t-1} t log(1 + t)) ) (plug-in bet, Eq. 26) +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), sigma2_0 = 1/4 +CS_t = intersection_{i<=t} { m in [0, 1] : K±_i(m) < 1/alpha } (Theorem 3) +``` + +* **Validity.** Theorem 3 of the paper: for each fixed `m = mu` the capital processes are nonnegative + martingales, so by Ville's inequality the true mean leaves the set at *some* time with probability at + most `alpha`. The running intersection keeps the same guarantee. +* **Grid search.** The set at each time is an interval (Theorem 3), so the module evaluates `K±` on the grid + `m = 0, 1/g, ..., 1` (`g = grid_size`, default 1000), as the paper suggests. Each bound is the first + *excluded* grid point outside the run of included points. The result is a superset of the exact set, + conservative by at most one grid step `(hi - lo) / g`. +* **No grid point inside.** If no grid point is inside, the bounds bracket the grid minimisers of `K±`. + `K+` is non-increasing and `K-` non-decreasing in `m`, so `K±` is quasiconvex and the exact set lies in + that bracket. +* **Returns.** `lower` and `upper` (running intersection), `lower_raw` and `upper_raw` (the per-time set), + `final` and `empty`. The intersection is empty with probability at most `alpha`. + +### Paired e-process (`paired_e_process`) + +The null hypothesis is `H0: E[D_t | D_1..D_{t-1}] = 0`, for differences with `|D_t| <= B`. Map each +difference to `X_t = (1 + D_t / B) / 2` in `[0, 1]` and test `m = 1/2`: + +``` +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) +lam+_t = max(lam_t, 0) lam-_t = max(-lam_t, 0) +E_t = (K+_t(m) + K-_t(m)) / 2 (the paper's mixture M±_t with theta = 1/2, Sec. 4.4) +``` + +* **Estimators.** `mu` and `sigma2` are the Eq. 26 estimators. App. B.3 writes the bet with `mu_{t-1}` and + `sigma2_{t-1}` without restating them; the paper defines that notation only in Eq. 26, which the module + follows. +* **Sign split.** The bet is split by sign: `K+` gathers evidence for a positive mean, `K-` for a negative + one. +* **Validity.** Every factor is at least `1 - c > 0` and the bets are predictable. Under `H0`, `K+`, `K-` + and `E` are therefore nonnegative martingales that start at 1. Ville's inequality then gives + `P(exists t: E_t >= 1/alpha) <= alpha` at every stopping time, so optional stopping does not break it. +* **Finite outputs.** Reported values are capped at `exp(690)` so they stay finite. `log_e_process` is + uncapped. + +### Paired comparison (`anytime_compare`) + +`D_t = candidate_t - reference_t` with a known bound `|D_t| <= bound`. The e-process is checked after every +observation. + +* **Rejection.** `rejected` is true at the first time `E_t >= 1/alpha`. `stopped_at` is that time (1-based) + and `e_value` is the stopped value. `e_value_final` is the value at the last observation. +* **Direction.** The direction comes from the larger one-sided process at the stopping time. Declaring + `positive` needs `K+_tau >= E_tau >= 1/alpha`. When the true conditional mean is `<= 0`, `K+` is a + nonnegative supermartingale (`lam+ >= 0`), so a wrong-direction declaration also has probability at most + `alpha`. +* **Verdict.** `improved` or `worse` depends on the direction and `higher_is_better`. Without a rejection + the verdict is `no_detectable_difference`. +* **CS bounds.** `cs_lower` and `cs_upper` are the hedged betting CS for the mean difference on + `[-bound, bound]` at the last observation, at level `1 - alpha`. The verdict comes from the e-process + only. The CS is reported beside it, with `cs_excludes_zero`, and the two can disagree near the threshold. + +### Invalid baseline (`naive_peeking_t_test`) + +A two-sided one-sample t-test of mean 0 repeated at every look `n >= min_n`. It reports whether *any* look +rejected and whether the single final look rejected. The tests check it against `scipy.stats.ttest_1samp` +at every look. + +## Validation experiment (`run_experiment`, `EXPERIMENTS = {'anytime_inference': run_experiment}`) + +For every seed the experiment draws `replicates` independent sequences of length `horizon` per scenario. +Every statistic is evaluated after every observation. Each scenario has its own generator, +`np.random.default_rng(seed + offset)`. + +| scenario | data | used for | +|---|---|---| +| `null_paired_bernoulli` | `D = Bern(0.6) - Bern(0.6)`, independent, bound 1 | type-I error under optional stopping | +| `null_skewed_continuous` | `D = Beta(0.5, 4) - 1/9` (mean exactly 0, skewed), bound 1 | type-I error under optional stopping | +| `effect` | `D = Bern(0.75) - Bern(0.5)` (mean 0.25), bound 1 | power, stopping time, wrong-direction rate | +| `cover_beta` | `X ~ Beta(2, 5)` on `[0, 1]` (mean 2/7) | time-uniform CS coverage and width | +| `cover_bernoulli` | `X ~ Bern(0.3)` | time-uniform CS coverage and width | + +The checks are pooled over seeds. Monte-Carlo slack is `mc_z = 3` standard errors. The verdict is `pass` +only if all 12 checks hold: + +* `e_process_type1_le_alpha_{null}`: the rate of `sup_t E_t >= 1/alpha` is at most `alpha + 3 se`. +* `naive_peeking_t_exceeds_alpha_{null}`: the repeated t-test (looks from `n = 10`) rejects more often than + `alpha` by more than 3 se. +* `mean_final_e_value_le_1_{null}`: the sample mean of `E_horizon` is at most `1 + 3 se`. + * The expectation is exactly 1, but the terminal value is heavy-tailed. + * Rare large values carry the mean, so the sample mean usually falls below 1, and the check is one-sided. + * A 200,000-path run of the paired-Bernoulli null (the experiment's generator, `D = Bern(0.6) - Bern(0.6)`, + `np.random.default_rng(12345)`, `c = 0.5`, horizon 200; measured 2026-11-20) gave sample means 1.000, + 0.9996, 1.0006, 1.007, 1.339 and 0.763 at `t = 5, 10, 20, 50, 100, 200`. + * The `t = 100` mean is above 1 only because one path reached `E_100 ≈ 82,000`, which alone adds 0.41 to + the mean. No path came close to that at `t = 200` (largest value about 16,000), and the mean fell to 0.763. + * The tests check that the expectation is exactly 1 by enumerating every path of short sequences instead. +* `power_on_clear_effect`: the rejection rate under `effect` is at least `power_min = 0.8`. +* `wrong_direction_rate_le_alpha`: wrong-direction rejections under `effect` are at most `alpha`. +* `cs_uniform_coverage_ge_1_minus_alpha_{beta,bernoulli}`: the true mean stays inside the + running-intersection CS at every one of the `horizon` times with frequency at least `1 - alpha - 3 se`. +* `cs_shrinks_{beta,bernoulli}`: the mean final width is below the mean width at `t = 20`. + +Defaults: `alpha = 0.05`, `replicates = 400`, `horizon = 500`, `grid_size = 400`, `c = 0.5`, `theta = 0.5`, +`naive_min_n = 10`, seeds `(0, 1, 2)`. `quick=True` uses `replicates = 100`, `horizon = 200` and +`grid_size = 200`. Unknown overrides raise `ValueError`, and so do sizes above the memory bounds +(`replicates × horizon <= 4,000,000`, `replicates × (grid_size + 1) <= 20,000,000`). + +## Public API + +```python +betting_confidence_sequence(x, lo, hi, alpha=0.05, *, grid_size=1000, c=0.5, theta=0.5) -> dict +paired_e_process(differences, bound, *, c=0.5) -> dict +anytime_compare(candidate, reference, *, bound, alpha=0.05, higher_is_better=True, c=0.5, grid_size=1000) -> dict + # keys: e_value, e_value_final, rejected, stopped_at, direction, cs_lower, cs_upper, cs_excludes_zero, + # cs_empty, mean_difference, verdict in ('improved', 'no_detectable_difference', 'worse'), ... +naive_peeking_t_test(differences, alpha=0.05, *, min_n=2) -> dict +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> sealed receipt +EXPERIMENTS = {'anytime_inference': run_experiment} +``` + +* **Input validation.** Inputs are validated before any computation, and bad input raises `ValueError`. + This covers non-finite or out-of-range values, `alpha`, `c` or `theta` outside `(0, 1)`, a mismatched + length and `|difference| > bound`. +* **Determinism.** Everything is deterministic. The module uses NumPy, plus `scipy.special.stdtrit` for the + t-test baseline. It never touches the global NumPy RNG and never imports torch. + +## Connection to Sonapse + +* **Not wired in.** `harness.compare` decides lab verdicts with a paired 95 % t interval over a fixed set of + seeds. That interval is valid only at a sample size fixed in advance. +* **When to use it.** `anytime_compare` is the anytime-valid alternative for studies that add seeds or + evaluation episodes and check results as they arrive. Examples are held-out correctness streams of two + NEUROWEAVE arms, or paired per-seed scores with a known range. +* **How to use it.** The caller supplies the bound on `|candidate - reference|`. For 0/1 correctness or + accuracies it is 1. +* **Scope.** The module does not change `harness.compare` or any other module's verdict. Using it there + would mean editing the shared harness. + +## Not implemented + +* **From Waudby-Smith & Ramdas (2024).** + * The other betting strategies: GRAPA root-finding, LBOW, ONS-m, dKelly, ConBo and SRP (App. B). + * Sampling without replacement (Sec. 5.2). + * The fixed-sample-size CI tuning of Remark 3 / Eq. 27. + * The closed-form predictable plug-in Hoeffding and empirical-Bernstein CSs (Sec. 3). + * Root-finding in place of the grid. + * The point estimator `argmin_m K±_t(m)`. +* **Not covered by the guarantees.** + * The CS assumes a constant conditional mean. + * Streams whose conditional mean drifts are not covered (the paper's Sec. E.5). + * The e-process needs `E[D_t | past] = 0` under the null. +* **From Ramdas et al. (2023).** + * Composite nulls beyond a zero mean. + * Universal inference, e-value merging and p-to-e calibration. + +## Verified references + +* Ian Waudby-Smith and Aaditya Ramdas. **Estimating means of bounded random variables by betting.** + *Journal of the Royal Statistical Society Series B: Statistical Methodology* 86(1):1–27, February 2024 + (read before the Royal Statistical Society, with discussion on pp. 28–61). doi:10.1093/jrsssb/qkad009. + · preprint arXiv:2010.09686 (v1 19 October 2020; + v7 25 August 2022), . + * Bibliographic data checked against the publisher and arXiv pages on 2026-11-20. + * The following were checked against the text of arXiv v7 the same day; section, equation and appendix + numbers in this document follow v7: + * the hedged capital process, Sec. 4.4, Eq. 24, and the mixture `M±`; + * the truncation `|lam~| ∧ c/m`, `∧ c/(1-m)` with `c = 1/2` or `3/4`, Eq. 25; + * Theorem 3 (valid CS, interval for each `t`, running intersection); + * the plug-in bet and estimators, Eq. 26; + * the grid-search remark, Sec. 4.4; + * quasiconvexity, Remark 2; + * aGRAPA, App. B.3, truncated to `[-c/(1-m), c/m]`. +* Aaditya Ramdas, Peter Grünwald, Vladimir Vovk and Glenn Shafer. **Game-theoretic statistics and safe + anytime-valid inference.** *Statistical Science* 38(4):576–601, November 2023. doi:10.1214/23-STS894. + + · preprint arXiv:2210.01948. Bibliographic data was checked against Project Euclid and the Royal Holloway + repository on 2026-11-20. The CWI repository lists the page range as 576–597, and Project Euclid gives + 576–601. + +## Measured results + +All numbers were measured on 2026-11-20 (UTC) on Windows 11 ARM64 with Python 3.12.10 and NumPy 2.4.3, with +`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`. Other agents shared the CPU, so wall-clock is +indicative only. Rates are pooled over seeds `(0, 1, 2)`. `se` is the binomial Monte-Carlo standard error. + +**Quick mode** (`run_experiment(quick=True)`): 3 × 100 sequences per scenario, horizon 200, grid 200, +`alpha = 0.05`, `c = theta = 0.5`. + +| | value | +|---|---| +| verdict | **pass** (12 of 12 checks) | +| 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) | +| 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) | +| mean final e-value (paired Bernoulli / skewed) | 0.52 (max 4.56) / 1.00 (max 4.89) | +| effect (mean difference 0.25): power, wrong direction, median stopping time | 0.98 (294/300), 0, 59 observations | +| CS uniform coverage, Beta(2, 5) / Bernoulli(0.3) | 0.990 (297/300) / 0.957 (287/300) | +| CS mean width at t = 20 → t = 200, Beta / Bernoulli | 0.323 → 0.072 / 0.515 → 0.212 | +| digest (prefix) | `a07208ae621e340b` (identical across separate processes) | +| measured wall-clock | 3.1–3.9 s | + +**Default size** (`run_experiment()`): 3 × 400 sequences per scenario, horizon 500, grid 400, same `alpha`, +`c` and `theta`. + +| | value | +|---|---| +| verdict | **pass** (12 of 12 checks) | +| 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) | +| 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) | +| mean final e-value (paired Bernoulli / skewed) | 0.49 (max 19.5) / 0.96 (max 14.9) | +| effect (mean difference 0.25): power, wrong direction, median stopping time | 1.00 (1200/1200), 0, 57.5 observations | +| CS uniform coverage, Beta(2, 5) / Bernoulli(0.3) | 0.985 (1182/1200) / 0.966 (1159/1200) | +| CS mean width at t = 20 → t = 500, Beta / Bernoulli | 0.319 → 0.045 / 0.510 → 0.148 | +| running intersection empty at t = 500 | 0 / 1 of 1200 (counted as a coverage miss) | +| digest (prefix) | `7b05678cbd3aa5b7` (identical in two separate runs) | +| measured wall-clock | 81.9–94.1 s, almost all of it in the 401-point grid search | + +Reading: + +* **Peeking breaks the t-test.** At default size the repeated t-test rejects a true null in 41–46 % of + sequences when it looks after every observation. A single t-test at the final time stays near the nominal + 5 %. +* **The e-process stays valid.** It rejected at most 1.8 % of null sequences under the same monitoring, and + it still detected the 0.25 mean difference in every sequence (median 57.5 paired observations). +* **The betting CS covers the mean.** It covered the true mean at all 500 times in 98.5 % and 96.6 % of + sequences. That is above the stated 95 %, as expected from a conservative construction. +* **Limits of these checks.** They test the stated guarantees on these generators only. They say nothing + about data that violate the assumptions. diff --git a/docs/frontier/modules/btsp_memory.md b/docs/frontier/modules/btsp_memory.md new file mode 100644 index 0000000000000000000000000000000000000000..057d258710d5e8663f1f12246fb76d9239422883 --- /dev/null +++ b/docs/frontier/modules/btsp_memory.md @@ -0,0 +1,311 @@ +# `btsp_memory`: one-shot BTSP memory with binary synapses + +Module file: `synapse/frontier/btsp.py` · tests: `tests/test_frontier_memory.py` · +experiment ids: `btsp_memory`, `btsp_memory_capacity` · engine extension: `BTSPExtension` (id `btsp_memory`) · +baselines: `WillshawMemory`, `RandomRecallControl` · evidence tier: `synthetic_abstraction`. + +The module implements the binary-weight rule for **behavioural time-scale synaptic plasticity** (BTSP) of +Wu & Maass (*Nature Communications*, 2025). In this rule, random plateau potentials gate stochastic flips of +binary synapses, so a pattern is stored after a single presentation. The module also implements the paper's +feedback pathway for completing a pattern from a partial cue. It uses the memory in three settings: + +* a capacity benchmark against a classic Willshaw memory with the same number of synapses, +* a NEUROWEAVE engine extension that adds familiarity features to the readout, +* direct use as a content-addressable memory (`BTSPMemory`). + +It is *inspired by* the paper and does not reproduce it. The paper's default network has 25,000 input and +39,000 memory neurons, while this module's largest benchmark uses 1,000 inputs and 833 memory units. Thresholds +are set more simply here (see below). None of the paper's figures or results are attempted. The model says nothing about +hippocampal biology. + +## What it computes + +`BTSPMemory(input_dim, memory_dim, *, density=0.6, plateau_prob=0.02, flip_prob=0.5, threshold=0.35, +feedback_threshold=0.5, seed=0)` has `m = input_dim` binary input units and `n = memory_dim` binary memory +units. + +``` +masks C (n x m) forward, D (m x n) feedback: independent Bernoulli(density) connections, fixed by the seed +weights W (n x m) forward, B (m x n) feedback: binary, initially all 0 + +store x plateau set Q: every memory unit independently with probability plateau_prob (firing is irrelevant) + for j in Q and every input i with x_i = 1 and C_ji = 1: + W_ji: 0 -> 1 with probability p_ltp, 1 -> 0 with probability p_ltd (paper Eq. 1: both 0.5) + then, with the updated W: B_ij <- B_ij OR (D_ij AND x_i AND z_j(x)) (one-shot Hebbian, saturating) + +trace z_j(c) = 1[ (W c)_j > threshold * density * |c| ] (McCulloch-Pitts memory units) +recall r_i(c) = 1[ (B z(c))_i > feedback_threshold * density * |z(c)| ] (McCulloch-Pitts input units) +``` + +`|c|` is the number of ones. `flip_prob` is one number (`p_ltp = p_ltd`) or a `(p_ltp, p_ltd)` pair. Masks come +from `default_rng(seed + 61403)`. Plateau and flip draws come from `default_rng(seed + 61417)`, so the same seed +and store sequence give identical weights. Weights are boolean arrays. Only existing synapses ever change. + +How this maps onto the paper: + +* **Plasticity (Eq. 1).** The binary-weight rule flips a weight from an active input to a memory neuron with + a plateau, with probability 0.5: 0 becomes 1 and 1 becomes 0. The paper derives the 0.5 from the plateau's + time window: input in the inner part of the window potentiates a weight that is not yet at its maximum, + input in the outer part depresses a weight that is not yet at its minimum, and both parts are taken as + equally likely, so with probability 0.5 a weight is not updated. + * Every memory neuron receives a plateau independently with probability `f_q` for each new item. The default + `f_q` is 0.005. + * The paper notes that "BTSP does not depend on the firing of the postsynaptic neuron". + * Initial weights are a zero matrix, and each item is presented once. + * The paper also varies the LTD probability, which `flip_prob=(p_ltp, p_ltd)` allows. +* **Neurons.** Memory and input neurons are McCulloch-Pitts units. They fire when the weighted sum *exceeds* the + threshold, as here. +* **Thresholds (simplified here).** The paper uses grid search to set one absolute memory threshold for its + memory-trace experiments. For input completion, it sets both layers' thresholds by linear functions of the + average fraction of ones in the input, fitted in preliminary simulations. This module sets the memory + threshold proportional to the number of ones in the cue (within one cue condition every cue has the same + number of ones, so this is a linear function of that fraction with zero intercept) and the input-layer + threshold proportional to the number of active units in the memory trace. +* **Feedback.** Random feedback connections from memory to input units have the same density as the forward + ones (0.6 in the paper). They are trained in one step by a Hebbian-like rule: a weight is incremented when + both its memory unit and its input unit are 1, and saturates at one. Here the memory units' activity is the + trace of the stored pattern under the updated forward weights. +* **Recall.** As in the paper, input completion is one forward and one feedback pass with no iteration (the + paper produces it at the next time step after the cue; only its Hopfield comparison networks iterate). + +Metrics: + +* `overlap(a, b) = |a & b| / sqrt(|a| |b|)` is this module's recall metric, a cosine similarity. It is not the + paper's "overlap ratio" of two memory traces, which divides the common ones by the average number of ones + in a trace. +* `reconstruction_error(x, x', r) = HD(r, x) / HD(x, x')` is the paper's scaled reconstruction error. 0 is + perfect, and 1 is no better than the cue. +* `make_cue` deletes a fraction of the active bits. With `kind='flip'`, it also turns on the same number of + inactive bits. + +Tests check these properties on cases with a known answer: + +* With `plateau_prob = 1` and `flip_prob = 1`, a store sets exactly the connected synapses from active inputs. + The trace and the feedback weights equal a hand computation. Storing the same pattern again is then pure + depression and returns every forward weight to 0, while feedback weights never decrease. +* Without a plateau nothing changes, and synapses from inactive inputs never change. Weights stay boolean and + stay on existing synapses. +* On a 200 x 200 network, the measured flip rates match `p_ltp = 0.3` and `p_ltd = 0.8` to within ±0.02. +* **One-shot storage.** 10 patterns are each stored once (200 inputs, 20 active, 200 memory units, plateau + probability 0.1; means over 3 seeds and the 10 patterns). + * Every stored pattern evokes a non-empty memory trace, and a full cue reconstructs the pattern with overlap + above 0.95. + * With 20 %, 40 % and 60 % of the active bits deleted, the overlap degrades gradually (never rising by more + than 0.01 from one level to the next) and stays above 0.8. + * At every deletion level the mean reconstruction overlap beats the mean overlap of the degraded cue, and + cues with 30 % of their bits moved are also cleaned up. +* Storing 40 patterns instead of 10 lowers recall from 40 %-deleted cues by more than 0.1 (interference grows + with load). Cues that were never stored retrieve little: on average their reconstruction overlaps neither + the cue nor the closest stored pattern by more than 0.5. +* Each parameter (plateau probability, LTP and LTD probabilities, both thresholds, density, seed) changes what + is recalled. + +## Baselines + +* `WillshawMemory(input_dim, *, threshold=1.0)` is the auto-associative form of the clipped-Hebbian binary + memory of Willshaw, Buneman & Longuet-Higgins (1969). + * Storing sets `A_ii' = 1` for every pair of co-active units, including `i = i'`. + * Recall is `r_i = 1[(A c)_i >= threshold * |c|]`. `threshold = 1`, where every cue unit must agree, is the + classic rule as usually described. + * Tests: exact completion of half-deleted cues at threshold 1, tolerance of a wrong bit at threshold 0.8, and + saturation after an all-ones pattern. +* `RandomRecallControl(input_dim, active, seed=0)` ignores the cue and returns a seeded random pattern with + `active` ones. That is chance level, with expected overlap `active / input_dim`, which a test checks. + +## Engine extension (`BTSPExtension`, id `btsp_memory`) + +`BTSPExtension(memory_dim=64, *, active_fraction=0.25, density=0.6, plateau_prob=0.1, flip_prob=0.5, +threshold=0.35, feedback_threshold=0.5, gate=0.5, projection_dim=6, seed=0)` is a readout-only extension over +the binarised brain output. + +* **Size.** `bind(engine)` copies `engine.n`, an integer up to 4096, and builds an empty `BTSPMemory` with that + many inputs. Units born later are ignored. +* **Binarising.** After each engine step, the output is turned into a pattern `x_t` with the top + `k = max(1, round(active_fraction * n))` units set (ties go to the lower index). +* **Features.** Recall happens *before* any store and gives three kinds of feature: + * `recall_overlap = overlap(x_t, r(z(x_t)))`, how familiar the current state is; + * `recall_confidence = min(1, |z(x_t)| / max(1, plateau_prob * memory_dim))`, the trace size relative to the + expected trace size; + * `projection_dim` fixed `+-1` projections of the trace, `P z / sqrt(max(1, |z|))`. + + In total `feature_dim = 2 + projection_dim` (8 by default). +* **Storing.** Only when `ctx['learn']` is true, the pattern is stored one-shot when its salience + `max(min(|reward|, 1), 1 - recall_overlap)` exceeds `gate`. The plateau probability is scaled by that + salience. This novelty-and-reward gate is this module's design, not the paper's, whose plateaus are random. +* **What it does not touch.** The extension never changes the drive. It keeps no engine reference, and + `copy.deepcopy` gives an independent clone, including the plasticity random generator. With `ctx['learn']` + false it never stores; it counts `frozen_steps` instead. `reset()` clears the features and keeps the stored + memories. +* **Budget.** `parameter_count()` is the number of existing plastic synapses, forward plus feedback. + +## Capacity benchmark (`run_capacity_benchmark`, id `btsp_memory_capacity`) + +* **Patterns.** `patterns` random binary patterns with exactly `active` ones are stored once each, in order. + At `checkpoints` evenly spaced loads, `test_per_checkpoint` stored patterns are recalled from degraded cues + under every condition in `cue_kinds x cue_fractions` (delete and flip, 30 % and 50 %). Every arm sees the + same cues. +* **Metric.** The metric is the normalised overlap between the stored pattern and its reconstruction, + averaged over checkpoints and conditions (the mean of the capacity curve). Receipts also give the + reconstruction error per checkpoint and condition. +* **Arms.** + * `btsp`: `BTSPMemory` with `memory_dim = round(input_dim / (2 * density))`. Its forward plus feedback + synapses then match the Willshaw matrix's `input_dim**2` in expectation; receipts report the exact counts. + * `willshaw`: `WillshawMemory`. + * `random_recall`: chance level. + * `cue_only`: no memory; the degraded cue is its own reconstruction. This shows whether a memory improves on + the cue at all. +* **Fair tuning.** Free parameters are tuned per arm on separate seeds (1000 and 1001; 1000 in quick mode) by + the same metric. For BTSP these are the plateau probability, the threshold and the feedback threshold. For + Willshaw it is the threshold. BTSP gets the larger grid because it has three free parameters. + `tuning..chosen_on_grid_edge` names any chosen value on a grid edge. +* **Verdict.** The verdict is a paired 95 % t interval over seeds, BTSP against Willshaw (higher is better). + Receipts also report each memory against `random_recall` and against `cue_only`. Per-seed diagnostics give + BTSP's fraction of forward weights at 1 and its mean trace size at each load. +* **Sizes.** The default uses 1,000 inputs with 50 active, 400 patterns, loads of 100, 200, 300 and 400, 64 + tested patterns per load, and 833 memory units at density 0.6. Quick mode uses 400 inputs with 20 active, + 120 patterns, loads of 30, 60, 90 and 120, 24 tested patterns per load, and 333 memory units. + +## Lab experiment (`run_experiment`, id `btsp_memory`) + +`harness.run_extension_experiment('btsp_memory', ...)` runs the NEUROWEAVE `delayed_recall` task (the target +is the input bit from two steps ago) with three arms: + +* `baseline`: the unmodified engine and readout. +* `candidate`: the baseline plus `BTSPExtension` features. +* `control`: the baseline plus the same number of random leaky-trace features (the harness's capacity-matched + `random_trace` control). + +All arms share seeds, streams and the readout protocol, and held-out streams are evaluated frozen. The headline +verdict is `improved` only if the candidate beats both the baseline and the control. The control matches the +candidate's readout feature count (8), not its stored numbers: for seed 0 the measured receipts report 6,544 +(quick) or 12,688 (default size) extension state numbers for the candidate and 208 or 400 for the control. + +The defaults are the harness's: seeds 0, 1, 2; held-out seeds 100, 101; 300 steps; 48 neurons; clustered +topology; no extra mechanisms. The extension uses its defaults. Quick mode uses the harness `QUICK_ARGS` sizes +(24 neurons, 24 steps, one 12-step held-out stream) with the caller's seeds. The extension keys and the harness +keys (`task`, `heldout_seeds`, `steps`, `heldout_steps`, `neurons`, `topology`, `mechanisms`) can be +overridden. + +## Public API + +```python +MODULE_ID = 'btsp_memory'; CAPACITY_ID = 'btsp_memory_capacity' +EXPERIMENTS = {'btsp_memory': run_experiment, 'btsp_memory_capacity': run_capacity_benchmark} +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +run_capacity_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +BTSPMemory(input_dim, memory_dim, *, density=0.6, plateau_prob=0.02, flip_prob=0.5, threshold=0.35, + feedback_threshold=0.5, seed=0) + .store(pattern, *, plateau_prob=None) -> {'plateau_units', 'ltp_flips', 'ltd_flips', 'trace_size', + 'new_feedback_synapses'} + .drive(cue); .code(cue); .reconstruct(code); .recall(cue) -> {'code', 'reconstruction'} + .forward_mask; .feedback_mask; .synapse_count; .state_numbers; .weight_fractions(); .config() + .reset(); .export_state(); .import_state(state) +WillshawMemory(input_dim, *, threshold=1.0) # .store, .recall, .synapse_count, .export_state, .import_state +RandomRecallControl(input_dim, active, seed=0) # .store, .recall +BTSPExtension(memory_dim=64, *, active_fraction=0.25, density=0.6, plateau_prob=0.1, flip_prob=0.5, + threshold=0.35, feedback_threshold=0.5, gate=0.5, projection_dim=6, seed=0) + .binarise(output); .after_step(output, ctx); .features(); .telemetry(); .config(); .export_state(); .import_state(state) +overlap(a, b); hamming(a, b); reconstruction_error(target, cue, reconstruction) +make_cue(pattern, fraction, kind, rng); random_patterns(count, size, active, rng) +CAPACITY_DEFAULTS, CAPACITY_QUICK, CUE_KINDS, SOURCE +``` + +Every public function and constructor validates its input and raises `ValueError` before any state changes. +`export_state()` is JSON-safe: weights on existing synapses are stored as packed bits in base64, together with +the counters and the PCG64 state of the plasticity generator. `import_state` checks the configuration, the +exact bit lengths, the zero padding, the counters and the generator state before replacing anything, so a +failed import leaves the memory unchanged. After an import, further stores continue exactly as they would have +without the export. No global NumPy or torch random or thread state is touched. + +## Connection to Sonapse + +* **Not a live observer.** `btsp_memory` is not in `spec.OBSERVER_MODULE_IDS`. +* **Engine extension.** It influences nothing unless it is attached to a NEUROWEAVE engine with + `attach_extension`, as in the lab experiment. Even when attached, it only adds readout features. It never + changes the drive. +* **Standalone benchmark.** `run_capacity_benchmark` uses only the memories and synthetic patterns. +* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes. + +## Not implemented, and differences from the paper + +* The paper's network sizes and sparsity. Its default is 25,000 inputs, 39,000 memory neurons, 0.5 % active + bits and a plateau probability of 0.005, so about 195 memory neurons receive a plateau for each item. In the + capacity benchmark, the tuned plateau probabilities give an expected 8.3 (default size) and 13.3 (quick mode) + plateau units per stored pattern, and the measured mean traces hold about 8–15 units. +* The paper's threshold procedures: grid search for an absolute memory threshold, and fitted linear functions + of the input's fraction of ones for input completion. Thresholds here are proportional to the active count. +* The time course of plateau potentials and the asymmetric time window. As in the paper's simplified rule, they + are summarised by the flip probability. +* The paper's analyses and comparisons: random projections, Hopfield networks, the earlier + postsynaptic-firing-dependent one-shot rule, repulsion of similar memory traces, and the line-drawing task. + The paper does not compare BTSP with a Willshaw memory; this module does. +* Forgetting in the feedback pathway. As in the paper, feedback weights only saturate, so under a long store + sequence they fill up (see the measured weight fractions below). +* The extension's salience gate and the plateau probability scaled by salience are this module's own design. + +## Verified references + +Each reference was checked on 2026-11-20. + +1. Yujie Wu, Wolfgang Maass. **A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides + content addressable memory with binary synapses and one-shot learning.** *Nature Communications* 16, 342 + (2025), published online 2 January 2025 (PMC record). doi:10.1038/s41467-024-55563-6, + https://doi.org/10.1038/s41467-024-55563-6 · PMC11695864 · PMID 39747916 (the identifiers were matched with + the PMC ID converter). The PMC record says the article was corrected, *Nat. Commun.* 16, 1150 (29 January + 2025). The following were checked in the PMC full text: + * Eq. 1, applied "with probability 0.5" to inputs that arrive within the plateau's time window. + * The per-neuron, per-item plateau probability `f_q` (default 0.005), and that BTSP does not depend on + postsynaptic firing. + * The zero initial weights and the strict firing threshold. + * The grid-searched memory threshold, and the fitted linear threshold functions for input completion. + * The Hebbian-like, saturating feedback learning at density 0.6. + * The scaled reconstruction error `HD(r(x'), x) / HD(x, x')` and the overlap-ratio definition. + * The default sizes: m = 25,000, n = 39,000, f_w = 0.6, f_p = 0.005. + * Input completion is produced at the next time step after the cue (one pass); the Hopfield comparison + networks are iterated 100 times. + * Fig. 6D varies the LTD probability, and the main text points to Figs. S4–S5 for variants with a higher + LTD and a lower LTP probability. + + The paper compares BTSP with random projections, Hopfield networks and an earlier one-shot rule that depends + on postsynaptic firing. Neither its text nor its reference list mentions Willshaw. The supplementary + material itself was not checked. +2. D. J. Willshaw, O. P. Buneman, H. C. Longuet-Higgins. **Non-Holographic Associative Memory.** *Nature* + 222(5197), 960–962, June 1969 (Crossref). doi:10.1038/222960a0. Only the bibliographic record was verified; + the full text could not be opened in this build. The all-cue-units retrieval threshold (`threshold = 1`) is + taken from later descriptions of the Willshaw model and was not checked against the 1969 text. + +## Measured results + +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 +thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Every call used its defaults apart from +`quick`, with seeds 0, 1, 2. Each quick run was made three times and gave the same receipt digest every time; +each default-size run was made once (earlier runs on the same day gave the same numbers). The tests also check +that a second run gives the same digest. The digest prefix is listed so a rerun on this setup can be compared; +another platform may round floating-point results differently. Wall-clock covers the whole call and is given +as the range over the runs. The machine was shared with other jobs, so wall-clock is only indicative. + +| Run | Verdict | Key numbers | Digest | Wall-clock | +|---|---|---|---|---| +| `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 | +| `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 | +| `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 | +| `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 | + +At the same synapse count and at these toy sizes, the BTSP memory recalled worse than a tuned Willshaw memory +on average over the capacity curve. + +* **Reconstruction against the cue.** Averaged over loads, BTSP's reconstruction did not improve on the + degraded cue: no detectable difference in quick mode, and slightly worse at default size. +* **By load.** At the lowest default load, its mean overlap (0.813) was above both the cue (0.686) and + Willshaw (0.626), whose single threshold is tuned for the whole curve. At higher loads it fell below both. + Over the same loads the fraction of forward weights at 1 and the trace size grew (seed 0 above), which is + consistent with growing interference between stored patterns; this was not tested further. +* **Engine extension.** On `delayed_recall`, the BTSP familiarity features made no detectable difference to + the NEUROWEAVE readout. In the quick run every arm stays at chance, so it only checks that the pipeline runs. + In the default run the feedback pathway filled up: 81 % of feedback synapses were at weight 1 on seed 0. + +A possible reason for the gap to the paper is scale. Here an expected 8.3 (default size) or 13.3 (quick mode) +memory units receive a plateau for each stored pattern, and the measured mean traces hold about 8–15 units. In +the paper's default network about 195 neurons receive a plateau for each item. This explanation was not +tested. These results are statements about this toy only. They do not test the paper's network sizes or +claims. diff --git a/docs/frontier/modules/causal_emergence.md b/docs/frontier/modules/causal_emergence.md new file mode 100644 index 0000000000000000000000000000000000000000..8898899f10fb58e74a8708c846d888e5b0fd49e6 --- /dev/null +++ b/docs/frontier/modules/causal_emergence.md @@ -0,0 +1,247 @@ +# `causal_emergence`: effective information and causal emergence + +Module file: `synapse/frontier/causal_emergence.py` · tests: `tests/test_frontier_causal_emergence.py` · +experiment id: `causal_emergence` · live observer: `CausalEmergenceObserver` · kind: `analysis` · +evidence tier: `synthetic_abstraction`. + +The module computes **effective information** (EI) of transition probability matrices (TPMs), its +determinism/degeneracy decomposition, and **causal emergence** (CE): whether a coarse-grained (macro) description +of a system has more EI than the micro description. It is inspired by Hoel, Albantakis & Tononi (PNAS 2013) and +Hoel (Entropy 2017), and by the macro-vs-micro EI experiment of the sibling project `kai9987kai/SONAPSE-ORIGIN` +(`sonapse_origin/theories/causal_emergence.py`, which builds a TPM from a weight matrix and compares one fixed +pairing of states against a 0.05-bit threshold). The sibling project `kai9987kai/GhostInTheMachine` measures +emergence with the Psi criterion of Rosas et al. (2020) instead; its practice of reading an emergence statistic +against a matched null is what the nulls here follow. Nothing here measures consciousness, agency or biological +causation, and no claim is made that NEUROWEAVE brains "have" causal emergence. + +## What it computes + +**Effective information.** For a row-stochastic TPM `T` over `n` states and maximum-entropy (uniform) +interventions on the current state: + +``` +E_D = (1/n) sum_i T_i (effect distribution) +EI(T) = (1/n) sum_i D_KL(T_i || E_D) = H(E_D) - (1/n) sum_i H(T_i) [bits] +``` + +i.e. the mutual information between uniform interventions and their effects. Identity and permutation TPMs give +`EI = log2 n`; a TPM with identical rows gives `EI = 0`. + +**Decomposition** (formulas as printed in Hoel 2017; Hoel et al. 2013 introduce the determinism and degeneracy +components of effectiveness), with `U` the uniform distribution: + +``` +determinism = (1/n) sum_i D_KL(T_i || U) / log2 n = (log2 n - mean_i H(T_i)) / log2 n +degeneracy = D_KL(E_D || U) / log2 n = (log2 n - H(E_D)) / log2 n +effectiveness = determinism - degeneracy, EI = log2(n) * effectiveness +``` + +The normalised terms are `None` for a one-state TPM. + +**Estimation from data.** `transition_counts(states, n)` counts consecutive pairs of a state sequence, or, with +`next_states=`, interventional pairs `(s_t, s'_t)`. `estimate_tpm(C, alpha=1)` is additive smoothing +`T_ij = (C_ij + alpha) / (sum_k C_ik + alpha n)` (`alpha = 1`: Laplace). Every row receives `alpha n` +pseudo-counts, so with few transitions per state the estimate is pulled towards uniform rows and EI is shrunk, +more for a many-state micro TPM than for a few-state macro TPM. + +**Coarse-graining.** A partition of the micro states into macro states (`labels`, one per micro state). The macro +TPM is the effect of intervening uniformly on the micro states of each macro state (Hoel et al. 2013): + +``` +T_M[A, B] = (1/|A|) sum_{i in A} sum_{j in B} T[i, j] +``` + +Two candidate families are searched exhaustively, with the micro description itself excluded (so CE can be +negative): + +* `state_partition_candidates(n)` / `best_state_partition(T)`: every set partition of `3 <= n <= 10` states with + `2 <= m < n` blocks (restricted-growth strings; 4138 candidates for `n = 8`). +* `unit_sum_candidates(u)` / `best_unit_coarse_graining(T, u)`: for `2^u` binary micro states (`2 <= u <= 6`), + every partition of the `u` units into groups except all-singletons; each group's macro variable is its number + of active units (`m = prod_g (|g| + 1)` macro states; 202 candidates for `u = 6`). + +All candidates of a family are evaluated in one sparse matrix product (`macro_ei_batch`), checked against a +direct `scipy.stats.entropy` computation in the tests. + +**Causal emergence.** `CE = max_M EI(T_M) - EI(T)` over the candidates. + +**Nulls.** Both nulls re-run the search for the best coarse-graining in every draw, so the selection of the +maximum is part of the null. Each reports `z = (CE - mean_null) / sd_null` and the one-sided rank p-value +`(1 + #{CE_null >= CE}) / (1 + draws)`. + +* *Successor block permutation* (`successor_block_null`): the successor sequence `s_{1..T}` is block-permuted + (blocks of `round(T^(1/3))` steps by default) against the unchanged `s_{0..T-1}`. Visit counts and the successor + marginal are kept; lag-1 dependence is broken. +* *Independent units* (`independent_units_null`, binary-unit data only): each unit's bit sequence is circularly + shifted by its own random offset, which keeps each unit's occupancy and autocorrelation but makes the units + independent. + +Neither null tests "the true macro EI exceeds the true micro EI". Because smoothing shrinks the micro TPM more +than a macro TPM, the estimated CE of *any* temporally dependent sequence with few transitions per micro state +lies above the successor null, including independent slow units whose exact CE is negative (measured below). +Against the independent-units null, a large `z` says that the coarse-graining gains from coordination between +units beyond what the units' own dynamics give. + +## Live observer (`CausalEmergenceObserver`) + +`CausalEmergenceObserver(n_units, *, seed=7, history=256, units=6, alpha=1.0, null_draws=19, block=None, +min_transitions=None, **params)`; `CausalEmergenceObserver.from_spec(n_units, spec, **params)` takes `seed` +and `history` from a `FrontierSpecV1`. The spec parameters of other observers (`sync_pairs`, `sae_features`, +`sae_k`, `fc_window`, `max_observed_units`, `observe_every`) are accepted and ignored; any other keyword, and +any out-of-range value, raises `ValueError`. + +* `u = min(units, n_units)` units (a seeded, sorted sample when `n_units > units`) are binarised online: a value + is on when it is above the median of that unit's last `history` raw values (including the new one). A value + tied with the median is on when more of the window lies strictly below the median than above it, so a + discrete 0/1 unit that is on most of the time is binarised as itself rather than as constant 0 (a constant unit + is off). The `2^u` micro states of the last `history` observations are kept in a ring buffer, so transition + counts are bounded. +* `summary()` estimates the micro TPM from the buffered transitions (smoothing `alpha`) and reports micro EI with + determinism/degeneracy/effectiveness, the best count-per-group coarse-graining, its macro EI and + determinism/degeneracy, and `ce`. Once `min_transitions` transitions exist (default `min(32, history - 1)`) it + adds both nulls with `null_draws` draws each, seeded by `(seed, observed steps)`; the smallest attainable p is + `1 / (null_draws + 1)`. Results are a pure function of the buffered state and are cached per step, so they do + not depend on how often `summary()` is called. +* `summary()` keys: `module`, `evidence_tier`, `n_units`, `analysed_units`, `unit_sample`, `history`, + `micro_states`, `alpha`, `null_draws`, `min_transitions`, `observed_steps`, `buffered`, `transitions`, + `transitions_per_micro_state`, `visited_states`, `ei_micro`, `determinism_micro`, `degeneracy_micro`, + `effectiveness_micro`, `ei_macro`, `determinism_macro`, `degeneracy_macro`, `macro_partition` (groups of + observed-unit indices), `macro_states`, `ce`, `null_ready`, `null_block`, successor null `null_ce_mean`, + `null_ce_sd`, `ce_excess`, `ce_z`, `ce_p`, and independent-units null `indep_ce_mean`, `indep_ce_sd`, + `ce_excess_indep`, `ce_z_indep`, `ce_p_indep`. Metric values are `None` before the first transition and the + null fields are `None` until `null_ready`. +* `export_state()` / `import_state(state)` round-trip through JSON; `import_state` checks the schema, the + configuration, the unit sample, buffer shapes and finiteness, the counters and ring position, that nothing is + stored beyond the observed steps, and that stored states are the median-binarisation of the stored raw values + (all of them while every raw value is still buffered, the newest one afterwards) before replacing anything. + `reset()` returns to the empty state. +* Cost: one `summary()` with nulls evaluates `2 * null_draws + 1` TPMs against 202 candidates at `u = 6` + (about 0.4–0.9 s measured on 2026-11-20 at history 256–2048); `observe()` costs one median per unit. In its + per-step telemetry the frontier hub (`runtime.py`) runs full `causal_emergence` summaries only for the first + `heavy_every` (32) observed steps and on multiples of it. + +**Reading the observer.** At the defaults (6 units, 64 micro states, history 256) there are about 4 +transitions per micro state against 64 Laplace pseudo-counts per row: measured EI values are a small fraction of +the exact ones and the best grouping is not stable across seeds (on a six-unit pair-count copy ring, measured +2026-11-20: micro EI 0.03–0.05 bits against an exact 3.29 bits, best grouping varying with the seed at history +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 +longer history or a smaller `alpha` when the estimate matters, and read `ce` against `ce_z_indep`. + +## Lab experiment (`run_experiment`, `EXPERIMENTS = {'causal_emergence': run_experiment}`) + +`run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides)` returns a sealed `kind: 'validation'` receipt +with `verdict` in `('pass', 'fail')` and 22 named checks. + +Exact checks (no sampling): + +| Check | Known answer | +|---|---| +| `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 | +| `ei_equals_size_times_effectiveness` | `EI = log2(n) * effectiveness` on every example TPM | +| `hoel2017_M1_M2_M3_exact` | Hoel (2017) M1, M2, M3: 2, 1, 0 bits | +| `hoel2017_chain8_micro_closed_form` | 8-state chain (seven states mix uniformly, one absorbing): `EI = 3 - (7/8) log2 7 = 0.5436` bits | +| `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) | +| `hoel2017_chain8_search_finds_1_bit_seven_plus_one` | Exhaustive search over 4138 partitions finds the macro `{s1..s7}, {s8}` with 1 bit | +| `hoel2017_chain8_varied_matches_printed` | Unequal-row variant: printed 0.81 bits micro, 1 bit macro, same partition | +| `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}` | +| `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 | +| `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) | +| `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 | +| `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 | + +Sampled checks (every seed): + +| Check | Criterion | +|---|---| +| `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) | +| `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) | +| `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` | +| `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` | +| `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 | +| `unit_independent_units_null_calibrated` | Independent slow units: independent-units null flags at most half of the replicates, mean `z` within ±2 | +| `neuroweave_values_finite` | The descriptive part is finite | + +How often the successor null flags the independent slow units is reported (`independent_successor_null_*`), +not checked: it is the documented bias above. + +**NEUROWEAVE report (descriptive).** For each mechanism set (default `baseline = ()` and +`dynamics = (sparse_code, synaptic_delays, membrane_dynamics)`) and seed, a frozen engine (`learn=False`, +`clustered` topology) runs on the task stream; after burn-in a `CausalEmergenceObserver` over `units = 4` output +units (16 micro states, chosen so the run gives about 11 (quick) or 34 (default) transitions per micro state) +reports EI, CE and both nulls. No verdict is drawn from these values. + +The receipt also holds `config`, `estimated_cost` (TPM evaluations of each part, engine steps), +`measured_wallclock_s` (excluded from the digest) and `notes`. + +## Public API + +`MODULE_ID`, `CausalEmergenceObserver`, `entropy_bits`, `as_tpm`, `effective_information`, `ei_decomposition`, +`transition_counts`, `estimate_tpm`, `median_binarize`, `encode_bits`, `decode_states`, `coarse_grain_tpm`, +`set_partitions`, `unit_sum_labels`, `unit_sum_candidates`, `state_partition_candidates`, `macro_ei_batch`, +`best_state_partition`, `best_unit_coarse_graining`, `causal_emergence`, `successor_block_null`, +`independent_units_null`, `hoel2017_examples`, `and_gate_network`, `pair_count_copy_tpm`, +`noisy_permutation_tpm`, `independent_flip_tpm`, `PRINTED_VALUES`, `run_experiment`, `EXPERIMENTS`. +All randomness uses `numpy.random.default_rng(seed + offset)`; no global NumPy or torch state is touched +(tested). + +## Connection to Sonapse + +* The live observer reports EI/CE of a few units of the running brain without touching it (frontier observer + hub, `causal_emergence` in `FrontierSpecV1.modules`). +* The lab experiment runs NEUROWEAVE engines through `neuroweave.experiments.make_spec` and + `neuroweave.tasks.make_stream`; the successor null reuses `connectomics.block_permutation`. + +## Not implemented + +* Only uniform (maximum-entropy) interventions; no other intervention distributions, no "black-boxing" or + removal of units, no temporal coarse-graining, no search over partitions of more than 10 states or of more + than 6 binary units. +* No integrated information (Phi) and no Rosas et al. Psi / synergy-based emergence measures. +* TPMs are estimated from observational sequences with additive smoothing; there is no bias correction of EI. +* The six-AND-gate wiring is reconstructed from the papers' text; the figure itself was not used. + +## Verified references + +Checked on 2026-11-20 (Crossref metadata; PMC full text for the 2013 paper; the arXiv v1 text of the 2017 paper +for every printed value used above). + +* Erik P. Hoel, Larissa Albantakis, Giulio Tononi. **Quantifying causal emergence shows that macro can beat + micro.** *Proceedings of the National Academy of Sciences* 110(49), 19790–19795, issue of 3 December 2013 + (online 18 November 2013). — EI as the mutual information between + uniform interventions and effects, macro interventions by averaging over grouped micro states; Fig. 4 values: + micro EI 2.43 bits, effectiveness 0.4, determinism coefficient 1, degeneracy coefficient 0.6, macro 3 bits, + CE 0.57 bits. +* Erik P. Hoel. **When the Map Is Better Than the Territory.** *Entropy* 19(5), 188, 26 April 2017. + (preprint arXiv:1612.09592, v1 of 30 December 2016) — determinism, + degeneracy, effectiveness and `EI = size * eff`; M1/M2/M3 (2, 1, 0 bits); the 8-state chain (eff 0.18, + 0.55 bits, macro 1 bit, CE 0.45 bits); its unequal-row variant (0.81 bits); the AND-gate network (2.43 bits, + 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). +* Fernando E. Rosas, Pedro A. M. Mediano, Henrik J. Jensen, Anil K. Seth, Adam B. Barrett, Robin L. + Carhart-Harris, Daniel Bor. **Reconciling emergences: An information-theoretic approach to identify causal + emergence in multivariate data.** *PLOS Computational Biology* 16(12), e1008289, 21 December 2020. + — the Psi criterion used by GhostInTheMachine; not implemented + here. +* Sibling projects: `kai9987kai/SONAPSE-ORIGIN` and `kai9987kai/GhostInTheMachine` (read-only clones; ideas, + not code, reused). + +## Measured results + +Measured on 2026-11-20, Windows 11 on ARM64, Python 3.12, NumPy 2.4, one BLAS thread +(`OPENBLAS_NUM_THREADS=1`), seeds 0, 1, 2, on a machine shared with other jobs (wall-clock varies with load). + +| Run | Verdict | Key numbers | Wall-clock | +|---|---|---|---| +| `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 | +| `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) | + +NEUROWEAVE (descriptive; 4 units, `clustered`, means over seeds): + +* quick (24 neurons, 200 steps, 24 burn-in, 175 transitions): `baseline` micro EI 0.257, macro 0.308, CE 0.051, + 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, + z 2.53 (p 0.05 / 0.30 / 0.05). +* default (32 neurons, 600 steps, 50 burn-in, 549 transitions): `baseline` micro EI 0.745, macro 0.764, + CE 0.019, independent-units z 2.45; `dynamics` micro EI 0.684, macro 0.665, CE −0.019, z 1.13. + +The sign of the NEUROWEAVE CE changes between the quick and default sizes, and per-seed p-values are mostly at +or above the smallest attainable value; these numbers do not show causal emergence in NEUROWEAVE brains or a +difference between the mechanism sets. diff --git a/docs/frontier/modules/connectomics.md b/docs/frontier/modules/connectomics.md new file mode 100644 index 0000000000000000000000000000000000000000..f84f497d36f89a7dce437c1bf7f7fceb4e1d1102 --- /dev/null +++ b/docs/frontier/modules/connectomics.md @@ -0,0 +1,195 @@ +# `connectomics`: structural, functional and effective connectivity + +Module file: `synapse/frontier/connectomics.py` · tests: `tests/test_frontier_connectomics.py` · +experiment id: `connectomics` · live observer: `ConnectivityObserver` · kind: `analysis` · +evidence tier: `synthetic_abstraction`. + +The module keeps three kinds of connectivity apart, as the sibling project `kai9987kai/SONAPSE-CONNECTOME` +does (`sonapse_connectome/connectome/functional.py`, `effective.py`): **structure** (the synapse table of a +NEUROWEAVE brain), **function** (statistical dependence between unit activities) and **effective connectivity** +(lagged, directed, predictive influence). It re-implements those ideas for NEUROWEAVE activity and checks every +estimator on a synthetic process whose answer is known before it is applied to a brain. It is a computational +abstraction: the "structure" is a toy synapse table and the "function" is the activity of abstract units, not +imaging data, and nothing here is evidence of biological fidelity. + +## What it computes + +**Functional connectivity (FC).** For a `(T, n)` activity array: + +* Pearson FC `R_ij = corr(x_i, x_j)` and Spearman FC (Pearson correlation of per-unit ranks, average ranks for + ties). Zero-variance units get zero rows/columns and a zero diagonal entry. Rescaling each channel into + different measurement units preserves its Pearson and partial correlations. +* Partial correlation from the ridge-regularised precision of the correlation matrix, + `Omega = (R + ridge I)^-1`, `P_ij = -Omega_ij / sqrt(Omega_ii Omega_jj)` (unit diagonal). + `partial_from_covariance(cov, ridge=0)` is exact and raises `ValueError` on a singular matrix; + `partial_correlation(X, ridge=1e-2)` is the sample version. + +For a Gaussian chain `x -> y -> z` (`y = a x + e`, `z = a y + e`, unit noise) the precision matrix is +`[[1 + a^2, -a, 0], [-a, 1 + a^2, -a], [0, -a, 1]]`, so the exact partial correlations are +`P_xy = a / (1 + a^2)`, `P_yz = a / sqrt(1 + a^2)` and `P_xz = 0`, while the Pearson correlation +`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. + +**Dynamic FC (dFC).** Pearson FC in sliding rectangular windows (`window`, `step`); the upper triangles of the +window matrices are clustered with a deterministic k-means (Lloyd iterations, D²-weighted seeding, +`n_init` restarts, empty clusters re-seeded, labels in order of first appearance) for `k = 2 .. k_max`, and the +`k` with the largest mean silhouette width (Rousseeuw, 1987) wins. If no `k` reaches `min_silhouette` +(a heuristic default of 0.25) or there are fewer than three windows, the series is reported as one FC state. +Dwell times are run lengths of the window-state sequence (in windows and in samples, `x step`), with occupancy +and the number of state transitions. + +**Effective connectivity (EC).** A ridge VAR(1) with intercepts, +`A = argmin_A sum_t ||x_{t+1} - A x_t||^2 + lambda ||A||_F^2`, `lambda = ridge * (T - 1)`, on (optionally z-scored) +series; `A[target, source]`. Significance comes from a **per-target conditional block-permutation null**: for +each draw, the past of all sources is block-permuted jointly in time (blocks of `round((T-1)^(1/3))` steps by +default, at least 2), except that each target keeps its own unpermuted past; every target's ridge regression is +refit (all targets in one batched solve). Each edge gets `z = (A - mean_null) / sd_null`, a two-sided normal +p-value and a rank p-value `(1 + #{|null - mean| >= |A - mean|}) / (1 + draws)`; the mask is +Benjamini-Hochberg at FDR `alpha` over the off-diagonal edges. This is lagged predictive (Granger-style) +influence, not an interventional effect. + +**Structure and coupling.** + +* `structural_matrix(n, src, dst, weight)`: dense `W[src, dst]` from an edge list (duplicates summed, `|w|` by + default, diagonal zeroed). +* `weighted_communicability(S) = exp(D^-1/2 S D^-1/2)`, `D = diag(sum_k S_ik)`, the weighted communicability + of Crofts & Higham (2009) (Estrada & Hatano, 2008, for the unweighted version); isolated nodes keep zero rows. +* `structure_function_coupling(S, FC)`: Spearman correlation over node pairs `i < j` between symmetrised + structure and FC (all pairs and structurally connected pairs, signed and absolute FC), and the same for + communicability, which also credits indirect walks; in the spirit of Honey et al. (2009). +* `modularity(W, labels)`: Newman-Girvan `Q = (1/2m) sum_ij (W_ij - k_i k_j / 2m) [c_i = c_j]`. +* `fc_communities(FC)`: leading-eigenvector communities (Newman, 2006) of the positive part of FC by + recursive bisection with the generalised modularity matrix `B^(g)_ij = B_ij - delta_ij sum_{l in g} B_il`, + without vertex-moving refinement, so the reported modularity is a proxy (a lower bound on the maximum). + +## Live observer (`ConnectivityObserver`) + +`ConnectivityObserver(n_units, *, seed=7, history=256, window=None, max_units=32, k_max=4, ec_null_draws=31, +ridge=0.05, alpha=0.05, min_silhouette=0.25, **params)`; `ConnectivityObserver.from_spec(n_units, spec)` takes +`seed`, `history` and `fc_window` (clipped to `history`) from a `FrontierSpecV1`. `window` defaults to 128; the +spec name `fc_window` is accepted as the same parameter (a conflicting pair raises `ValueError`), and the spec +parameters of other observers (`sync_pairs`, `sae_features`, `sae_k`, `max_observed_units`, `observe_every`) +are accepted and ignored; any other keyword raises `ValueError`. + +* A seeded, sorted subset of at most `max_units` units is copied into a ring buffer of `history` rows; + `observe(x)` validates `x` (1-D, length `n_units`, finite) before touching any state and never writes to it. +* Metrics are recomputed once `window` rows exist and then every `max(8, window // 4)` observations: static FC + and EC on the last `window` rows (non-constant units only), dFC on the whole buffer with windows of + `max(8, window // 4)` rows and half-window steps. The EC null is seeded by `(seed, observed steps)`, so results + do not depend on how often `summary()` is called. +* `summary()` keys: `module`, `evidence_tier`, `n_units`, `analysed_units`, `unit_sample`, `history`, `window`, + `recompute_every`, `observed_steps`, `buffered`, `ready`, `computed_at`, `rows`, `constant_units`, + `mean_abs_fc`, `fc_modularity`, `fc_communities`, `dfc_window`, `dfc_windows`, `dfc_states`, + `dfc_silhouette`, `dfc_mean_dwell_windows`, `dfc_mean_dwell_steps`, `dfc_transitions`, `ec_density`, + `ec_significant` and `ec_top_edges` (at most five `{source, target, weight, z, significant}` records, by + `|z|`). Values are `None` until the first recompute. Unit indices refer to positions in the observed vector. +* `export_state()` / `import_state(state)` round-trip through JSON; `import_state` validates the schema, the + configuration, the unit sample, the buffer (shape, finiteness, zeros beyond the observed steps), the recompute + schedule and every cached metric before replacing anything. `reset()` returns to the empty state. + +The observer runs inside the frontier observer hub (`synapse/frontier/runtime.py`) when `connectomics` is in +`FrontierSpecV1.modules`; it is read-only and never writes into the brain or any shared RNG. + +## Lab experiment (`run_experiment`, `EXPERIMENTS = {'connectomics': run_experiment}`) + +`run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides)` returns a sealed `kind: 'validation'` receipt +with `verdict` in `('pass', 'fail')` and nine named checks, each required for every seed: + +| Check | Known answer | +|---|---| +| `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 | +| `var_sign_accuracy_at_least_0.9` | Signs of the estimated true edges | +| `var_mask_pooled_precision_at_least_0.8` | Precision of the BH mask pooled over seeds | +| `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 | +| `chain_fc_xz_clearly_nonzero` | `|R_xz| > 0.3` (the indirect link FC cannot remove) | +| `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 | +| `switching_pure_window_accuracy_at_least_0.9` | Label accuracy on windows that lie inside one block (up to label swap) | +| `stationary_control_single_state` | Same length, stationary, with the averaged covariance: dFC reports 1 state | +| `neuroweave_values_finite` | The descriptive part below is finite | + +Then, for each topology (quick: `clustered`, `ring_lattice`, `hub_skewed`; default adds `multi_region`) and +seed, a frozen NEUROWEAVE engine (`learn=False`, so the synapse table that generates the activity stays fixed) +runs on the task stream; after burn-in the module reports structure metrics, mean |FC| and |partial|, the FC +modularity proxy, structure-function and communicability-function coupling, EC density, the AUROC of `|A_hat|` +against the synapse table, the fraction of significant EC edges that sit on a synapse, sign agreement, and the +dFC state count. This part is descriptive: no verdict is drawn from it beyond finiteness. + +The receipt also holds `config`, `estimated_cost` (engine steps, ridge solves of the nulls, FC windows), +`measured_wallclock_s` (excluded from the digest) and `notes`. + +## Public API + +`MODULE_ID`, `ConnectivityObserver`, `pearson_fc`, `spearman_fc`, `partial_correlation`, +`partial_from_covariance`, `precision_to_partial`, `sliding_window_fc`, `kmeans`, `silhouette_score`, +`dwell_statistics`, `dynamic_fc_states`, `var1_fit`, `block_permutation`, `var1_permutation_null`, +`benjamini_hochberg`, `effective_connectivity`, `auroc`, `structural_matrix`, `weighted_communicability`, +`structure_function_coupling`, `modularity`, `fc_communities`, `run_experiment`, `EXPERIMENTS`. +All randomness uses `numpy.random.default_rng(seed + offset)`; inputs are validated with `ValueError`. +`block_permutation` is shared with `causal_emergence`. + +## Connection to Sonapse + +* The live observer gives the workbench FC, dFC and EC summaries of the running brain without touching it. +* The lab experiment uses `neuroweave.experiments.make_spec` / `engine_topology` and + `neuroweave.topology.topology_metrics`, so the structural side is the engine's own synapse table. + +Differences from SONAPSE-CONNECTOME: that project computes partial correlation from a shrinkage covariance, +labels dFC "states" by quantile bins of the mean |FC| of each window, and fits a ridge lagged regression without +intercepts or a significance test. Here dFC states are clustered with k-means and a silhouette criterion, EC has +intercepts, a conditional permutation null and FDR control, and every estimator has a known-answer check. + +## Not implemented + +* No imaging data, haemodynamic model or parcellation; no dynamic causal modelling; EC is a single-lag linear + model (no higher-order lags, no nonlinear or interventional EC). +* The dFC pipeline is in the spirit of Allen et al. (2014) but simpler: they used tapered windows (a 22-TR + rectangle convolved with a Gaussian), graphical-LASSO regularised covariance per window, k-means with the L1 + distance and the elbow criterion for k (k = 7); here windows are rectangular, FC is plain Pearson, k-means is + Euclidean and k is chosen by the mean silhouette with a 0.25 floor (a heuristic, not a test). +* The FC community split has no vertex-moving refinement (a modularity proxy). +* The observer only analyses up to `max_units` units and recomputes on a fixed schedule. + +## Verified references + +Checked on 2026-11-20 (Crossref metadata and the publishers' or PMC pages). + +* Christopher J. Honey, Olaf Sporns, Leila Cammoun, Xavier Gigandet, Jean-Philippe Thiran, Reto Meuli, Patric + Hagmann. **Predicting human resting-state functional connectivity from structural connectivity.** + *PNAS* 106(6), 2035–2040, 10 February 2009. +* Elena A. Allen, Eswar Damaraju, Sergey M. Plis, Erik B. Erhardt, Tom Eichele, Vince D. Calhoun. **Tracking + Whole-Brain Connectivity Dynamics in the Resting State.** *Cerebral Cortex* 24(3), 663–676, March 2014 + (online 11 November 2012). +* Ernesto Estrada, Naomichi Hatano. **Communicability in complex networks.** *Physical Review E* 77(3), 036111, + March 2008. +* Jonathan J. Crofts, Desmond J. Higham. **A weighted communicability measure applied to complex brain + networks.** *Journal of the Royal Society Interface* 6(33), 411–414, April 2009 (online 13 January 2009). + +* M. E. J. Newman. **Modularity and community structure in networks.** *PNAS* 103(23), 8577–8582, June 2006. + +* C. W. J. Granger. **Investigating Causal Relations by Econometric Models and Cross-spectral Methods.** + *Econometrica* 37(3), 424–438, August 1969. +* Yoav Benjamini, Yosef Hochberg. **Controlling the False Discovery Rate: A Practical and Powerful Approach to + Multiple Testing.** *Journal of the Royal Statistical Society, Series B* 57(1), 289–300, 1995. + +* Peter J. Rousseeuw. **Silhouettes: a graphical aid to the interpretation and validation of cluster + analysis.** *Journal of Computational and Applied Mathematics* 20, 53–65, November 1987. + +* Sibling project: `kai9987kai/SONAPSE-CONNECTOME` (read-only clone; ideas, not code, reused). + +## Measured results + +Measured on 2026-11-20, Windows 11 on ARM64, Python 3.12, NumPy 2.4, one BLAS thread +(`OPENBLAS_NUM_THREADS=1`), seeds 0, 1, 2, on a machine shared with other jobs (wall-clock is indicative). + +| Run | Verdict | Key numbers | Wall-clock | +|---|---|---|---| +| `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 | +| `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) | + +NEUROWEAVE (quick, 24 neurons, 240 steps, 40 burn-in; descriptive, means over seeds): structure-FC Spearman +0.21 (`clustered`), 0.46 (`ring_lattice`), 0.15 (`hub_skewed`); communicability-FC Spearman 0.23 / 0.52 / 0.15; +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. +Default size (32 neurons, 600 steps, 50 burn-in), `clustered` / `ring_lattice` / `hub_skewed` / `multi_region`: +structure-FC Spearman 0.16 / 0.23 / 0.15 / 0.12, communicability-FC Spearman 0.18 / 0.18 / 0.19 / 0.18, +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 +differ (network size, run length), so neither is a stable property of a topology; these are small runs of a toy +model, reported, not tested. diff --git a/docs/frontier/modules/continuum_memory.md b/docs/frontier/modules/continuum_memory.md new file mode 100644 index 0000000000000000000000000000000000000000..0ece48f0c8ecfbd88f6becd804bea07e665571d3 --- /dev/null +++ b/docs/frontier/modules/continuum_memory.md @@ -0,0 +1,264 @@ +# `continuum_memory`: continuum memory system + +Module file: `synapse/frontier/continuum_memory.py` · tests: `tests/test_frontier_memory.py` · +experiment ids: `continuum_memory`, `continuum_memory_recall` · engine extension: `ContinuumMemoryExtension` +(id `continuum_memory`) · evidence tier: `synthetic_abstraction`. + +The module combines two ideas from Behrouz and colleagues and uses them at toy scale: + +* the **continuum memory system** (CMS) of *Nested Learning*: several memories, each updated at its own + frequency, so fast levels adapt quickly and slow levels keep information longer (the paper's Hope module is + a self-modifying Titans followed by a CMS); +* the **neural long-term memory update** of *Titans*: a gradient step on an associative loss, accumulated + with momentum ("surprise") and shrunk by a forgetting gate. + +It is *inspired by* these papers and does not reproduce either. The memories are linear maps, not MLP blocks. +Momentum, learning rate and forgetting are fixed numbers, not learned functions of the input. There is no +attention, no self-modifying Titans, no meta-learned initial state and no language modelling. None of the +papers' results are attempted. + +## What it computes + +`ContinuumMemory(key_dim, value_dim, levels=4, base_period=1, lr=0.5, momentum=0.0, forget=0.01, *, +surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', bound=100.0)` holds `L = levels` linear memories +`M_l` (`value_dim x key_dim`), one momentum buffer `S_l` per level, and one gradient accumulator per level. +Level `l` has period `P_l = base_period * 2**l` (1, 2, 4, 8 with the defaults). A key is either one +`(key_dim,)` vector shared by every level or a `(levels, key_dim)` array with one key block per level. + +``` +read r_l = M_l k_l y = sum_l r_l (read / predict) +loss L_t = ||y_t - v_t||^2 g_{l,t} = dL_t/dM_l = 2 (y_t - v_t) k_{l,t}^T +chunk G_l = sum of g_{l,t} over the P_l writes of the chunk ('sum') or G_l / P_l ('mean') +when the write count is a multiple of P_l: + S_l <- clip(momentum * S_l - lr * G_l) + M_l <- clip((1 - alpha_l) * M_l + S_l) + alpha_l = min(max_forget, forget + surprise_forget * (mean surprise of the chunk)) +surprise s_t = e_t / (e_t + ||v_t||^2), e_t = ||y_t - v_t||^2 (s_t = 0 when e_t = 0) +``` + +Every gradient is taken from the joint read `y_t` with the memories as they are at that write, so a slow +level accumulates the errors left after the fast levels have adapted. `clip` bounds `M` and `S` to +`[-bound, bound]`. Every array has a fixed shape, so the state stays finite and bounded. The memory has no +randomness. + +How this maps onto the sources: + +* **Nested Learning, Eq. 71.** The parameters of level `l` change only once every `C(l)` steps, by the sum of + `eta_t f(theta_t; x_t)` over the chunk, where `f` is the optimiser's error term. Here `f` is the gradient of + `L_t` with respect to `M_l`. `chunk_reduce='sum'` is a constant `eta`, and `'mean'` is `eta = lr / P_l`. +* **Nested Learning, Eq. 74.** This is the independent ("head-wise") CMS: the levels read the input + independently and an aggregation combines their outputs. The paper suggests a learnable weighted sum. This + module uses a fixed, unweighted sum. +* **Titans, Eqs. 10, 12 and 13.** The associative loss is `||M(k) - v||^2`. The surprise recurrence is + `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 + `momentum` is `eta`, `lr` is `theta`, and `alpha` is a fixed number (`forget`), optionally raised by the + chunk's surprise. In Titans' experiments `eta_t`, `theta_t` and `alpha_t` are functions of the token. +* **Surprise score.** `s_t` is this module's own bounded score. It is 0 for a perfect read, 1/2 for an empty + memory, and approaches 1 for a confidently wrong read. Titans calls the gradient term itself the "momentary + surprise". `s_t` only feeds the optional surprise-raised forgetting (`surprise_forget > 0`, off by default). + +Tests check these properties on cases with a known answer: + +* One write with `lr = 1/2` on a unit key stores exactly `v k^T`. The value reads back, and an orthogonal key + reads zero. +* Level `l` changes exactly on the writes divisible by `P_l`. This was checked over 48 writes with periods + 3, 6, 12 and 24. +* The chunk update equals a hand computation (sum of per-write gradients, or their mean). +* Momentum and forgetting follow the Titans recurrences step by step. +* With zero gradient, level `l` decays by `(1 - forget)` per own update, so it decays at its own rate. A stored + association fades as `(1 - forget)^n`. +* Surprise raises `alpha` up to `max_forget`. +* The state stays within `bound` under extreme inputs. +* Each mechanism (momentum, forgetting, surprise forgetting, chunk mean, base period, level count, learning + rate) changes the predictions when toggled. + +## Engine extension (`ContinuumMemoryExtension`, id `continuum_memory`) + +`ContinuumMemoryExtension(levels=4, key_dim=8, base_period=1, lr=0.25, momentum=0.0, forget=0.01, *, +features_per_level=2, surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', seed=0)` is a readout-only +extension. + +* **Context.** `c_t` is the task input (zero-padded or truncated to `TASK_INPUT_DIM = 8`; zeros when absent) + followed by the 16-channel fused sensory frame from the step context (24 numbers). +* **Key.** The key is a fixed binary random-feature map, `k(c) = sign(R c + b) / sqrt(levels * key_dim)`, with + `R` and `b` drawn from `default_rng(seed + 51407)`. It is split into one `key_dim` block per level and has + unit norm overall. +* **Write.** After every engine step, and only when `ctx['learn']` is true, the extension writes the + association `k(c_{t-1}) -> sensory_t`, so the memory learns to forecast the next sensory frame from the + current context. Nothing is written before a previous context exists, for example right after `reset()`. +* **Features.** The extension reads every level with `k(c_t)`. Each level's 16-channel read is projected onto + `features_per_level` fixed unit-norm directions (from `default_rng(seed + 51419)`) and clipped to + `[-10, 10]`. The result is `feature_dim = levels * features_per_level` features (8 by default). +* **What it does not touch.** The extension never changes the drive and does not read the brain output. It + keeps no engine reference, and `copy.deepcopy` gives an independent clone. With `ctx['learn']` false it does + not write; it counts `frozen_steps` instead. `reset()` forgets the previous context and the features, and + keeps the memory. +* **Budget.** `parameter_count()` is the number of memory entries, `levels * 16 * key_dim` (512 by default). + `state_numbers()` adds the momentum buffers, accumulators, random features, projections and counters. + +A test feeds a period-3 sequence of sensory frames. Within 60 steps, the forecast error falls below 1 % of its +initial value. + +## Recall benchmark (`run_recall_benchmark`, id `continuum_memory_recall`) + +The benchmark tests the CMS schedule on a task with a known structure. It does not use the NEUROWEAVE engine. + +* **Stream** (`make_recall_stream`). Keys are random unit vectors in `levels * key_dim` dimensions (128 by + default). Values are standard normal (8 dimensions). + * 4 short-gap items recur after gaps of 3–10 steps, and 8 long-gap items recur after gaps of 40–80 steps. + When several items are due, the earliest-due one is shown and the others wait, so a realised gap can be + longer than the drawn one. + * Every step without a due item shows a fresh one-off association, which acts as interference. + * An optional `remap_prob` gives a short-gap item a new value at a recurrence. This is off in the experiment. +* **Scoring.** Scoring is prequential: predict the value from the key, score the squared error at short-gap + and long-gap recurrences, then write. +* **Arms.** + * `cms`: 4 levels with periods 1, 2, 4 and 8. Level `l` reads block `l` of the key. + * `single`: one Titans-style memory (momentum and forgetting) that reads the whole key with period 1. + * `none`: the running mean of the values seen so far. + + The two memory arms read the same keys and hold the same number of entries (`8 x 128 = 1024`). If every + CMS level had period 1, the two arms would compute the same thing. The difference between them is therefore + the update schedule, including how often forgetting acts. +* **Fair tuning.** For each memory arm, `(lr, momentum, forget)` is chosen from the same grid on separate + tuning seeds (1000 and 1001; 1000 in quick mode). The objective is the mean of short-gap and long-gap MSE. + `tuning..chosen_on_grid_edge` names any chosen value that sits on a grid edge, where the optimum may lie + outside the grid. A value of 0 is treated as a natural bound, not an edge. +* **Verdict.** The verdict is a paired 95 % t interval over seeds on long-gap MSE (lower is better), `cms` + against `single`. Receipts also report the short-gap comparison and both memories against `none`. +* **Sizes.** The default uses 800 steps, `lr` in {1/64, …, 1/2} (6 values), `momentum` in + {0, 0.5, 0.75, 0.875, 0.9375} and `forget` in {0, 0.01}. Quick mode uses 240 steps, `lr` in + {0.125, 0.25, 0.5}, `momentum` in {0, 0.25, 0.5} and `forget` in {0, 0.02}. + +## Lab experiment (`run_experiment`, id `continuum_memory`) + +`harness.run_extension_experiment('continuum_memory', ...)` runs the NEUROWEAVE `delayed_recall` task (the +target is the input bit from two steps ago) with three arms: + +* `baseline`: the unmodified engine and readout. +* `candidate`: the baseline plus `ContinuumMemoryExtension` features. +* `control`: the baseline plus the same number of random leaky-trace features of the brain output (the + harness's capacity-matched `random_trace` control). + +All arms share seeds, streams and the readout protocol, and held-out streams are evaluated frozen. The headline +verdict is `improved` only if the candidate beats both the baseline and the control. The control matches the +candidate's readout feature count (8), not its stored numbers: the measured receipts report 2,525 extension +state numbers for the candidate and 208 (quick) or 400 (default size) for the control. + +The defaults are the harness's: seeds 0, 1, 2; held-out seeds 100, 101; 300 steps; 48 neurons; clustered +topology; no extra NEUROWEAVE mechanisms. The extension uses its defaults. Quick mode uses the harness +`QUICK_ARGS` sizes (24 neurons, 24 steps, one 12-step held-out stream) with the caller's seeds. The extension +keys (`levels`, `key_dim`, `base_period`, `lr`, `momentum`, `forget`, `features_per_level`, +`surprise_forget`, `max_forget`, `chunk_reduce`) and the harness keys (`task`, `heldout_seeds`, `steps`, +`heldout_steps`, `neurons`, `topology`, `mechanisms`) can be overridden. + +## Public API + +```python +MODULE_ID = 'continuum_memory'; RECALL_ID = 'continuum_memory_recall' +EXPERIMENTS = {'continuum_memory': run_experiment, 'continuum_memory_recall': run_recall_benchmark} +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +run_recall_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +ContinuumMemory(key_dim, value_dim, levels=4, base_period=1, lr=0.5, momentum=0.0, forget=0.01, *, + surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', bound=100.0) + .read(query) -> (levels, value_dim); .predict(query) -> (value_dim,) + .write(key, value) -> {'error', 'surprise', 'updated_levels'} + .periods; .parameter_count; .state_numbers; .config(); .reset(); .export_state(); .import_state(state) +ContinuumMemoryExtension(levels=4, key_dim=8, base_period=1, lr=0.25, momentum=0.0, forget=0.01, *, + features_per_level=2, surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', seed=0) + .key(context); .after_step(output, ctx); .features(); .telemetry(); .export_state(); .import_state(state) +make_recall_stream(seed, steps, *, key_dim=128, value_dim=8, n_short=4, n_long=8, short_gap=(3, 10), + long_gap=(40, 80), remap_prob=0.0) -> {'keys', 'values', 'kind', 'item', 'gap'} +RECALL_DEFAULTS, RECALL_QUICK, KIND_CODES, CHUNK_REDUCTIONS, SOURCE +``` + +Every public function and constructor validates its input and raises `ValueError` before any state changes. +`import_state` validates the whole state before replacing anything. It checks the configuration, shapes, +finiteness, the bound, and that the chunk and update counters are consistent with the write count. A failed +import leaves the memory unchanged. No global NumPy or torch random or thread state is touched. + +## Connection to Sonapse + +* **Not a live observer.** `continuum_memory` is not in `spec.OBSERVER_MODULE_IDS`. +* **Engine extension.** It influences nothing unless it is attached to a NEUROWEAVE engine with + `attach_extension`, as in the lab experiment. Even when attached, it only adds readout features. It never + changes the drive. +* **Standalone benchmark.** `run_recall_benchmark` uses only `ContinuumMemory` and synthetic streams. +* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes. + +## Not implemented, and differences from the papers + +* MLP memory blocks (Titans uses MLPs with `L_M >= 1` layers; Hope's CMS uses MLP blocks). Here every level is + one linear map. +* Learned, input-dependent `eta_t`, `theta_t` and `alpha_t`, and learned key, value and query projections. + The extension uses a fixed random binary key map. +* The learnable aggregation weights of the independent CMS, and the nested and sequential CMS variants + (Nested Learning Eqs. 72 and 73), including meta-learned initial states. +* Hope's self-modifying Titans module (and the softmax attention of the paper's Hope-Attention variant), the + parallel chunk-wise training of Titans (mini-batch gradients with a parallel associative scan for the + surprise terms), and every language-modelling, continual-learning and long-context result. +* Per-level momentum and forgetting applied at chunk boundaries. This combination of the two papers' update + rules is this module's own design. +* Periods on a fixed geometric ladder (`base_period * 2**l`). Nested Learning defines each level's chunk size + from its update frequency, `C(l) = max_i C(i) / f_l`; the geometric ladder is this module's choice. +* The surprise score `s_t` (see above). + +## Verified references + +Each reference was checked on 2026-11-20 against its arXiv listing and arXiv HTML full text, and against the +NeurIPS 2025 virtual-conference pages. + +1. Ali Behrouz, Meisam Razaviyayn, Peilin Zhong, Vahab Mirrokni. **Nested Learning: The Illusion of Deep + Learning Architectures.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*, poster + (https://neurips.cc/virtual/2025/poster/116123). arXiv:2512.24695, v1 submitted 31 December 2025 (the only + version listed on 2026-11-20); the arXiv comment says a version of the work is published at NeurIPS 2025. + https://arxiv.org/abs/2512.24695. Checked in the arXiv HTML of v1: + * Section 7.1, Eq. 70: the CMS chain of MLP blocks. + * Eq. 71: level `l` is updated every `C(l)` steps with the summed error terms of its chunk, and + `C(l) = max_i C(i) / f_l`. + * Eqs. 72–73: the nested and sequential variants. + * Eq. 74: the independent ("head-wise") variant with an aggregation function; the text suggests "a learnable + weighted sum". + * Definition 2: the update frequency is the "number of updates per unit of time". + * Section 8.3: Hope is self-modifying Titans followed by a CMS; the Hope-Attention variant replaces the + self-modifying Titans with softmax attention. +2. Ali Behrouz, Peilin Zhong, Vahab Mirrokni. **Titans: Learning to Memorize at Test Time.** *Advances in + Neural Information Processing Systems (NeurIPS) 2025*, poster + (https://neurips.cc/virtual/2025/loc/san-diego/poster/119639). arXiv:2501.00663, v1 submitted + 31 December 2024. https://arxiv.org/abs/2501.00663. Checked in the arXiv HTML: + * Eqs. 9–10: surprise with momentum, with the "past surprise" and "momentary surprise" terms. + * Eqs. 11–12: keys and values, and the loss `||M_{t-1}(k_t) - v_t||^2`. + * Eqs. 13–14: the forgetting gate `alpha_t` in `[0, 1]`. + * Eq. 15: retrieval without a weight update. + * Section 3.1: the memory is an MLP with `L_M >= 1` layers. + * Section 3.2: chunk-wise mini-batch training, a parallel associative scan for the surprise terms, and the + statement that, in their experiments, `alpha_t`, `theta_t` and `eta_t` are functions of the tokens. + +## Measured results + +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 +thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Every call used its defaults apart from +`quick`, with seeds 0, 1, 2. Each quick run was made three times and gave the same receipt digest every time; +each default-size run was made once (an earlier run on the same day gave the same numbers). The tests also +check that a second run gives the same digest. The digest prefix is listed so a rerun on this setup can be +compared; another platform may round floating-point results differently. Wall-clock covers the whole call +and is given as the range over the runs. The machine was shared with other jobs, so wall-clock is only +indicative. + +| Run | Verdict | Key numbers | Digest | Wall-clock | +|---|---|---|---|---| +| `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 | +| `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 | +| `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 | +| `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 | + +At equal entries and equal keys, with each arm tuned on the same grid, the multi-period schedule did not +detectably improve long-gap recall over a single Titans-style memory at these sizes, and it was slightly worse +on short gaps in the default run. Tuning gave both arms no forgetting and the same effective step +`lr / (1 - momentum)`: 0.25 in the default run, and 1/3 in quick mode, where both chose the same grid point. +Both memories beat the no-memory predictor by a wide margin. On `delayed_recall` the sensory-forecast +features made no detectable difference to the NEUROWEAVE readout. In the quick run every arm stays at chance, +so it only checks that the pipeline runs. + +These are statements about a linear toy on synthetic streams. They say nothing about language modelling or +about the published results. diff --git a/docs/frontier/modules/dendritic_layer.md b/docs/frontier/modules/dendritic_layer.md new file mode 100644 index 0000000000000000000000000000000000000000..7d74fa991ea4579f7af4d1889664a4ccfaf531e8 --- /dev/null +++ b/docs/frontier/modules/dendritic_layer.md @@ -0,0 +1,233 @@ +# `dendritic_layer`: structured dendritic layer + +Module file: `synapse/frontier/dendritic.py` · tests: `tests/test_frontier_models.py` · +experiment id: `dendritic_layer` · kind: standalone model (no engine extension, no live observer) · +evidence tier: `synthetic_abstraction`. + +The module implements a **dendritic artificial neural network** (dANN) layer inspired by Chavlis & Poirazi (2025). +Each dendrite receives a small, fixed subset of the inputs, which gives the layer structured sparsity through a +fixed binary mask. Each dendrite applies a nonlinearity, and each soma sums only its own dendrites through +trainable cable weights. The lab experiment compares dANNs with three input-sampling rules against a dense MLP at +matched trainable parameters, on a procedurally generated glyph dataset. + +This is not a reproduction. The paper's datasets (MNIST variants, CIFAR-10), sizes, efficiency scores and +sparse-ANN controls are not used. The units are abstract nodes, not models of real dendrites. + +## What it computes + +**Layer (`DendriticLayer`).** There are `somas` somata, each with `dendrites_per_soma` dendrites (`D` dendrites +in total). Dendrite `k` has exactly `S = synapses_per_dendrite` synapses: + +``` +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 +s_j = lrelu( sum_{k in dendrites(j)} c_jk d_k + a_j ) # soma j sums only its own dendrites +lrelu(u) = max(u, 0.1 u) # leaky ReLU, slope 0.1, as in the paper +``` + +* **Masking.** + * The weights are multiplied by the mask in the forward pass, so masked weights get exactly zero gradient. + This is the paper's Eq. 3, gradient masking. + * `W <- W ⊙ M` is re-applied after every optimiser step (`enforce_mask`, Eq. 1). + * The mask is a registered buffer. It never changes and travels with `state_dict()`. +* **Tree structure.** Every dendrite connects to exactly one soma. `cable_weight` therefore has shape + `(somas, dendrites_per_soma)`; `cable_mask()` shows the equivalent dense 0/1 soma-by-dendrite matrix. +* **Initialisation** uses a `torch.Generator`. Synapses and dendritic biases are uniform in + ±1/√S, the dendrite's own fan-in. Cable weights and somatic biases are uniform in ±1/√`dendrites_per_soma`. +* **`parameter_count()`** counts only parameters that exist: unmasked synapses, dendritic biases, cable weights + and somatic biases. The weight tensor is stored densely, but masked entries are not counted. `macs()` gives the + multiply-accumulates a sparse implementation would need. + +**Input sampling (`sample_receptive_fields`).** The mask is fixed at construction from +`default_rng(seed + 41011)`: + +* **`random`** (dANN-R): each dendrite samples `S` distinct inputs uniformly. +* **`local`** (dANN-LRF): each dendrite gets a uniformly drawn centre pixel and takes the `S` pixels nearest to it. + It starts from the centre's 3×3 block (a random subset when `S < 9`). It then adds Chebyshev rings of radius 2, + 3, … and takes a random subset of the last ring it needs. Blocks are clipped at the image border. +* **`global`** (dANN-GRF): each soma gets a uniformly drawn centre. Its dendrites' centres are + `dendrites_per_soma` distinct pixels nearest that centre, chosen by the same rule. Each dendrite then samples + locally around its own centre. + +The paper's Methods text says each dendrite takes 16 pixels from "the 4 × 4 neighbourhood" of its centre. The +authors' released `receptive_fields.py` instead builds the 3 × 3 block and grows it ring by ring, as described +above, and that is what this module follows. The default here is `S = 9`, a full 3 × 3 block. + +In the released somatic (GRF) mode, dendrite centres are drawn without replacement from the 3 × 3 block around +the soma centre. An inverted guard there never grows the block, so a soma with more than 9 dendrites, or one at +an image corner, leaves some dendrites without inputs. The ring rule used here avoids that case. + +**Networks.** + +* `DendriticNet` is a `DendriticLayer` followed by a dense linear read-out, the paper's "fully connected output + layer". +* `DenseMLP` is the control: two dense hidden layers of equal width `h` with the same leaky ReLU, then a linear + read-out. `matched_dense_hidden` picks the `h` whose parameter count is closest to the dANN's. + +The trainable parameter counts are: + +``` +dANN = D·S + 2·D + somas + somas·classes + classes (dann_parameter_count; D = somas · dendrites_per_soma) +dense = 144·h + h + h² + h + h·classes + classes (dense_parameter_count) +``` + +## Benchmark (`run_experiment`, `EXPERIMENTS = {'dendritic_layer': run_experiment}`) + +**Glyphs (`render_glyph`, `make_glyph_dataset`).** There are ten stroke classes, defined as polylines in the unit +square: `box, bar, plus, cross, ell, tee, zed, caret, aitch, cup`. Each image is rendered anti-aliased into +12 × 12 pixels, so the input is 144-dimensional: + +* random scale 6–8.5 px; +* rotation ±0.25 rad; +* translation ±2 px; +* half stroke width 0.35–0.9 px; +* additive Gaussian pixel noise with σ = 0.2. + +The pixel value is `clip(half_width + 0.5 − distance to the nearest segment, 0, 1)` plus noise. Nothing is +downloaded. + +**Per seed** (default `seeds=(0, 1, 2)`): + +* independent training (60 per class), validation (50 per class) and held-out (200 per class) sets, drawn from + different generator seeds; +* a noisy copy of the held-out set with extra Gaussian noise σ = 0.5, drawn from a `torch.Generator`. This copy + measures robustness. + +**Arms.** + +* `dann_random`, `dann_local` and `dann_global`: 16 somata × 8 dendrites × 9 synapses. +* `dense_mlp`: the dense control. + +All arms share the data, the minibatch order (one generator seed), Adam (lr 3e-3, β = (0.9, 0.999)), batch 64 +and 1000 updates. The paper uses Adam with lr 1e-3. Here 3e-3 is used because, with this update budget, lr 1e-3 +left the models short of fitting their training set; see the calibration row under *Measured results*. The +parameter budget is computed **before training**. If the dense control cannot be matched within +`param_tolerance` (10 %), `run_experiment` raises `ValueError`. That happens, for example, when the dANN is +smaller than the narrowest dense MLP, which has 167 parameters. + +**Verdict.** + +1. The best dANN is the sampling mode with the highest mean *validation* accuracy. The held-out set plays no part + in that choice. +2. `verdict = harness.compare(best dANN, dense MLP)` on held-out accuracy per seed, a paired 95 % t interval over + seeds. +3. `robustness_verdict` is the same comparison on the extra-noise held-out copy. + +The receipt also compares every sampling mode with the dense MLP, on clean and on noisy data, and records: + +* the per-arm train, validation, held-out and noisy accuracies; +* the mask density, and a count of nonzero masked weights after training (always 0); +* the parameter budget; +* the estimated MACs; +* the measured wall-clock, which is kept out of the digest. + +| option | default | quick | +|---|---|---| +| images per class train / val / held-out | 60 / 50 / 200 | 40 / 20 / 50 | +| noise / extra noise (σ) | 0.2 / 0.5 | same | +| somata × dendrites × synapses | 16 × 8 × 9 (mask density 9/144 = 0.0625) | same | +| trainable parameters dANN / dense (width) | 1,594 / 1,670 (10) | same | +| Adam updates / batch / lr | 1000 / 64 / 3e-3 | 250 / 64 / 3e-3 | + +## Public API + +```python +MODULE_ID = 'dendritic_layer' +EXPERIMENTS = {'dendritic_layer': run_experiment} +run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict # overrides: any DEFAULTS key + +DendriticLayer(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling='random', *, + image_shape=None, seed=0, negative_slope=0.1) + .forward(x) -> somatic activity (batch, somas) .dendritic_activity(x) -> (batch, D) + .enforce_mask() .cable_mask() .parameter_count() .mask_density() .macs() + buffers: synaptic_mask (D, in_features), fields (D, S) input indices per dendrite +DendriticNet(in_features, classes, somas, dendrites_per_soma, synapses_per_dendrite, sampling='random', *, + image_shape=None, seed=0) +DenseMLP(in_features, classes, hidden, *, seed=0) +sample_receptive_fields(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling, *, + image_shape=None, rng) -> np.ndarray (D, S) +dann_parameter_count(somas, dendrites_per_soma, synapses_per_dendrite, classes) -> int +dense_parameter_count(in_features, classes, hidden) -> int +matched_dense_hidden(target_params, in_features, classes) -> int +render_glyph(label, rng, *, noise=0.0, shift=2.0, size=(6.0, 8.5), thickness=(0.35, 0.9), rotation=0.25) +make_glyph_dataset(n_per_class, *, seed, noise=0.2, **render_kw) -> (x float32 (n, 144), y int64 (n,)) +train_classifier(model, x, y, *, updates, batch_size, lr, generator) -> dict +accuracy(model, x, y) -> float +SAMPLING_MODES = ('random', 'local', 'global'), GLYPHS, GLYPH_NAMES, GLYPH_SIDE (12), DEFAULTS, QUICK +``` + +Image shapes default to a square, `(sqrt(n), sqrt(n))`, when `in_features` is a perfect square, and to +`(1, n)` otherwise. Pass `image_shape` to override. + +Determinism and global state: + +* masks use NumPy `default_rng`, and weights, minibatch order and test noise use `torch.Generator`; +* the global torch RNG is never touched; +* `run_experiment` runs on one torch thread and restores the caller's thread count afterwards. + +## Connection to Sonapse + +This is a standalone lab model (contract rule 3). It is not wired into the brain, a graft or the actor, and it +changes no Sonapse default. The frontier lab registry picks it up from `EXPERIMENTS`. + +Sonapse already has two different dendrite abstractions: + +* `synapse/dendritic_ltc.py` is a two-compartment, basal/apical liquid time-constant sub-graft; +* `synapse/dsag/` is the dual-soma axodendritic graft. + +`DendriticLayer` is a plain `nn.Module`. It could replace a dense input projection in such a graft behind an +opt-in flag. That is not done here. + +## Not implemented + +* **Paper controls and analyses:** + * dANN-F (all-to-all dendrites) and the sparse-ANN (sANN) controls; + * vANNs with unequal hidden widths; + * the accuracy and loss efficiency scores (Eq. 4–5); + * the sequential-learning, dropout and depth studies; + * the entropy and selectivity analyses. +* **Datasets:** MNIST, Fashion-MNIST, Kuzushiji-MNIST, EMNIST and CIFAR-10. No data is downloaded. +* **Biological constraints:** positive or fixed cable weights, which the paper names as a more bio-realistic + option. +* **Sparse kernels.** The masked layer runs as a dense matrix product, so it is not faster than the dense MLP. + `estimated_cost.macs_per_example` reports what a sparse implementation would need. + +## Verified references + +* Spyridon Chavlis and Panayiota Poirazi. **Dendrites endow artificial neural networks with accurate, robust and + parameter-efficient learning.** *Nature Communications* 16, 943 (2025), published 22 January 2025 (received + 4 April 2024, accepted 13 January 2025). DOI [10.1038/s41467-025-56297-9](https://doi.org/10.1038/s41467-025-56297-9); + open access as PMC11754790 (PMID 39843414). Preprint: arXiv:2404.03708, v1 4 April 2024, v2 13 September 2024, + . + * **Re-checked on 2026-11-20 (review)** against PMC11754790 (title, authors, volume 16, article 943, + 22 January 2025, received 4 April 2024, accepted 13 January 2025; R / LRF / GRF sampling, 16 synapses + per dendrite, leaky ReLU 0.1, `W ⊙ M` with masked gradients) and `codes_/receptive_fields.py` (3 × 3 + block, ring expansion with a random subset of the last ring, centres with replacement, the inverted + somatic expansion guard). `sample_receptive_fields` matches the code, with the guard fixed. + * **Checked on 2026-11-17 against the PMC full text and the arXiv preprint:** + * Eq. 1, `W ← W ⊙ M`, and Eq. 3, gradient masking; + * one soma per dendrite, and a fully connected output layer; + * the three restricted sampling strategies R, LRF and GRF, and 16 inputs per dendrite; + * leaky ReLU with negative slope 0.1 on all hidden nodes; + * Adam with lr 0.001, betas 0.9 and 0.999, minibatch 128; + * a 90 / 10 train / validation split. + * **Checked in the authors' code** the same day: , + `codes_/receptive_fields.py`. + * `allocate_synapses` uses the 3 × 3 base block, random subsampling, and ring expansion with a random subset + of the last ring. + * Centres are drawn uniformly with replacement. + * In somatic mode, dendrite centres come from the 3 × 3 block without replacement, behind the inverted + expansion guard noted above. + +## Measured results + +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`): + +| Arm | Train acc | Val acc | Held-out acc | Held-out noisy acc | Held-out Δ vs `dense_mlp` (95 % CI) | +|---|---:|---:|---:|---:|---| +| `dann_random` | 0.9067 | 0.6650 | 0.6560 | 0.4007 | −0.0127 (`[-0.0844, +0.0591]`, `no_detectable_difference`) | +| `dann_local` (best val) | 0.8625 | 0.6667 | 0.6780 | 0.4440 | +0.0093 (`[-0.0424, +0.0611]`, `no_detectable_difference`) | +| `dann_global` | 0.8158 | 0.6400 | 0.6433 | 0.4227 | −0.0253 (`[-0.1536, +0.1029]`, `no_detectable_difference`) | +| `dense_mlp` (baseline) | 0.9758 | 0.6633 | 0.6687 | 0.4080 | — | + +* **Headline verdict (`best_dann(dann_local)_vs_dense_mlp`):** `no_detectable_difference` (mean +0.0093, 95 % CI `[-0.0424, +0.0611]`). +* **Robustness verdict (`best_dann_vs_dense_noisy`):** `no_detectable_difference` (mean +0.0360, 95 % CI `[-0.0372, +0.1092]`). diff --git a/docs/frontier/modules/experiment_design.md b/docs/frontier/modules/experiment_design.md new file mode 100644 index 0000000000000000000000000000000000000000..85e898310b7df31b83d17f3bff09fe57db0cf991 --- /dev/null +++ b/docs/frontier/modules/experiment_design.md @@ -0,0 +1,211 @@ +# `experiment_design`: decision-sensitive experiment selection + +Module file: `synapse/frontier/experiment_design.py` · tests: `tests/test_frontier_addons.py` · +experiment ids: `experiment_design`, `experiment_design_costed` · kind: methodology (no engine extension, no live observer) · +evidence tier: `synthetic_abstraction`. + +The module implements **one-step decision-sensitive Bayesian experimental design** over a finite hypothesis set, +inspired by COUNTERFORM's decision-risk acquisition and Mnemorph (`kai9987kai`) and by classical Bayesian +decision-theoretic design (Lindley, 1956; Chaloner & Verdinelli, 1995). Instead of picking the experiment that +maximises expected information gain about which hypothesis is true, the selector picks the experiment that +maximises the expected reduction in the **downstream decision's Bayes risk**, net of any experiment cost, and +**abstains** (recommends stopping) when no experiment improves expected net risk beyond a threshold. + +This is a synthetic finite-hypothesis abstraction. It does not reproduce COUNTERFORM's physical oscillator studies +or any published benchmark. + +## What it computes + +**Problem (`DecisionProblem`).** There are $K$ hypotheses with prior weights $w \in \Delta^{K-1}$, $M$ candidate +experiments, and $D$ downstream decisions with a loss matrix $L \in \mathbb{R}^{D \times K}$ and non-negative +per-experiment costs $c \in \mathbb{R}_{\ge 0}^M$. Under hypothesis $k$, experiment $e$ produces a scalar Gaussian +outcome + +$$ +y \mid (k, e) \sim \mathcal{N}\!\left(\mu_{k,e},\; \sigma_{k,e}^2\right). +$$ + +* **Bayes update (`update`).** Given belief $w$ and outcome $y$ from experiment $e$, the posterior $w'(y)$ is + computed in log space: + $$ + w'_k(y) \propto w_k \,\mathcal{N}\!\left(y;\; \mu_{k,e},\, \sigma_{k,e}^2\right), + \qquad w_k = 0 \implies w'_k(y) = 0. + $$ +* **Bayes decision and Bayes risk (`decision`, `bayes_risk`).** The optimal decision at belief $w$ and its expected + loss are + $$ + d^*(w) = \arg\min_{d \in \{0,\dots,D-1\}} \sum_{k=0}^{K-1} L_{d,k}\, w_k, + \qquad R(w) = \min_{d} (L w)_d, + $$ + breaking ties by lowest decision index. +* **Deterministic posterior-predictive quadrature (`_fantasies`).** Under belief $w$, the marginal outcome + distribution of experiment $e$ is the Gaussian mixture $\sum_{k} w_k \,\mathcal{N}(\mu_{k,e}, \sigma_{k,e}^2)$. + Expectations over $y$ are evaluated with $Q$-point Gauss–Hermite quadrature (`quadrature=20` by default) applied + to each mixture component: + $$ + y_{k,q} = \mu_{k,e} + \sigma_{k,e}\sqrt{2}\,x_q, \qquad p_{k,q} = \frac{w_k\,\omega_q}{\sqrt{\pi}}, + $$ + where $(x_q, \omega_q)_{q=1}^Q$ are the standard Gauss–Hermite nodes and weights ($\sum_q \omega_q / \sqrt{\pi} = 1$). + Because quadrature is deterministic, acquisition scores have zero Monte-Carlo variance. +* **Expected Bayes-risk reduction (`risk_reduction`).** The one-step value of information of experiment $e$ is + $$ + \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). + $$ +* **Expected information gain (`information_gain`).** Lindley's mutual information (in nats) between the hypothesis + and the outcome of experiment $e$: + $$ + \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), + \qquad H(w) = -\sum_{k:\,w_k>0} w_k \ln w_k. + $$ + +**Selectors.** + +* **`DecisionSensitiveSelector` (`decision_risk`)** scores each experiment by net value $\Delta R(e \mid w) - c_e$, + picks the lowest index among maxima, and returns `None` (abstains) when + $\max_e \{\Delta R(e \mid w) - c_e\} \le \tau$ (`abstain_threshold = 1e-9`). Once a study abstains, no further + experiments are run and no further cost is paid. +* **`_NoAbstainDecisionSelector` (`decision_risk_no_abstain`)** uses the same net-value ranking but never abstains; + it separates the effect of the decision-sensitive ranking from the stopping rule in costed studies. +* **`InformationGainSelector` (`information_gain`)** picks $\arg\max_e \mathrm{IG}(e \mid w)$ (abstaining only when + $\max_e \mathrm{IG}(e \mid w) \le 10^{-12}$, i.e., when every experiment has identical outcome distributions across + supported hypotheses). +* **`RandomSelector` (`random`)** draws uniformly from $\{0, \dots, M-1\}$ using a seeded NumPy generator + (`default_rng(seed + 104729)`). + +## Benchmarks (`EXPERIMENTS = {'experiment_design': run_experiment, 'experiment_design_costed': run_costed_experiment}`) + +**Synthetic studies (`make_study`).** The generator constructs problems where **information about the hypothesis** +and **relevance to the decision** diverge: + +1. The $K$ hypotheses are partitioned into $D$ decision groups ($g_k = k \bmod D$). Decision $d$ has zero loss on + hypotheses in group $d$ and an asymmetric loss $L_{d,k} \sim \mathrm{Uniform}(0.5, 2.0)$ when $d \ne g_k$. +2. Prior weights follow $\mathrm{Dirichlet}(4, \dots, 4)$. +3. The $M - M_{\text{dist}}$ **relevant** experiments draw a group mean $\mathcal{N}(0, 1)$ per decision group plus + small within-group jitter $\mathcal{N}(0, 0.15^2)$: they separate decision groups with modest signal-to-noise. +4. The $M_{\text{dist}}$ **distractor** experiments repeat the same large within-group spacing (amplitude + $\mathrm{Uniform}(2, 4)$) inside every decision group: they carry high mutual information about *which* + hypothesis holds within a group, but almost zero information about *which group* holds. +5. Experiment columns are randomly permuted so the selector must infer relevance from $(\mu, \sigma, L)$. + +**Common random numbers (`simulate_study`).** For each study, the hidden true hypothesis $k^* \sim w^{(0)}$ and the +standard-normal observation noise draws $z_0, \dots, z_{B-1}$ are shared across every selector arm. After $B$ +steps (or earlier abstention), the terminal decision $d^*(w^{(B)})$ is scored by its **decision regret** against an +oracle that knows $k^*$: + +$$ +\mathrm{regret}\!\left(d, k^*\right) = L_{d, k^*} - \min_{d'} L_{d', k^*}. +$$ + +* **`experiment_design` (`run_experiment`)** compares `decision_risk`, `information_gain`, and `random` at zero + experiment cost (`c_e = 0`). Headline verdict: `harness.compare(decision_risk, information_gain, higher_is_better=False)` + on mean final decision regret across seeds. +* **`experiment_design_costed` (`run_costed_experiment`)** assigns per-experiment costs + $c_e \sim \mathrm{Uniform}(\text{cost\_low}, \text{cost\_high})$ and compares `decision_risk`, + `decision_risk_no_abstain`, and `information_gain` on **mean total loss** ($\text{final regret} + \sum c_e$, + lower is better). + +| option | `experiment_design` default / quick | `experiment_design_costed` default / quick | +|---|---|---| +| studies per seed | 300 / 60 | 300 / 60 | +| experiment budget $B$ | 4 / 3 | 6 / 4 | +| hypotheses $K$ / decisions $D$ | 6 / 2 | 6 / 2 | +| experiments $M$ / distractors $M_{\text{dist}}$ | 8 / 3 | 8 / 3 | +| noise scale / quadrature $Q$ | 1.0 / 20 | 1.0 / 20 | +| per-experiment cost range | `(0.0, 0.0)` | `(0.02, 0.08)` | + +## Public API + +```python +MODULE_ID = 'experiment_design' +SELECTORS = ('decision_risk', 'information_gain', 'random') +EXPERIMENTS = { + 'experiment_design': run_experiment, + 'experiment_design_costed': run_costed_experiment, +} + +DecisionProblem(prior, means, sigmas, loss, costs=None, *, quadrature=20) + .n_hypotheses .n_experiments .n_decisions + .log_likelihood(e, y) -> np.ndarray + .update(w, e, y) -> np.ndarray + .decision(w) -> (decision_idx: int, bayes_risk: float) + .bayes_risk(w) -> float + .risk_reduction(w) -> np.ndarray # shape (M,) + .information_gain(w) -> np.ndarray # shape (M,), nats + .to_dict() -> dict +DecisionSensitiveSelector(problem, *, abstain_threshold=1e-9) + .scores(w) -> np.ndarray # risk_reduction(w) - costs + .choose(w) -> int | None +InformationGainSelector(problem, *, abstain_threshold=1e-12) + .scores(w) -> np.ndarray + .choose(w) -> int | None +RandomSelector(problem, *, seed=0) + .choose(w) -> int | None +make_selector(name, problem, *, seed=0, abstain=True) +make_study(seed, *, hypotheses=6, experiments=8, decisions=2, distractors=3, + noise=1.0, cost_range=(0.0, 0.0), quadrature=20) -> DecisionProblem +simulate_study(problem, truth, selector, budget, noise) -> dict +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict +run_costed_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict +``` + +## Connection to Sonapse + +This is a standalone methodology module (contract rule 3). It has no live observer and no engine extension, and it +changes no Sonapse or NEUROWEAVE default. Its `EXPERIMENTS` dictionary plugs into the frontier lab registry. + +## Not implemented + +* **Multi-step (non-myopic) lookahead.** Value of information is greedy (one step). When two experiments are + individually weak but jointly decisive, greedy one-step lookahead underestimates their combined value and can + abstain early. +* **Continuous hypothesis spaces or non-Gaussian likelihoods.** Hypotheses are finite and likelihoods are scalar + Gaussian so that one-step expectations are exact up to Gauss–Hermite quadrature. +* **COUNTERFORM's physical oscillator simulator and adequacy gates.** Only the decision-theoretic acquisition + principle is abstracted here. + +## Verified references + +* Dennis V. Lindley. **On a Measure of the Information Provided by an Experiment.** *The Annals of Mathematical + Statistics* 27(4), 986–1005 (December 1956). DOI [10.1214/aoms/1177728069](https://doi.org/10.1214/aoms/1177728069); + Project Euclid: . + * **Checked on 2026-11-19:** defines the expected Shannon information gain of an experiment as + $I = H_{\text{prior}} - \mathbb{E}_y[H_{\text{posterior}}(y)]$ (used here for `InformationGainSelector`). +* Kathryn Chaloner and Isabella Verdinelli. **Bayesian Experimental Design: A Review.** *Statistical Science* + 10(3), 273–304 (August 1995). DOI [10.1214/ss/1177009939](https://doi.org/10.1214/ss/1177009939); + Project Euclid: . + * **Checked on 2026-11-19:** reviews the decision-theoretic formulation of Bayesian experimental design (following + Raiffa & Schlaifer, 1961, and DeGroot, 1970) where an experiment $e$ is chosen to maximise expected utility + $\int \max_d \int u(d, \theta, y, e)\, p(\theta \mid y, e)\, d\theta\, p(y \mid e)\, dy$, equivalent to + minimising expected posterior Bayes risk plus experiment cost (`DecisionSensitiveSelector`). +* Portfolio provenance: `kai9987kai/COUNTERFORM` (v0.2 decision-sensitive fantasy design-risk acquisition with + abstention) and `kai9987kai/Mnemorph`, inspected in the local read-only portfolio clones on 2026-11-19. + +## Measured results + +Measured on **2026-11-19** with `seeds=(0, 1, 2)` on one CPU thread (`OPENBLAS_NUM_THREADS=1`). + +### `experiment_design` (fixed budget, zero cost; metric: mean final decision regret, lower is better) + +| 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 | +|---|---|---|---|---|---|---|---| +| `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` | +| `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` | + +Regret by budget step (`quick=False`, steps $t = 0, 1, 2, 3, 4$): + +* `decision_risk`: `[0.4885, 0.2164, 0.1157, 0.0698, 0.0481]` +* `information_gain`: `[0.4885, 0.4139, 0.1752, 0.0898, 0.0609]` +* `random`: `[0.4885, 0.3695, 0.2972, 0.2421, 0.2134]` + +On step 1, `information_gain` typically chooses a high-entropy distractor experiment (regret drops only from 0.4885 +to 0.4139 while posterior entropy falls sharply), whereas `decision_risk` chooses a group-separating experiment +(regret drops from 0.4885 to 0.2164). By step $B=4$, `information_gain` has also sampled relevant experiments and +nearly catches up in terminal regret, so the paired 95 % t interval across 3 seeds spans zero (`no_detectable_difference`), +while both active selectors beat `random` (`improved` at `quick=False`). + +### `experiment_design_costed` (costs in `[0.02, 0.08]`; metric: mean total loss = final regret + cost, lower is better) + +| 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 | +|---|---|---|---|---|---|---|---|---| +| `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` | +| `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` | diff --git a/docs/frontier/modules/hh_cable.md b/docs/frontier/modules/hh_cable.md new file mode 100644 index 0000000000000000000000000000000000000000..ccd3a3b0fc6686a43e01e0e34e6928ad2a61a9d9 --- /dev/null +++ b/docs/frontier/modules/hh_cable.md @@ -0,0 +1,217 @@ +# `hh_cable`: Hodgkin-Huxley cable reference + +Module file: `synapse/frontier/hh_cable.py` · tests: `tests/test_frontier_biophysics.py` · +experiment id: `hh_cable` (`kind: 'validation'`) · no observer, no engine extension · +evidence tier: `synthetic_abstraction`. + +A multi-compartment Hodgkin-Huxley (HH) cable, used as a **biophysical reference** next to NEUROWEAVE's +abstract discrete-time cell. It is *inspired by* NeuroPulse-CableLab (kai9987kai), a single-file browser HH +cable workbench with Euler, RK4 and Rush-Larsen integrators and a dt versus dt/2 comparison. It is built on +the membrane equations of Hodgkin & Huxley (1952). + +This is a numerical integration of the 1952 equations on a discretised cable. It does not reproduce the paper's +own procedure: HH solved a travelling-wave ODE (their eqn 30) by shooting for the velocity, using Hartree's +method. It is not a validated neuron simulator. The NEUROWEAVE comparison is descriptive only, and the +abstract cell is never "validated" against HH. + +## What it computes + +**Membrane and cable.** `v` is in mV with rest near −65 mV. HH's own variable is the displacement +`V = −(v + 65)`, with depolarisation negative. + +``` +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) +dx/dt = phi (alpha_x(v) (1 - x) - beta_x(v) x), x in {m, h, n}, phi = 3^((T - 6.3) / 10) +g_ax = a / (2 Ra dx^2) (HH eqn 28, I = (a / 2 R2) d2V/dx2, discretised by central differences) +``` + +* The rate functions are HH eqns 12, 13, 20, 21, 23 and 24 (p. 519), rewritten for `v`. For example, + `alpha_m = 0.1 (v + 40) / (1 - exp(-(v + 40)/10))` and `beta_h = 1 / (1 + exp(-(v + 35)/10))`. The removable + singularities at `v = −40` (alpha_m) and `v = −55` (alpha_n) take their limits, 1.0 and 0.1. +* Constants come from Table 3 (p. 520): `Cm = 1 uF/cm^2`, `gNa = 120`, `gK = 36`, `gL = 0.3 mS/cm^2`. The + reversal potentials `V_Na = −115`, `V_K = +12`, `V_l = −10.613 mV` become `ENa = 50`, `EK = −77` and + `EL = −54.387 mV`. +* Rates are for 6.3 °C, scaled by `phi` with a Q10 of 3 (pp. 519, 523). +* Both ends are sealed: no axial current leaves the first or last compartment. The stimulus is a current + density (uA/cm^2) on compartment 0. +* Each simulation starts at the resting state, the most negative stable zero of the steady-state ionic current. + +**Integrators.** + +* `'rk4'`: classical Runge-Kutta. The constructor rejects time steps beyond a conservative linear stability + bound. +* `'exp_euler'`: the gates are integrated exactly for frozen voltage (Rush-Larsen style). The voltage takes an + exponential step with conductances and neighbour voltages frozen. It is first order and stable for any step. + +Spike times are upward crossings of 0 mV, re-armed below −30 mV, located inside the step by cubic Hermite +interpolation. Everything is batched over amplitudes, intervals or diameters, so each search is a handful of +vectorised simulations. + +**Measurements (methods of `HHCable`).** + +* `resting_potential()`: bisection to 1e-10 mV. +* `threshold_current(duration_ms, ...)`: batched bisection for the smallest step amplitude that gives a spike + at a site, by default the last compartment. +* `fi_curve(amplitudes, ...)`: steady rate `(k − 1) / (t_last − t_first)` over the spikes after a transient. + A lone onset spike counts as 0 Hz. +* `conduction_velocity(...)`: distance over the difference in first-spike arrival at 1/3 and 2/3 of the + cable, optionally batched over diameters. +* `refractory_period(...)`: paired pulses. A conditioning pulse (2 × the single-pulse threshold) is followed by + a test pulse (4 × threshold). The result is the smallest onset-to-onset interval at which the test pulse + evokes a second spike. This is an operational estimate of the absolute refractory period for that test + strength. + +**NEUROWEAVE reference.** `neuroweave_fi_curve` drives isolated `CellPopulation` cells from +`synapse/neuroweave/cells.py` with constant external drive and counts spikes. The cells have the +`membrane_dynamics` flag, no recurrent input and neutral controls. `neuroweave_threshold` finds the smallest +drive that fires. `compare_fi_curves` then compares the two f-I curves: + +* Both curves are taken on the same threshold-normalised levels and normalised to their maximum. +* It reports the Spearman rank correlation over the suprathreshold levels, the level where repetitive firing + starts, and the mean absolute difference. +* `adaptation_index` gives the mean of `(ISI_{k+1} − ISI_k) / (ISI_{k+1} + ISI_k)` at one level. + +The comparison is descriptive: an abstract unit with one step as its time unit is compared in shape only. + +## Lab experiment (`run_experiment`, `EXPERIMENTS = {'hh_cable': run_experiment}`) + +Every named check must hold for `verdict: 'pass'`: + +| Check | Known answer | +|---|---| +| `resting_within_0.5mV_of_documented_-65mV` | HH chose `V_l` so the ionic current is zero at `V = 0` (Table 3 footnote) | +| `rest_stationary_without_input` | zero current: no spike, voltage stays at rest to 1e-6 mV | +| `subthreshold_steps_silent` / `suprathreshold_steps_fire` | all-or-none response at 0.5 × and ≥ 1.1 × the long-step threshold | +| `spike_peak_above_0mV` | overshoot in the patch and at mid-cable for every diameter | +| `velocity_positive`, `velocity_increases_with_diameter` | | +| `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) | +| `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 | +| `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 | +| `exp_euler_first_order_convergence` | observed order between 0.7 and 1.5 | +| `velocity_changes_below_1pct_at_dt_half` | cable velocities at dt and dt/2 | +| `refractory_second_pulse_fails_then_recovers` | the test pulse fails at one pulse width and succeeds at the longest interval | + +Settings: + +* Patch at 6.3 °C, with `dt` 0.0125 ms and RK4. +* Cable at 18.5 °C: 40 mm long, 200 compartments, `dt` 0.0006 ms, diameters 119, 238 and 476 um, stimulated + 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 + both ends bias the local speed over several millimetres. +* `quick=True` uses 60 compartments and `dt` 0.005 ms for the cable, shorter windows, single-round searches and + fewer f-I levels. +* The HH model is deterministic. `seeds` only seed the NEUROWEAVE `CellPopulation` constructors, and the + receipt reports per-seed NEUROWEAVE curves with `seed_invariant`. +* All settings are overridable (`_DEFAULTS` keys). Unknown overrides raise `ValueError`. + +## Public API + +```python +MODULE_ID = 'hh_cable'; EXPERIMENTS = {'hh_cable': run_experiment}; METHODS = ('rk4', 'exp_euler') +HH_REST_MV = -65.0; HH1952_REFERENCE_AXON = {'diameter_um': 476.0, 'Ra_ohm_cm': 35.4, ...} +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed validation receipt +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, + ENa=50.0, EK=-77.0, EL=-54.387, dt_ms=0.01, method='rk4', temperature_c=6.3) + .run(pulses, *, t_stop_ms, record=None, trace_site=None, trace_every=1) # pulses: (P, 3) or (B, P, 3) + .resting_potential(); .threshold_current(duration_ms, ...); .fi_curve(amplitudes, ...) + .conduction_velocity(*, amplitude=3000.0, duration_ms=0.2, t_stop_ms=2.0, sites=None, diameters_um=None) + .refractory_period(*, pulse_ms=0.5, threshold=None, ...); .replace(**changes); .config() +vtrap(x, y); hh_rates(v); steady_state_gates(v); temperature_factor(temperature_c) +neuroweave_fi_curve(drives, *, steps=400, transient=100, seed=0, flags=('membrane_dynamics',)) +neuroweave_threshold(*, steps=400, seed=0, bracket=(0.0, 2.0), rounds=2, batch=64, flags=...) +adaptation_index(isis); average_ranks(x); spearman_rho(a, b); compare_fi_curves(levels, hh_rates, nw_rates) +``` + +* Units: um, ohm cm, uF/cm^2, mS/cm^2, mV, ms and uA/cm^2. +* Input is validated before anything runs, and bad input raises `ValueError`. + The convergence study requires three successive time steps, each half its predecessor. The f-I study + requires strictly increasing drive levels with at least three at or above threshold and one at or above + 1.1 times threshold. +* Simulations are bounded: at most 2 M steps, 4096 batch elements and 64 pulses. Non-finite states raise + `FloatingPointError`. +* No randomness is used, and no global NumPy or torch RNG or thread state is touched (tested). + +## Connection to Sonapse + +* An offline reference. It neither reads nor writes any brain, engine or graft state, apart from + constructing its own isolated `CellPopulation` cells for the comparison. +* No Sonapse or NEUROWEAVE default, API or checkpoint format changes. +* It gives the abstract NEUROWEAVE cell a fixed biophysical yardstick for the shape of its f-I curve and its + adaptation. This is not a fidelity target. + +## Not implemented + +* Branched or tapered morphologies, non-uniform channel densities, synapses, extracellular potentials, + myelination and other channel types. The cable is uniform and unbranched, with sealed ends. +* HH's own travelling-wave shooting method. Their observed 21.2 m/s is not a target; the check compares with + their computed 18.8 m/s. +* Temperature dependence of `Cm` or of the conductances. HH also held these constants independent of + temperature. +* Any claim that the NEUROWEAVE cell is biologically realistic. +* The refractory estimate depends on the test strength (4 × threshold) and the temperature (6.3 °C), and it + is not compared with a published value. + +## Verified references + +Checked on 2026-11-20. + +1. A. L. Hodgkin, A. F. Huxley. **A quantitative description of membrane current and its application to + conduction and excitation in nerve.** *The Journal of Physiology* 117(4), 500–544, 28 August 1952. + doi:10.1113/jphysiol.1952.sp004764, https://physoc.onlinelibrary.wiley.com/doi/10.1113/jphysiol.1952.sp004764, + PubMed 12991237. Checked against page images of the paper's scanned PDF: + * the rate equations (12), (13), (20), (21), (23), (24) and the 6.3 °C / Q10 = 3 statement (p. 519); + * Table 3 constants and its footnote on `V_l` (p. 520); + * eqns 27–30 for the propagated action potential (p. 522); + * the factor `phi = 3^((T − 6.3)/10)` and the numerical method (p. 523); + * `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 + computed 18.8 m/s against the observed 21.2 m/s (p. 528). +2. NeuroPulse-CableLab (kai9987kai), a sibling repository. Its README and integrator list (Euler, RK4, + Rush-Larsen gates, the dt versus dt/2 comparison) were read in a read-only clone. None of its code was + executed or copied. + +## Measured results + +Measured on 2026-11-20 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP thread +(`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Seeds were 0, 1 and 2. Receipts are deterministic: +two runs of the quick receipt gave the same digest (tested). Wall-clock covers the whole call on a machine +shared with other jobs. + +| Run | Verdict | Wall-clock | +|---|---|---| +| `run_experiment(quick=True)` | `pass` (13/13 checks) | 6.1–6.8 s | +| `run_experiment()` | `pass` (13/13 checks) | 36.4 s | + +Key numbers (quick / default): + +* **Rest:** −64.996 mV. Table 3 gives `V_l` to three decimals (−10.613 mV), which leaves the computed rest + 0.004 mV above −65. +* **Long-step threshold** (a spike within 15 / 40 ms of onset): 2.22–2.30 / 2.229–2.248 uA/cm^2. +* **Patch spike peak:** 41.8 / 42.7 mV. +* **Repetitive firing:** + * With the default levels, the HH patch fires a single onset spike up to 2.5 × threshold, and repetitive + firing starts between 2.5 × and 3 × (56.7 Hz at 3 ×, 112.8 Hz at 20 ×, 6.3 °C). + * With the quick levels, it starts between 2 × and 3 × (57.1 Hz at 3 ×). + * The HH adaptation index at 4 × threshold is −0.008 / −0.0007, so firing is essentially regular. +* **Convergence** (patch, 20 uA/cm^2 for 1 ms): + * RK4 first-spike times at dt 0.0125, 0.00625 and 0.003125 ms agree to 2.1e-9 ms, which is the + interpolation and rounding floor. + * Exponential Euler changes by 1.9e-4 and then 8.6e-5 ms, an observed order of 1.15. +* **Velocity** (40 mm cable, 18.5 °C): + * Quick (60 compartments, dt 0.005 ms): 9.23 / 13.15 / 18.65 m/s for 119 / 238 / 476 um. Log-log slope + 0.507. The 476 um axon is 0.79 % below HH's computed 18.8 m/s. + * 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. + * Relative change at dt/2 ≤ 4.7e-7. +* **Paired-pulse refractory estimate** (6.3 °C; 0.5 ms pulses; conditioning 2 ×, test 4 × the single-pulse + threshold of 13.3 uA/cm^2): 9.45–9.63 / 9.46–9.49 ms. +* **NEUROWEAVE cell** (descriptive): + * The threshold drive is 0.277 per step. + * Repetitive firing starts at 1.1 × (quick) or 1.5 × (default) threshold, earlier than in HH. + * The normalised rate saturates at 1.0 from 3 × (quick) or 3.5 × (default) threshold upwards. + * Spearman rank correlation with the HH curve over the suprathreshold levels is 0.839 / 0.858, and the + mean absolute difference of the normalised curves is 0.20 / 0.24. + * The adaptation index is 0.0, so firing is regular. + * Curves are identical across seeds (`seed_invariant: true`). + +The cable reproduces the two quantitative anchors it is checked against: the √diameter scaling of eqn 34, and +HH's computed velocity for their axon, to under 1 %. The abstract NEUROWEAVE cell has a monotone f-I curve of +broadly similar rank order. It fires repetitively closer to threshold than HH, its normalised rate saturates +early, and it shows no adaptation. These are shape observations only. diff --git a/docs/frontier/modules/joint_failure.md b/docs/frontier/modules/joint_failure.md new file mode 100644 index 0000000000000000000000000000000000000000..d4dfa868f150651847f873ac80f638951b91c435 --- /dev/null +++ b/docs/frontier/modules/joint_failure.md @@ -0,0 +1,307 @@ +# `joint_failure`: joint-failure ensemble selection + +Module file: `synapse/frontier/joint_failure.py` · tests: `tests/test_frontier_methodology.py` · +experiment ids: `joint_failure` (kind `selection_benchmark`) and `joint_failure_neuroweave` (kind +`selection_application`) · no live observer · evidence tier: `synthetic_abstraction`. + +The module chooses an odd-sized majority-vote **panel** of components from boolean failure observations +(component × condition × trial). It compares four selection rules and scores the frozen panels on held-out +trials. + +The module is *inspired by* FAULTLINE, a kai9987kai portfolio laboratory for correlated and higher-order +failures in small voting ensembles. The following follow FAULTLINE's design: + +* the four rules and their tie-breaking; +* the second factorial-moment pairwise bound; +* the 3-bit parity example. + +These parts are this module's own: + +* the NumPy array format; +* the seeded family generator with exact population errors; +* the three further constructed trap cases; +* the NEUROWEAVE application. + +It reproduces none of FAULTLINE's recorded numbers. + +## What it computes + +**Data.** `failures[i, c, t]` is true when component `i` is wrong on trial `t` of condition `c`. Every +condition has the same number of trials `T`. + +**Majority-vote error.** A panel `P` of odd size `k` votes by majority, with threshold `s = (k + 1) / 2`: + +``` +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 ] +``` + +* **Two labels.** With binary labels every wrong member votes for the single wrong label, so this is the + exact vote error. +* **More labels.** With more labels it is an upper bound on plurality-vote error. If fewer than `s` members + are wrong, the correct label has a strict majority. +* **Signatures.** `Err` depends only on the joint failure pattern of each trial. `failure_signatures` lists, + per condition, every distinct set of failing components with its count. These are the empirical failure + hyperedges, and the list includes the empty set. +* **Signature path.** `majority_error_from_signatures` recomputes `Err` from those counts alone. The tests + check it against the array computation on every 3-member panel of random correlated data. + +**Pairwise bound.** Since `1[W >= s] <= C(W, 2) / C(s, 2)`, taking expectations gives: + +``` +B(P | c) = sum_{i= Err(P | c) (k = 1: the individual error) +k = 3: B = Pr(W = 2) + 3 Pr(W = 3) but Err = Pr(W = 2) + Pr(W = 3) +``` + +A unanimous failure therefore counts three times in the pairwise score. This is FAULTLINE's argument for +why pairwise co-failure misranks panels with rare higher-order faults. + +**Selectors.** All four use calibration trials only. Every key is an integer count, so ties are exact. A tie +goes to the next key and finally to the lexicographically first panel. + +| policy | ranking key (minimised) | +|---|---| +| `accuracy` | `sum_{i in P}` individual failures (pooled individual error) | +| `pairwise` | worst-condition `B(P \| c)`, then `sum_c B(P \| c)`, then accuracy | +| `pooled` | pooled majority error, then worst-condition majority error, then accuracy | +| `joint` | worst-condition majority error `max_c Err(P \| c)`, then pooled, then accuracy | + +* **Equivalence to FAULTLINE.** With equal trials per condition, the sums over conditions are proportional + to FAULTLINE's pooled rates. The keys therefore match FAULTLINE's `core.select_panel`, which uses exact + fractions and breaks the last tie by component id order. +* **Tested against a direct implementation.** The tests compare every selector with a direct exact-fraction + re-implementation of those keys. They cover 12 random correlated arrays, `k ∈ {1, 3, 5}` and all four + policies. +* **`run_selection`.** It selects on calibration, freezes the panels and scores them on the held-out test + trials. It also reports an `oracle`: the panel with the lowest *test* worst-condition error. The oracle + is chosen on test data, so it is a reference, never a selector. +* **`evaluate_panel`.** It reports per-condition error, worst condition, pooled error, unanimous-failure rate + and the worst pairwise bound. +* **Bounds.** At most 24 components, 64 conditions, 100,000 trials, 5,000,000 cells and 100,000 candidate + panels. Panels are scored in chunks of at most 2,000,000 panel-condition-trial cells. Bad input raises + `ValueError` before any computation. + +## Constructed known-answer cases (`constructed_cases`, `check_constructed_cases`) + +| case | construction | known answer | +|---|---|---| +| `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** | +| `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 | +| `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 | +| `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) | + +* **In the receipt.** The nine named checks are recorded in every benchmark receipt as `constructed_checks`. +* **Further hand cases in the tests.** One has failing sets `{}, {0}, {0,1}, {1,2}, {0,1,2}`, where + `Err = 3/5` exactly and the pairwise sum is `5/5`. Another is a 5-member case. + +## Synthetic generator (`make_failure_data`) + +**Components and conditions.** There are `families × family_size` components (default 3 × 3 = 9), +shuffled per seed so that tie-breaking cannot favour a family. The conditions are `nominal` plus one +`stress_f` per family (default 4). + +* **`shared`.** + * Base error: family 0 (the "accurate" family) draws from `U(0.01, 0.03)`, the others from + `U(0.03, 0.07)`. + * In `stress_f`, family `f`'s stressor is active with probability `U(0.25, 0.40)`, drawn once per seed and + family. + * When active, it hits each member of family `f` with probability 0.85. +* **`independent`** (negative control). + * There is no stressor. Component `i` fails with `e_i · mu_c`, where `e_i ~ U(0.04, 0.16)`, `mu_0 = 1` and + `mu_c ~ U(1.0, 1.6)`. + * Every condition ranks the components identically. Poisson-binomial tails increase in each `p_i`, so the + `k` individually best components form the optimal panel in every condition. +* **`shift`** (unobserved common cause). + * Calibration is identical to `shared`. + * On held-out `nominal` trials a common cause is active with probability 0.6. It then hits each member of + a cross-family set with probability 0.9. + * With `shift_target='hardened'` (the default) the set is the lowest-base-error member of every family. + That is adversarial to diversity-based selection by construction. `'random'` draws one member per + family. + +**Population errors.** `expected_condition_errors(structure, panel, split)` gives the exact population +`Err(P | c)`. Given the state of the (at most one) channel acting in a condition, components fail +independently, so `Err` is a mixture of Poisson-binomial tails. The tests compare it with 40,000-trial +Monte Carlo (within 5 standard errors). + +**Digest.** Each dataset carries a SHA-256 digest of its packed arrays. + +## Benchmark (`run_experiment`, id `joint_failure`) + +* **Protocol.** For every seed and scenario, all four selectors see the same calibration trials and the same + `C(9, 3) = 84` candidate panels. The frozen panels are scored on fresh test trials. +* **Verdict.** `harness.compare` of joint vs accuracy held-out worst-condition error in the `shared` scenario + (lower is better). `improved` requires the paired 95 % t interval over seeds to exclude zero. +* **Also reported.** + * Joint vs pairwise and joint vs pooled (`shared`), and joint vs accuracy (`independent`, `shift`). + * The exact population error of every chosen panel. + * The oracle. + * The constructed checks. + * A budget: candidate panels, calibration component calls (`9 × 4 × T_cal`), `k` deployment calls per case + and 0 trainable parameters. +* **No capacity-matched control.** Every rule deploys `k` components with no trainable parameters and the + same calibration data, so the comparison is between selection rules at equal cost. +* **Sizes.** Defaults: `k = 3`, 64 calibration and 512 test trials per condition. `quick=True` uses 48 and 256. + Generator parameters can be overridden, and unknown keys raise `ValueError`. + +## NEUROWEAVE application (`run_neuroweave_application`, id `joint_failure_neuroweave`) + +* **Components.** Each component is a NEUROWEAVE engine that differs only in its mechanism set. Seed, + `clustered` topology, neuron count, training stream and head initialisation are shared. +* **Training.** Each engine is trained with the lab's `run_task_phase(learn=True)`, with one `ReadoutHead` + per task. The first task, `delayed_recall`, supplies the engine reward. +* **Conditions.** The four temporal tasks: `delayed_recall`, `xor`, `rhythm` and `context_switch`. Targets + are binary, so majority-of-failures equals majority-vote error exactly. +* **Failure recording.** Failures are recorded frozen (`learn=False`, cloned engines and head copies) on a + calibration stream (`seed + 50,000`) and a disjoint test stream (`seed + 60,000`). Training, calibration + and test stream seeds must be pairwise disjoint. +* **Verdict.** `harness.compare` of joint vs accuracy held-out worst-task error over seeds. +* **Mechanism sets.** `()`, `sparse_code`, `homeostatic_governor`, `astrocyte_regulation`, `multi_soma`, + `reward_plasticity` and `dendritic_compartments`. Quick mode uses the first five. + * **How they were chosen.** A decision-diversity probe on seed 99, which is not an evaluation seed. It + trained each single mechanism at 16 neurons for 120 steps and at 24 neurons for 160 steps (clustered + topology, one head per task) and ranked mechanisms by how many training-phase head decisions they changed + relative to the unmodified engine. Accuracy and selector outcomes played no part. The six sets are the + probe's top six, in rank order (244, 127, 116, 71, 66 and 62 changed decisions over both sizes). + * **Many mechanisms do nothing here.** 17 of the 45 single mechanisms changed no decision in that probe. + A re-run of the probe on 2026-11-20 gave the same ranking and the same 17. +* **Sizes.** Defaults: 7 sets, 24 neurons, 160 training / 96 calibration / 96 test steps. Quick: 5 sets, + 16 neurons, 120 / 32 / 32 steps. + +## Public API + +```python +POLICIES = ('accuracy', 'pairwise', 'pooled', 'joint'); SCENARIOS = ('shared', 'independent', 'shift') +validate_failures(failures, *, name='failures') -> bool ndarray (components, conditions, trials) +majority_threshold(panel_size) -> int +majority_error(failures, panel) -> ndarray (per condition) +pairwise_bound(failures, panel) -> ndarray (per condition) +failure_signatures(failures) -> list[dict]; majority_error_from_signatures(signatures, panel) -> ndarray +panel_scores(failures, panel_size) -> dict; evaluate_panel(failures, panel) -> dict +select_panels(failures, panel_size, policies=POLICIES) -> dict[str, tuple]; select_panel(failures, panel_size, policy) +run_selection(calibration, test, panel_size) -> dict # every policy + oracle, frozen panels on test +make_failure_data(seed, *, scenario='shared', **params) -> dict +expected_condition_errors(structure, panel, *, split='test') -> ndarray +constructed_cases() -> dict; check_constructed_cases() -> dict[str, bool] +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> sealed receipt +run_neuroweave_application(*, quick=False, seeds=(0, 1, 2), **overrides) -> sealed receipt +EXPERIMENTS = {'joint_failure': run_experiment, 'joint_failure_neuroweave': run_neuroweave_application} +``` + +Randomness comes only from `numpy.random.default_rng(seed + offset)`. The module never touches the global +NumPy RNG, never imports torch, and has no stateful observer or extension to export or import. + +## Connection to Sonapse + +* **What it consumes.** This is a methodology module. It does not attach to an engine or observe live + activity. It consumes failure arrays, so any set of Sonapse or NEUROWEAVE components with per-trial + correctness under named conditions can be compared. The application builds those arrays from per-task + readout correctness of differently configured engines. +* **What it uses.** The NEUROWEAVE lab helpers (`make_spec`, `ReadoutHead`, `run_task_phase`, + `clone_engine`, `make_stream`) and `synapse.frontier.harness` (`base_receipt`, `compare`, `seal`, + `TASKS`). +* **Scope.** It does not change any engine or any other module. + +## Differences from FAULTLINE and not implemented + +* **Data.** FAULTLINE reads `faultline-dataset-v1` JSON (ids, truth, predictions; 3–12 components; unequal + trials per condition allowed). This module takes boolean failure arrays with equal trials per condition + and up to 24 components. +* **Fixtures.** + * FAULTLINE's fixtures are 8 named sensor specialists with hand-designed regimes, driven by event-keyed + SHA-256 draws. They include `glare_surge` faults that hit five components at once and a latent clock + fault on a hardened triad. + * The generator here is parametric and has no composed higher-order faults. On it the `pairwise`, + `pooled` and `joint` rules chose the same panels in every measured seed of the `shared` scenario. + * Their differences are therefore shown only on the constructed traps. +* **Not implemented.** + * FAULTLINE's receipts and replay verifier, HTTP API, browser UI, test witnesses, bootstrap intervals and + dataset import. + * Plurality or weighted voting. + * Any defence against common causes absent from calibration. No rule here protects against them, and the + `shift` scenario exists to show that. + +## Source (portfolio) + +* **FAULTLINE: Joint-Failure Ensemble Selection Laboratory** (kai9987kai). + . +* **Files read.** In a read-only clone at commit `b7ae1b9` (24 October 2026), the following were read on + 2026-11-20: + * `README.md`; + * `docs/design.md` (design decision dated 24 October 2026); + * `PAPER.md` (dated 24 October 2026); + * `faultline/core.py` (selector keys and metrics); + * `faultline/fixtures.py` (scenarios and the parity demo). +* **Nothing executed.** No FAULTLINE code was run. +* **Not re-verified.** The literature FAULTLINE cites was not re-checked for this module and is not cited + here. + +## Measured results + +All numbers were measured on 2026-11-20 (UTC) on Windows 11 ARM64 with Python 3.12.10 and NumPy 2.4.3, with +`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`. Other agents shared the CPU, so wall-clock is +indicative only. Errors are held-out (test) majority-vote errors averaged over seeds `(0, 1, 2)`. "pop." is +the exact population worst-condition error of the chosen panels under the generator. + +**Benchmark, quick** (`run_experiment(quick=True)`: 9 components, 4 conditions, `k = 3`, 48 calibration and +256 test trials per condition). + +| scenario | accuracy | pairwise | pooled | joint | oracle | joint − accuracy, 95 % CI | +|---|---|---|---|---|---|---| +| `shared` | 0.160 (pop. 0.155) | 0.038 | 0.038 | 0.038 (pop. 0.029) | 0.021 | −0.122 [−0.387, +0.143] | +| `independent` | 0.030 (pop. 0.027) | 0.035 | 0.035 | 0.035 (pop. 0.034) | 0.022 | +0.005 [−0.010, +0.020] | +| `shift` | 0.398 (pop. 0.414) | 0.197 | 0.197 | 0.197 (pop. 0.197) | 0.027 | −0.202 [−0.756, +0.352] | + +* **Verdict.** **no_detectable_difference**. +* **Per-seed `shared` differences.** 0.000, −0.195 and −0.172. In seed 0 `accuracy` happened to pick the + same panel as the other rules. +* **Other values.** All 9 constructed checks pass. The digest prefix is `2ef7216676bbedb6` (identical across + separate processes). Wall-clock was 0.08–0.10 s. + +**Benchmark, default** (`run_experiment()`: 64 calibration and 512 test trials per condition). + +| scenario | accuracy | pairwise | pooled | joint | oracle | joint − accuracy, 95 % CI | +|---|---|---|---|---|---|---| +| `shared` | 0.258 (pop. 0.259) | 0.027 | 0.027 | 0.027 (pop. 0.028) | 0.023 | **−0.231 [−0.239, −0.224]** | +| `independent` | 0.029 (pop. 0.026) | 0.038 | 0.028 | 0.028 (pop. 0.028) | 0.025 | −0.001 [−0.004, +0.002] | +| `shift` | 0.327 (pop. 0.335) | 0.382 | 0.382 | 0.382 (pop. 0.373) | 0.029 | +0.055 [−0.977, +1.086] | + +* **Verdict.** **improved**: joint selection lowered held-out worst-condition error in `shared`. +* **Other values.** All 9 constructed checks pass. The digest prefix is `1bfc6d4ab8e769a7` (identical in two + separate runs). Wall-clock was 0.10–0.20 s. +* **Same panels.** `pairwise`, `pooled` and `joint` chose the same panel in every `shared` seed of the quick, + default and ten-seed runs. +* **Ten seeds.** A further run, `run_experiment(seeds=range(10))` at default size, gave these joint − + accuracy differences: + * `shared`: −0.224 [−0.243, −0.206], improved; + * `independent`: +0.002 [−0.007, +0.011]; + * `shift`: −0.023 [−0.236, +0.189]. + +**NEUROWEAVE application.** + +| | quick (5 sets, 16 neurons, 120/32/32 steps) | default (7 sets, 24 neurons, 160/96/96 steps) | +|---|---|---| +| verdict | **no_detectable_difference** | **no_detectable_difference** | +| 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) | +| 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 | +| best single component's worst-task error (per seed) | 0.438 / 0.563 / 0.500 | 0.365 / 0.583 / 0.469 | +| oracle panel's worst-task error (per seed; chosen on test data) | 0.594 / 0.563 / 0.500 | 0.469 / 0.583 / 0.469 | +| components with identical calibration failures (pairs) | 1 / 6 / 1 of 10 | 0 / 0 / 0 of 21 | +| mean pairwise calibration-failure agreement | 0.68 / 0.86 / 0.79 | 0.88 / 0.87 / 0.67 | +| a component's mean test accuracy over tasks (min–max over components and seeds) | 0.49–0.65 | 0.53–0.72 | +| digest (prefix) | `1f7709e86ceea33e` (identical across separate processes) | `6f1e1af36c5f24f6` (identical in separate runs) | +| measured wall-clock | 9.7–10.9 s | 25.2–27.9 s | + +Reading: + +* **Synthetic benchmark.** Joint-failure selection removes the shared-stressor failure mode that accuracy + selection walks into. The improvement shows at default size and over ten seeds. Quick mode is too small, + with 3 seeds and one tie. +* **Negative controls.** The independent control shows no difference, as it should. In the unobserved + common-cause scenario the advantage disappears: every rule is far from the oracle, and joint is not + significantly better or worse than accuracy. +* **What this generator cannot separate.** It does not distinguish `joint` from `pairwise` or `pooled`. +* **NEUROWEAVE.** The readouts are close to chance on most tasks and their failures are strongly correlated. + No selector beats another detectably. In all six measured seed runs (quick and default), even the oracle + panel was no better than the best single component on test worst-task error: worse in seed 0, equal in + seeds 1 and 2. These runs exercise the pipeline on real engine outputs; they are not evidence for any + mechanism or selector. diff --git a/docs/frontier/modules/kuramoto_binding.md b/docs/frontier/modules/kuramoto_binding.md new file mode 100644 index 0000000000000000000000000000000000000000..3ca08267f1cc4d26b79efd49c0a3cbac8fb34a51 --- /dev/null +++ b/docs/frontier/modules/kuramoto_binding.md @@ -0,0 +1,337 @@ +# `kuramoto_binding`: oscillatory binding units + +Module file: `synapse/frontier/kuramoto.py` · tests: `tests/test_frontier_kuramoto.py` · +experiment ids: `kuramoto_binding`, `kuramoto_binding_benchmark` · engine extension: `KuramotoExtension` · +live observer: `KuramotoObserver` · evidence tier: `synthetic_abstraction`. + +The module implements the discrete oscillator update of **Artificial Kuramoto Oscillatory Neurons** (AKOrN, +Miyato et al., ICLR 2025) and uses it in three small settings: + +* a NEUROWEAVE engine extension that adds synchrony features to the readout, +* a read-only live observer of unit activity, +* a synthetic binding benchmark with a known answer. + +It is *inspired by* AKOrN and does not reproduce it. Couplings here are fixed rather than learned. There are no +convolutional or attention couplings, no readout blocks and no training. None of the paper's tasks or results +(object discovery, adversarial robustness, calibration, Sudoku) are attempted. The oscillators are an abstract +computational device, not a model of neural oscillations. + +## What it computes + +**Oscillators.** Each oscillator is a unit vector `x_i` in `R^N`, with `N` even and `N = 2` by default. The +update is the paper's Eq. 2 in discrete form (Eqs. 4–5): + +``` +dx_i = Omega_i x_i + Proj_{x_i}( c_i + sum_j J_ij x_j ) Proj_x(y) = y - x +x_i <- Pi( x_i + gamma * dx_i ) Pi(v) = v / ||v|| +``` + +* `Omega_i` is antisymmetric: a natural-frequency block `[[0, -w], [w, 0]]` on each coordinate plane + `(2p, 2p+1)`. +* `c_i` is the conditional stimulus. +* `J_ij` is a scalar coupling (`J_ij * I_N`). A full `(C*N, C*N)` block matrix is also accepted, and + `kron(J, I_N)` gives exactly the scalar result (tested). +* `K` iterations run per call (`akorn_step`, `akorn_run`). + +Properties that are tested: + +* The projection is tangent (` = 0`) and idempotent, and every update returns unit rows. +* With `J = 0` and `c = 0`, each rotation plane advances by exactly `arctan(gamma * w)` per step. The plane + amplitudes change when frequencies differ. As `gamma -> 0`, the phase follows `dtheta/dt = w`. +* Uniform positive coupling `2/(C-1)` takes `R` from 0.05 to 1 (to `1 - 1e-9` with identical frequencies, and + above 0.99 with a 0.1 frequency spread, for both `N = 2` and `N = 4`). Uniform negative coupling drives + `R` below `1e-6`. +* 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 + increases by more than `1e-12` per step under the paper's Lyapunov conditions. Those conditions are symmetric + scalar couplings, a shared `Omega` (here 0) and `Omega c_i = 0`. The tested regime is `gamma = 0.1` with + `||J||_2 = 1`. + +**Measures.** + +* Order parameter `R = ||mean_i x_i||`, and per-group coherence `||mean_{i in g} x_i||`. +* Phase `atan2(x_1, x_0)`. This is the first rotation plane, which is exact for `N = 2`. +* Phase-locking value `|mean_t exp(i (phi_a - phi_b))|`. It is a time-averaged variant of the PLV of Lachaux + et al. (1999); the extension uses an exponentially weighted, bias-corrected average over engine steps. +* Phase-cluster count: the number of circular runs of *dense* bins in a 36-bin angle histogram. A bin is dense + when it holds at least 10 % of the oscillators. An incoherent population, or one with no sparse bin at all, + gives 0. A cluster smaller than about 20 % of the population can be missed if it straddles a bin edge. +* Shanahan (2010) indices from the community synchrony `phi_c(t)`, with the paper's sample variances: + * Metastability `lambda`: the mean over communities of `1/(T-1) sum_t (phi_c(t) - )^2`. + * Chimera index `chi`: the mean over time of `1/(M-1) sum_c (phi_c(t) - )^2`. + + The tests reproduce the paper's reference values: `sigma_chi = 2/7` for a "perfect" chimera state, + `chi_max = 1/7`, and `sigma_met -> 1/12` for uniformly distributed synchrony. +* Adjusted Rand index (Hubert & Arabie, 1985), implemented in NumPy from the contingency table. It returns 1 + for identical partitions, including the degenerate one-cluster and all-singleton cases. The tests check it + against hand cases (`24/99`, `-1/2`, `4/7`) and against a brute-force pair-counting formula. +* Seeded k-means with k-means++ seeding (Arthur & Vassilvitskii, 2007). It runs several restarts, and the + lowest inertia wins. + +## Engine extension (`KuramotoExtension`, id `kuramoto_binding`) + +```python +KuramotoExtension(seed=0, *, mode='region', units=16, dim=2, iterations=4, gamma=0.1, coupling_scale=1.0, + stimulus_scale=1.0, omega_mean=1.0, omega_spread=0.5, top_pairs=4, plv_rate=0.1) +``` + +**Oscillators.** In `mode='region'` there is one oscillator per NEUROWEAVE region (10). In `mode='units'` +there is one oscillator per unit, for `units` units sampled at `bind` with the extension seed. + +**Coupling (copied at `bind`).** The engine itself is not kept. + +* Synapse weights `brain.synapses.w` are summed over `src -> dst` into `J[group(dst), group(src)]`. +* Each row is divided by the size of its target group, which gives the mean input per target unit. +* The diagonal is zeroed, because self-coupling vanishes under the projection. +* `J` is scaled so that its largest absolute row sum equals `|coupling_scale|`. +* Inhibitory synapses give negative (anti-phase) couplings. +* `J` is a snapshot: later plasticity is not tracked. + +**Stimulus.** `c_g = stimulus_scale * m_g * u_g`, where `m_g` is the group's current mean output and `u_g` is a +fixed, seeded unit vector. + +**Dynamics.** Each engine step runs `iterations` AKOrN updates. Natural frequencies are +`omega_mean + omega_spread * N(0, 1)`, drawn per oscillator and plane. + +**Features.** There are `feature_dim = C + 1 + top_pairs` of them: **15** in region mode with the defaults. All +lie in `[-1, 1]`. + +1. `C` cosines between each oscillator and the global mean-field direction. These are 0 when `R` is about 0. + Like the other two blocks, they only see relative phases: rotating every oscillator by the same angle leaves + all features unchanged (tested to `1e-12`). +2. The global order parameter `R`. +3. The `top_pairs` largest pairwise PLVs, in descending order. + +**Rules.** + +* The extension only adds readout features. `transform_drive` is the neutral base method, and the tests check + that the engine's trajectory and exported state are bit-identical with and without it. +* It has no trainable parameters (`parameter_count() == 0`). It is therefore frozen when `ctx['learn']` is + false, and its oscillator state evolves the same way in both cases. +* It is deep-copyable. +* `export_state` and `import_state` round-trip exactly through JSON. `import_state` validates everything before + mutating: config, `n`, shapes, finiteness, unit norm, `|PLV| <= 1` and a zero coupling diagonal. +* Accessors return copies: `coupling_matrix()` and `states()`. +* `telemetry()` reports the order parameter, mean and max PLV, and coupling statistics. + +## Live observer (`KuramotoObserver`) + +```python +KuramotoObserver(n_units, *, seed=7, history=256, oscillators=64, dim=2, iterations=2, gamma=0.1, omega_mean=1.0, + omega_spread=0.3, fan_in=4, coupling=0.5, hebbian_rate=0.01, hebbian_scale=2.0, stimulus_scale=0.5, + communities=8, groups=None, bins=36, min_cluster_fraction=0.1, **spec_params) +KuramotoObserver.from_spec(n_units, spec: FrontierSpecV1, **params) # uses spec.seed and spec.history +``` + +**Oscillators and stimulus.** There are `M = min(oscillators, n_units)` oscillators, each driven by one +subsampled unit (seeded, sorted indices). The stimulus is `c_i = stimulus_scale * tanh(rate_i) * u_i`. + +**Coupling.** `J = J0 + hebbian_scale * H / sqrt(M - 1)`. + +* `J0` is fixed, seeded and sparse: `fan_in` partners per oscillator, each with weight `coupling / fan_in`. +* `H` is a slow Hebbian co-activity estimate, built as follows: + * Rates are standardised with a running EWMA mean and variance (rate 0.05) and clipped to ±3 sd. + * `S <- (1 - eta) S + eta z z^T` starts at the identity, a shrinkage prior. + * `H_ij = S_ij / sqrt(S_ii S_jj)` off the diagonal, so `|H| <= 1`. + + The tests check that `H` recovers a two-block correlation structure: above 0.95 within blocks, where the true + value is 0.99, and below 0.1 across blocks. They also check that `J - hebbian_scale * H / sqrt(M - 1)` stays + equal to the fixed `J0`. + +**Communities.** Shanahan's indices are computed over communities: contiguous blocks of the sampled unit order +(NEUROWEAVE regions are contiguous unit blocks), or the given `groups` labels. + +**`summary()` keys.** The summary is JSON-safe and contains no wall-clock. + +* Always present: `module`, `evidence_tier`, `observed_steps`, `history_len`, `history`, `oscillators`, `dim`, + `communities`, `hebbian_mean_abs` and `hebbian_max_abs`. +* `None` before the first observation: `R_last`, `R_mean` and `R_std` (the standard deviation of `R` over the + history, a metastability measure), `metastability_index`, `chimera_index`, `community_R_mean`, + `phase_clusters` (the latest histogram count) and `phase_clusters_mean`. + +**Rules.** + +* The observer copies its input and never writes to it. +* All buffers have a fixed size. +* `export_state` and `import_state` (schema `KuramotoObserverStateV1`) round-trip bit-exactly. Imports are fully + validated before any state changes. +* Unknown keyword parameters raise `ValueError`. `FrontierSpecV1` parameters meant for other observers + (`sync_pairs`, `sae_features`, `sae_k`, `fc_window`, `max_observed_units`, `observe_every`) are accepted and + ignored. + +## Binding benchmark (`run_binding_benchmark`, id `kuramoto_binding_benchmark`) + +**Task.** There are `groups` latent signals `s_g(t) ~ N(0, 1)`. Feature `i` of group `g` is +`a_i s_g(t) + noise * eps_i(t)`, with loading `a_i ~ U(0.5, 1.5)`. + +**Candidate coupling.** The Pearson correlation of the feature rows, minus the mean off-diagonal correlation +(a uniform inhibition), with a zero diagonal. It is scaled so that the largest absolute row sum equals +`coupling_scale` (2.0). + +**Dynamics.** The stimulus is `c_i = 0`, so binding comes from the coupling alone. Each seed draws its own +initial states and near-identical natural frequencies (`1 ± 0.05`), and all arms of that seed share them. + +**Readout.** Seeded k-means (`k = groups`) on the final unit vectors after `K` iterations, scored by the ARI +against the ground truth. The receipt also records the ARI at the checkpoints `0, K/8, K/4, K/2, K`. + +**Arms.** + +* `candidate`: the correlation coupling. +* `shuffled_control`: the same multiset of coupling values, permuted and kept symmetric. +* `zero_control`: no coupling. +* `reference_correlation_kmeans`: a non-oscillatory reference, k-means on the correlation rows. + +**Verdict.** The verdict is `harness.compare` (a paired 95 % t interval over seeds) of candidate against +shuffled-control ARI. The candidate and the shuffled control have the same coupling budget. + +**Defaults.** + +* Full: `groups=4, per_group=8, samples=256, dim=2, iterations=120, gamma=0.1`. +* Quick: `groups=3, per_group=6, samples=128`. + +**Diagnostics.** Per seed, the receipt reports: + +* `within_group_R`: the mean ground-truth group coherence. +* `global_R`. +* `max_group_cosine`: the largest cosine between two groups' mean-field directions. A value near 1 means two + groups ended up in phase. + +**Limitation (measured).** With symmetric scalar couplings, the between-group repulsion only constrains the +resultant of the group mean fields. Any arrangement whose resultant is zero is an equilibrium. For four or more +groups that includes two groups settling nearly in phase. The same happens for three groups whose latents are +correlated by chance in a short sample. Groups still synchronise internally (per-seed `within_group_R` between +0.89 and 1.00 in every cell of the sweep below), but the ARI drops, to 0.41 at worst. + +The table below is a pilot sweep: mean (min) ARI over seeds 0–9 at 120 iterations, with `noise = 1`. It was +measured on 2026-11-17 with the shipped coupling rule, and a second run later that day gave identical numbers +(the runs are deterministic). In the same sweep, the shuffled-coupling controls stayed within ±0.05 mean ARI +(largest magnitude 0.033). + +| groups × per_group, samples | N = 2 | N = 4 | N = 8 | +|---|---|---|---| +| 3 × 6, T = 48 | 0.902 (0.54) | 0.943 (0.60) | 0.948 (0.83) | +| 4 × 8, T = 64 | 0.705 (0.41) | 0.794 (0.58) | 0.791 (0.59) | +| 4 × 8, T = 256 | 0.910 (0.45) | 0.991 (0.91) | 1.000 (1.00) | +| 6 × 6, T = 128 | 0.749 (0.46) | 0.912 (0.77) | 0.916 (0.77) | + +Two things drive the result. More samples give more accurate couplings, and larger `N` gives more room to keep +groups apart. At `N = 2` with four groups (4 × 8, seeds 0–9), running longer does not help. At 120, 160, 200 and +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 +with `T = 512`: no upward trend. + +The task is also easy for direct clustering of the correlation matrix. Over the same seeds 0–9, the +non-oscillatory reference arm scored mean ARI 1.000 in every sweep cell except 3 × 6 with `T = 48`, where it +scored 0.983 (min 0.83). That is at or above the oscillators in every cell. The benchmark therefore tests that +the oscillator dynamics *implement* binding. It does not show that they beat conventional clustering. + +## Lab experiment (`run_experiment`, id `kuramoto_binding`) + +`harness.run_extension_experiment('kuramoto_binding', ...)` on the NEUROWEAVE `context_switch` task compares +three arms: + +* `baseline`: the unmodified engine and readout. +* `candidate`: `KuramotoExtension` with its 15 features. +* `control`: random leaky traces with the same feature count (the harness's `random_trace` control). + +All arms share seeds, streams and the readout protocol, and held-out streams are evaluated frozen. The headline +verdict requires a win over both the baseline and the capacity-matched control. Extension parameters and +harness run parameters (`task`, `steps`, `neurons`, ...) can be overridden. `quick=True` uses the harness quick +sizes: 24 neurons, 24 training steps, and one 12-step held-out stream. + +## Public API + +```python +MODULE_ID = 'kuramoto_binding'; BENCHMARK_ID = 'kuramoto_binding_benchmark' +EXPERIMENTS = {'kuramoto_binding': run_experiment, 'kuramoto_binding_benchmark': run_binding_benchmark} +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +run_binding_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +project_tangent(x, y); natural_frequency_matrices(frequencies, dim) +akorn_step(x, coupling=None, stimulus=None, omega=None, *, gamma=0.1) +akorn_run(x, coupling=None, stimulus=None, omega=None, *, gamma=0.1, iterations=16) +kuramoto_energy(x, coupling=None, stimulus=None); order_parameter(x); group_coherence(x, labels, n_groups=None) +phases(x); phase_locking_value(phase_a, phase_b); count_phase_clusters(phase, *, bins=36, min_fraction=0.1) +shanahan_indices(community_order); adjusted_rand_index(labels_true, labels_pred) +kmeans_labels(points, k, *, seed=0, restarts=8, max_iter=100) +make_binding_task(seed, *, groups=4, per_group=8, samples=64, noise=1.0) +correlation_coupling(features, *, scale=2.0, center=True); shuffle_coupling(coupling, seed) +``` + +All randomness comes from `numpy.random.default_rng(seed + offset)`. Every public function validates its input +and raises `ValueError` on bad input. + +## Connection to Sonapse + +* **Live observer.** `kuramoto_binding` is in `spec.OBSERVER_MODULE_IDS`, so a `FrontierSpecV1` can list it in + `modules`. The observer reads a copy of activity and never writes to the brain, graft bus, actor or any + shared RNG. This module does not wire it into the live runtime; the runtime hook lives elsewhere. +* **Engine extension.** It influences nothing unless it is attached to a NEUROWEAVE engine with + `attach_extension`, as in the lab experiment. Even when attached, it only adds readout features. +* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes. + +## Not implemented + +* Learned couplings, frequencies or step size. In the paper, `J`, `Omega` and `gamma` are learned per layer. +* Convolutional or attention connectivity, and multi-block AKOrN networks. +* The paper's readout block (norms of learned projections, Eq. 6). +* Training through the dynamics, and any of the paper's tasks or results. +* In the extension, couplings that track later synaptic plasticity: `J` is a snapshot taken at `bind`. +* A stimulus in the binding benchmark. A symmetry-breaking stimulus might resolve the group-collision + degeneracy described above, but it is not tested here. + +## Verified references + +Each reference below was checked on 2026-11-17 against the arXiv, conference, publisher, Crossref or PubMed +listing (checked twice that day, the second time in a separate session). On 2026-11-20 (review) the AKOrN +title, authors and update rule (Eq. 2, the projection, and the discrete Eqs. 4–5 with `Pi(x) = x / ||x||`) +were re-checked against the arXiv HTML of v3; `akorn_step` matches them. + +1. Takeru Miyato, Sindy Löwe, Andreas Geiger, Max Welling. **Artificial Kuramoto Oscillatory Neurons.** + *International Conference on Learning Representations (ICLR) 2025*, oral, held 24–28 April 2025 at the + Singapore EXPO. arXiv:2410.13821 (v1 17 October 2024, v2 14 February 2025, v3 16 May 2025; arXiv comment + "Accepted for Oral presentation at ICLR2025"). https://arxiv.org/abs/2410.13821 · + https://iclr.cc/virtual/2025/oral/31776. The update rule (Sec. 3 Eq. 2 and Sec. 4 Eqs. 4–5), the projection + `Proj_x(y) = y - x`, the energy and its Lyapunov conditions (Eq. 3: `J_ij = J_ij I` with + `J_ij = J_ji`, `Omega_i = Omega`, `Omega c_i = 0`), and the readout (Eq. 6) were checked against the paper's + method section (arXiv HTML of v3). +2. Murray Shanahan. **Metastable chimera states in community-structured oscillator networks.** + *Chaos* 20(1), 013108, March 2010 issue (published online 22 February 2010, per Crossref). + doi:10.1063/1.3305451, https://pubs.aip.org/aip/cha/article/20/1/013108/280633 · arXiv:0908.3881. The + definitions of `lambda` (variance over time with `1/(T-1)`) and `chi` (variance over communities with + `1/(M-1)`), and the reference values 1/12, 2/7 (eight communities, half fully synchronised) and 1/7, were + checked against the text of the arXiv PDF. +3. Jean-Philippe Lachaux, Eugenio Rodriguez, Jacques Martinerie, Francisco J. Varela. **Measuring phase + synchrony in brain signals.** *Human Brain Mapping* 8(4), 194–208, 1999 (PubMed Central lists the issue date + as 30 November 1999). doi:10.1002/(SICI)1097-0193(1999)8:4<194::AID-HBM4>3.0.CO;2-C, + https://pubmed.ncbi.nlm.nih.gov/10619414/ (PMID 10619414, PMC6873296). Only the bibliographic details and + the abstract were verified; the abstract names the method "phase-locking statistics". The full-text PLV + definition could not be opened in this build, so the module calls its measure a time-averaged *variant*. +4. Lawrence Hubert, Phipps Arabie. **Comparing partitions.** *Journal of Classification* 2(1), 193–218, + December 1985 (Crossref). doi:10.1007/BF01908075, https://link.springer.com/article/10.1007/BF01908075. +5. David Arthur, Sergei Vassilvitskii. **k-means++: the advantages of careful seeding.** *Proceedings of the + 18th ACM-SIAM Symposium on Discrete Algorithms (SODA '07)*, New Orleans, 7–9 January 2007, SIAM, + pp. 1027–1035. https://dl.acm.org/doi/10.5555/1283383.1283494. + +## Measured results + +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 +thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Receipts are deterministic: the same +arguments give the same digest, and every number below was reproduced exactly by a second run later the same +day. Wall-clock covers the whole call. It is given as the range over those two runs, because the machine was +shared with other jobs running in parallel. + +| Run | Seeds | Verdict | Key numbers | Wall-clock | +|---|---|---|---|---| +| `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 | +| `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 | +| `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 | +| `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 | +| `run_binding_benchmark(dim=4)` | 0, 1, 2 | `improved` | ARI: candidate 0.971 (min 0.914) / shuffled 0.050 | 0.25–0.39 s | +| `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 | + +On `context_switch` at these sizes, the synchrony features did not help the readout. The quick run is too short +for any arm to learn the task. The binding benchmark shows the mechanism working on a task with a known +partition: correlation-coupled oscillators synchronise by latent group, while shuffled and zero coupling stay at +chance. That is a statement about the dynamics on synthetic data only. + +**Observer cost.** One `observe()` with 256 units, 64 oscillators, `N = 2` and 2 iterations took 0.33–0.73 ms +(mean of 300 calls; range over two runs on the shared machine). A `summary()` is about +0.5 KB of JSON (529 bytes measured), and `export_state()` is about 143 KB of JSON with `history = 256`. diff --git a/docs/frontier/modules/morphogenesis.md b/docs/frontier/modules/morphogenesis.md new file mode 100644 index 0000000000000000000000000000000000000000..7de60aa3e1f085b13def9da026eb81fc40b936aa --- /dev/null +++ b/docs/frontier/modules/morphogenesis.md @@ -0,0 +1,182 @@ +# `morphogenesis`: developmental growth and regeneration of a connectome + +Module file: `synapse/frontier/morphogenesis.py` · tests: `tests/test_frontier_addons.py` · +experiment id: `morphogenesis` · kind: discovery (no engine extension, no live observer) · +evidence tier: `synthetic_abstraction`. + +The module grows a 2-D multi-cell body from a single seed cell (**organizer**) under a compact five-parameter +developmental program, converts the grown tissue into a valid `synapse.neuroweave.topology.Topology` connectome, +and studies **regeneration after lesions** with and without a stored **pattern memory** (plus a capacity-matched +shuffled-memory control). It is inspired by the user's `morpheus`, `prometheus-alpha`, `GenesisEngine` and `MOLT` +repositories (`kai9987kai`), by Growing Neural Cellular Automata (Mordvintsev, Randazzo, Niklasson & Levin, 2020), +and by the bioelectric pattern-memory perspective on regeneration (Pezzulo & Levin, 2015). + +This is a synthetic five-parameter growth-logit abstraction on a small grid, not a trained neural cellular +automaton or a biophysical tissue model. + +## What it computes + +**Developmental program (`DevelopmentalProgram`) and growth (`grow`).** A body lives on an $S \times S$ grid +($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)$. +At each developmental step ($2S$ steps by default): + +1. For every grid site $(y, x)$, define scaled coordinates relative to the organizer: + $$ + \Delta x = \frac{x - o_x}{S / 4}, \qquad \Delta y = \frac{y - o_y}{S / 4}, + $$ + and let $n(y, x) \in \{0, \dots, 8\}$ be the number of living 8-neighbours. +2. Evaluate the five-parameter growth logit $\theta = (\theta_0, \theta_1, \theta_2, \theta_3, \theta_4)$: + $$ + \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 + + \mathbf{1}_{\text{memory}}\, \alpha \left(2 M(y, x) - 1\right), + $$ + where $M(y, x) \in [0, 1]$ is the upsampled pattern-memory setpoint field (when present) and $\alpha \ge 0$ is + `memory.strength` (default `3.0`). +3. Draw an asynchronous stochastic update mask $U(y, x) \sim \mathrm{Bernoulli}(p_{\text{update}})$ (`p_update = 0.5`), + analogous to the per-cell stochastic update mask of Mordvintsev et al. (2020): + * an empty site with $n(y, x) > 0$, $\ell(y, x) > 0$, and $U(y, x) = 1$ becomes alive; + * a living non-organizer site with $\ell(y, x) < -\delta_{\text{death}}$ (`death_margin = 2.0`) and $U(y, x) = 1$ + dies (the organizer persists while alive). + +**Positional differentiation (`_assign_types`).** Living cells differentiate into four functional types by position +relative to the organizer (French-flag style) and map to NEUROWEAVE region indices: + +* `sensory` (`visual_sensory`, region `0`): $\Delta x < -1$; +* `action` (`premotor`, region `8`): $\Delta x > +1$; +* `memory` (`working_memory`, region `5`): $(\Delta x)^2 + (\Delta y)^2 \le 0.36$ (and $|\Delta x| \le 1$); +* `association` (`association_a`, region `3`): all remaining living sites. + +**Connectome conversion (`body_to_topology`).** Living cells become neurons in row-major order ($N$ neurons): + +* **Dale sign:** $\mathrm{sign}(y, x) = -1$ when $(7y + 13x) \bmod 5 = 0$ (~20 % inhibitory) and $+1$ otherwise, + pinned to grid coordinates so a regenerated site keeps its sign. +* **Directed edges** connect distinct cells within Euclidean distance $r$ (`radius = 1.5` by default) when: + * they have the **same** cell type (local recurrent), + * the source has strictly **lower** processing rank (`KIND_RANK`: `sensory < association < memory < action`) than + the target (feedforward), or + * the source has strictly **higher** rank and is a direct 4-neighbour ($d \le 1$, local feedback). +* **Delays and weights:** integer delay $1 + \mathbf{1}_{d > 1.5} + \mathbf{1}_{d > 2.5} \in \{1, 2, 3\}$; signed + weight $\mathrm{sign}_{\text{src}} \cdot \left(w_{\min} + w_{\text{span}} \cdot \mathrm{clip}(1 - (d - 1)/r, 0, 1)\right)$. + Every generated `Topology` passes `topo.validate()` (no self-loops, no duplicate edges, delays in `[1, 3]`, + weights matching source signs) and can be passed directly to `topology_metrics(topo)`. + +**Evolution (`evolve_program`).** A seeded $(1 + \lambda)$ evolution strategy (`generations=30`, `offspring=8`, +`sigma=0.4`) mutates $\theta$ with isotropic Gaussian perturbations clipped to $[-50, 50]$ to maximise intersection-over-union +(`iou`) with a target binary mask (`two_lobes`, `ellipse`, or `cross`). Ties keep the parent so fitness is +monotonically non-decreasing. + +**Lesion and regeneration (`lesion`, `make_memory`, `shuffled_memory`, `regrow`).** + +* `lesion(body, box)` clears all cells in `[r0:r1, c0:c1)`. +* `make_memory(body, block=2, strength=3.0)` stores a coarse setpoint map of shape $(S/b) \times (S/b)$ holding the + fractional occupancy of each $b \times b$ block (`0.5` is neutral inside $2M - 1$), plus the organizer coordinates + $(o_y, o_x)$ (`(S // b)**2 + 2` numbers in total). +* **Regrowth arms (`regrow`):** + 1. **`pattern_memory` (candidate):** restores the organizer coordinates from the stored pattern memory and biases + the growth logit by $\alpha (2M - 1)$. + 2. **`no_memory` (baseline):** runs the developmental program alone; if the lesion removed the organizer, the new + organizer is re-derived as the surviving cell nearest the centroid of surviving tissue. + 3. **`shuffled_memory` (capacity-matched control):** stores the exact same number of numbers (`PatternMemory.numbers`) + and total occupancy mass, with the block occupancies and organizer coordinates randomly permuted by a seeded + generator (`default_rng(seed + 141421)`). + +## Benchmark (`run_experiment`, `EXPERIMENTS = {'morphogenesis': run_experiment}`) + +For each seed (`seeds=(0, 1, 2)` by default): + +1. Evolve a `DevelopmentalProgram` towards `target_mask(target, size)` (`two_lobes` by default) and grow the intact + body and its connectome. +2. Apply `lesions_per_seed` random square lesions covering `lesion_fraction = 0.4` of the body's bounding box + (centred on randomly chosen living cells; some lesions remove the organizer, others spare it). +3. Regrow from each damaged state under `pattern_memory`, `no_memory`, and `shuffled_memory`, measuring: + * **`iou`**: mask IoU with the pre-lesion body (headline metric, higher is better); + * **`edge_jaccard`**: Jaccard similarity of position-keyed directed connectome edge sets; + * **`type_agreement`**: fraction of overlapping living cells that recover their pre-lesion cell type; + * **`metric_similarity`**: $1 - \text{mean relative gap}$ across connectome `density`, `clustering_mean`, + `modularity`, and `global_efficiency`. +4. Headline verdict uses `harness.headline_verdict(vs_no_memory, vs_shuffled_memory)`: `improved` requires a paired + 95 % t-interval win over **both** `no_memory` and `shuffled_memory`. + +| option | default | quick | +|---|---|---| +| grid size $S$ / target | 20 / `two_lobes` | 14 / `two_lobes` | +| ES generations / offspring $\lambda$ / $\sigma$ | 30 / 8 / 0.4 | 10 / 6 / 0.4 | +| lesions per seed / lesion fraction | 4 / 0.4 | 3 / 0.4 | +| memory block $b$ / strength $\alpha$ | 2 / 3.0 | 2 / 3.0 | +| pattern-memory numbers $(S/b)^2 + 2$ | 102 | 51 | + +## Public API + +```python +MODULE_ID = 'morphogenesis' +CELL_TYPES = ('sensory', 'association', 'memory', 'action') +TARGETS = ('two_lobes', 'ellipse', 'cross') +EXPERIMENTS = {'morphogenesis': run_experiment} + +DevelopmentalProgram(theta=(2.0, 1.0, -1.2, -1.2, 0.0), p_update=0.5, death_margin=2.0) +PatternMemory(setpoint, block, organizer, strength=3.0) + .field(size) -> np.ndarray (size, size) + .numbers -> int +Body(alive, cell_type, organizer) + .size -> int .cells -> int .copy() -> Body +target_mask(name, size) -> np.ndarray +grow(program, size, *, seed=0, steps=None) -> Body +lesion(body, box) -> Body +make_memory(body, *, block=2, strength=3.0) -> PatternMemory +shuffled_memory(memory, *, seed=0) -> PatternMemory +regrow(program, damaged, *, memory=None, seed=0, steps=None) -> Body +body_to_topology(body, *, radius=1.5, name='morphogenesis', seed=0) -> Topology +iou(a, b) -> float +edge_jaccard(body_a, body_b, *, radius=1.5) -> float +evolve_program(target, *, seed=0, generations=30, offspring=8, sigma=0.4, + growth_seed=0, steps=None) -> dict +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict +``` + +## Connection to Sonapse + +`body_to_topology` returns a validated `synapse.neuroweave.topology.Topology` with ten-region indexing and +Dale-signed weights, compatible with `topology_metrics` and with `NeuroWeaveEngine`. The module is default-off and +does not alter any existing `build_topology` generator. + +## Not implemented + +* **Differentiable multi-channel neural cellular automata** trained by backpropagation through time on RGBA images + (Mordvintsev et al., 2020). This module evolves a 5-parameter radial/neighbour growth logit with a $(1+\lambda)$-ES. +* **Explicit voltage-gated ion channels or gap-junction diffusion equations** for bioelectric pattern memory + (Pezzulo & Levin, 2015); the pattern memory is represented directly as a coarse spatial setpoint field plus the + organizer coordinates. +* **Activity-dependent synaptic plasticity during development.** Connectome weights come from geometry and cell-type + ranks after growth finishes. + +## Verified references + +* Alexander Mordvintsev, Ettore Randazzo, Eyvind Niklasson and Michael Levin. **Growing Neural Cellular Automata.** + *Distill* (published 11 February 2020). DOI [10.23915/distill.00023](https://doi.org/10.23915/distill.00023); + URL . + * **Checked on 2026-11-19:** single-seed growth on a 2-D grid, local neighbourhood perception, asynchronous + per-cell stochastic update mask, and regeneration experiments after rectangular lesions. +* Giovanni Pezzulo and Michael Levin. **Re-membering the body: applications of computational neuroscience to the + top-down control of regeneration of limbs and other complex organs.** *Integrative Biology* 7(12), 1487–1517 + (December 2015). DOI [10.1039/c5ib00221d](https://doi.org/10.1039/c5ib00221d); PMC4700597 (PMID 26571072). + * **Checked on 2026-11-19:** conceptualises regeneration as error-minimising remodelling guided by an encoded + target-morphology "pattern memory" distinct from local growth rules alone. +* Portfolio provenance: `kai9987kai/morpheus`, `kai9987kai/prometheus-alpha`, `kai9987kai/GenesisEngine`, and + `kai9987kai/MOLT`, inspected in the local read-only portfolio clones on 2026-11-19. + +## Measured results + +Measured on **2026-11-19** with `seeds=(0, 1, 2)` on one CPU thread (`OPENBLAS_NUM_THREADS=1`). + +| 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`) | +|---|---|---|---|---|---|---|---|---|---| +| `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`) | +| `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`) | + +In both modes `pattern_memory` restores 100 % cell-type agreement on overlapping tissue and beats the +capacity-matched `shuffled_memory` control with a wide margin (`improved`). At `quick=False` ($20 \times 20$), +several random lesions spare the organizer cell, allowing the developmental rule alone (`no_memory`) to regrow +most of the symmetrical shape (mean IoU 0.9358 vs 0.9739 with pattern memory), so across 3 seeds the paired 95 % t +interval against `no_memory` spans zero (`[-0.2242, +0.3004]`, `no_detectable_difference`). When a lesion removes +the organizer, `no_memory` shifts the organizer to the centroid of surviving tissue and systematically misplaces +cell-type poles (`test_regrowth_with_pattern_memory_recovers_better_after_losing_the_organizer`). diff --git a/docs/frontier/modules/muon_optimizer.md b/docs/frontier/modules/muon_optimizer.md new file mode 100644 index 0000000000000000000000000000000000000000..c6dce74705ceac709d1601aef68c1072ce307834 --- /dev/null +++ b/docs/frontier/modules/muon_optimizer.md @@ -0,0 +1,259 @@ +# `muon_optimizer`: orthogonalised-momentum optimiser (Muon) + +Module file: `synapse/frontier/muon.py` · tests: `tests/test_frontier_optim.py` · +experiment id: `muon_optimizer` · kind: `tool` (an optimiser plus a benchmark; no engine extension, no live +observer) · evidence tier: `synthetic_abstraction`. + +The module implements a **Muon**-style optimiser (MomentUm Orthogonalized by Newton–Schulz) for matrix +parameters, with an internal **AdamW** for everything else, in one `torch.optim.Optimizer` +(`MuonWithAuxAdam`). It is *inspired by* Jordan et al. (2024), whose blog post and reference code define the +algorithm, and by Liu et al. (2025), whose update scale and decoupled weight decay it uses. It also provides +`make_graft_optimizer`, the opt-in optimiser for Sonapse's live neural graft +(`FrontierSpecV1(graft_optimizer='muon')`), and a small benchmark of Muon against Adam on the graft's own +architecture. Nothing here reproduces a published training result, and no speed or scale claim is made. + +## What it computes + +For a 2-D parameter `W` of shape `A × B` with gradient `G_t`, momentum `mu`, learning rate `lr` and weight decay +`wd`, one step is: + +``` +M_t = mu * M_{t-1} + (1 - mu) * G_t momentum (EMA form of Jordan's code: lerp) +U_t = (1 - mu) * G_t + mu * M_t Nesterov input (U_t = M_t with nesterov=False) +X_0 = U_t / (||U_t||_F + 1e-7) Frobenius normalisation: singular values in (0, 1] +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 +W_t = W_{t-1} - lr * (0.2 * sqrt(max(A, B)) * X_5 + wd * W_{t-1}) (Liu et al., Eq. 4) +``` + +* **Orientation.** The iteration runs on the wide orientation of the matrix (transposed when `A > B`), as in + the reference code, so the Gram matrix is the smaller one. +* **What Newton–Schulz returns.** It keeps the singular vectors of `U_t` and maps every singular value `s` of + `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 + scalar map on a dense grid (2,000,001 points, recomputed on 2026-11-20) gives outputs in + `[0.6818, 1.1344]` for every start `s >= 0.01` and in `(0, 1.2024]` for every `s` in `(0, 1]`; the tests check + this band on random matrices and the exact scalar map on a matrix with a known SVD. +* **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 + form above is the same sequence multiplied by `1 - mu`, and the Frobenius normalisation removes that factor + (up to the `1e-7`), so both give the same update. +* **Update scale.** `update_scale * sqrt(max(A, B))` with `update_scale = 0.2` (Liu et al., Eq. 4). It lets the + Muon part and the AdamW part share one learning rate. Jordan's reference code scales by + `max(1, A / B) ** 0.5` instead and uses separate learning rates for the two parts; that variant is not + implemented. +* **Other shapes.** A parameter with more than two dimensions that is routed to Muon is flattened to + `(shape[0], -1)`, as the reference code does for convolution filters, and `max(A, B)` is taken on the flattened + shape. +* **AdamW part.** Every parameter not routed to Muon (biases, norm gains, embeddings, output heads, other + shapes) is updated with the arithmetic of `torch.optim.AdamW`'s single-tensor path, in the same order + (decoupled decay, bias-corrected moments; defaults `betas = (0.9, 0.999)`, `eps = 1e-8`). A test checks that + vector parameters follow `torch.optim.AdamW` bit for bit. +* **Overflow.** When the squares of finite entries overflow the Frobenius norm, the matrix is first divided by + its largest absolute entry (the reference code would return zeros there). The update is invariant to the + gradient's scale, which a test checks up to a gradient scale of `1e25`. + +**Atomic steps.** `step()` computes the whole update first. A non-finite gradient, or an update that would make +a parameter or a state tensor non-finite, raises `ValueError` and changes no parameter and no state, the Muon +part included. Sparse gradients are refused. `load_state_dict` validates the group layout, the routing of every +parameter (`use_muon`), the hyper-parameters, the state keys, shapes, dtypes and finiteness, and +`exp_avg_sq >= 0`, before it changes anything, and then loads a private deep copy. + +## Parameter routing + +* `MuonWithAuxAdam(params, ...)` accepts an `nn.Module` (routed by `muon_param_groups`), an iterable of tensors + (2-D tensors go to Muon, the rest to AdamW) or group dicts. A group may set `use_muon` explicitly (`True` needs + at least 2 dimensions) and override any hyper-parameter. Groups added later with `add_param_group` are + validated the same way. Sets are refused because their order is not deterministic. +* `muon_param_groups(module, *, aux_modules=(), **hyper)` puts every 2-D parameter on Muon except + `nn.Embedding` / `nn.EmbeddingBag` weights and parameters owned by `aux_modules`; everything else goes to + AdamW. Jordan et al. recommend AdamW for embeddings, classifier heads, input layers and scalar or vector + parameters; Liu et al. use AdamW for the norm, LM-head and embedding parameters. +* `make_graft_optimizer(params_or_module, kind='adam', lr=3e-4, *, heads_on_adam=True, inputs_on_adam=None, + **muon_options)`: + * `kind='adam'` returns exactly `torch.optim.Adam(params, lr=lr)`, the graft's existing optimiser (a test + checks identical trajectories and state); any other option is refused. + * `kind='muon'` on a module with the graft's structure (`actor_encoder`, `value` and `dynamics` + `nn.Sequential` paths plus `actor_head`) keeps the three output layers (`graft_output_layers`: the actor head + and the last linear layer of the value and dynamics paths) and the three input layers + (`graft_input_layers`: the first linear layer of each path) on AdamW, which leaves Muon the three + hidden-to-hidden matrices. This follows Jordan et al., who write that input and output parameters should be + optimised with AdamW even though they are 2-D. `inputs_on_adam=None` (the default) means `True` for a + graft-structured module and `False` for any other module or a parameter iterable, where input layers cannot + be identified; `inputs_on_adam=False` puts the graft's input layers on Muon as well (the routing ablation + below); `inputs_on_adam=True` on a non-graft module is refused. + +| routing on the graft network | matrices on Muon | numbers on Muon / AdamW (hidden 32) | (hidden 64) | +|---|---|---|---| +| `kind='muon'` (default, the live opt-in) | the 3 hidden-to-hidden matrices | 3,072 / 19,221 | 12,288 / 38,421 | +| `kind='muon', inputs_on_adam=False` (ablation) | the 3 input + 3 hidden matrices | 21,344 / 949 | 48,832 / 1,877 | + +*Review fix (2026-11-20).* Until this review the live opt-in used the second row (input layers on Muon), which +contradicts both sources' guidance and measured worse than Adam in this module's own benchmark (see *Measured +results*); the default is now the first row. + +## Benchmark (`run_experiment`) + +* **Architecture.** `synapse.neural_graft._ResidualNetwork` (the live graft's network: policy, value and + dynamics heads), built inside `torch.random.fork_rng` and then re-initialised from a private + `torch.Generator`, so the global torch RNG is left as it was. +* **Task.** Teacher–student regression. Inputs are shaped like the graft's: a 256-wide state (155 observation + values and 64 feature values from `N(0, 1)`, 5 baseline-action and 32 prior values from `U(-1, 1)`, clipped to + `[-5, 5]`), the 155 observation values for the value head and observation plus a 5-wide action for the + dynamics head. A fixed, never-trained teacher of the same architecture, with every linear layer (the actor + head included) at `teacher_gain = 2` times PyTorch's default initialisation range, gives the targets, which + are standardised per output with the training split's mean and standard deviation. +* **Student and training.** Every arm trains the same student initialisation (PyTorch's default + `nn.Linear` distribution and the architecture's zero actor head) on the same minibatch sequence for the same + number of steps, with the graft's loss form (the sum of the three heads' MSE) and gradient-norm clipping at 1. +* **Arms.** `adam`: `torch.optim.Adam` (with `weight_decay > 0`, `torch.optim.AdamW` with the same decay as + the Muon arms); `muon`: `make_graft_optimizer(kind='muon')`, the routing the live opt-in uses (input and + output layers on AdamW); `muon_with_inputs` (the routing ablation, `routing_ablation=True`): + `inputs_on_adam=False`, the input layers on Muon too. Both Muon arms use the same `heads_on_adam`. +* **Learning rate.** For every arm separately, the learning rate is chosen from `lr_grid` by the lowest mean + validation MSE over seeds. The receipt flags a choice at the edge of the grid + (`selected_at_grid_edge`) and lists every run, so a grid that is too narrow is visible. +* **Verdict.** `harness.compare` (paired 95 % t interval over seeds, lower is better) of held-out test MSE, + `muon` minus `adam`, at the selected learning rates. `muon_with_inputs` minus `adam` is reported as a + secondary comparison and does not set the verdict. If an arm diverges at its selected learning rate, the + basis becomes `training_diverged_at_selected_lr` (paired statistics drop non-finite pairs, so a divergence is + never hidden). +* **Receipt.** `config` (every option), `parameter_routing` (parameter names, counts and shapes per arm), + `arms` (selected learning rate, the grid of mean validation MSE with diverged seeds, per-seed results with + per-head test MSE and optimiser state size, every run), `comparisons`, `verdict`, `verdict_basis`, `budget` + (parameters, steps and runs, Muon/AdamW split and optimiser state numbers per arm), `estimated_cost` + (analytic forward–backward and Newton–Schulz FLOPs per step) kept apart from `measured_wallclock_s`, the + teacher's raw output scale and `notes`. + +| setting | quick | default | +|---|---|---| +| hidden width, parameters | 32, 22,293 | 64, 50,709 | +| train / val / test examples | 512 / 256 / 256 | 2048 / 512 / 1024 | +| steps × batch | 40 × 128 | 300 × 128 | +| `lr_grid` | 1e-3, 1e-2 | 3e-4, 1e-3, 3e-3, 1e-2, 3e-2 | +| momentum, Nesterov, Newton–Schulz steps, weight decay | 0.95, yes, 5, 0 | same | + +## Public API + +```python +MODULE_ID = 'muon_optimizer' +NS_COEFFICIENTS = (3.4445, -4.7750, 2.0315) +ARMS = ('adam', 'muon', 'muon_with_inputs') +EXPERIMENTS = {'muon_optimizer': run_experiment} +DEFAULT_CONFIG, QUICK_CONFIG # benchmark options (overridable by keyword) + +zeropower_via_newtonschulz5(matrix, steps=5, eps=1e-7) -> torch.Tensor +MuonWithAuxAdam(params, lr=1e-3, *, momentum=0.95, nesterov=True, ns_steps=5, weight_decay=0.0, + betas=(0.9, 0.999), eps=1e-8, update_scale=0.2) + .step(closure=None) .add_param_group(group) .load_state_dict(state) .state_dict() + .muon_parameters() .adam_parameters() .state_numbers() +muon_param_groups(module, *, aux_modules=(), **hyper) -> list[dict] +graft_output_layers(network) -> tuple[nn.Module, ...] +graft_input_layers(network) -> tuple[nn.Module, ...] +make_graft_optimizer(params_or_module, kind='adam', lr=3e-4, *, heads_on_adam=True, inputs_on_adam=None, + **muon_options) -> torch.optim.Optimizer +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +``` + +Every constructor and function validates its input and raises `ValueError` on bad input. The benchmark draws +data from `numpy.random.default_rng(seed + offset)` and weights from private `torch.Generator` objects, runs +PyTorch on one thread and restores the caller's thread count; a test checks that the global torch RNG state and +the thread count are unchanged after a run. + +## Connection to Sonapse + +* `FrontierSpecV1.graft_optimizer` defaults to `'adam'`: the live neural graft keeps `torch.optim.Adam`, and its + checkpoint settings stay free of an `optimizer_kind` entry, so nothing changes by default. +* With `graft_optimizer='muon'`, `NeuralResidualGraft` builds its optimiser with + `make_graft_optimizer(network, kind='muon', lr=learning_rate)`, that is, the `muon` routing above (input + layers, output heads and vectors on AdamW; the hidden-to-hidden matrices on Muon). Its checkpoints record the + optimiser kind and refuse to load into an Adam graft. A Muon-graft checkpoint written before the 2026-11-20 + routing fix stores the old routing and is refused by `load_state_dict`'s routing check. +* The benchmark measures that routing (`muon` arm) and the alternative with the input layers on Muon; see + *Measured results* before choosing the opt-in. + +## Not implemented, and differences from the sources + +* **Precision and hardware.** The reference code runs Newton–Schulz in bfloat16 on GPUs. Here it runs in float32 + (float64 for float64 inputs) on the CPU. No speed, memory or scale benefit is claimed. +* **Scale and learning rates.** Liu et al.'s `0.2 sqrt(max(A, B))` scale with one shared learning rate is used. + Jordan's `max(1, A / B) ** 0.5` scale with separate learning rates (Muon 0.02, Adam 3e-4 in the reference + `MuonWithAuxAdam`, whose Adam part uses `betas = (0.9, 0.95)` and `eps = 1e-10`) is not. +* **Not attempted.** Distributed or sharded orthogonalisation, the language-model and speed-run benchmarks of + both sources, other Newton–Schulz coefficient schedules, and learning-rate schedules (the benchmark uses a + constant learning rate). +* **Benchmark scope.** One synthetic teacher–student task on one small architecture, with a short training + budget. It does not show how Muon behaves on the live graft, whose targets come from executed transitions. + +## Measured results + +Measured on **2026-11-20**, Windows 11 on ARM64, Python 3.12.10, torch 2.11 CPU, NumPy 2.4, +`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1` (the benchmark also runs torch on one thread). The machine +was shared with other jobs, so wall-clock is indicative only. Seeds 0, 1, 2. Test MSE is the mean over the three +heads of the MSE on standardised targets (a constant prediction scores about 1); lower is better. + +**Quick** (`run_experiment(quick=True)`; digest `fe48c4d94d312b14`, identical in two calls; 14.3 s): + +| Arm | Selected lr | Held-out test MSE (per seed) | Mean | +|---|---|---|---:| +| `adam` | 1e-2 (grid edge) | 0.3895, 0.4110, 0.4056 | 0.4020 | +| `muon` (input and output layers on AdamW) | 1e-2 (grid edge) | 0.3880, 0.3999, 0.4081 | 0.3987 | +| `muon_with_inputs` (input layers on Muon) | 1e-2 (grid edge) | 0.5432, 0.5858, 0.5516 | 0.5602 | + +* `muon − adam`: −0.0034, 95 % CI [−0.0207, +0.0140] → **`no_detectable_difference`** (verdict). + `muon_with_inputs − adam`: +0.1582, CI [+0.1212, +0.1952] (`worse`). +* The quick grid has two values and every arm picked its upper edge; quick mode is a pipeline check, not + evidence. + +**Default** (`run_experiment()`; digest `c23a6ae52d6e23c7`; 207.6 s, of which 49.5 / 70.8 / 82.9 s were the 15 +`adam` / `muon` / `muon_with_inputs` runs): + +| Arm | Selected lr | Held-out test MSE (per seed) | Mean | Per head: policy / value / dynamics | Optimiser state numbers | +|---|---|---|---:|---|---:| +| `adam` | 1e-3 | 0.2668, 0.2761, 0.2797 | 0.2742 | 0.174 / 0.163 / 0.485 | 101,418 | +| `muon` | 1e-3 | 0.2628, 0.2707, 0.2726 | 0.2687 | 0.164 / 0.157 / 0.486 | 89,130 | +| `muon_with_inputs` | 3e-3 | 0.3351, 0.3420, 0.3507 | 0.3426 | 0.212 / 0.234 / 0.582 | 52,586 | + +* `muon − adam`: −0.0055, 95 % CI [−0.0094, −0.0016] → **`improved`** (verdict): about 2 % lower test MSE, + from the policy and value heads; the dynamics head is unchanged. No arm selected a learning rate at the edge + of the five-value grid, and no run diverged. +* `muon_with_inputs − adam`: +0.0684, CI [+0.0622, +0.0746] (`worse`). +* Analytic cost per step (`estimated_cost`, not measured): forward–backward 38.5 MFLOP; Newton–Schulz + 23.6 MFLOP for `muon` and 78.2 MFLOP for `muon_with_inputs`. + +**How to read this.** The `muon` routing was changed during the 2026-11-20 review, after both routings had +been measured: before the fix the candidate arm put the input layers on Muon and the input-layers-on-AdamW +routing was the ablation (then called `muon_hidden_only`). The receipts from before the fix (quick digest +`2aa131161a125fc2`, default `bab33558fdf5241c`, both run on 2026-11-20) contain the same per-seed numbers with +the two Muon arms swapped and gave the verdict `worse`. The change follows the routing both sources prescribe +(input and output layers on AdamW), not the result, but the order of events is stated here so the verdict can +be weighed accordingly. The effect is small, on one synthetic teacher–student task with three seeds and a +short budget; it is no evidence about the live graft. What the benchmark does show clearly, at both sizes, is +that putting the graft's input layers on Muon hurts. + +Unit tests with known answers (`tests/test_frontier_optim.py`, Muon part): the Newton–Schulz output on a +matrix with a known SVD equals the scalar map `p^5` applied to its normalised singular values; the singular +value band on random matrices; scale invariance up to a gradient scale of `1e25`; one hand-computed Muon step +(momentum, Nesterov input, scale `0.2 sqrt(max(A, B))`, decoupled decay); the AdamW part equal to +`torch.optim.AdamW` bit for bit; `make_graft_optimizer('adam')` equal to `torch.optim.Adam`; the graft +routing (default and ablation); atomic refusal of non-finite steps; `load_state_dict` validation before any +change; and a sealed, deterministic receipt that leaves the global torch RNG and thread count unchanged. + +## Verified references + +* Keller Jordan, Yuchen Jin, Vlado Boza, Jiacheng You, Franz Cesista, Laker Newhouse, Jeremy Bernstein. + **Muon: An optimizer for hidden layers in neural networks.** Blog post, 8 December 2024. + . Checked on 2026-11-20: the coefficients + `(3.4445, -4.7750, 2.0315)`, the replacement of `G` by `G / ||G||_F` before the iteration, Nesterov-style + momentum as the default, and AdamW for scalar and vector parameters, input and output layers, embeddings and + classifier heads. +* Reference code: (`muon.py`), read on 2026-11-20: + `zeropower_via_newtonschulz5` (bfloat16, transpose when rows > cols, Frobenius normalisation with `1e-7`), + `muon_update` (`momentum.lerp_(grad, 1 - beta)`, Nesterov `grad.lerp_(momentum, beta)`, the + `max(1, rows / cols) ** 0.5` scale, defaults `beta = 0.95`, `ns_steps = 5`), decoupled weight decay + `p.mul_(1 - lr * wd)`, and the `MuonWithAuxAdam` defaults quoted above. +* 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, Zhilin Yang. **Muon is Scalable for LLM Training.** Technical report, arXiv:2502.16982 + (v1, 24 February 2025). . Checked on 2026-11-20 against the arXiv listing + and the HTML text: Eq. 1 (Muon with `M_t = mu M_{t-1} + grad`), Eq. 3 (weight decay), Eq. 4 (the + `0.2 · O_t · sqrt(max(A, B))` scale), momentum 0.95 "same as Jordan et al.", the Nesterov-style input, and + AdamW for the non-matrix parameters (RMSNorm, LM head, embeddings). diff --git a/docs/frontier/modules/nir_export.md b/docs/frontier/modules/nir_export.md new file mode 100644 index 0000000000000000000000000000000000000000..3e63ba3cfeffcb17845512d99836f2fd5679dc21 --- /dev/null +++ b/docs/frontier/modules/nir_export.md @@ -0,0 +1,220 @@ +# `nir_export`: NIR-style interchange export of NEUROWEAVE brains + +Module file: `synapse/frontier/nir_export.py` · tests: `tests/test_frontier_biophysics.py` · +experiment id: `nir_export` (`kind: 'validation'`) · no observer, no engine extension · +evidence tier: `synthetic_abstraction`. + +The module exports a NEUROWEAVE brain as a graph in the style of the **Neuromorphic Intermediate +Representation** (NIR, Pedersen et al., *Nature Communications* 2024). It uses NIR's node types and the +parameter names of the `nir` Python package. It is *inspired by* NIR and follows its primitives. It does not +claim equivalence with any NIR backend or hardware, and it has not been run on one. + +The export is a **lossy approximation** of the abstract NEUROWEAVE cell. Every feature that cannot be +represented is listed in the graph metadata and in the receipt. + +## Graph format + +``` +{'nodes': {name: {'type': , 'params': {field: value}}}, # values are nested float lists + 'edges': [[src, dst], ...], # incoming edges are summed + 'metadata': {...}} # optional; ignored by equality +``` + +Handled node types and fields (same names as the `nir` dataclasses): `Input(shape)`, `Output(shape)`, +`Affine(weight, bias)`, `Linear(weight)`, `Scale(scale)`, `Delay(delay)`, `I(r)`, +`IF(r, v_threshold, v_reset)`, `LI(tau, r, v_leak)`, `LIF(tau, r, v_leak, v_threshold, v_reset)`, +`CubaLI(tau_syn, tau_mem, r, v_leak, w_in)` and +`CubaLIF(tau_syn, tau_mem, r, v_leak, v_threshold, v_reset, w_in)`. Weights are `(out, in)` matrices. + +## What it computes + +**Layout of `brain_to_nir(source, *, input_dim=None, step_ms=1.0)`.** `source` can be a `NeuroWeaveBrain`, a +`NeuroWeaveEngine`, or either one's `export_state()` dict. The exporter works on a validated private copy and +never mutates the source (tested). + +``` +input (Input, d) -> input_projection (Linear, n x d) -> cells (CubaLIF or LIF, n) -> output (Output, n) +for each synaptic delay class k (steps): + cells -> delay_k (Delay, k * step_ms) -> recurrent_k (Linear, n x n) -> cells +``` + +* `input_projection` is the exact linear part of `brain.project_input`. It is computed column by column on a + copy with FlyHash switched off, because FlyHash is nonlinear. +* `recurrent_k[dst, src]` holds `0.52 * w` summed over the synapses with delay `k`, where `0.52` is the + recurrent gain of the fast channel. Static gains are folded into `w` when their mechanisms are on: int8 + quantisation, region-pair route gains, myelin gain `0.85 + 0.25 * myelin`, and structural source weights. + The recurrent weights are a frozen snapshot of the synapse table. +* `delay_k` holds the delay in ms. Without `synaptic_delays` there is a single class `k = 1`, the one-step + recurrence of the engine. That class also breaks the recurrent loop in the simulator. + +**Cell mapping (`cell_parameters`).** The constants come from `CellPopulation.step` in +`synapse/neuroweave/cells.py`. A per-step decay maps to a time constant by the zero-order-hold relation +`tau = -dt / ln(decay)`: + +| NEUROWEAVE (per step) | NIR parameter | +|---|---| +| `fast = 0.58 fast + u + 0.52 I_rec` | `CubaLIF` current: `tau_syn = -dt / ln 0.58`, `w_in = 1 / (1 - 0.58)` | +| `membrane = 0.78 membrane + 0.22 (0.84 fast) - 0.06 adaptation` | `tau_mem = -dt / ln 0.78`, `r = 0.84`, `v_leak = 0` | +| spike when `membrane > threshold`, `threshold = 0.53` at rest | `v_threshold = 0.53` | +| `membrane <- 0.26 membrane` at a spike | `v_reset = 0.26 * 0.53` (closest constant) | + +Cells without `membrane_dynamics` become `LIF` on the fast channel: `tau = -dt / ln 0.58`, +`r = 1 / (1 - 0.58)`, and `v_threshold = atanh(0.53) / 0.84`, the fast level at which `tanh(0.84 fast)` +crosses 0.53. The source never resets the fast channel, so `v_reset = v_threshold`. + +**Lossy features (`unrepresentable_features`).** Each entry gives `feature`, `kind` and `treatment` +(`approximated`, `dropped` or `frozen_snapshot`) with a reason. The entries are: + +* Always: graded `tanh` output transmission (NIR edges from a spiking node carry 0/1 spikes), the direct 0.16 + recurrent feed-through, the readout head, input clipping, and runtime controls. +* With `membrane_dynamics`: the multiplicative reset, the refractory hold, the adaptive threshold and + adaptation current, and calcium feedback. +* Without `membrane_dynamics`: the threshold on the graded output and the absence of reset in the source. +* Every enabled neuron mechanism (multi-soma, dendrites, sparse code, ...) and state-dependent connectome gain. +* Plasticity rules, exported as a `frozen_snapshot` of current weights. +* Engine-level mechanisms outside the brain graph. + +**Validation (`validate_graph`).** The checks are: + +* known node types with exactly the expected parameter fields, and finite parameters; +* consistent 1-D parameter vectors and 2-D weights, positive time constants and non-negative delays; +* edge endpoints that exist, and no duplicate edges; +* no edges into an `Input` or out of an `Output`; +* matching shapes along every edge, and at least one `Input` and one `Output`. + +The function returns a report (`valid`, `errors`, `warnings`, counts and node types). It never raises on a bad +graph. + +**Serialisation (`write_nir`, `read_nir`).** With `backend='auto'`, the module writes a real NIR file with +`nir.write` and reads it back with `nir.read`, but only if the optional `nir` package imports. Otherwise it +writes JSON tagged `'format': 'nir-json-fallback'`. `backend='json'` forces the fallback, and `'nir'` requires +the package. `read_nir` detects the format from the HDF5 signature. Either path reports whether the read-back +graph equals the written one: same node names and types, the same parameter values compared exactly, and the +same edge set. + +**Simulator (`simulate_graph`).** A small NumPy discrete-time simulator for the node types above. It uses the +zero-order-hold forms of the NIR equations: + +* `LI`/`LIF`: `v <- a v + (1 - a)(v_leak + r x)` with `a = exp(-dt / tau)`. +* `Cuba*`: `i <- a_s i + (1 - a_s) w_in x`, then `v` as above, driven by `r i`. +* Spiking types emit `v > v_threshold` and reset to `v_reset`. The simulator checks the membrane potential + before reset so numerical overflow appears in the `finite` result even when the output spike is finite. +* `Delay` outputs its input from `round(delay / dt)` steps earlier. Delays of at least one step break + recurrent loops; a loop without one raises `ValueError`. + +**Experiment (`run_experiment`).** Each seed builds a brain with `make_spec`, by default 48 neurons on the +`clustered` topology with `membrane_dynamics`, `synaptic_delays`, `quantised_synapses` and `stdp`. It runs +warm-up steps on seeded inputs, then exports, validates, writes and reads back a file, and simulates the +exported graph. The checks, all of which must hold for `verdict: 'pass'`: + +* `graph_valid`, `node_types_known`. +* `round_trip_equal`, `edge_and_node_counts_preserved`. +* `synapse_count_matches`: the non-zero recurrent entries equal the represented count, which is at most the + number of unique `(src, dst, delay)` triples. +* `recurrent_drive_parity`: the exported Delay/Linear pairs, applied to NEUROWEAVE's own output history, + reproduce `SynapseTable.transmit` within `1e-9`. This check does not apply, and is recorded as such, when + state-dependent gains are on. +* `synaptic_current_parity`: isolated cells, with no recurrent input and the same random drive. The exported + current equals the fast channel within `1e-9`. +* `membrane_parity_before_first_spike`: the exported membrane equals NEUROWEAVE's membrane minus its + accumulated adaptation current (a dropped feature, corrected for explicitly) within `1e-9`, up to each + cell's first spike. +* `simulation_finite`, `simulation_active` (at least one spike). +* `lossy_features_listed`. + +The spike rates of the exported graph and of NEUROWEAVE on the same inputs, and the first-spike agreement of +isolated cells, are reported side by side as descriptive numbers. They are not expected to agree, because of +the listed approximations. + +## Public API + +```python +MODULE_ID = 'nir_export'; EXPERIMENTS = {'nir_export': run_experiment} +FALLBACK_FORMAT = 'nir-json-fallback'; NIR_FORMAT = 'nir-hdf5' +NODE_PARAMS; NIR_NODE_TYPES; NEURON_TYPES; SPIKING_TYPES; CELL_CONSTANTS +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed validation receipt +brain_to_nir(source, *, input_dim=None, step_ms=1.0) -> dict +cell_parameters(model, *, dt=1.0) -> dict # model in ('CubaLIF', 'LIF') +unrepresentable_features(source) -> list[dict] +validate_graph(graph) -> dict; node_io_shapes(name, node, errors=None) +canonical_graph(graph, *, include_metadata=True) -> dict; graphs_equal(a, b) -> bool +write_nir(graph, path, *, backend='auto') -> dict; read_nir(path) -> dict; nir_status() -> dict +simulate_graph(graph, inputs, *, dt=None, record_states=False, max_steps=100_000) -> dict +``` + +The `run_experiment` overrides are `neurons`, `topology`, `mechanisms`, `warmup_steps`, `simulate_steps`, +`input_dim`, `input_scale`, `step_ms`, `parity_cells`, `parity_steps`, `parity_drive_max`, +`parity_tolerance` and `backend`. `quick=True` sets 24 neurons, 30 warm-up steps, 80 simulated steps, and 8 +parity cells for 80 steps. + +All randomness comes from `numpy.random.default_rng(seed + offset)`. No global NumPy or torch RNG or thread +state is touched (tested). Bad input raises `ValueError` before anything is written. Graph and file sizes are +bounded (4096 nodes, 65 536 edges, 4 M parameter elements per field, 100 000 simulated steps). + +## Connection to Sonapse + +* An offline tool. It reads a brain, an engine or their exports and never writes back. Nothing in the live + runtime calls it, and no Sonapse or NEUROWEAVE default, API or checkpoint format changes. +* `nir` is an optional dependency. It is imported lazily, and a broken install falls back to JSON. + +## Not implemented + +* **The real-NIR path is untested here.** The `nir` package is not installed in this build, so `nir.write`, + `nir.read`, the conversion to `nir.NIRGraph` and NIR's own type checking of this recurrent graph have not + been exercised. The test `test_real_nir_round_trip` is skipped. The conversion code follows the field names + verified in the package source (see below). +* NIR's other primitives: `Conv1d`, `Conv2d`, `Flatten`, `SumPool2d`, `AvgPool2d` and `Threshold`. + Multi-dimensional shapes are also not handled. +* Exact representation of the NEUROWEAVE cell. Graded transmission, multiplicative reset, refractoriness, the + adaptive threshold and every listed mechanism are approximated or dropped. Plasticity is not representable + in NIR and is exported as a frozen snapshot. +* Continuous-time semantics. The simulator is a zero-order-hold discretisation with the step `dt`, and NIR + backends may integrate differently. +* Importing a NIR graph back into a NEUROWEAVE brain. + +## Verified references + +Checked on 2026-11-20. + +1. Jens E. Pedersen, Steven Abreu, Matthias Jobst, Gregor Lenz, Vittorio Fra, Felix Christian Bauer, Dylan + Richard Muir, Peng Zhou, Bernhard Vogginger, Kade Heckel, Gianvito Urgese, Sadasivan Shankar, Terrence C. + Stewart, Sadique Sheik, Jason K. Eshraghian. **Neuromorphic intermediate representation: A unified + instruction set for interoperable brain-inspired computing.** *Nature Communications* 15, 8122, published + 16 September 2024 (PubMed Central). doi:10.1038/s41467-024-52259-9, + https://www.nature.com/articles/s41467-024-52259-9, https://pmc.ncbi.nlm.nih.gov/articles/PMC11405706/. + Preprint: arXiv:2311.14641. Title, author order, volume, article number and date were checked on the PMC + page. The base primitives (Input, Output, Affine, Convolution, Delay, Flatten, Integrator, Leaky + integrator, Linear, Scale, Spike) and the higher-order IF, LIF and CuBa-LIF were checked against the + paper's primitives table on the same page. (OSTI lists 15 September 2024.) +2. NIR Python package, https://github.com/neuromorphs/NIR, main branch, checked on 2026-11-20: + * `nir/ir/neuron.py`: field names and order of `I`, `IF`, `LI`, `LIF`, `CubaLI`, `CubaLIF`, and the + documented dynamics `tau dv/dt = (v_leak - v) + R I` and `tau_syn dI/dt = -I + w_in S`. + * `nir/ir/linear.py`: `Affine(weight, bias)`, `Linear(weight)`, `Scale(scale)`, with the output size taken + from `weight.shape[-2]`. + * `nir/ir/delay.py`: `Delay(delay)` with `y(t) = x(t - tau)`. + * `nir/ir/graph.py`: `Input(input_type)`, `Output(output_type)`, and `NIRGraph(nodes, edges)` with type + checking on by default. + * `nir/serialization.py`: `write(filename, graph, compression='gzip', ...)` and + `read(filename, type_check=True)`, using HDF5 through `h5py`. + * PyPI https://pypi.org/project/nir/ lists release 1.0.8 (6 July 2026) as the latest. + +## Measured results + +Measured on 2026-11-20 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP thread +(`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`), without the `nir` package, so the JSON fallback +was used. Seeds were 0, 1 and 2. Receipts are deterministic: two runs of the quick receipt gave the same digest +(tested). Wall-clock covers the whole call on a machine shared with other jobs. + +| Run | Verdict | Key numbers | Wall-clock | +|---|---|---|---| +| `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 | +| `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 | + +Cell parameters at `dt = 1 ms`: `tau_syn = 1.836`, `tau_mem = 4.025`, `r = 0.84`, `w_in = 2.381`, +`v_threshold = 0.53`, `v_reset = 0.1378`. + +The parity checks show that the parts called exact (linear input map, recurrent synapse table, synaptic +current, and the membrane up to the dropped adaptation current) are exact to rounding. The network-level spike +rates differ widely between the exported graph and NEUROWEAVE. This is expected: NIR edges carry binary spikes +where NEUROWEAVE transmits a graded `tanh` output, and refractoriness and the adaptive threshold are dropped. +The export is an interchange format with documented losses, not a faithful re-implementation. diff --git a/docs/frontier/modules/quality_diversity.md b/docs/frontier/modules/quality_diversity.md new file mode 100644 index 0000000000000000000000000000000000000000..7d4fabac7e7f0dff19c0fa1a42b4aa512fe93415 --- /dev/null +++ b/docs/frontier/modules/quality_diversity.md @@ -0,0 +1,439 @@ +# `quality_diversity`: quality-diversity architecture search + +Module file: `synapse/frontier/quality_diversity.py` · tests: `tests/test_frontier_quality_diversity.py` · +experiment id: `quality_diversity` · kind: discovery (a search over NEUROWEAVE configurations; no live observer) · +evidence tier: `synthetic_abstraction`. + +The module searches a small, declared space of NEUROWEAVE configurations with a **MAP-Elites** archive (Mouret & +Clune, 2015): a grid over two behaviour descriptors that keeps the best configuration found in each cell. Parents +are drawn from the **Darwin Gödel Machine** (DGM) parent distribution (Zhang et al., 2025), which favours fit +elites that have few verified children. Every candidate passes a **verification gate** before it may enter the +archive: its sealed receipt must verify and match what the search asked for, and every k-th candidate is run again +and must reproduce the same receipt digest. Rejected candidates are logged with reasons, every evaluated candidate +is a node of a lineage DAG, and the archive exports to JSON with a SHA-256 integrity hash. + +The design also borrows from two sibling `kai9987kai` projects. SONAPSE-ORIGIN contributes a 2-D MAP-Elites grid +with edge-clipped bins, NSGA-II Pareto sorting, and mutation plus crossover. sonapse-evo contributes structural +operators with preconditions, audit receipts, a failure archive with reasons, and verify-before-commit +transactions. + +The module is *inspired by* these sources and reproduces none of them. DGM evolves self-modifying coding agents +that are checked on coding benchmarks. Here each candidate is a tiny NEUROWEAVE engine (16–32 neurons) trained for +16–48 steps on a synthetic temporal task, and a run evaluates 5–48 candidates per arm. + +## What it computes + +### Genome and search space + +``` +genome = (mechanisms ⊆ M, topology ∈ T, neurons ∈ N, sparsity ∈ S) +M = 10 NEUROWEAVE switches (SEARCH_MECHANISMS): structural_encoder, sparse_code, reward_plasticity, + synaptic_delays, homeostatic_governor, context_attention, flyhash_projection, adaptive_routing, + hierarchical_temporal_memory, membrane_dynamics +T = all 12 NEUROWEAVE topologies (synapse.neuroweave.spec.TOPOLOGIES) +N = (16, 24, 32) neurons S = (0.05, 0.15, 0.3, 0.5) k-winners-take-all fraction +|space| = 2^10 · 12 · 3 · 4 = 147,456 genomes +``` + +`Genome.to_spec(seed=, steps=)` is the NEUROWEAVE lab spec (`experiments.make_spec`) with the genome's `sparsity`. +The sparsity gene only acts when `sparse_code` is on. Without it, two genomes that differ only in sparsity give +identical metrics and descriptors but different specs, so their receipt digests differ (tested). Genomes are +canonical: mechanisms are kept in NEUROWEAVE order, and `Genome.key` (canonical JSON) identifies duplicates. + +Measured on 2026-11-20 (16 neurons, `clustered`, 16 training steps, held-out seed 100 × 8 steps): + +* five of the ten switches change the estimated operation count of a training run (17,840 with no switch): + `structural_encoder` +3,072, `adaptive_routing` +2,848, `context_attention` +2,048, `flyhash_projection` +2,048 + and `sparse_code` +1,024; the other five change nothing; +* topology changes it too (15,872 to 21,200 with no switch); +* log2 ops per training step is 10.12 / 10.68 / 11.06 at 16 / 24 / 32 neurons (no switch, `clustered`). + +### Variation (sonapse-evo style operators) + +| Operator | Precondition | Change | +|---|---|---| +| `toggle_mechanism` | the space has a mechanism | flips one search-set mechanism on or off | +| `swap_mechanism` | 1 ≤ active < \|M\| | replaces one active mechanism with an inactive one | +| `change_topology` | ≥ 2 topologies | a different topology, uniformly | +| `step_neurons` | ≥ 2 neuron choices | an adjacent neuron count | +| `step_sparsity` | ≥ 2 sparsity choices | an adjacent k-WTA fraction | + +`mutate` applies one applicable operator chosen uniformly. It then applies each further operator with +probability `extra_prob` (0.25), up to `max_operators` (3). A child that equals its parent (for example, the same +mechanism toggled twice) gets one more change, so a child always differs from its parent. Each change is logged +as an operator string, for example `toggle_mechanism:+sparse_code` or `step_neurons:16->24`; the tests replay these +trails and recover the child exactly. `crossover` is uniform: each mechanism's membership, and each other gene, +comes from either parent with probability 1/2. + +### Evaluation, fitness and descriptors + +`NeuroWeaveEvaluator(task, steps, heldout_seeds, heldout_steps)` follows the protocol of the lab's +`experiments._task_arm`: + +* **Training.** A fresh engine is built from the genome's spec. It and a fresh `ReadoutHead` (logistic, learning + rate 0.05) run prequentially, with learning on, over `make_stream(seed, steps)`. +* **Held out.** For each held-out seed `h`, the trained engine and a copy of the head run frozen (`learn=False`) + over `make_stream(h, heldout_steps)`. Every stream starts from the trained state: a validated clone runs every + stream except the last, and the trained engine itself runs the last. An `ActivityRecorder` is attached to each. + +At `sparsity = 0.15` (the spec default), the metrics, estimated cost and budget equal `_task_arm`'s exactly +(tested). The recorder is a read-only engine extension: it adds no readout features and leaves the drive +untouched. Engine outputs and the engine's state digest are identical with and without it (tested). + +``` +fitness f = mean held-out accuracy (ties: lower mean held-out log loss, then earlier) +d_cost = log2( estimated_cost.total_ops / training steps ) (from the candidate's own receipt) +d_activity = mean over held-out steps t of H(y_t), H(x) = (√n − ‖x‖₁ / ‖x‖₂) / (√n − 1) (Hoyer, 2004) +``` + +`y_t` is the engine output vector. `H` is 1 for a single non-zero entry and 0 for equal magnitudes. All-zero +steps are skipped (H is undefined there) and counted as `silent_steps`; a run with no scored step counts as 1.0. +Each candidate's result is a sealed receipt (`experiment_id 'quality_diversity_candidate'`, `kind +'candidate_evaluation'`) with the genome, seed, spec, protocol, train and held-out metrics, activity statistics, +estimated cost, budget, fitness and descriptors. Wall-clock is kept outside the digest. + +Measured on 2026-11-20 (same settings as above): without `sparse_code` the outputs are dense, with `d_activity` +0.0008 (0.0000 to 0.0796 across the 12 topologies). With `sparse_code`, `d_activity` is 0.829 / 0.741 / 0.507 / +0.339 at sparsity 0.05 / 0.15 / 0.3 / 0.5. In this space the activity axis therefore mostly sorts `sparse_code` +genomes by their k-WTA fraction. + +`LandscapeEvaluator(target, space)` is a deterministic synthetic evaluator with a known answer, used by the tests. +It runs no NEUROWEAVE engine. Fitness is the fraction of genes equal to a hidden target genome, so the target is +the unique optimum with fitness 1. Its descriptors are analytic: ops per step `16 · neurons · (4 + #mechanisms)`, +and activity `1 − sparsity` with `sparse_code` or 0.05 without. + +### Archive (MAP-Elites grid) + +``` +cell(d) = ( bin(d_cost; lo_c, hi_c, B_c), bin(d_activity; lo_a, hi_a, B_a) ) +bin(v) = clip( ⌊(v − lo) / (hi − lo) · B⌋, 0, B − 1 ) # out-of-range values join the edge cells +admit x' into cell b' iff b' is empty or (f', −loss') > (f, −loss) of the elite in b' +``` + +This is the replacement rule of the paper's Fig. 2 (`P(b′) = ∅ or P(b′) < p′`), with log loss as tie-break. +Exact ties keep the earlier elite. The invariant is that each cell holds the verified candidate with the highest +`(f, −loss)` among all verified candidates that mapped to it. It is tested against a brute-force map of a +32-genome space, and checked again on import by replaying the lineage. + +### Parent selection (DGM) + +``` +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 +``` + +* **Eligibility.** The distribution is taken over elites with `f_i < 1`, as in DGM. When every elite has + `f_i = 1`, all elites are eligible: this fallback is ours, because DGM does not define that case. DGM writes + the normaliser `Σ_j` over the whole archive while sampling from the eligible set; we normalise over the + eligible set, so the probabilities sum to 1. +* **Values.** `λ = 10` and `f_0 = 0.5` are DGM's values. `n_i` is the number of the elite's children that passed + verification; DGM counts children that kept their codebase-editing functionality. +* **Drawing parents.** DGM samples `k` parents with replacement, and each makes its own child. Here each variation + step draws two parents with replacement and makes one child. With probability `crossover_rate` (0.25), and only + when the two are distinct elites, the child is `mutate(crossover(a, b))`; otherwise it is `mutate(a)`. + +`selection='uniform'` gives the paper's uniform random choice of elite and serves as the ablation. The first +`initial_random` candidates (G in the paper) are random genomes. Up to `max_resample` (16) proposals are drawn to +avoid re-proposing a genome that was already evaluated. + +### Verification gate + +`verify_candidate(genome, receipt, seed=, protocol=, space=)` never raises for a bad receipt. It returns the +failed reason codes, and an empty list means the candidate passed. Each check is made against what the search +asked for, not against the receipt itself. + +| Reason | Meaning | +|---|---| +| `receipt_not_a_mapping` | the evaluator returned something other than a mapping | +| `receipt_digest_mismatch` | the SHA-256 seal does not verify (edited after sealing) | +| `receipt_schema_mismatch` | schema, experiment id, kind, evidence tier or module differ | +| `genome_outside_space` | the genome is outside the declared space | +| `genome_mismatch` | the receipt's genome is not the proposed one | +| `protocol_mismatch` | the protocol or the seed differ from the search's | +| `invalid_spec` | the receipt's spec is not a valid `NeuroWeaveSpecV1` | +| `spec_mismatch` | the spec is valid but is not the spec the genome implies | +| `invalid_metrics` | fitness or descriptor source fields are missing or out of range | +| `inconsistent_metrics` | the stated fitness or descriptors differ from those recomputed from the raw fields | +| `evaluation_error` | the evaluator raised; the message is logged, truncated to 200 characters | +| `spot_check_digest_mismatch` | the re-evaluation produced a different digest | +| `spot_check_error` | the re-evaluation raised | + +**Spot checks.** With `spot_check_every = k` (default 4), candidates number k, 2k, 3k, … (in evaluation order) +that pass the static checks are evaluated again. The re-run calls the evaluator itself, never the cache, and must +reproduce the receipt digest. `k = 0` disables spot checks; it exists only as an ablation. + +**Rejection.** A rejected candidate goes into the lineage and the rejection log. The grid and the child counts are +untouched. + +What the gate catches (tested): + +* receipts edited after sealing; +* re-sealed receipts whose stated fitness disagrees with their raw metrics; +* wrong specs, genomes, protocols and seeds; +* evaluator exceptions. + +A *consistently* re-sealed lie passes every static check. Only a re-evaluation catches it, and only on candidates +that are spot-checked. In the tests, inflated answers were all rejected with `spot_check_every = 1`. With +`spot_check_every = 0` they were admitted, and a later `audit()`, which re-evaluates every elite, flagged them. A +SHA-256 seal detects accidental or naive edits; it is not a signature. + +### Lineage, persistence and metrics + +* **Lineage.** Every evaluated candidate is a node with: id, genome, origin (`random` / `mutation` / + `crossover`), parents, operator trail, status (`elite` / `not_elite` / `rejected`), reasons, error, cell, + fitness, log loss, descriptors, receipt digest, `spot_checked` and `displaced_by`. A child's parents were + elites when it was created, so the lineage is a DAG in id order. It is bounded by the evaluation budget + (`max_nodes`). +* **Export.** `export_json()` writes canonical JSON: + `{schema: 'QualityDiversityArchiveV1', schema_version: 1, sha256, payload}`. The payload holds the grid + configuration, the elites with their sealed receipts (wall-clock removed, so exports are deterministic), the + lineage and the rejection log. `sha256` is the SHA-256 of the canonical payload (sorted keys, compact + separators). +* **Import.** `import_json()` / `EliteArchive.from_json()` validate everything before changing anything: + * the hash, the schema and the grid configuration; + * every lineage node; + * a full replay of the lineage, which must reproduce each node's status and `displaced_by`, the grid and the + rejection log; + * every elite's receipt, which must verify and match its entry and its lineage node. + + Eighteen tamper cases are tested, and none changes the target archive. +* **Metrics.** + * QD-score is the total fitness over filled cells (Pugh et al., 2015). Coverage is filled cells over grid cells. + * Reliability, precision and `coverage_of_union` (Mouret & Clune, 2015, Sec. 5 and 9.4) are computed per seed + over the union of cells that either arm filled. + * Our convention: a filled cell whose best value is 0 counts with ratio 1. The paper instead divides by the + number of cells with a non-zero best value, and takes the best over all runs of all treatments, not over + the two arms of one seed. + * The summary also lists the Pareto front of the elites in (fitness, −log2 ops per step), cheapest first. This + is the sibling projects' multi-objective view of the same archive. + +## Lab experiment (`run_experiment`, id `quality_diversity`) + +The two arms are `quality_diversity` (MAP-Elites with DGM selection) and `random_search`. Per seed they share: + +* the evaluator: the task, the training stream `seed` and the held-out streams; +* the search space, the grid, the verification gate and the spot-check schedule; +* the candidate budget. + +Their first `initial_random` candidates are identical (common random numbers). Those candidates are evaluated once +through a per-seed cache, which the spot checks bypass. After the search, each arm's best elite is re-evaluated on +fresh `test_seeds` streams (`best_test`), because `best_fitness` is selected on the held-out streams and is +therefore optimistic. + +* **Metrics per arm and seed.** `qd_score`, `coverage`, `best_fitness`, `best_test_accuracy`, `reliability`, + `precision` and `coverage_of_union`. +* **Comparisons.** `harness.compare` of QD − random for every metric, paired over seeds. +* **Verdict.** The `qd_score` comparison: `improved` only when the 95 % t interval excludes zero on the better + side. + +| Setting | Default | `quick=True` | +|---|---|---| +| task | `delayed_recall` | same | +| training / held-out steps | 48 / 24 | 16 / 8 | +| held-out seeds / test seeds | (100, 101) / (200, 201) | (100,) / (200,) | +| candidates per arm per seed (`budget`) | 16 | 5 | +| `initial_random` / `spot_check_every` | 6 / 4 | 3 / 2 | +| neurons | (16, 24, 32) | (16,) | +| grid | 4 × 4; cost (10.0, 12.0), activity (0.0, 0.8) | cost (10.1, 10.8) | +| selection / `crossover_rate` / `extra_mutation_prob` | DGM (λ 10, f₀ 0.5) / 0.25 / 0.25 | same | + +`delayed_recall` is the default task because it separated genomes best in a scan on 2026-11-20. The scan covered +10 random genomes from the default space (drawn with `default_rng(0)`; seed 0; 48 training steps; held-out seeds +100 and 101 × 24 steps): + +| Task | Distinct held-out accuracies | sd (population) | Best / majority-class rate | +|---|---|---|---| +| `delayed_recall` | 6 | 0.075 | 0.604 / 0.583 | +| `xor` | 4 | 0.062 | 0.688 / 0.542 | +| `parity` | 3 | 0.028 | 0.521 / 0.500 | +| `delayed_recall_6` | 2 | 0.115 | 0.625 / 0.625 | +| `rhythm` | 1 (all genomes equal) | 0 | 0.792 / 0.792 | +| `context_switch` | 1 (all genomes equal) | 0 | 0.500 / 0.542 | + +Even on `delayed_recall` the best value (0.604) was close to the majority-class rate (0.583). On `xor` the best +genome rose further above its majority-class rate (0.688 vs 0.542) but the accuracies took fewer distinct values; +the choice of default task was made on the number of distinct values only. + +The receipt (`kind: 'search_comparison'`) contains: + +* `config`, with the space, grid, evaluator protocol and admission rule; +* per-seed rows for each arm: evaluations, spot checks, evaluator calls, cache hits, status counts, rejections by + reason, QD-score and coverage trajectories, elites with their candidate-receipt digests, the best elite, + `best_test`, the Pareto front, lineage statistics and the archive SHA-256; +* `comparisons`, `verdict` and `verdict_basis`; +* `budget`: equal candidate budgets and counted evaluator calls; +* `estimated_cost`: the estimated ops of the verified candidates, kept apart from `measured_wallclock_s`; +* `notes`. + +Candidate digests are stored as `receipt_digest`, because receipt seals skip keys named `digest`. + +## Public API + +```python +MODULE_ID = 'quality_diversity' +EXPERIMENTS = {'quality_diversity': run_experiment} +run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict # overrides: any _DEFAULTS key + +SEARCH_MECHANISMS, NEURON_CHOICES, SPARSITY_CHOICES, MUTATION_OPERATORS, REJECTION_REASONS, DESCRIPTOR_KEYS, +ARCHIVE_SCHEMA, CANDIDATE_RECEIPT_ID, MAX_BUDGET, SOURCE + +Genome(mechanisms, topology, neurons, sparsity) .to_dict() / .from_dict(d) / .key / .to_spec(seed=, steps=) +GenomeSpace(mechanisms=..., topologies=..., neurons=..., sparsity=...) + .size / .contains(g) / .random_genome(rng) / .to_dict() / .from_dict(d) +applicable_operators(genome, space) -> tuple[str, ...] +mutate(genome, space, rng, *, extra_prob=0.25, max_operators=3) -> (Genome, operator_trail) +crossover(a, b, space, rng) -> Genome +dgm_parent_probabilities(fitness, children, *, sharpness=10.0, midpoint=0.5) -> np.ndarray +hoyer_sparseness(x) -> float | None +ActivityRecorder() # read-only EngineExtension, id 'qd_activity_recorder' +NeuroWeaveEvaluator(*, task='delayed_recall', steps=48, heldout_seeds=(100, 101), heldout_steps=24) + (genome, seed) -> sealed candidate receipt; .evaluate(genome, seed, *, heldout_seeds=None); .protocol() +LandscapeEvaluator(target, space, *, steps=16) # known-answer synthetic evaluator +candidate_metrics(receipt) -> dict # recomputed fitness, log loss and descriptors +verify_candidate(genome, receipt, *, seed, protocol, space) -> list[str] +EliteArchive(*, cost_bins=4, cost_range=(9.75, 11.75), activity_bins=4, activity_range=(0.0, 0.8), max_nodes=10000) + .record(...) / .cell_of(d) / .elites() / .elite_receipt(cell) / .best() / .pareto_front() / .qd_score() + .coverage() / .lineage() / .rejections() / .children_count(id) / .sha256 / .export_json() / .import_json(text) + EliteArchive.from_json(text) +QualityDiversitySearch(evaluator, *, seed=0, budget=32, method='qd'|'random', space=None, initial_random=8, + selection='dgm'|'uniform', crossover_rate=0.25, extra_mutation_prob=0.25, spot_check_every=4, + selection_sharpness=10.0, selection_midpoint=0.5, max_resample=16, cost_bins=4, + cost_range=(9.75, 11.75), activity_bins=4, activity_range=(0.0, 0.8), cache=None) + .step() / .run() -> summary / .summary() / .audit() / .parent_probabilities() / .config() / .done / .archive +illumination_metrics({run: {cell: fitness}}) -> {run: {reliability, precision, coverage_of_union}} +pareto_front(points) -> list[int] +``` + +Determinism and global state: all randomness comes from `numpy.random.default_rng(seed + offset)`. The random +genome stream uses offset 67,001 and the variation stream 67,013; the NEUROWEAVE runs are seeded by the engine. The +module does not import torch and never touches the global NumPy or `random` state; the tests compare the NumPy, +`random` and (when it is loaded) torch RNG and thread state before and after a search and `run_experiment`. The +same arguments give the same receipt digest and the same archive export. + +Each search switch is tested for an effect: DGM vs uniform selection, sigmoid sharpness 0 (only the child-count +term is left, checked against `1 / (1 + n_i)`), crossover off, single-operator mutation (one operator per child), +the random method and the spot-check frequency all change the archive. The shared evaluation cache, by design, +leaves the archive byte-identical. + +## Connection to Sonapse + +* The module uses the NEUROWEAVE lab read-only: `make_spec`, `NeuroWeaveEngine`, `ReadoutHead`, + `run_task_phase`, `make_stream`, `clone_engine`, `_estimated_cost`, and the receipt helpers via + `frontier.harness`. It reproduces the protocol of `_task_arm`. +* Its only engine attachment is `ActivityRecorder`, a read-only extension, and only on the module's own + evaluation engines. +* It changes no Sonapse or NEUROWEAVE default and is not a live observer. The frontier lab picks it up from + `EXPERIMENTS`. +* Each elite is a complete `NeuroWeaveSpecV1` (`Genome.to_spec`) with a sealed receipt. Possible follow-ups, not + implemented: seed other lab experiments with archive elites, or search over topology-metric descriptors such as + modularity. + +## Not implemented + +* **From MAP-Elites:** + * any of the alternative variants discussed in the paper (Sec. 8); + * the paper's global-performance metric, which is normalised by the best value found; + * adaptive or centroidal grids. The descriptor ranges are fixed in the config. +* **From DGM:** + * self-modification of code, foundation-model-proposed changes, staged benchmark evaluation, and `k` parents each + producing their own child. + * Only the parent-selection rule and the idea of admitting changes after empirical validation are reused. +* **Statistical strength of fitness.** + * Fitness is held-out accuracy on one short stream per held-out seed. It is coarse (multiples of 1 / 48 by + default), often near the majority-class rate, and noisy, so elites are partly selected on noise. + * Candidates are not re-trained with other seeds. + * The `best_test` re-evaluation on fresh streams is the only guard against this optimism. +* **Equal budget means equal candidate counts, not equal compute.** Candidates differ in estimated cost. The + receipt reports the estimated ops of the verified candidates per arm. +* **Spot-check schedule.** It is periodic and deterministic, so an adversarial evaluator that knew `k` could cheat + on the other candidates. The gate is designed for detecting faults, not for security. + +## Verified references + +Each reference was checked on 2026-11-20 against the listed pages and, where noted, the paper's text. + +1. Jean-Baptiste Mouret, Jeff Clune. **Illuminating search spaces by mapping elites.** arXiv:1504.04909 + [cs.AI], v1 submitted 20 April 2015 (arXiv comment "Early draft"; no later version is listed). + . Checked in the PDF: + * the Fig. 2 pseudocode: G random solutions, then a random elite, random variation, and a store when the cell + is empty or `P(b′) < p′`; + * the Sec. 5 criteria (global performance, global reliability, precision / opt-in reliability, coverage); + * the Sec. 9.4.1–9.4.3 formulas, with the best per cell taken over all runs of all treatments and unfilled + cells excluded. +2. Jenny Zhang, Shengran Hu, Cong Lu, Robert Lange, Jeff Clune. **Darwin Gödel Machine: Open-Ended Evolution of + Self-Improving Agents.** arXiv:2505.22954 (title spelled "Godel" on arXiv), v1 29 May 2025, v3 12 March 2026. + ICLR 2026 poster: (OpenReview + ). . Checked in the v3 HTML, + App. C.2 "Parent Selection": + * the eligible set `α_i < 1`; + * `s_i = 1/(1 + exp(−λ(α_i − α_0)))`; + * `h_i = 1/(1 + n_i)`, with `n_i` the children with codebase-editing functionality; + * `p_i = w_i / Σ w_j`, with λ = 10 and α_0 = 0.5; + * `k` parents sampled with replacement: k = 2 for SWE-bench and 4 for Polyglot. +3. Justin K. Pugh, L. B. Soros, Paul A. Szerlip, Kenneth O. Stanley. **Confronting the Challenge of Quality + Diversity.** GECCO '15, Madrid, 11–15 July 2015, pp. 967–974. doi:10.1145/2739480.2754664, + . Checked in the PDF: the QD score is the "total fitness across + all filled grid bins". +4. Justin K. Pugh, Lisa B. Soros, Kenneth O. Stanley. **Quality Diversity: A New Frontier for Evolutionary + Computation.** *Frontiers in Robotics and AI* 3, published 12 July 2016. doi:10.3389/frobt.2016.00040, + . Checked on the publisher page: the + QD-score sums the highest fitness found in each grid bin, credited to Pugh et al. (2015). +5. Patrik O. Hoyer. **Non-negative Matrix Factorization with Sparseness Constraints.** *Journal of Machine + Learning Research* 5, 1457–1469, November 2004. . Checked in + the PDF: `sparseness(x) = (√n − Σ|x_i| / √(Σ x_i²)) / (√n − 1)`. + +The sibling projects were read from read-only clones on 2026-11-20; no code from them was executed or copied: + +* SONAPSE-ORIGIN: `sonapse_origin/evolution/map_elites.py`, `search_engine.py` and `nsga2.py`. These hold a 2-D + grid with clipped bins and strict-improvement replacement, uniform elite sampling, mutation and crossover, and + NSGA-II fronts. +* sonapse-evo: `src/sonapse_evo/evolution/operators.py`, `evolution/transaction_manager.py` and + `discovery/pareto_optimizer.py`. These hold operators with `can_apply` preconditions, mutation receipts, a + `FailureArchive` with reasons, parent-digest checks before commit with rollback, and constrained Pareto sorting. + +## Measured results + +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 +thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). The machine was shared with other jobs, so +wall-clock times are indicative. Receipts are deterministic: six quick runs gave the same digest, and re-running +the default and `budget=48` experiments later the same day reproduced their digests exactly. + +Each row compares MAP-Elites with DGM selection (QD) against random search; numbers are QD vs random. + +| Run | Seeds | Verdict (QD-score) | Key numbers (QD vs random) | Wall-clock | +|---|---|---|---|---| +| `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) | +| `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 | +| `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 | + +The receipt digests are tied to the NEUROWEAVE code of that date: + +* quick: `11618e7bd20da10be677b4b48c7d40523cc479e2f5172d3d0998c72e89259d53`; +* default: `c5c757eb4f4cca55832d39434ad5d09ab21048318084fdee7a4f23c544a10555`; +* `budget=48`: `8453ba874164518d5b99a426bb758443f95f5d4f30c5e3ba8bee05482bd9e414`. + +Neither arm learned the quick task: no best elite beat the test stream's majority-class rate. + +**Known-answer landscape** (from the tests, `LandscapeEvaluator`). The space has 6 mechanisms × 3 topologies × +2 neuron counts × 2 sparsities (768 genomes) and a hidden target. The budget is 80 candidates; seeds 0–4; 4 × 4 +grid. + +| | MAP-Elites with DGM selection | Random search | +|---|---|---| +| Reached the unique optimum | 4 of 5 seeds | 0 of 5 | +| Mean best fitness | 0.978 | 0.844 | +| Mean QD-score | 4.756 (higher on all 5 seeds) | 4.422 | +| Filled cells | 6 on every seed | 6–7 | +| Mean fitness of verified candidates | 0.613 | 0.493 | + +**Reading.** On the known landscape, MAP-Elites with DGM selection climbed within cells and reached a higher +QD-score while filling slightly fewer cells. + +In the NEUROWEAVE space at 5 and 16 candidates per arm, it was the other way round. Held-out accuracy differed +little between configurations and stayed near the majority-class rate, so climbing had little to gain. Random +search filled more cells, and coverage decided the QD-score; precision was about the same for both arms. + +At 48 candidates per arm, both arms filled most of the 16 cells and the QD-score difference was not detectable. +However, the best elites found by MAP-Elites scored lower on fresh test streams. One possible reason is stronger +selection on held-out noise; this was not tested. + +These statements cover these settings only and say nothing about other tasks, sizes or budgets. diff --git a/docs/frontier/modules/recursive_refiner.md b/docs/frontier/modules/recursive_refiner.md new file mode 100644 index 0000000000000000000000000000000000000000..aeed2b5698cdeb824ab1e15b632020d89044b4b6 --- /dev/null +++ b/docs/frontier/modules/recursive_refiner.md @@ -0,0 +1,258 @@ +# `recursive_refiner`: recursive latent refinement + +Module file: `synapse/frontier/recursive_refiner.py` · tests: `tests/test_frontier_models.py` · +experiment id: `recursive_refiner` · kind: standalone model (no engine extension, no live observer) · +evidence tier: `synthetic_abstraction`. + +The module implements a tiny recursive model in the style of the **Tiny Recursive Model** (TRM; +Jolicoeur-Martineau, 2025), which simplifies the **Hierarchical Reasoning Model** (HRM; Wang et al., 2025). +One small network repeatedly refines a latent state `z` and an answer state `y`. It is trained with deep +supervision: one loss and one optimiser step per supervision step, with the state detached in between. A halting +head is trained to predict whether the current answer is already correct. The benchmark is 4×4 Sudoku completion +on grids the model never saw during training. + +The module is *inspired by* these papers and does not reproduce them. The papers use 9×9 Sudoku-Extreme, mazes +and ARC-AGI, 5–27 M parameters, EMA weights, heavy data augmentation and GPUs. This module uses 4×4 Sudoku, +about 1.8–3.5 k parameters, no EMA, no augmentation and one CPU thread. + +## What it computes + +**Model (`TinyRecursiveModel`).** States have shape `tokens × latent_dim`; for Sudoku there is one token per cell +(16 tokens). Each supervision step embeds the question once, `e = E x`, where `x` is the per-cell one-hot code +over {blank, 1, 2, 3, 4}. The single shared network is a residual mixer block: + +``` +f(s) = N( t + W2 relu(W1 t + b1) + b2 ) # channel MLP, hidden width `hidden` +t = N( s + Mix(s) ) # token-mixing MLP across the 16 positions (width `token_hidden`) +N = layer norm without learned scale or shift (keeps recursed states bounded) +``` + +`Mix` is skipped when `tokens == 1` (a plain vector model). TRM uses an MLP over the sequence instead of +self-attention for Sudoku, with RMSNorm and SwiGLU in 2-layer blocks. Here one block with ReLU and an affine-free +layer norm is used, which is cheaper on CPU. + +One **latent recursion**: + +``` +repeat n times: z <- f(z + y + e) # latent reasoning: sees the question +once: y <- f(y + z) # answer refinement: no question +``` + +The same `f` performs both updates. Whether `e` is in the sum is what tells the network which update it is doing, +as in TRM. + +One **supervision step** (TRM's "deep recursion"): + +1. `T - 1` latent recursions without gradient (`recursions = T`), then one latent recursion with gradient. +2. Read-outs from `y`: + * answer logits `O y`, 4 digits per cell; + * halting logit `q = w · mean_cells(y) + b`, with `P(halt) = sigmoid(q)`. +3. `(y, z)` are detached before the next supervision step. + +The initial states `y_init` and `z_init` are fixed truncated-normal vectors (std 1, cut at ±2), shared by all +cells and stored as non-trainable buffers. The halting head starts at `w = 0, b = -5`, so early training rarely +halts. Both choices follow the TRM code. `net_calls` counts applications of `f`; one supervision step is +`T (n + 1)` applications. + +**Training (`train_recursive`): deep supervision with ACT-style halting.** + +* A batch of `batch_size` slots is carried across optimiser updates. Each update runs one supervision step for + every slot. +* Each update takes one AdamW step (β = (0.9, 0.95), weight decay 0.01, gradient-norm clip 1.0) on + `L = CE(logits, solution) + BCE(sigmoid(q), 1[all 16 cells correct])`. These are the two loss terms of TRM's + Figure 3 pseudocode. +* A slot halts when `q > 0` (once its minimum step count is reached) or after `N_sup = supervision_steps` steps. + It is then refilled with the next example of a deterministic shuffled stream, and its `(y, z)` are reset to the + initial states. There is no Q-continue head, as in TRM. +* Exploration: with probability `halt_exploration` (0.1) a new example gets a minimum of 2..`N_sup` steps. This + is HRM's `M_min` rule. Here it is drawn once per example, as the HRM paper describes it; the reference code + redraws it at every step. + +**Evaluation (`evaluate_recursive`).** All `N_sup` supervision steps are run, as TRM does at test time, and the +headline metrics use the last step: + +* `exact_solve`: fraction of puzzles with all 16 cells right; +* `cell_accuracy`: fraction of *blank* cells right; +* `per_step_exact_solve`: exact-solve after each supervision step; +* `adaptive_*`: the answer taken at the first step with `P(halt) > 0.5` (or the last step), with the mean number + of steps used; +* `halting_brier` and `halting_decision_accuracy`: calibration of `P(halt)` against per-step correctness, and + `halt_prob_range`. + +## Benchmark (`run_experiment`, `EXPERIMENTS = {'recursive_refiner': run_experiment}`) + +Per seed (default `seeds=(0, 1, 2)`): + +1. **Grids.** `enumerate_sudoku4()` returns all 288 valid 4×4 grids, found by backtracking. The tests check the + count, validity, distinctness and closure under digit relabelling. +2. **Disjoint split by grid.** The grids are permuted by `default_rng(seed + 31001)` and split into 160 training, + 32 validation and 96 held-out grids. The receipt records the overlap between splits, which is 0 for every seed. +3. **Puzzles (`make_puzzles`).** Pick a grid of the split and draw a target of 8–12 blanks. Blank cells in random + order, skipping any removal that would admit a second solution. The check is an exact count of the grids + consistent with the givens, using bitsets over the 288 grids. Every puzzle therefore has exactly one solution. + The default sizes are 4096 training, 512 validation and 1024 held-out puzzles; the first 512 training puzzles + are re-scored as "train". +4. **Encoding.** One-hot per cell over {blank, 1, 2, 3, 4} (80 inputs); the targets are the 16 digits. + +**Arms.** All arms share the data, the example stream (`torch.Generator(seed + 31301)`) and the number of AdamW +updates. + +| arm | model | training | +|---|---|---| +| `trm` | `TinyRecursiveModel` | deep supervision with halting (`train_recursive`) | +| `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 | +| `shallow` | the same network and initial weights with one latent recursion (`n + 1` applications) | one loss, full backpropagation | +| `mlp` | `SinglePassMLP`: flat 2-hidden-layer ReLU MLP on the 80 inputs | cross-entropy, single pass | + +The MLP width is chosen by `matched_mlp_hidden` so that its trainable parameters are closest to `trm`'s. All +budgets are computed **before training**. If any arm is more than `param_tolerance` (10 %) away from `trm`, +`run_experiment` raises `ValueError`. + +**Verdict.** The best baseline is the one with the highest mean *validation* exact-solve; held-out grids play no +part in that choice. `verdict = harness.compare(trm, best baseline)` on held-out exact-solve per seed, a paired +95 % t interval over seeds. The receipt also compares `trm` with each baseline separately, and with the best +baseline on cell accuracy: + +* `trm_vs_unrolled` isolates deep supervision and the one-step gradient at equal depth; +* `trm_vs_shallow` isolates recursion depth; +* `trm_vs_mlp` mixes recursion with per-cell weight sharing. + +**Receipt fields.** + +* `config`, including `quick` and every option; +* `data`: overlap between splits, mean blanks, uniqueness note; +* `parameter_budget`: per-arm counts, MLP width, relative gap, tolerance; +* `arms`: per-seed train / validation / held-out metrics, training logs and summaries; +* `best_baseline`, `comparisons`, `verdict`, `verdict_basis`; +* `estimated_cost`: inference MACs per puzzle, network applications per puzzle, backpropagated applications per + update, examples drawn by `trm`; +* `measured_wallclock_s`, which is kept out of the digest; +* `notes`. + +| option | default | quick | +|---|---|---| +| grids train / val / held-out | 160 / 32 / 96 | same | +| puzzles train / val / held-out / train-eval | 4096 / 512 / 1024 / 512 | 1024 / 128 / 256 / 128 | +| blanks per puzzle | 8–12 | same | +| `latent_dim` / `hidden` / `token_hidden` | 24 / 48 / 24 | 16 / 32 / 16 | +| `n_latent_steps` (n) / `recursions` (T) / `supervision_steps` (N_sup) | 2 / 2 / 4 | 1 / 2 / 2 | +| applications of `f` per puzzle (trm, unrolled) | 24 | 8 | +| AdamW updates / batch / lr | 600 / 32 / 2e-3 | 100 / 64 / 4e-3 | +| trainable parameters trm / mlp (MLP width) | 3,453 / 3,384 (20) | 1,797 / 1,791 (11) | + +## Public API + +```python +MODULE_ID = 'recursive_refiner' +EXPERIMENTS = {'recursive_refiner': run_experiment} +run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict # overrides: any DEFAULTS key + +TinyRecursiveModel(input_dim, answer_dim, latent_dim, hidden, n_latent_steps, supervision_steps, *, + recursions=2, tokens=1, token_hidden=None, seed=0) + .net(s) / .embed(x) / .initial_state(batch) / .latent_recursion(e, y, z) / .read_out(y) + .supervision_step(e, y, z) -> (y_detached, z_detached, logits, q) + .forward(x, *, steps=None) -> {'logits', 'step_logits', 'halt_prob'} + .unrolled(x) -> (logits, q) # same depth, gradient through every recursion + .halt_probability(y), .calls_per_supervision_step(), .parameter_count(), .inference_macs(), .net_calls +SinglePassMLP(input_dim, answer_dim, hidden, *, depth=2, seed=0) +matched_mlp_hidden(target_params, input_dim, answer_dim, depth=2) -> int + +enumerate_sudoku4() -> np.ndarray (288, 16) is_valid_sudoku4(grid) -> bool +is_consistent_puzzle(puzzle) -> bool solution_count(puzzle) -> int +make_puzzles(grids, count, *, rng, min_blanks, max_blanks, max_attempts=64) -> (puzzles, solutions) +encode_puzzles(puzzles) -> torch.Tensor (n, 80) +train_recursive / train_unrolled / train_single_pass(model, x, target, cfg, generator) -> dict +evaluate_recursive / evaluate_single_pass(model, x, target, puzzles) -> dict +ARMS, GRID_COUNT (288), CELLS, DIGITS, INPUT_DIM (80), ANSWER_DIM (64), UNITS, DEFAULTS, QUICK +``` + +Determinism and global state: + +* all initialisation uses `torch.Generator(seed + offset)` and all data uses `numpy.random.default_rng(seed + offset)`; +* the global torch RNG is never used; +* `run_experiment` runs on one torch thread and restores the caller's thread count afterwards. + +The tests check that the global RNG state and the thread count are unchanged after a run. + +## Connection to Sonapse + +This is a standalone lab model (contract rule 3). It does not attach to a NEUROWEAVE engine, has no live +observer, and changes no Sonapse default. The frontier lab registry picks it up from `EXPERIMENTS`. + +A possible follow-up, not implemented: use `TinyRecursiveModel` as a refinement readout over NEUROWEAVE +features, where `tokens=1` gives the plain-vector form. + +## Not implemented + +* **From the TRM paper and code:** + * 2-layer SwiGLU / RMSNorm blocks, self-attention and rotary embeddings; + * EMA of the weights (0.999); + * the 1000-fold data augmentation; + * the puzzle-identifier embedding token (TRM's halting head reads that first position; here it reads the + mean over cells); + * the 0.5 weight on the halting loss (here 1, as in the paper's pseudocode); + * the stable-max cross-entropy option; + * TRM's sizes (T = 3, n = 6, N_sup = 16, hidden 512). +* **From the HRM paper:** + * two separate networks at two frequencies; + * the Q-continue head and its Q-learning target; + * the fixed-point / one-step-gradient justification. TRM's recursion is used instead. +* **Datasets:** 9×9 Sudoku-Extreme, Maze-Hard and ARC-AGI. 4×4 Sudoku is far easier, so the numbers here say + nothing about those benchmarks. +* **A compute-matched protocol.** All arms get equal optimiser updates. `unrolled` therefore backpropagates + through `N_sup` times more network applications per update than `trm`, while `trm` draws fewer distinct + examples per update (`trm_examples_drawn` in the receipt). + +## Verified references + +Each was checked on 2026-11-17 against the arXiv abstract page and the paper's HTML text. TRM was also checked +against the authors' code. On 2026-11-20 (review) the TRM arXiv listing was re-checked (single author, v1 of +6 October 2025 is still the only version) and the recursion, deep-supervision loop and halting code paths of +this module were re-read against the Figure 3 pseudocode below. + +* Alexia Jolicoeur-Martineau. **Less is More: Recursive Reasoning with Tiny Networks.** arXiv:2510.04871 + [cs.LG], v1 submitted 6 October 2025. . + * **Checked in the paper:** + * Figure 3 pseudocode: `latent_recursion` (n × `z = net(x, y, z)`, then `y = net(y, z)`) and + `deep_recursion` (T − 1 recursions under `no_grad`, one with gradient, return detached `(y, z)`, output + head and Q head); + * the deep-supervision loop: cross-entropy plus binary cross-entropy of `q_hat` against + `(y_hat == y_true)`, an optimiser step every supervision step, and early stop when `q_hat > 0`; + * the text forms `z ← f(x + y + z)` and `y ← f(y + z)`; + * the same network for both updates, distinguished by the presence of `x`; + * T = 3, n = 6, N_sup = 16, a 2-layer network, EMA 0.999; + * an MLP over the sequence instead of self-attention on Sudoku; + * no continue loss, a single forward pass; + * Sudoku-Extreme with 1K training examples and 1000 augmentations each. + * **Checked in the code**, + (`models/recursive_reasoning/trm.py`): + * `H_init` / `L_init` truncated-normal buffers with std 1; + * `q_head` with weight 0 and bias −5, reading `z_H[:, 0]`; + * injection `z_L ← L(z_L, z_H + input)` and `z_H ← L(z_H, z_L)`; + * training halts on `q_halt > 0` (`no_ACT_continue`), with exploration minimum steps drawn from + [2, `halt_max_steps`] with probability `halt_exploration_prob`; + * evaluation runs to `halt_max_steps`; + * post-norm RMSNorm blocks with SwiGLU. +* Guan Wang, Jin Li, Yuhao Sun, Xing Chen, Changling Liu, Yue Wu, Meng Lu, Sen Song, Yasin Abbasi Yadkori. + **Hierarchical Reasoning Model.** arXiv:2506.21734 [cs.AI], v1 submitted 26 June 2025, later revised. + . Checked in the paper: + * deep supervision over segments, with the state detached between segments and an optimiser step per segment; + * the one-step gradient approximation; + * ACT: a Q-head on the final high-level state with halt / continue values; + * halting when the segment count exceeds `M_max`, or when `Q_halt > Q_continue` and the count is at least + `M_min`, where `M_min` is uniform on {2, …, M_max} with probability ε and 1 otherwise; + * the halt target 1[ŷ = y]; + * Sudoku-Extreme with 1000 training examples. + +## Measured results + +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`): + +| Arm | Train exact-solve | Val exact-solve | Held-out cell acc | Held-out exact-solve | Held-out Δ vs arm (95 % CI) | +|---|---:|---:|---:|---:|---| +| `trm` (candidate) | 0.2630 | 0.2734 | 0.8394 | 0.3242 | — (per-step: `0.2240 → 0.3242`, halting Brier `0.2236`) | +| `unrolled` (best baseline) | 0.4089 | 0.4089 | 0.8829 | 0.4245 | `trm − unrolled`: −0.1003 (`[-0.1999, -0.0007]`, `worse`) | +| `shallow` | 0.3073 | 0.2943 | 0.8503 | 0.3112 | `trm − shallow`: +0.0130 (`[-0.0501, +0.0762]`, `no_detectable_difference`) | +| `mlp` | 0.0026 | 0.0000 | 0.3459 | 0.0000 | `trm − mlp`: +0.3242 (`[+0.2286, +0.4198]`, `improved`) | + +* **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`). diff --git a/docs/frontier/modules/rigl_sparse.md b/docs/frontier/modules/rigl_sparse.md new file mode 100644 index 0000000000000000000000000000000000000000..640085503697cad8cb51a752450016979e8bf8a0 --- /dev/null +++ b/docs/frontier/modules/rigl_sparse.md @@ -0,0 +1,204 @@ +# `rigl_sparse`: dynamic sparse training (RigL) + +Module file: `synapse/frontier/rigl.py` · tests: `tests/test_frontier_optim.py` · +experiment id: `rigl_sparse` · kind: `tool` (a training-loop scheduler; no engine extension, no live observer) · +evidence tier: `synthetic_abstraction`. + +The module keeps the `nn.Linear` layers of a PyTorch model at a fixed number of active weights and, every +`delta_t` iterations until `t_end`, moves a cosine-decayed fraction of them: the smallest-magnitude active weights +are dropped and the same number of inactive weights with the largest gradient magnitude are grown, starting at +zero. It is *inspired by* **RigL** (Evci et al., ICML 2020) and by the `AuthenticRigL` class of the sibling +project `kai9987kai/sonapse-evo`. It does not reproduce the paper's ImageNet or CIFAR results, and it stores +weights densely with binary masks, so it saves no time or memory. + +## What it computes + +**Layer budgets.** For managed layers with weight shapes `(n_out, n_in)` and a target overall sparsity `S`: + +* `'uniform'`: every layer has density `1 - S`. +* `'erk'` (Erdős–Rényi; for linear layers ERK and ER coincide): density `eps * (n_in + n_out) / (n_in * n_out)`, + with one scale `eps` chosen so the total number of active weights equals the uniform budget. A layer whose + density would exceed 1 is made dense and `eps` is recomputed for the others, as in the reference code. + +A layer with `N` weights and density `d` keeps `a = N - floor((1 - d) N)` active weights (at least 1). The initial +masks are random (`numpy.random.default_rng(seed + offset)`), applied to the weights at construction, and every +inactive weight is exactly `0.0` from then on. + +**Schedule.** Training iterations are counted `t = 1, 2, …`. Iteration `t` is a *connectivity update* when + +``` +t mod delta_t == 0 and t < t_end (RigL Algorithm 1) +f(t) = alpha / 2 * (1 + cos(pi * t / t_end)) (cosine update fraction of Evci et al.) +k = floor(f(t) * a) (per layer; a = active weights of the layer) +``` + +**Update (per sparse layer).** + +1. *Drop* the `k` active weights with the smallest `|w|` (ties: lowest flat index). +2. *Grow* the `k` weights with the largest `|dL/dw|` among all weights that were not kept, i.e. the inactive ones + plus the ones just dropped (ties: lowest flat index). The gradient is the dense gradient of the current batch, + which autograd gives at every position because inactive weights are zeros of a dense tensor. +3. Newly activated weights are set to `0.0`, so the network output does not change. A weight that is dropped and + grown back in the same update keeps its value (the reference code's default, `reinit_when_same=False`). +4. Every per-element optimiser state tensor of the layer (SGD momentum, Adam moments) is zeroed at inactive and + newly activated positions. +5. No optimiser step is taken on an update iteration (Algorithm 1). On every other iteration the gradients of + inactive weights are zeroed before `optimizer.step()` and the masks are re-applied after it, so inactive + weights stay exactly zero even with weight decay or momentum. + +The number of active weights per layer never changes. Biases stay dense. + +## Public API + +```python +MODULE_ID = 'rigl_sparse' +DISTRIBUTIONS = ('uniform', 'erk') +STATE_SCHEMA = 'RigLSchedulerStateV1' +ARMS = ('dense', 'static_sparse', 'rigl') +EXPERIMENTS = {'rigl_sparse': run_experiment} + +cosine_drop_fraction(t, alpha, t_end) -> float +layer_densities(shapes, sparsity, distribution='erk') -> list[float] +layer_active_counts(shapes, sparsity, distribution='erk') -> list[int] + +RigLScheduler(model, sparsity, delta_t=100, alpha=0.3, t_end=1000, distribution='erk', *, + layers=None, seed=0, dynamic=True, history=256) + .step(optimizer) -> bool # call once per iteration after loss.backward(); False = connectivity update + .update_connections(fraction, optimizer=None) -> dict + .apply_masks() .mask_gradients() + .is_update_step(t) -> bool .drop_fraction(t) -> float + .active_counts() -> list[int] .parameter_budget() -> dict .summary() -> dict + .masks (copies) .history (copies; at most `history` records) + .state_dict() -> dict .load_state_dict(state) + +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +``` + +`layers` selects which `nn.Linear` modules are managed (default: all, in `model.modules()` order; pass a subset to +keep, for example, the first layer dense). `dynamic=False` keeps the initial masks for the whole run (static sparse +training with identical masks). Inputs are validated before anything changes: `update_connections` refuses +missing, sparse or non-finite gradients without touching masks, weights or optimiser state, and +`load_state_dict` checks the schema, the configuration, the counters and every mask's dtype, shape and active +count before loading. The scheduler state holds the masks, counters and history, not the optimiser state. + +## Benchmark (`run_experiment`) + +* **Task (`sparse_teacher`).** Gaussian inputs (`n_inputs = 64`), of which only a seeded subset of + `n_informative = 8` drives the label: the label is the argmax of a fixed random tanh teacher on those inputs + (4 classes, logits centred on the training split). The other 56 inputs are distractors, so which connections + exist matters. +* **Model.** ReLU MLP `64-hidden-hidden-4` with PyTorch's default `nn.Linear` initialisation drawn from a private + `torch.Generator` (the global RNG is untouched). +* **Arms.** `dense`; `static_sparse` (the scheduler with `dynamic=False`); `rigl`. Per seed all three share the + initial weights, the minibatch sequence, `torch.optim.SGD(lr, momentum, weight_decay)` and the number of + training iterations; `static_sparse` and `rigl` also share the initial masks (checked in the receipt). +* **Verdict.** `harness.compare` (paired 95 % t interval over seeds) of held-out test accuracy, `rigl` minus + `static_sparse`: the two arms have the same parameter budget, so a win cannot come from capacity. `rigl` vs + `dense` and `static_sparse` vs `dense` are reported as context. If a sparse arm diverges, the verdict basis + becomes `training_diverged`. +* **Receipt.** `config` (every size and hyper-parameter, `t_end`), per-arm `per_seed` results (accuracies, final + loss, optimiser steps, mask digests, update trace, connections activated, the share of first-layer + connections that read an informative input), `budget` (active and dense parameters, per-layer densities, shared + masks, constant budget, zero inactive weights), `estimated_cost` (analytic FLOPs for ideal sparse kernels, + apart from `measured_wallclock_s`), `comparisons`, `verdict`, `verdict_basis` and `notes`. + +| Setting | quick | default | +|---|---|---| +| `hidden`, train / val / test examples | 64, 1024 / 256 / 512 | 128, 4096 / 1024 / 2048 | +| iterations, batch, SGD lr / momentum / weight decay | 300, 64, 0.05 / 0.9 / 1e-4 | 2000, 64, 0.05 / 0.9 / 1e-4 | +| sparsity, distribution | 0.9, `erk` | 0.9, `erk` | +| `delta_t`, `alpha`, `t_end` | 25, 0.3, 225 (0.75 × iterations) | 50, 0.3, 1500 | + +The paper uses `delta_t = 100`, `alpha = 0.3` and `T_end` at about 75 % of training; the shorter runs here use a +smaller `delta_t` so that several updates happen. + +## Connection to Sonapse + +A standalone lab tool (`EXPERIMENTS['rigl_sparse']`). Nothing in Sonapse or NEUROWEAVE calls it, and no default +training loop, graft schedule, API or checkpoint format changes. `sonapse-evo`'s `AuthenticRigL` +(`src/sonapse_evo/evaluation/rigl.py`, read in the local read-only clone) applies the same cosine drop/regrow idea +to a single recurrent edge vector and regrows weights at `±0.05` with a random sign; this module follows the +paper instead (per-layer masks, ERK budgets, zero-initialised growth, no optimiser step on update iterations). + +## Not implemented, and differences from the paper + +* **No sparse kernels.** Masks over dense tensors: no measured speed-up or memory saving is claimed. + `estimated_cost` gives analytic FLOPs for ideal sparse kernels. +* **`nn.Linear` only.** No convolutions, so ERK equals ER here. +* **Tie-breaking.** Ties go to the lowest flat index; the reference code adds small Gaussian noise + (std `1e-5`) to the drop scores. +* **Update condition.** Algorithm 1's `t mod delta_t == 0 and t < t_end`. The reference code's TensorFlow + scheduler also allows an update at `t = t_end` and uses a `begin_step`. +* **Optimiser state.** All per-element state at inactive and newly grown positions is zeroed (the reference + resets the momentum of new connections; inactive positions have zero gradient here anyway). +* **First layer under `'uniform'`.** The paper keeps the first layer dense for the uniform distribution; here + that is the caller's choice (`layers=`). The benchmark uses ERK and sparsifies every layer. +* **Not attempted.** SET (random growth) and SNFS (momentum growth), the ImageNet/ResNet-50, CIFAR-10 and + character-level experiments, and the paper's longer training schedules. + +## Verified references + +* Utku Evci, Trevor Gale, Jacob Menick, Pablo Samuel Castro, Erich Elsen. **Rigging the Lottery: Making All + Tickets Winners.** *Proceedings of the 37th International Conference on Machine Learning (ICML 2020)*, PMLR + vol. 119, pp. 2943–2952, July 2020. · arXiv:1911.11134, + . Checked on 2026-11-20 against the PMLR page (title, authors, volume, pages, + date) and the arXiv text: Algorithm 1 (update condition, `k = f_decay(t) (1 - s) N`, drop by `ArgTopK(-|θ|)`, + grow by gradient magnitude among the non-kept connections, plain gradient step otherwise), the cosine + `f_decay(t; α, T_end) = α/2 (1 + cos(tπ / T_end))`, the defaults `ΔT = 100`, `α = 0.3`, `T_end` ≈ 75 % of + training, zero-initialised growth, the ER/ERK distributions, and the dense first layer under the uniform + distribution. +* Reference code: , `rigl/sparse_optimizers_base.py`, read on + 2026-11-20: `n_prune` is a truncating cast of `n_ones * drop_fraction`; kept connections get the lowest grow + score; `reinit_when_same=False` by default, with new connections defined as grown and previously inactive; + `grow_init='zeros'`; momentum of new connections reset to zero; cosine decay over `end_step - begin_step`. +* Portfolio provenance: `kai9987kai/sonapse-evo`, `src/sonapse_evo/evaluation/rigl.py` (`AuthenticRigL`). + +## Measured results + +Measured on **2026-11-20**, Windows 11 on ARM64, Python 3.12.10, torch 2.11 CPU, NumPy 2.4, +`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1` (the experiment also runs torch on one thread). The +machine was shared with other jobs, so wall-clock is indicative only. Receipts are deterministic: two calls in +one process gave the same digest, and the quick digest was identical in two separate processes run about twelve +hours apart that day. + +**Quick** (`run_experiment(quick=True)`, seeds 0, 1, 2; digest `906545bf0ed9d08c`; 6.7–7.4 s): + +| Arm | Parameters (active weights + biases) | Train acc | Held-out test acc | First-layer informative share (chance 0.125) | +|---|---:|---:|---:|---:| +| `dense` | 8580 | 0.9997 | 0.6986 | 0.125 | +| `static_sparse` | 980 | 0.6849 | 0.6510 | 0.117 (unchanged) | +| `rigl` | 980 | 0.8128 | 0.7357 | 0.117 → 0.186 | + +* Realised density 0.100 (848 of 8448 weights); ERK gives the per-layer densities 0.082, 0.082 and 0.695. + RigL made 8 connectivity updates (t = 25 … 200) and 292 optimiser steps per run; it activated 710–780 + connections per run, and its first-layer share of informative inputs rose on every seed + (0.099 → 0.158, 0.134 → 0.194, 0.119 → 0.206). +* `rigl − static_sparse`: +0.0846, 95 % CI [−0.0126, +0.1818] → **`no_detectable_difference`** (verdict). + `rigl − dense`: +0.0371, CI [−0.0282, +0.1024]; `static_sparse − dense`: −0.0475, CI [−0.1806, +0.0856]. +* Quick mode is a pipeline check with three seeds; its interval is wide. + +**Default** (`run_experiment()`, seeds 0, 1, 2; digest `555ce009ccb76e7b`; 51.6 s; hidden 128, 2000 iterations, +`delta_t = 50`, `t_end = 1500`): + +| Arm | Parameters (active weights + biases) | Train acc | Held-out test acc (per seed) | Mean | First-layer informative share | +|---|---:|---:|---|---:|---:| +| `dense` | 25348 | 0.9928 | 0.714, 0.767, 0.766 | 0.7492 | 0.125 | +| `static_sparse` | 2772 | 0.8805 | 0.758, 0.813, 0.818 | 0.7961 | 0.110, 0.149, 0.142 (unchanged) | +| `rigl` | 2772 | 0.9107 | 0.809, 0.795, 0.824 | 0.8091 | 0.110 → 0.165, 0.149 → 0.207, 0.142 → 0.182 | + +* Realised density 0.100 (2512 of 25088 weights); ERK gives 0.105, 0.070 and 1.0 (the 128 × 4 output layer is + dense). RigL made 29 connectivity updates (t = 50 … 1450) and 1971 optimiser steps per run and activated + 6203–6636 connections per run. +* `rigl − static_sparse`: +0.0130, 95 % CI [−0.0733, +0.0993] → **`no_detectable_difference`** (verdict). + `rigl − dense`: +0.0599, CI [−0.0227, +0.1425]; `static_sparse − dense`: +0.0469, CI [+0.0361, +0.0577]. On this + distractor-heavy task the dense network fits the training set almost perfectly and generalises worse than + both sparse arms. Static random masks alone already beat it at this size, so that gap does not depend on mask + updates, and the mask updates add no detectable accuracy over the static masks. + +Unit tests with known answers (`tests/test_frontier_optim.py`): the cosine fraction at fixed points; the ERK +ratios and budget; a hand-worked drop/grow example (including a tie, a regrown-same weight that keeps its value, +zero-initialised growth and optimiser-state zeroing); constant budgets, exactly-zero inactive weights and the +update trace over a training run; static masks never moving; growth moving first-layer connections toward the +inputs that carry the signal on a planted regression (measured share 0.107 → 0.369, full-data MSE 0.0016 vs +0.0039 for static masks); refusal of bad gradients without any change; and state round-trips that continue +identically. diff --git a/docs/frontier/modules/sparse_dictionary.md b/docs/frontier/modules/sparse_dictionary.md new file mode 100644 index 0000000000000000000000000000000000000000..09755220c5550b2efc97af559e1c0e12a92d4ba3 --- /dev/null +++ b/docs/frontier/modules/sparse_dictionary.md @@ -0,0 +1,258 @@ +# `sparse_dictionary`: sparse dictionary of brain activity + +Module file: `synapse/frontier/sparse_dictionary.py` · tests: `tests/test_frontier_sae.py` · +experiment id: `sparse_dictionary` · live observer: `SparseDictionaryObserver` · +evidence tier: `synthetic_abstraction`. + +The module learns an online **TopK sparse autoencoder** (a sparse dictionary) of unit activity. It also runs a +lab experiment that asks whether the dictionary features that best predict a task target matter more to a +frozen readout than random features do. The dictionary is *inspired by* the TopK autoencoders of Gao et al. +(2024). It does not reproduce that paper's setting or results: the paper trains on language-model activations +with millions of latents on GPUs, while this module uses float64 NumPy with tens of units and latents on one +CPU thread. Dictionary features are directions in a toy model's activity space. They are not cell types or +biological circuits. + +## What it computes + +**Autoencoder (`TopKSAE`).** For an input `x` (one activity vector, `d` units) and `n` latents: + +``` +z = ReLU( TopK_k( W_enc (x - b_pre) + b_enc ) ) # keep the k largest pre-activations, zero the rest +x_hat = W_dec z + b_pre # ||W_dec[:, j]||_2 = 1 for every latent j +``` + +* **TopK.** The k largest pre-activations of each row are kept and the rest are set to zero. Ties go to the + lower index. A ReLU on the kept values makes `L0 <= k`, with equality whenever the top k are positive. + `b_enc` is optional (`encoder_bias=True` by default): the paper's main equation leaves it out, its Appendix C.3 + reports that it does not change the converged MSE, and the authors' reference code keeps it. +* **Initialisation.** + * Decoder columns are random unit vectors. + * The encoder is the decoder's transpose. The two are tied only at initialisation. + * `b_pre` is set to the geometric median of a data sample (Weiszfeld iterations). +* **Main loss.** `L = s * mean((x - x_hat)^2)`. The scale `s = 1 / Var(x)` is computed once, on the + initialisation sample. +* **Dead latents and AuxK.** + * A latent is *dead* once it has not fired (`z_j > 1e-3`) for `dead_after` training samples. + * The firing statistics are updated with the current batch before the dead mask is read. + * `e = x - x_hat` is the main residual, treated as a constant. `z_aux` keeps the top-`k_aux` dead latents by + pre-activation, with ReLU applied, and `e_hat = W_dec z_aux`. + * The auxiliary loss is `L_aux = mean_i ||e_i - e_hat_i||^2 / ||e_i||^2`. The paper (App. A.6) says the + AuxK normalisation is computed "per token" because the error scale changes during training, and + per-sample division by `||e_i||^2` is this module's reading of that. The authors' reference code does it + differently: its `normalized_mse` divides the batch MSE of the AuxK reconstruction by the MSE of + predicting the batch-mean residual (a per-batch, mean-centred normalisation; re-read on 2026-11-20 in + `sparse_autoencoder/kernels.py` and `train.py`). Both are scale-free; they are not numerically identical. + * The total loss is `L + alpha * L_aux`, with `alpha = 1/32` and `k_aux = d/2` by default. A non-finite AuxK + term is dropped. +* **Optimiser.** + * Adam with `beta = (0.9, 0.999)`, `eps = 6.25e-10` and a constant learning rate. Plain SGD is also available. + * The gradient component parallel to each decoder column is projected out before the step. The decoder + columns are renormalised to unit norm after every step. +* **Additions for bounded online use.** These are not from the paper: global gradient-norm clipping (default + 1.0), parameter clipping (`max_param`), counter caps, and input validation (finite values, `|x| <= 1e6`). +* **Metrics** (`evaluate`): + * Fraction of variance unexplained, `FVU = sum ||x - x_hat||^2 / sum ||x - mean(x)||^2`. This is the paper's + "normalized MSE". + * MSE and mean `L0`. + * The fraction of features that never fired. + * 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]`. + * The training dead fraction. + +Training is fully deterministic. Initialisation uses `default_rng(seed + offset)`, and each epoch's shuffle uses +a generator keyed by `(seed + offset, epoch)`. The object holds no generator state, so `export_state` / +`import_state` round-trip exactly and `fit(2); fit(1)` equals `fit(3)`. `import_state` validates everything +before it changes anything: schema, configuration, shapes, finiteness, unit-norm decoder, integer counters and +non-negative Adam second moments. + +**Live observer (`SparseDictionaryObserver(n_units, *, seed=7, history=256, features=64, k=8, ...)`).** +`observe(x)` follows these steps: + +1. It copies the activity vector into a fixed ring buffer of `history` rows. The caller's array is never aliased + or written. +2. Once `min(history, 32)` rows exist, it initialises `b_pre` from their geometric median. +3. Every `train_every` observations it takes one optimiser step on the new vector plus `batch_size - 1` replayed + buffer rows. The replay positions come from a generator keyed by `(seed + offset, observation count)`. +4. Its statistics are prequential: they are measured on each new vector before the update that uses it. + * `fvu_ema` is the exponential moving average (EMA) of the per-element squared error, divided by the EMA + variance of the units. + * `l0_ema` is the EMA of the number of active features. + * A per-feature usage EMA feeds the usage figures in the summary. +5. The default `dead_after` is `batch_size * history` samples, about one buffer's worth of observations. + +`summary()` is JSON-safe, about 3 KB, and contains no wall-clock. It returns: + +* `fvu_ema`, `mse_ema`, `l0_ema` and `dead_fraction`; +* `steps`, the optimiser updates; +* `observed` and `history_fill`; +* `top_features`, up to 8 features by usage EMA, each with its 5 units of largest absolute decoder weight; +* `usage_histogram`; +* `decoder_norm_max_error`; +* `evidence_tier`. + +`export_state` / `import_state` validate fully and continue bit-identically. `reset()` returns the observer to +its constructed state. `from_spec(n_units, FrontierSpecV1)` maps `seed`, `history`, `sae_features` and `sae_k` +to the observer's arguments. + +## Lab experiment (`run_experiment`, `EXPERIMENTS = {'sparse_dictionary': run_experiment}`) + +Per training seed (default `seeds=(0, 1, 2)`): + +1. **Train.** A NEUROWEAVE engine (`make_spec`, default `delayed_recall`, 48 neurons, `clustered`, no extra + mechanisms) and the lab `ReadoutHead` are trained prequentially on `make_stream(seed, steps)` with + `run_task_phase(..., learn=True)`. +2. **Record (training data only).** A frozen clone replays the training stream and records the first `n0` unit + outputs and the head's features. With `readout='refit'` (default), the head is refit on those features by + L2-regularised logistic regression (damped Newton) to give a competent frozen probe. `readout='online'` + keeps the online head. Held-out streams are never used for fitting. +3. **Dictionary.** A `TopKSAE` is fit to the recorded outputs (default 64 features, `k=8`, `dead_after` = one + pass over the training stream). +4. **Selection (training data only).** Only "alive" features are eligible: those that fired on at least + `min_fire_rate` of the rows. The `n_ablate` alive features with the largest `|Pearson r|` between activation + and the training target are *targeted*. `random_draws` uniform draws of the same number of alive features + form the random arm. A draw may overlap the targeted set, and the receipt reports the overlap. +5. **Causal ablation (held-out, frozen clones).** For every held-out stream, three arms run on fresh frozen + clones of the trained engine: **none**, **targeted** and **random**. After every engine step the chosen + features' decoder contributions `sum_j z_j W_dec[:, j]` are subtracted from the clone's + `engine.brain.cells.output` (clipped to the cells' `[-1, 1]` range) before the readout reads it. This is the + place where `run_task_phase`'s `silence` zeroes units, so the change also reaches the next step's recurrent + input. With no features, this phase reproduces `run_task_phase(..., learn=False)` number for number (tested). + The original engine is never stepped, and its state digest is checked before and after. +6. **Verdict.** The verdict uses `harness.compare` (paired 95 % t interval over seeds) on held-out log-loss of + targeted vs random ablation, and the receipt also reports Cohen's d_z. + **`improved` here means only that the targeted features matter more to the frozen readout than random + ones**: ablating them raised held-out log-loss more, and the interval excludes zero. `worse` means they + matter less. It does not mean that any model got better. The receipt also carries these supporting + comparisons: + * targeted vs random accuracy; + * targeted vs none log-loss; + * random vs none log-loss. + +The receipt also reports: + +* dictionary train and held-out FVU, L0, dead and never-fired fractions, and the usage histogram; +* the selected features with their correlation and fire counts; +* the energy that the targeted and random sets carry on the training data, and the per-step norm actually + removed; +* budgets, estimated operation counts and measured wall-clock. + +Ablation can remove different amounts of activity in the two arms. Before reading a difference as +feature-specific, compare `selection.targeted_train_energy`, `selection.random_train_energy` and +`heldout.*.removed_norm`. + +## Connection to Sonapse + +* **Live (read-only).** `sparse_dictionary` is in `spec.OBSERVER_MODULE_IDS`. A runtime hook that receives + `FrontierSpecV1(enabled=True, modules=('sparse_dictionary', ...))` builds the observer with + `SparseDictionaryObserver.from_spec(n_units, spec)` and feeds it copies of the observed unit activity. The + observer never writes into the brain, graft bus, actor or any shared RNG. Wiring that hook into the Sonapse + runtime is outside this module. +* **Lab.** `EXPERIMENTS['sparse_dictionary']` is the frontier-lab entry. It uses the NEUROWEAVE lab helpers + (`make_spec`, `ReadoutHead`, `run_task_phase`, `clone_engine`) and `synapse.frontier.harness` (`base_receipt`, + `compare`, `seal`). + +## Not implemented + +* **From the paper.** + * Weight EMA (paper A.5). + * Encoder-magnitude matching at initialisation. The paper reports that it has no effect or a weak negative + effect. + * Rounding `k_aux` to a power of two. + * Multi-TopK. + * Sharded or fused kernels. + * Scaling laws. + * The paper's feature-quality metrics: probe recovery, explainability and downstream-effect sparsity. +* **In this module.** + * Energy-matched random controls. + * Any claim about biological interpretation. + +## Verified references + +* Leo Gao, Tom Dupré la Tour, Henk Tillman, Gabriel Goh, Rajan Troll, Alec Radford, Ilya Sutskever, Jan Leike, + Jeffrey Wu. **Scaling and evaluating sparse autoencoders.** arXiv:2406.04093 (submitted 6 June 2024); + International Conference on Learning Representations (ICLR) 2025. · + . + The following were checked against the paper text on 2026-11-17: + * TopK, eq. 2 and footnote 5 (ReLU in code); + * tied initialisation, Sec. 2.4 and A.1; + * geometric-median `b_pre` and the unit-norm decoder after each step, A.1; + * AuxK with "typically 1/32", zeroed when NaN, A.2; + * Adam settings and the parallel-gradient projection, A.3; + * normalisation, A.6; + * "power of two close to d_model/2", B.1; + * `b_enc`, C.3; + * normalized MSE, Sec. 2.1. + + The firing threshold `1e-3` and the `latent_bias` follow the authors' reference code, + , read the same day. +* **Auxiliary dead-latent loss lineage.** Adam Jermyn and Adly Templeton. **Ghost Grads: An improvement on + resampling.** In *Circuits Updates – January 2024*, Transformer Circuits Thread, January 2024. + . Gao et al. describe + AuxK as similar to ghost grads. This module implements AuxK, not ghost grads. +* **TopK activation origin.** Alireza Makhzani and Brendan Frey. **k-Sparse Autoencoders.** arXiv:1312.5663 + (December 2013, revised March 2014); listed by DBLP under ICLR 2014. . + +## Measured results + +All numbers were measured on 2026-11-17 on Windows 11 ARM64 (Qualcomm ARMv8 CPU), Python 3.12.10, NumPy 2.4.3, with +`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`. Other agents shared the CPU, so wall-clock is +indicative only. + +**Quick mode** (`run_experiment(quick=True)`): seeds `(0, 1, 2)`, held-out seed `(100,)`, `delayed_recall`, 24 +neurons, `clustered`, no mechanisms, 120 training / 60 held-out steps, 32 features, `k=4`, `n_ablate=3`, +`random_draws=2`, 40 dictionary epochs (batch 16, lr 3e-3), refit readout (L2 1e-2). + +| | value | +|---|---| +| verdict | **no_detectable_difference** | +| targeted − random held-out log-loss | +0.0139, 95 % CI [−0.0579, 0.0857], d_z 0.48 | +| targeted − none held-out log-loss | +0.0236, 95 % CI [−0.0367, 0.0839] | +| random − none held-out log-loss | +0.0097, 95 % CI [−0.0238, 0.0433] | +| held-out log-loss (none / targeted / random) | 0.638 / 0.661 / 0.647; constant predictor 0.691 | +| held-out accuracy (none / targeted / random) | 0.628 / 0.567 / 0.625; chance 0.533 | +| dictionary FVU, train / held-out (per seed) | 0.047 / 0.126, 0.032 / 0.067, 0.032 / 0.183 | +| dead fraction at end of training (per seed) | 0.34, 0.31, 0.38 | +| original engines unchanged | true | +| digest (prefix) | `0562be1283cf59b4` (identical across two processes) | +| measured wall-clock | 2.70 s; 6.39 s in an earlier run under heavier CPU load | + +**Default size** (`run_experiment()`): seeds `(0, 1, 2)`, held-out seeds `(100, 101)`, 48 neurons, 300 / 150 +steps, 64 features, `k=8`, `n_ablate=4`, `random_draws=4`, 60 epochs (batch 32). + +| | value | +|---|---| +| verdict | **no_detectable_difference** | +| targeted − random held-out log-loss | +0.0053, 95 % CI [−0.0373, 0.0478] | +| targeted − none held-out log-loss | +0.0350, 95 % CI [0.0085, 0.0616] (interval excludes zero) | +| random − none held-out log-loss | +0.0298, 95 % CI [−0.0367, 0.0962] | +| readout skill over the constant predictor (held-out, none arm) | 0.127 nats | +| dictionary FVU, train (per seed) | 0.013, 0.016, 0.014 | +| digest (prefix) | `93a7ef790ae2b8a9` | +| measured wall-clock | 28.9 s under concurrent load | + +**Observer cost** at the default size: 256 units, 64 features, `k=8`, batch 8, train every observation. + +* About 1.4 ms per `observe` and 0.6 ms per `summary()`. +* `summary()` JSON is 2.9 KB. +* `export_state()` JSON is 3.65 MB. That covers the ring buffer, parameters and Adam moments, which an exact + continuation needs. +* Measured over 500 observations on random dense activity. FVU EMA is 0.91 there, because that data has no + sparse structure. + +Reading: in these small engines, removing the dictionary features most correlated with the delayed-recall target +does raise held-out log-loss at default size. The paired interval does not show that it raises log-loss more +than removing the same number of random alive features. The features selected by correlation are only weakly +predictive (|r| ≈ 0.14–0.26), and the readout has little skill to lose (0.05–0.13 nats over a constant). + +Unit-level checks in `tests/test_frontier_sae.py` (21 tests, about 7 s single-threaded): + +* TopK matches a brute-force sort exactly. +* Gradients, including AuxK, match central finite differences to within 1e-6. +* A planted dictionary is recovered. With 16 unit-norm atoms in 12 dimensions, 2 active per sample, 800 samples + and 30 epochs, FVU is below 0.1 and at least 14 of 16 atoms have a decoder column with cosine above 0.9. +* Decoder norms stay within 1e-12 of 1. +* AuxK revives latents whose encoder rows were shrunk 50×. With AuxK, at least 2 of 4 fire on more than 5 % of + samples and FVU is lower. Without AuxK they stay dead. +* Observer FVU EMA falls from above 0.5 to below 0.3 on planted data. +* Exact state round-trips with full validation. +* Ablation on clones only, with the original engine's digest unchanged. +* The quick receipt is sealed and deterministic. diff --git a/docs/frontier/modules/synchrony.md b/docs/frontier/modules/synchrony.md new file mode 100644 index 0000000000000000000000000000000000000000..17d97626e7365cd5501751cbfc746088d4844957 --- /dev/null +++ b/docs/frontier/modules/synchrony.md @@ -0,0 +1,338 @@ +# `synchrony`: synchronisation representation and neuron-level models + +Module file: `synapse/frontier/synchrony.py` · tests: `tests/test_frontier_synchrony.py` · +experiment ids: `synchrony`, `synchrony_ctm` · engine extension: `SynchronyExtension` (id `synchrony`) · +live observer: `SynchronyObserver` · standalone model: `MiniCTM` · evidence tier: `synthetic_abstraction`. + +The module borrows three ideas from **Continuous Thought Machines** (CTM; Darlow et al., NeurIPS 2025) and uses +them at toy scale: + +* **Synchronisation as a representation.** The exponentially decayed inner product of two units' activity + histories, kept by a two-number recursion per unit pair. It is used as extra readout features of a NEUROWEAVE + brain (engine extension) and as a read-only activity statistic (live observer). +* **Private neuron-level models (NLMs).** Every neuron of `MiniCTM` has its own tiny MLP over its last `M` + pre-activations. +* **Internal ticks with a tick-selecting loss.** `MiniCTM` "thinks" for `T` ticks per input and is trained + on the minimum-loss tick and the most-certain tick. + +It is *inspired by* the CTM and does not reproduce it. The models here are thousands of parameters, not +millions. The benchmark is cumulative parity of 12-bit sequences (8 in quick mode), not 64. Nothing below says +anything about the paper's mazes, ImageNet or parity results, about biological synchrony, or about thought. + +## What it computes + +**Synchronisation (CTM Sec. 3.4, Eq. 10; App. H, Eqs. 13–17).** For a unit pair `(i, j)` with decay rate +`r >= 0` and activities `z^1 … z^t`: + +``` +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)} ) + +alpha <- e^{-r} alpha + z_i z_j beta <- e^{-r} beta + 1 S = alpha / sqrt(beta) +``` + +The recursion needs two numbers per pair and no stored history. `decayed_synchrony(history, left, right, +decay)` is the closed form. Tests check that the extension's recursion equals it on a hand-computed +three-step example, to 1e-12 relative error, and on a random 40-step history, to 1e-12 absolute. They also +check that `MiniCTM`'s batched recursion equals it at every tick for both of its synchronisation +representations. + +**Bounds.** With `|z| <= 1`, `|alpha| <= beta`, so `|S| <= sqrt(beta) < 1 / sqrt(1 - e^{-r})`. For a steady +product, `S` grows like the square root of the effective window; that is the paper's normalisation. The +optional "unit" scale `S * sqrt(1 - e^{-r})` stays in `[-1, 1]`; with `z = 1` everywhere it equals +`sqrt(1 - e^{-r t})` exactly (tested). + +**Pair sampling (CTM App. C.2, "random pairing").** `sample_pairs(n, pairs, self_pairs, rng)` returns +`self_pairs` self pairs `(i, i)` first, then distinct unordered cross pairs `i < j`. The CTM adds self pairs +so the representation can recover a snapshot of single-unit activity. One difference from the reference code: +it samples indices with replacement, while here self pairs use distinct units and cross pairs repeat only +when more are requested than `n (n - 1) / 2` exist. + +**Timescales.** The CTM learns one rate `r_ij` per pair, starting at 0 (no decay). The extension and the +observer fix the rates instead: `log_uniform_timescales` spreads `tau_p = 1 / r_p` log-uniformly (stratified, +in a seeded order) over a range, so features cover several timescales at once. + +## Engine extension (`SynchronyExtension`, id `synchrony`) + +```python +SynchronyExtension(pairs=32, *, seed=0, self_pairs=None, timescales=(1.0, 32.0), feature_scale='ctm') +``` + +* `bind(engine)` samples `pairs` unit pairs (default `self_pairs = pairs // 8`) from the `engine.n` units + present at bind time. It keeps no reference to the engine. Units born later are ignored and missing units + count as silent, so the feature shape never changes. +* `after_step(output, ctx)` runs the recursion on the brain output `z` (clipped to `[-1, 1]`; brain outputs + already lie there). Pair `p` has the fixed decay `exp(-1 / tau_p)`, with `tau_p` log-uniform over + `timescales` steps. +* `features()` returns the `pairs` values of `S` (`feature_scale='ctm'`), or `S * sqrt(1 - decay)` (`'unit'`), + clipped to `[-10, 10]`. Before the first step it returns zeros. +* Nothing adapts: there are no trainable parameters (`parameter_count() == 0`), and `ctx['learn']` changes + nothing. The accumulators still follow activity, which is inference. `transform_drive` is not overridden, + so the brain's drive and outputs are bit-identical with and without the extension (tested). +* `export_state()` / `import_state()` round-trip exactly. `import_state` validates everything before it + changes anything: the configuration and pair indices must match, the arrays must be finite and of the + right shape, `beta` must equal its closed form `(1 - d^steps) / (1 - d)`, and `|alpha| <= beta`. +* `copy.deepcopy` gives an independent clone. `telemetry()` reports mean and max `|S|`. + +## Live observer (`SynchronyObserver`) + +```python +SynchronyObserver(n_units, *, seed=7, history=256, pairs=64, self_pairs=None, zclip=5.0) +SynchronyObserver.from_spec(n_units, spec) # FrontierSpecV1: seed, history, sync_pairs +``` + +* **z-scoring.** Each unit has a running mean and variance. They are exact (Welford) for the first `history` + observations and exponentially weighted with rate `1/history` afterwards. z-scores are clipped to + `[-zclip, zclip]`. +* **Timescales.** `observer_timescales(history)` gives `2 * 4^k` steps up to `history / 2`, so + `(2, 8, 32, 128)` for `history = 256`. At each timescale every sampled pair keeps the recursion above on + z-scores, and every unit in a pair keeps `q_u <- d q_u + z_u^2`. +* **Two measures per pair and timescale.** `S` is the CTM-scaled synchrony. The decayed correlation + `C = alpha / sqrt(q_i q_j)` lies in `[-1, 1]` by Cauchy–Schwarz. +* **`summary()`** (JSON-safe, no wall-clock, under 16 KB even at 4096 pairs; tested): + `module`, `n_units`, `pairs`, `self_pairs`, `cross_pairs`, `timescales`, `zscore_window`, + `observed_steps`; + `per_timescale` (one row per timescale with `tau`, `mean_abs_S`, `max_abs_S`, `mean_abs_corr` and + `max_abs_corr` over cross pairs); + `global_synchrony_index` (mean `|C|` over cross pairs at the slowest timescale); + `top_pairs` (the 8 cross pairs with the largest `|C|` at the slowest timescale, each with `i` and `j` + indices into the observed units, plus `corr`, `corr_by_tau` and `S_by_tau`); + `synchrony_entropy` (Shannon entropy of the `|C|` distribution over cross pairs divided by `log(cross pairs)`: + 1 when synchrony is spread evenly, lower when it is concentrated; `None` when undefined). +* **Known answers (tested).** Identical units give `C = 1` on every pair and timescale and entropy 1. A planted + in-phase pair and two planted anti-phase pairs are the top three pairs, with `C = +1` and `C = -1`. For + independent noise, mean `|C|` falls monotonically with the timescale and is below 0.15 at `tau = 128`. +* The observer copies its input and never writes to it. Every buffer has a fixed size: `O(n_units)` moments + and `O(timescales × pairs)` accumulators, with no activity history. `import_state` validates fully before + mutating, including the `beta`/`steps` identity and the Cauchy–Schwarz bound. + +## `MiniCTM` (PyTorch) + +```python +MiniCTM(seq_len, *, vocab=2, classes=2, d_model=32, memory=4, nlm_hidden=4, ticks=8, d_input=16, + n_sync_out=32, n_sync_action=16, self_pairs=4, decay_init=(0.03, 1.0), seed=0) +model(tokens, ticks=None, *, track=False) -> (logits (B, T, L, C), certainty (B, T)) [, record] +``` + +The input (token ids, shape `(B, L)`) is read whole. Token and learned position embeddings pass through +Linear and LayerNorm to give identical keys and values (as in the paper's parity setup, App. F.4). From learnable +start states `z^0` and pre-activation history `A^0`, each tick `t = 1 … T` runs, in the reference code's order: + +``` +q = W_in S_action action synchrony -> attention query (Eq. 7) +o = softmax(kv q / sqrt(d_input)) kv single-head attention over the input (Eq. 8) +a = LayerNorm(GLU(W_syn [z ; o] + b)) synapse model, depth 1 (Eq. 1) +A = [A[:, 1:], a] last M pre-activations per neuron (Eq. 2) +z_d = GLU(GLU(A_d W1_d + b1_d) W2_d + b2_d) private NLM of neuron d (Eq. 3) +alpha <- e^{-r} alpha + z_i z_j ; S_out = alpha / sqrt(beta) +y_t = W_out S_out per-tick logits for all L positions (Eq. 6) +``` + +* **NLMs** (`NeuronLevelModels`). The weights `W1` with shape `(D, M, 2H)` and `W2` with shape `(D, H, 2)` + hold one private slice per neuron. Each layer is one batched einsum over the neuron axis + (`'dbm,dmh->dbh'`), the reference's `einsum('BDM,MHD->BDH')` with the neuron axis first. A test checks the + two contractions agree. It also checks privacy: the gradient of neuron `k`'s output reaches only neuron + `k`'s weights and history, and changing every other neuron's history leaves neuron `k`'s output and + weight gradients bit-identical. +* **Synchronisation** uses random pairing with `self_pairs` self pairs per representation. Each pair has a + learnable rate `r = softplus(rho)`, initialised log-uniform over `decay_init`, which gives timescales of + 1–33 ticks. The action pairs and the output pairs share one recursion state, because both read the same + post-activations. The action representation at tick `t` is therefore built from `z^0 … z^{t-1}`, and the + output representation from `z^0 … z^t`. Both start from the learnable `z^0`, as in the reference code. +* **Certainty** `C_t` is 1 minus the normalised entropy, averaged over output positions. +* **Loss** (`ctm_tick_loss`, Sec. 3.5, Eq. 11). `L_t` is the cross-entropy averaged over positions. Per sample, + `t1 = argmin_t L_t` and `t2 = argmax_t C_t`, and `loss = (L_t1 + L_t2) / 2`. With one tick it reduces to + plain cross-entropy (tested). Evaluation reads each sample's most-certain tick. +* **Tested.** Output shapes. A 1-tick run equals the first tick of a longer run. Logits differ across ticks. + Parameter counts match the analytic formula. Construction never touches the global torch RNG, and the same + seed gives the same weights whatever the global RNG state. The fused attention equals explicit softmax + attention in values and gradients. + +**Baselines.** `AttentiveGRU` is a `GRUCell` unrolled for the same `T` ticks. It reads the input through the +same attention reader, with the query taken from its hidden state, and is trained with the same tick loss. It +stands in for the paper's parameter-matched LSTMs run for the same number of ticks. `ParityMLP` is one hidden +ReLU layer over the whole ±1 sequence, with one tick. + +## CTM benchmark (`run_ctm_benchmark`, id `synchrony_ctm`) + +* **Task.** Cumulative parity (CTM Sec. 6, App. F.3): the target at position `l` is the parity of bits + `0 … l`, and the whole sequence is presented at once. `cumulative_parity_data(L, seed, heldout)` enumerates + all `2^L` sequences and splits off `heldout` of them by a seeded permutation, so held-out sequences are + never trained on. +* **Arms.** `MiniCTM`, `AttentiveGRU` and `ParityMLP`. The GRU and MLP widths are chosen so their trainable + parameter counts match `MiniCTM`'s within 10 % (else `ValueError`). Counts are computed analytically and + checked against the instantiated models. +* **Protocol.** Per seed, all three models share the split, the minibatch index sequence (NumPy generator), + AdamW (fused CPU kernel where available), the learning rate, weight decay 0.01, gradient clipping at 1.0 + and the step count. PyTorch runs on one thread, and the caller's thread count is restored. The global torch + RNG is never used. +* **Verdict.** `harness.compare` on per-seed held-out per-position accuracy (mean over positions and held-out + sequences), MiniCTM against the best baseline. The best baseline is the one with the higher mean, chosen + after the fact, which favours the baseline. `verdict_basis` names it. Comparisons against both baselines are + also stored. +* **Receipt.** `config` (every size, the optimiser, the readout, the loss, the torch version and threads); + `models.` with `trainable_parameters`, `per_seed` (held-out and train accuracy, per-position accuracy, + whole-sequence accuracy, last-tick accuracy, mean most-certain tick, a loss curve, the optimiser + implementation and wall-clock) and a `summary`; `parameter_budget`; `comparisons`; `verdict`; + `verdict_basis`; `estimated_cost` (forward multiply-accumulates per sequence and for training), kept apart + from `measured_wallclock_s`; and `notes`. + +| Setting | quick | default | +|---|---|---| +| `seq_len` L / held-out of 2^L | 8 / 64 of 256 | 12 / 512 of 4096 | +| `ticks`, `d_model`, `d_input`, `memory`, `nlm_hidden` | 4, 24, 12, 4, 4 | 8, 32, 16, 4, 4 | +| `n_sync_action`, `n_sync_out`, `self_pairs` | 12, 24, 3 | 16, 32, 4 | +| steps × batch, learning rate | 100 × 32, 0.01 | 800 × 64, 0.01 | +| trainable parameters: MiniCTM / GRU / MLP | 4036 / 3978 (h 25) / 4041 (h 161) | 6600 / 6680 (h 32) / 6610 (h 178) | + +## Lab experiment (`run_experiment`, id `synchrony`) + +`harness.run_extension_experiment('synchrony', factory, task='rhythm', control='random_trace', +metric='accuracy', ...)` runs three arms: the NEUROWEAVE baseline readout, the baseline plus +`SynchronyExtension` features, and the baseline plus the same number of random leaky-trace features (the +capacity-matched control). All arms share seeds, streams and the readout protocol, and held-out streams are +evaluated frozen. The verdict is `improved` only if the candidate beats both the baseline and the control. The +defaults are those of the harness (seeds 0, 1, 2; held-out seeds 100, 101; 300 steps; 48 neurons; clustered +topology; no extra mechanisms), with 32 pairs, `timescales=(1, 32)` and `feature_scale='unit'`, so the +features share the control's `[-1, 1]` range. Quick mode uses the harness `QUICK_ARGS` sizes with the +caller's seeds and 16 pairs. Overrides: `pairs`, `self_pairs`, `timescales`, `feature_scale`, `task`, +`heldout_seeds`, `steps`, `heldout_steps`, `neurons`, `topology`, `mechanisms`. + +## Public API + +```python +MODULE_ID = 'synchrony' +EXPERIMENTS = {'synchrony': run_experiment, 'synchrony_ctm': run_ctm_benchmark} +run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +run_ctm_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt +SynchronyExtension(pairs=32, *, seed=0, self_pairs=None, timescales=(1.0, 32.0), feature_scale='ctm') +SynchronyObserver(n_units, *, seed=7, history=256, pairs=64, self_pairs=None, zclip=5.0) +sample_pairs(n, pairs, self_pairs, rng); log_uniform_timescales(count, low, high, rng) +decayed_synchrony(history, left, right, decay); observer_timescales(history) +cumulative_parity_data(seq_len, seed, heldout); ctm_tick_loss(logits, targets, certainty=None) +# PyTorch classes, created on first attribute access (importing the module does not import torch): +MiniCTM, NeuronLevelModels, SequenceReader, AttentiveGRU, ParityMLP +``` + +NumPy randomness comes from `numpy.random.default_rng(seed + offset)`. PyTorch parameters are drawn from +private seeded `torch.Generator` objects by small private layer classes (linear, layer norm, GRU cell) that +create their own parameters with PyTorch's default initialisation distributions instead of calling the +`torch.nn` constructors, so the global torch RNG is never read or advanced. Tests check each layer against its +`torch.nn` counterpart and check that construction leaves the global RNG state unchanged. Every public function +and constructor validates its input and raises `ValueError` on bad input. + +## Connection to Sonapse + +* **Live observer.** `synchrony` is in `spec.OBSERVER_MODULE_IDS`, so a `FrontierSpecV1` may list it in + `modules`. `SynchronyObserver.from_spec(n_units, spec)` takes `seed`, `history` and `sync_pairs` from the + spec. The observer reads a copy of activity and never writes to the brain, graft bus, actor or any shared + RNG. This module does not wire it into the live runtime; the runtime hook lives elsewhere. +* **Engine extension.** It influences nothing unless attached to a NEUROWEAVE engine with + `attach_extension`, as in the lab experiment. Even then it only adds readout features. +* **Standalone model.** `MiniCTM` and its baselines exist only inside `run_ctm_benchmark`. +* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes. + +## Not implemented, and differences from the paper + +* **Decay rates.** They are fixed in the extension and the observer; the CTM learns them. In `MiniCTM` they + are learned as `r = softplus(rho)` with a log-uniform start. The reference code clamps `r` to `[0, 15]` and + starts it at 0. +* **Attention.** It is single-head, without the separate query/key/value and output projections of the + reference's `nn.MultiheadAttention`; the paper's parity models used 8 heads. Keys and values come from a + learned embedding reader, not a convolutional backbone. +* **Synapse model.** Only the depth-1 Linear–GLU–LayerNorm block is implemented, not the U-Net synapse. +* **NLMs.** They omit the reference `SuperLinear`'s learnable output temperature, its optional LayerNorm and + dropout. +* **Pairing.** Only random pairing is implemented; the paper's parity runs used semi-dense pairing. +* **Training schedule.** Constant learning rate, with no warmup or cosine schedule (the paper used both). +* **Scale.** The paper used 64-bit sequences, `d_model` 1024, `d_input` 512, up to 100 ticks and 200,000 + iterations. Here L is 12 or 8, `d_model` is 32 or 24, there are 4–8 ticks and 100–800 AdamW + steps. These runs measure early learning of short parities. They are not a test of the + paper's claim. +* **Baselines.** The GRU replaces the paper's LSTM. It is trained with the same tick loss and read at its + most certain tick; the paper trained its LSTMs on the final tick, reporting that both losses were unstable + for them. +* **Not attempted.** Adaptive halting by certainty threshold at inference, and any of the paper's other tasks + (mazes, ImageNet, sorting, Q&A, RL). + +## Verified references + +Checked on 2026-11-17 against the arXiv listing, the NeurIPS virtual-conference page, the paper's full text +(arXiv PDF) and the reference code. Re-checked on 2026-11-20 (review) against the reference code: the +`compute_synchronisation` recursion (`alpha <- r alpha + z_i z_j`, `beta <- r beta + 1`, `S = alpha / sqrt(beta)`), +the decay clamp to `[0, 15]`, the initial output-synchronisation call before the tick loop, the loop order +(action synchronisation, attention, synapses, trace, neuron-level models, output synchronisation, prediction) +and `parity_loss` (per-position mean, `argmin` loss tick, `argmax` of `1 - normalised entropy`, mean of the +two); `MiniCTM` and `ctm_tick_loss` match them. + +1. Luke Darlow, Ciaran Regan, Sebastian Risi, Jeffrey Seely, Llion Jones (Sakana AI). **Continuous Thought + Machines.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*, spotlight poster. + arXiv:2505.05522 (v1 8 May 2025, v4 3 October 2025). https://arxiv.org/abs/2505.05522 · + https://neurips.cc/virtual/2025/loc/san-diego/poster/115192. Checked against the full text: Sec. 3.2–3.5 + (Eqs. 1–11: synapse, pre-activation history, NLMs, synchronisation and its decay rescaling, the + min-loss/max-certainty loss); App. C.2 (random pairing with `n_self` self pairs); App. F.3–F.5 (parity + data, architecture, optimisation and parameter-matched LSTM baselines); and App. H (Eqs. 12–17, the + recursive computation). +2. Reference implementation: **SakanaAI/continuous-thought-machines**, + https://github.com/SakanaAI/continuous-thought-machines. Read on 2026-11-17: `models/ctm.py` + (`compute_synchronisation` recursion; decay parameters initialised at 0 and clamped to `[0, 15]`; + random-pairing selection with self pairs; depth-1 synapse; tick-loop order), `models/modules.py` + (`SuperLinear`: per-neuron `einsum('BDM,MHD->BDH')` and a learnable temperature) and `utils/losses.py` + (`parity_loss`: cross-entropy averaged over positions, then the mean of the min-loss and most-certain + ticks). + +## Measured results + +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 +and `OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1` (the CTM benchmark also runs torch on one thread). +The machine was shared with other jobs, so wall-clock is indicative only. Receipts are deterministic: two calls +in one process gave the same digest, and the quick digests below were identical in two separate processes that +day. Seeds are `(0, 1, 2)` throughout. + +**CTM benchmark, quick** (`run_ctm_benchmark(quick=True)`; digest `c24433021c0c76a0`; 17.8 s under load). +Cumulative parity of 8 bits, 64 held-out of 256 sequences, 100 steps × 32. + +| Model | Parameters | Held-out per-position accuracy (per seed) | Mean | Train accuracy (mean) | +|---|---:|---|---:|---:| +| `MiniCTM` (4 ticks) | 4036 | 0.553, 0.572, 0.576 | 0.567 | 0.611 | +| `AttentiveGRU` (4 ticks) | 3978 | 0.537, 0.572, 0.596 | 0.568 | 0.591 | +| `ParityMLP` | 4041 | 0.658, 0.678, 0.662 | 0.666 | 0.841 | + +* `mini_ctm − gru`: −0.0013, 95 % CI [−0.0451, +0.0425]; `mini_ctm − mlp`: −0.0990, CI [−0.1270, −0.0709]. + The verdict compares against the MLP (the higher held-out mean): **`worse`**. + +**CTM benchmark, default** (`run_ctm_benchmark()`; digest `d838aee28cb46d8e`; 228.9 s under load). 12 bits, 512 +held-out of 4096 sequences, 800 steps × 64. + +| Model | Parameters | Held-out per-position accuracy (per seed) | Mean | Whole-sequence accuracy (mean) | +|---|---:|---|---:|---:| +| `MiniCTM` (8 ticks) | 6600 | 0.639, 0.648, 0.668 | 0.652 | 0.003 | +| `AttentiveGRU` (8 ticks) | 6680 | 0.622, 0.652, 0.708 | 0.660 | 0.005 | +| `ParityMLP` | 6610 | 0.908, 0.877, 0.889 | 0.891 | 0.210 | + +* `mini_ctm − gru`: −0.0087, CI [−0.0806, +0.0631]; `mini_ctm − mlp`: −0.2399, CI [−0.3043, −0.1754] → + **`worse`**. +* Per position, `MiniCTM` is at 1.0 for the first three positions, 0.89 for the fourth and near 0.5 (chance) + from the fifth on: at this size and training budget it does not learn cumulative parity beyond a few bits. + 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 + larger and trained far longer; this run says nothing about them. + +**Lab experiment** (`run_experiment`, task `rhythm`, metric held-out accuracy). + +| Run | Digest | Held-out accuracy: baseline / candidate / control | Candidate − baseline | Candidate − control | Verdict | Wall-clock | +|---|---|---|---|---|---|---| +| 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 | +| 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 | + +In quick mode every arm predicts the majority class on the 12 held-out steps, so accuracies tie exactly; the +synchrony features do change the readout (held-out log-loss 0.624 / 0.576 / 0.559 for the baseline and +0.635 / 0.580 / 0.559 for the candidate, per seed). At the default size the readout is close to the +majority-class rate for all arms; the features neither help nor hurt measurably. + +**Observer cost.** `SynchronyObserver.from_spec(256, FrontierSpecV1())` (64 pairs, `history = 256`): 0.09 ms +per `observe()` (mean of 300 calls on uniform random activity), and a `summary()` of 2.9 KB of JSON. + +Unit tests (`tests/test_frontier_synchrony.py`, 36 tests) check, among other things: the recursion against the +closed form `decayed_synchrony`; the CTM loss against a hand-computed min-loss / max-certainty selection; the +`MiniCTM` synchronisation against a direct sum over ticks; identical, in-phase and anti-phase units in the +observer; validated state round-trips; and sealed, deterministic receipts that leave the global RNGs and thread +count unchanged. diff --git a/docs/neuroweave/CHANGELOG.md b/docs/neuroweave/CHANGELOG.md index 9bbbf78926961c004252d849c82c21f07590881a..b1e1aa5f22494a7cf05b823dec2fbf6be09df525 100644 --- a/docs/neuroweave/CHANGELOG.md +++ b/docs/neuroweave/CHANGELOG.md @@ -1,5 +1,64 @@ # NEUROWEAVE changelog +## [Unreleased] — associative trace memory and fast weights (2026-11-19) + +### Added + +- `associative_memory` and `fast_weights` are now implemented as engine-level + mechanisms. Before this change they were declared in the spec but not + consumed by the runtime. + - `engine.AssociativeTraceMemory`: a bounded FIFO of 32 episodes, recalled + by cosine similarity. + - `engine.FastWeightMemory`: a reward-gated 8×8 value/key matrix. + - Both reads feed a new optional per-unit input, + `NeuroWeaveBrain.step(unit_input=...)`. + - The rules, constants and their source are in README section 6. +- The new state is exported under `export_state()['associative_memory']` and + `['fast_weights']` only when the flag is on. `import_state` validates both + before swapping, including the counts the rules imply (README section 6). + Older states without these keys still import, with fresh memories. This was + also checked with a real state exported by the pre-change package + (README section 12). +- New tests: `tests/test_neuroweave_assoc_fastweights.py`, 25 tests. + +### Changed + +- With neither flag, engine outputs, states and observatories are unchanged. + A 2026-11-20 check against the committed NEUROWEAVE package (commit + `b9d8270`) found them bit-identical for three mechanism sets (README + section 12). +- With either flag on, outputs change from the step after the first store or + write. Specs that enable them change behaviour, including the Max Mode preset + (every mechanism) and the `associative_memory` and `cross_modal_learning` + experiments. +- In the 8-step `associative_memory` lab run (seeds 0 and 1, held-out seed 100, + 4 held-out steps, 16 neurons), only `associative_memory` is still inert; + `fast_weights` now gets an ablation verdict. The expectation in + `tests/test_neuroweave_review_fixes.py::test_inert_ablation_is_flagged_not_reported_as_a_verdict` + that both are inert there therefore no longer holds. That test was not + edited in this change: it still expects both and fails until it is changed + to expect `associative_memory` alone (the new + `test_lab_associative_experiment_measures_fast_weights_and_flags_the_short_run_store_as_inert` + covers the new expectation). +- `standalone.py`: the not-executed reasons for the two mechanisms now say + that their state is engine state that the package does not carry. The JS + page still runs neither. + +### Known limitations + +- No benefit is shown. Quick-mode receipts re-run on 2026-11-20 (settings in + README section 12) gave `no_detectable_difference` for `associative_memory` + and `cross_modal_learning`. +- In runs of 12 or fewer training steps the lab never stores an episode, so + `associative_memory` is reported as `inert_in_this_configuration` there. + `fast_weights` is written on the first learning step with non-zero reward and + acts from the next step. At the reference constants its effect on outputs is + small in short runs, and with `q88_state` on Q8.8 rounding can absorb it + entirely (README section 12). +- `experiments._budget` does not count the fast-weight matrix or the episode + store in `trainable_parameters`. Counted, the quick `associative_memory` + receipt's parameter ratio would be 258/194 instead of 194/194. + ## [Unreleased] — NEUROWEAVE evolution v1 (2026-11-15) Baseline: git tag `sonapse-pre-neuroweave-baseline` (commit `6f2761b`). All @@ -97,7 +156,7 @@ checkpoint namespace or test was removed or changed in behaviour. ### Known limitations - `associative_memory` and `fast_weights` are declared in the spec but not - consumed by the runtime. + consumed by the runtime. (Implemented on 2026-11-19; see the entry above.) - Every verdict so far for the 24 registered experiments (quick mode only) is `no_detectable_difference`; the full-size experiments have not been run. The supplementary sequence-variant search reports `worse` overall and diff --git a/docs/neuroweave/FEATURE_MATRIX.md b/docs/neuroweave/FEATURE_MATRIX.md index b638b6cc8d269d06ad0c24a7a5b47bf15bb8ee9e..b91042f7be0db9f51d28dc67012155881ab1f50c 100644 --- a/docs/neuroweave/FEATURE_MATRIX.md +++ b/docs/neuroweave/FEATURE_MATRIX.md @@ -57,8 +57,8 @@ NEUROWEAVE versions are separate, independent implementations. | NEUROWEAVE 0.4.0 feature | Sonapse status | Where / notes | |---|---|---| -| Associative trace memory | **Not ported as a runtime mechanism** | `associative_memory` is declared in the spec but no runtime code reads it. Its role is taken by `memory_ecology`. | -| Universal fast weights (8×8) | **Not ported as a runtime mechanism** in NEUROWEAVE; **already present** in Sonapse | `fast_weights` is declared but not read by the runtime. Related pre-existing module: `synapse/fast_weight_memory.py`. | +| 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`. | +| 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`. | | Hierarchical temporal memory (fast/mid/slow per unit) | **Adapted** | `cells.py` | | — | **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` | diff --git a/docs/neuroweave/README.md b/docs/neuroweave/README.md index 785195040e7d1156fef080469a260532467fbb28..3fd00b7e9b1ed0b01eded87a9a2b28059bdc1e77 100644 --- a/docs/neuroweave/README.md +++ b/docs/neuroweave/README.md @@ -68,7 +68,7 @@ The pre-NEUROWEAVE system is frozen at git tag | Packets / events | `packets.py`, `events.py` | typed representation packets, fusion, event bus | | Ecology | `ecology.py` | 1200×660 arena with 7 configs; Sonapse 155-d observation adapter | | Hardware / packages | `hardware.py`, `package.py` | INT8/Q8.8, tile schedule, FPGA mapping manifest, `SONAPSE_NEUROWEAVE_PACKAGE`, legacy import | -| Engine | `engine.py` | `NeuroWeaveEngine` composes all subsystems | +| Engine | `engine.py` | `NeuroWeaveEngine` composes all subsystems; engine-level `AssociativeTraceMemory` and `FastWeightMemory` (added 2026-11-19) | | Sonapse bridge | `bridge.py` (the only torch module) | `NeuroWeaveBusChannel`, `obs_to_sensory` | | Laboratory | `tasks.py`, `experiments.py`, `lesion.py`, `promotion.py` | 24 experiments, lesion assay, promotion ledger | | Standalone runner | `standalone.py` | offline HTML page with JS frozen inference | @@ -154,9 +154,10 @@ extensions. - `connectome`: `brain.CONNECTOME_FLAGS` - `engine`: `engine.ENGINE_FLAGS` -The union of these sets has 43 ids. **`associative_memory` and `fast_weights` -are declared in the spec but no runtime code reads them.** They are marked -*declared only* below. Memory behaviour comes from `memory_ecology`. +The union of these sets covers all 45 ids. Until 2026-11-19 +`associative_memory` and `fast_weights` were declared in the spec but read by +no runtime code. They are now engine-level mechanisms (rows 4 and 18; rules in +section 6). `memory_ecology` is still a separate store. **Tests:** abbreviations for the test files. - `core` = `tests/test_neuroweave_core.py` @@ -164,6 +165,7 @@ are declared in the spec but no runtime code reads them.** They are marked - `ms` = `test_neuroweave_modulation_sensory.py` - `mm` = `test_neuroweave_micro_memory.py` - `pp` = `test_neuroweave_prediction_packets.py` +- `af` = `test_neuroweave_assoc_fastweights.py` - `hw` = `test_neuroweave_hardware_package.py` - `sa` = `test_neuroweave_standalone.py` @@ -180,7 +182,7 @@ against Python for the four mechanism sets in that file. | 1 | `multi_soma` | neuroweave | implemented | cells | core::each_neuron_flag, core::each_consumed | | 2 | `structural_encoder` | neuroweave | implemented | brain | core::each_consumed; sa (embedded weights) | | 3 | `sparse_code` | neuroweave | implemented | cells, brain | core::each_neuron_flag, `test_q88_and_sparse` | -| 4 | `associative_memory` | neuroweave | **declared only** | not read by the runtime | standalone lists it as not executed (`sa::test_capabilities_list_every_enabled_mechanism`) | +| 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` | | 5 | `reward_plasticity` | neuroweave | implemented | connectome | `core::test_reward_update_bounded_sign_preserving_and_meta`, core::each_consumed | | 6 | `synaptic_delays` | neuroweave | implemented | connectome | `core::test_delay_ring_buffer`, core::each_consumed | | 7 | `homeostatic_governor` | neuroweave | implemented | cells | core::each_neuron_flag | @@ -194,7 +196,7 @@ against Python for the four mechanism sets in that file. | 15 | `adaptive_conduction` | neuroweave | implemented | connectome | core::each_consumed, `core::test_frozen_step_does_not_change_synaptic_myelin` | | 16 | `quantised_synapses` | neuroweave | implemented | connectome | `core::test_quantised_int8`, `hw::test_quantise_int8_symmetric_and_bounded` | | 17 | `axonal_branches` | neuroweave | implemented | cells | core::each_neuron_flag, `core::test_cell_myelin_sets_axonal_release_efficacy` | -| 18 | `fast_weights` | neuroweave | **declared only** | not read by the runtime | standalone lists it as not executed | +| 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` | | 19 | `efference_self_model` | neuroweave | implemented | engine / prediction | `eng::test_engine_level_mechanism_changes_outputs`, `pp::test_efference_*` (4 tests) | | 20 | `predictive_coding` | neuroweave | implemented | cells | core::each_neuron_flag | | 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 | Specialist graft | A separate small recurrent predictor trained only through its own interface. Its coupling starts at 0. `detach()` removes it without residue. | | Representation fusion | Configured or delta-rule learned fusion weights. With zero weights or no packets the input passes through unchanged. | | Memory ecology | Store, retrieve, confirm, replay, forgetting and downscaling. `PREDICTED` items are never returned as verified and are promoted only by `confirm()`. | +| 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. | +| 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. | | 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. | +**Associative trace memory and fast weights (engine-level, added 2026-11-19).** +These are `AssociativeTraceMemory` and `FastWeightMemory` in `engine.py`. The +recall and the fast-weight read are summed into one per-unit input, +`NeuroWeaveBrain.step(unit_input=...)`. That input is added to the +feed-forward drive after any receptor gain. + +Behaviour and tests (all in `af`): +- **Exact no-op when off.** Without either flag the engine never passes + `unit_input`, and states and observatories gain no new keys + (`test_neither_flag_keeps_the_previous_code_path`). With the flags on but + nothing written yet, outputs are bit-identical to the engine without them + (`test_empty_store_and_zero_matrix_contribute_exactly_nothing`). +- **Learning only with `learn=True`.** Only learning steps store or write. + Frozen steps still read what was learned + (`test_frozen_steps_read_but_never_write`). +- **Known-answer tests** for both rules: + `test_associative_recall_picks_best_cosine_match_and_scales_the_stored_state`, + `test_associative_store_gating_fifo_capacity_and_clipping`, + `test_fast_weight_write_and_read_follow_the_rule_exactly`, + `test_fast_weights_store_reward_signed_value_key_associations` and + `test_engine_step_feeds_exactly_recall_plus_fast_read_into_the_brain`. +- **Bounds and determinism.** Contributions and stored state stay bounded under + hostile inputs (`test_contributions_and_state_stay_bounded`). Same seed gives + the same outputs and state digest, a JSON round trip continues exactly, and + the global NumPy RNG is untouched + (`test_determinism_round_trip_and_no_global_rng_use`). +- **Persistence.** The state is in `export_state()['associative_memory']` and + `['fast_weights']`, present only when the flag is on. `import_state` + validates both before it swaps anything in + (`test_import_validates_everything_before_mutating`). Besides shapes and + bounds it checks what the rules imply: episode steps are increasing + multiples of 12 below the engine step, exactly `min(stores, 32)` episodes + remain, there is at most one recall hit and one fast-weight write per step, + `stores` does not exceed the number of scheduled store steps, and a non-zero + matrix has at least one recorded write + (`test_from_state_enforces_capacity_and_per_step_counts`). A state saved + without these keys imports with an empty store and a zero matrix + (`test_states_saved_before_the_mechanisms_existed_import_with_fresh_memories`). +- **Step results.** `step()` reports per-step `associative_memory` and + `fast_weights` records, and `observatory()['learning']` reports their + summaries. + +**Where the constants come from.** They follow the NEUROWEAVE-LAB 0.4.0 +`memory` and `fastWeights` switches as re-implemented in the sibling +SONAPSE-EVO port (`src/sonapse_evo/neuroweave/memory/associative.py` and +`memory/fast_weights.py`, read at commit `eb498fb`). All eleven constants +match that port. The original JavaScript was not available to this build. This +version differs from that port in four ways: +- keys are taken from the engine's external drive, not the port's observation + vector; +- keys, stored states and fast-weight values are clipped to [−1, 1]; +- the stored state is the unit-output vector, not the port's rate vector; +- the fast-weight value is the first 8 of this engine's pooled readout + features (`NeuroWeaveBrain.readout_features`), not the port's + `pooled_features`. + +**Related work (inspired by, not reproductions).** +- The fast weights are a hetero-associative, reward-signed variant of the + decaying outer-product fast weights of Ba et al. (2016), + `A(t) = λA(t−1) + η h(t)h(t)ᵀ`. +- The recall resembles the key-similarity lookup of Neural Episodic Control + (Pritzel et al., 2017). It uses a single best cosine match, not that paper's + kernel-weighted sum over the p nearest neighbours. +- Both writes are reward-gated, in the spirit of three-factor learning rules + (Frémaux & Gerstner, 2016). + +References (titles, authors, venues and the two rules quoted above checked +against the publisher and arXiv pages on 2026-11-20): +- J. Ba, G. E. Hinton, V. Mnih, J. Z. Leibo, C. Ionescu, "Using Fast Weights to + Attend to the Recent Past", *Advances in Neural Information Processing + Systems 29* (NIPS 2016), Dec 2016. + + (arXiv:1610.06258; its rule, Eq. 1, is Hebbian and not reward-gated) +- A. Pritzel, B. Uria, S. Srinivasan, A. Puigdomènech Badia, O. Vinyals, + D. Hassabis, D. Wierstra, C. Blundell, "Neural Episodic Control", *Proc. + 34th ICML*, PMLR 70:2827–2836, Aug 2017. + (arXiv:1703.01988; its + lookup uses p = 50 neighbours and an inverse-squared-distance kernel) +- N. Frémaux, W. Gerstner, "Neuromodulated Spike-Timing-Dependent Plasticity, + and Theory of Three-Factor Learning Rules", *Frontiers in Neural Circuits* 9, + published 19 Jan 2016. + ## 7. Experiments (24) and methodology `spec.EXPERIMENTS` lists 24 experiments in six kinds. Each experiment's @@ -479,7 +565,14 @@ setting and does not generalise. `neuroweave=NeuroWeaveSpecV1.max_preset(seed=seed, neurons=min(256, max(48, total_neurons // 32)))`. The preset: -- turns every mechanism on +- turns every mechanism on. Since 2026-11-19 this includes the engine-level + `associative_memory` and `fast_weights` (section 6). They can act only after + a learning step has written to them: any non-zero reward writes the fast + weights, and a reward above 0.35 on a step that is a multiple of 12 stores + an episode. Runs made after that date can therefore differ from earlier + ones. The preset also turns on `q88_state`, whose rounding can absorb the + small fast-weight read (section 12). The difference has not been measured in + a Max Mode run. - sets `gain=0.02`, `max_gain=0.1`, `ramp_steps=32` - uses topology `dense_multi_region` - sets `max_neurons = min(4096, 2·neurons)` and `max_synapses = min(250000, max(8192, 48·neurons))` @@ -571,7 +664,9 @@ one of three lists: - **not executed:** - the learning-only mechanisms - the engine-level subsystems - - `associative_memory` and `fast_weights` + - `associative_memory` and `fast_weights`: their episode store and 8×8 + matrix are engine state (`NeuroWeaveEngine.export_state`), which the + package does not carry, so the page runs neither read **Abstain / review outcome (heuristic, not calibrated).** Each step also 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`). - The core of Max Mode section 06 (`run_neuroweave_laboratory` at the max preset, 256 neurons, 16 steps, no opt-in extras) took 2.6–2.8 s over three runs on 2026-11-16, on one CPU thread on the same machine. +- These timings predate the engine-level `associative_memory` and + `fast_weights` (added 2026-11-19). In the "all 45 on" columns those two did + no work then. Per step they now add a cosine search over at most 32 stored + keys of 32 values, an 8×8 read and write, and one per-unit vector addition. + The table has not been re-measured. **Estimates (not measurements):** - 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`). full-size experiments have not been run. The supplementary sequence-variant search reports `worse` overall and `improved` only for sparse vs random in one synthetic setting. Complexity is not evidence of improvement. -- **Two declared mechanisms are not implemented** in the runtime: - `associative_memory` and `fast_weights`. The `associative_memory` - experiment's measurable effect therefore comes only from `memory_ecology`. +- **`associative_memory` and `fast_weights` are new and show no benefit + yet.** Before 2026-11-19 they were declared but not implemented. They are now + engine-level mechanisms (section 6). Quick-mode receipts were re-run on + 2026-11-20 with `QUICK_ARGS`: seeds 0 and 1, held-out seed 100, 24 training + and 12 held-out steps, 24 neurons, one CPU thread. Each was run twice and + gave the same receipt digest both times. Other jobs were running on the + machine, so the wall-clock times are only indicative. Results: + - `associative_memory`: `no_detectable_difference` with reason + `degenerate_ci`; the held-out accuracy difference was 0 on both seeds. All + three ablations (`associative_memory`, `fast_weights`, `memory_ecology`) + are also `no_detectable_difference`, and none is inert. Wall-clock 2.30 s + and 1.91 s; digest `c331d9161422c3c8…`. + - `cross_modal_learning`, whose set includes `associative_memory`: + `no_detectable_difference`. The held-out accuracy difference was +0.042, + 95% CI [−0.488, 0.571], over 2 seeds. Its three ablations are also + `no_detectable_difference`, and none is inert. Wall-clock 1.61 s and + 1.96 s; digest `aa10527be1700e91…`. + + Without either flag the engine matched the committed pre-change NEUROWEAVE + package (`synapse/neuroweave/` at commit `b9d8270`, loaded from a scratch + copy) bit for bit in a 2026-11-20 check: outputs, `export_state()` and + `observatory()['learning']` over 30 steps (24 learning and 6 frozen; seed 5; + spec and inputs as in the scratch checks below; a reward of 0.7 on every 4th + step and −0.5 otherwise). Three mechanism sets were checked: none; + `multi_soma`, `membrane_dynamics`, `synaptic_delays`, `reward_plasticity`, + `neuromodulator_field`, `multimodal_sensory`, `memory_ecology`, + `predictive_ensemble` and `micro_collective`; and all 43 others. + + States saved by that pre-change package also import. In the same check, a + state exported by it after 25 rewarded steps, with both flags in the spec, + imported with an empty store and a zero matrix. Two engines that imported it + continued identically for 15 steps and then stored and wrote as usual. With + zero reward (so nothing is written), the new export equalled the old one + plus the two new keys. + + Limits of these mechanisms: + - Runs of 12 or fewer training steps never store an episode. Stores happen + only on step indices that are multiples of 12, and the lab's step-0 reward + is 0, so the first possible store is on step 12. In such runs + `associative_memory` is reported as `inert_in_this_configuration` + (`af::test_lab_associative_experiment_measures_fast_weights_and_flags_the_short_run_store_as_inert`). + `fast_weights` is not inert there: with seeds 0 and 1, held-out seed 100, + 8 training and 4 held-out steps and 16 neurons, its ablation verdict was + `no_detectable_difference` (2026-11-20). + - The lab's `trainable_parameters` budget (`experiments._budget`) counts + neither the 64 fast-weight entries nor the episode store. Both are counted + in `state_numbers`. So that receipt's `budget_matched_within_10pct: true` + (194 vs 194) leaves out 64 learned values on the candidate side. Counted, + the ratio would be 258/194 ≈ 1.33, outside the 10% band. + - At the reference constants (η = 0.0012, read gain 0.03) the fast-weight + read is small. Scratch checks on 2026-11-20 used + `NeuroWeaveSpecV1(neurons=24, max_neurons=48, structural_interval=5, + sleep_interval=10)`, with the task inputs and sensory vectors of + `tasks.make_stream(seed, steps)`, compared against the same spec without + the flag. Over 30 learning steps (seed 11, with `multi_soma`, + `membrane_dynamics`, `reward_plasticity`, `multimodal_sensory` and + `memory_ecology` on, and a reward of 0.7 on every 4th step from step 0 and + −0.5 otherwise): + - `fast_weights` alone: largest output change 4.7e-4; the largest matrix + entry was 1.6e-3 after 30 writes; + - `associative_memory` alone: largest output change 0.117, from 3 stores + and 28 recall hits; + - both first differed at step 1. + - With `q88_state` on, Q8.8 rounding can absorb that read entirely. Setup: + the other 43 mechanisms on, seed 5, a reward of 0 on step 0, then 0.7 on + every 4th step and −0.5 otherwise. Results: + - adding `fast_weights` changed no output in 40 steps with the inputs of + `make_stream(5, 40)`; + - with the inputs of `make_stream(5, 400)`, outputs first differed at + step 11; + - without `q88_state`, the 40-step comparison differed from step 2 + (largest change 2.5e-5); + - adding `associative_memory` instead changed outputs from step 13, the + step after the first store. + - The standalone page and the package carry neither memory. - **Sonapse sensory mapping is approximate.** Three channels have no source, and `audio_mid` is a speed proxy. - **Not tested here:** diff --git a/pyproject.toml b/pyproject.toml index 87e1473d2d11e15efc0e59809d0ee44fe6a79341..d7203647ea1dc20a96437725f50c93f69ad5fbee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,20 +1,49 @@ [build-system] -requires = ["setuptools>=68", "wheel"] +# setuptools>=77 implements PEP 639 (SPDX `license` expression + `license-files`). +requires = ["setuptools>=77", "wheel"] build-backend = "setuptools.build_meta" [project] name = "synapse-connectome-lab" -version = "0.2.0" +version = "0.3.0" description = "Integrated connectome, weight-programming and bounded RSI research workbench" -license = {text = "Apache-2.0"} +readme = "README.md" +license = "Apache-2.0" +license-files = ["LICENSE"] requires-python = ">=3.10" +keywords = [ + "computational-neuroscience", + "connectomics", + "neuromorphic-computing", + "spiking-neural-networks", + "reinforcement-learning", + "reproducibility", +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Science/Research", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Scientific/Engineering :: Artificial Intelligence", +] dependencies = ["torch>=2.4", "numpy>=1.26", "scipy>=1.11"] +[project.urls] +Homepage = "https://github.com/kai9987kai/Sonapse-LAB" +"Model card" = "https://huggingface.co/Kai9987kai/Sonapse-LAB" + [project.optional-dependencies] test = ["pytest>=8"] connectomes = ["pyarrow>=14", "pandas>=2"] yaml = ["PyYAML>=6.0"] +[dependency-groups] +dev = ["pytest>=8", "ruff>=0.8", "pip-audit>=2.7", "hypothesis>=6"] + [project.scripts] synapse-lab = "synapse.cli:main" @@ -24,6 +53,29 @@ include = ["synapse*"] [tool.setuptools.package-data] synapse = ["web/*", "source_manifest.json", "_vendor/**/*"] +[tool.setuptools.exclude-package-data] +"*" = ["*.pyc", "*.pyo", "**/*.pyc", "**/*.pyo"] + +[tool.setuptools.data-files] +"share/synapse-connectome-lab" = ["artifacts/tidal_core.pt"] + [tool.pytest.ini_options] testpaths = ["tests"] addopts = "-ra" + +[tool.ruff] +target-version = "py310" +line-length = 140 +extend-exclude = ["synapse/_vendor"] + +[tool.ruff.lint] +# Correctness checks +# (syntax errors, version-incompatible syntax, broken format strings, undefined +# exports, duplicate keys, invalid escapes, pylint errors, high-signal bugbear). +# The broader F,E,W,B,UP backlog is recorded in docs/ENGINEERING.md. +select = [ + "E9", "F63", "F7", "F50", "F52", "F601", "F602", "F621", "F622", "F821", "F822", "F823", "F901", + "W605", "PLE", + "B002", "B003", "B004", "B011", "B012", "B013", "B014", "B015", "B016", "B019", "B020", + "B021", "B022", "B025", "B026", "B029", "B030", "B031", "B032", "B033", "B034", "B035", "B039", +] diff --git a/scripts/neuroweave_compat_manifest.py b/scripts/neuroweave_compat_manifest.py index f9ca15f7a782bce9b3a21621fd13745cdbfcaa5a..e83b8d65a274ca3421a4554df3db891338f118cb 100644 --- a/scripts/neuroweave_compat_manifest.py +++ b/scripts/neuroweave_compat_manifest.py @@ -1,19 +1,43 @@ -"""Build or verify the pre-NEUROWEAVE Sonapse compatibility manifest. +"""Build or verify a Sonapse additive-compatibility manifest. The manifest is an additive-only contract: every public surface recorded here -(config fields and defaults, CLI sub-commands, HTTP routes, workbench DOM ids, -checkpoint namespaces and test modules) must remain present after the -NEUROWEAVE evolution. New surfaces may be added freely. +(config fields and defaults, CLI sub-commands and flags, HTTP routes, workbench +DOM ids, checkpoint namespaces, test modules and Max Mode features) must remain +present in later trees. New surfaces may be added freely. + +Two manifests are maintained: + +* ``docs/neuroweave/compatibility-manifest.json`` (default; tag + ``sonapse-pre-neuroweave-baseline``) - the pre-NEUROWEAVE contract. +* ``docs/compatibility/manifest-pre-frontier.json`` (tag + ``sonapse-pre-frontier-baseline``) - the pre-Frontier contract. Usage:: - python scripts/neuroweave_compat_manifest.py --write # (re)generate - python scripts/neuroweave_compat_manifest.py --check # verify superset + python scripts/neuroweave_compat_manifest.py --check # default manifest + python scripts/neuroweave_compat_manifest.py --write # regenerate default + python scripts/neuroweave_compat_manifest.py --check \\ + --manifest docs/compatibility/manifest-pre-frontier.json \\ + --baseline-tag sonapse-pre-frontier-baseline + +To (re)build a manifest for a historical tag, inspect a worktree of that tag +in a fresh interpreter:: + + git worktree add sonapse-pre-frontier-baseline + python scripts/neuroweave_compat_manifest.py --write --root \\ + --manifest docs/compatibility/manifest-pre-frontier.json \\ + --baseline-tag sonapse-pre-frontier-baseline + git worktree remove --force + +``--baseline-tag`` labels a written manifest; on ``--check`` it additionally +requires the manifest to record that tag. Defaults are unchanged, so a bare +``--check`` behaves exactly as before. """ from __future__ import annotations import argparse import json +import os import re import subprocess import sys @@ -27,6 +51,12 @@ BASELINE_COMMIT = '6f2761b' # Checkpoint namespaces written by Agent.export_state before NEUROWEAVE. _STATE_KEY = re.compile(r"state\[['\"]([A-Za-z0-9_]+)['\"]\]\s*=") +_ROUTE = re.compile(r"['\"](/api/[A-Za-z0-9_/.-]*)['\"]") +# Modules that register arguments on the main parser besides synapse/cli.py. +_EXTRA_CLI_SOURCES = ( + ('synapse', 'neuroweave', 'cli_commands.py'), + ('synapse', 'frontier', 'cli_commands.py'), +) def _json_default(value): @@ -37,40 +67,102 @@ def _json_default(value): return repr(value) -def collect() -> dict: - sys.path.insert(0, str(ROOT)) - from synapse.config import SynapseConfig - - cfg = SynapseConfig() - config_defaults = { - f.name: _json_default(getattr(cfg, f.name)) for f in fields(SynapseConfig) - } - cli_src = (ROOT / 'synapse' / 'cli.py').read_text(encoding='utf-8') - cli_commands = sorted(set(re.findall(r"add_parser\(\s*['\"]([A-Za-z0-9_-]+)['\"]", cli_src))) - cli_flags = sorted(set(re.findall(r"add_argument\(\s*['\"](--[A-Za-z0-9_-]+)['\"]", cli_src))) - server_src = (ROOT / 'synapse' / 'server.py').read_text(encoding='utf-8') - routes = sorted(set(re.findall(r"['\"](/api/[A-Za-z0-9_/.-]*)['\"]", server_src))) - html = (ROOT / 'synapse' / 'web' / 'index.html').read_text(encoding='utf-8') - dom_ids = sorted(set(re.findall(r'\bid="([^"]+)"', html))) - agent_src = (ROOT / 'synapse' / 'agent.py').read_text(encoding='utf-8') - checkpoint_keys = sorted(set(_STATE_KEY.findall(agent_src))) - tests = sorted(p.name for p in (ROOT / 'tests').glob('test_*.py')) - max_cfg = SynapseConfig.max_tandem(total_neurons=48) - max_audit = max_cfg.max_tandem_feature_audit() - return { - 'schema': 'sonapse-compatibility-manifest-v1', - 'baseline_tag': BASELINE_TAG, - 'baseline_commit': BASELINE_COMMIT, - 'contract': 'additive-only: every recorded item must remain present; defaults must stay equal', - 'config_defaults': config_defaults, - 'cli_commands': cli_commands, - 'cli_flags': cli_flags, - 'http_routes': routes, - 'web_dom_ids': dom_ids, - 'checkpoint_namespaces': checkpoint_keys, - 'test_modules': tests, - 'max_mode_enabled_features': sorted(max_audit['enabled_features']), - } +def _iter_synapse_py(root: Path) -> list[Path]: + """Every ``synapse/**/*.py`` file except the vendored third-party tree.""" + package = root / 'synapse' + return [path for path in sorted(package.rglob('*.py')) + if '_vendor' not in path.relative_to(package).parts] + + +def _http_routes(root: Path) -> list[str]: + """``/api/...`` string literals in every non-vendored ``synapse`` module.""" + routes: set[str] = set() + for py_file in _iter_synapse_py(root): + routes.update(_ROUTE.findall(py_file.read_text(encoding='utf-8', errors='ignore'))) + return sorted(routes) + + +def _cli_sources(root: Path) -> list[Path]: + """``synapse/cli.py`` plus the existing modules that register main-parser arguments.""" + extras = (root.joinpath(*parts) for parts in _EXTRA_CLI_SOURCES) + return [root / 'synapse' / 'cli.py', *(path for path in extras if path.exists())] + + +def _cli_surfaces(sources: list[Path]) -> tuple[list[str], list[str]]: + """Sub-command names and long flags registered in ``sources``.""" + text = '\n'.join(path.read_text(encoding='utf-8') for path in sources) + commands = sorted(set(re.findall(r"add_parser\(\s*['\"]([A-Za-z0-9_-]+)['\"]", text))) + flags = sorted(set(re.findall(r"add_argument\(\s*['\"](--[A-Za-z0-9_-]+)['\"]", text))) + return commands, flags + + +def _same_path(a: Path, b: Path) -> bool: + return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b)) + + +def _git_rev(tag: str, cwd: Path, *, short: bool) -> str | None: + cmd = ['git', 'rev-parse', '--short', tag] if short else ['git', 'rev-parse', tag] + try: + out = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return None + return out or None + + +def collect(root: Path | None = None, *, baseline_tag: str = BASELINE_TAG) -> dict: + """Collect the public surfaces of the tree at ``root`` (default: this checkout). + + ``root`` other than this checkout must be inspected in a fresh interpreter: + ``SynapseConfig`` is imported from ``root`` and a ``RuntimeError`` is raised + if a different ``synapse`` package was already imported. + """ + explicit_root = root is not None + repo = ROOT if root is None else Path(root).resolve() + inserted = False + if str(repo) not in sys.path: + sys.path.insert(0, str(repo)) + inserted = True + try: + from synapse.config import SynapseConfig + + if explicit_root: + loaded = Path(sys.modules['synapse.config'].__file__).resolve().parent + if not _same_path(loaded, repo / 'synapse'): + raise RuntimeError( + f'synapse.config was imported from {loaded}, not {repo / "synapse"}; ' + 'inspect another tree in a fresh interpreter (use --root)') + cfg = SynapseConfig() + config_defaults = { + f.name: _json_default(getattr(cfg, f.name)) for f in fields(SynapseConfig) + } + cli_commands, cli_flags = _cli_surfaces(_cli_sources(repo)) + routes = _http_routes(repo) + html = (repo / 'synapse' / 'web' / 'index.html').read_text(encoding='utf-8') + dom_ids = sorted(set(re.findall(r'\bid="([^"]+)"', html))) + agent_src = (repo / 'synapse' / 'agent.py').read_text(encoding='utf-8') + checkpoint_keys = sorted(set(_STATE_KEY.findall(agent_src))) + tests = sorted(p.name for p in (repo / 'tests').glob('test_*.py')) + max_cfg = SynapseConfig.max_tandem(total_neurons=48) + max_audit = max_cfg.max_tandem_feature_audit() + fallback = BASELINE_COMMIT if baseline_tag == BASELINE_TAG else 'unresolved' + commit_short = _git_rev(baseline_tag, repo, short=True) or fallback + return { + 'schema': 'sonapse-compatibility-manifest-v1', + 'baseline_tag': baseline_tag, + 'baseline_commit': commit_short, + 'contract': 'additive-only: every recorded item must remain present; defaults must stay equal', + 'config_defaults': config_defaults, + 'cli_commands': cli_commands, + 'cli_flags': cli_flags, + 'http_routes': routes, + 'web_dom_ids': dom_ids, + 'checkpoint_namespaces': checkpoint_keys, + 'test_modules': tests, + 'max_mode_enabled_features': sorted(max_audit['enabled_features']), + } + finally: + if inserted and str(repo) in sys.path: + sys.path.remove(str(repo)) def check(manifest: dict, current: dict) -> list[str]: @@ -88,25 +180,40 @@ def check(manifest: dict, current: dict) -> list[str]: def main(argv=None) -> int: - parser = argparse.ArgumentParser(description=__doc__) + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--write', action='store_true') group.add_argument('--check', action='store_true') + parser.add_argument('--manifest', type=Path, default=MANIFEST, + help='manifest JSON path, relative to the repository root ' + '(default: docs/neuroweave/compatibility-manifest.json)') + parser.add_argument('--baseline-tag', default=None, + help=f'git tag the manifest describes (default for --write: {BASELINE_TAG}); ' + 'with --check, the manifest must record this tag') + parser.add_argument('--root', type=Path, default=None, + help='tree to inspect, e.g. a git worktree of the baseline tag (default: this checkout)') args = parser.parse_args(argv) - current = collect() + manifest_path = args.manifest if args.manifest.is_absolute() else (ROOT / args.manifest) + tag = args.baseline_tag or BASELINE_TAG + root = None if args.root is None else args.root.resolve() + current = collect(root, baseline_tag=tag) if args.write: - MANIFEST.parent.mkdir(parents=True, exist_ok=True) + manifest_path.parent.mkdir(parents=True, exist_ok=True) + full = _git_rev(tag, ROOT if root is None else root, short=False) + if full: + current['baseline_commit_full'] = full + manifest_path.write_text(json.dumps(current, indent=2, sort_keys=True) + '\n', encoding='utf-8') try: - head = subprocess.run(['git', 'rev-parse', BASELINE_TAG], cwd=ROOT, - capture_output=True, text=True, check=True).stdout.strip() - current['baseline_commit_full'] = head - except (OSError, subprocess.CalledProcessError): - pass - MANIFEST.write_text(json.dumps(current, indent=2, sort_keys=True) + '\n', encoding='utf-8') - print(f'wrote {MANIFEST.relative_to(ROOT)}') + rel = manifest_path.relative_to(ROOT) + except ValueError: + rel = manifest_path + print(f'wrote {rel}') return 0 - manifest = json.loads(MANIFEST.read_text(encoding='utf-8')) + manifest = json.loads(manifest_path.read_text(encoding='utf-8')) problems = check(manifest, current) + if args.baseline_tag is not None and manifest.get('baseline_tag') != args.baseline_tag: + problems.insert(0, f'baseline tag mismatch: manifest records {manifest.get("baseline_tag")!r}, ' + f'expected {args.baseline_tag!r}') for problem in problems: print(problem) print('compatibility manifest OK' if not problems else f'{len(problems)} compatibility problem(s)') diff --git a/synapse/__init__.py b/synapse/__init__.py index bf8f75092775603b713e4afb0c8b90b54791c155..3f2350ddb1a0ed8a2d78d1219f48781c5c085920 100644 --- a/synapse/__init__.py +++ b/synapse/__init__.py @@ -1,2 +1,2 @@ """SYNAPSE: integrated connectome and recursive improvement research workbench.""" -__version__ = '0.1.0' +__version__ = '0.3.0' diff --git a/synapse/adaptation_study.py b/synapse/adaptation_study.py index 09cd0a2e348e1e8eed8481e103d269831ec419cc..cffcd5e5c60ad4dff9164b0761cc4f6ce2d42eed 100644 --- a/synapse/adaptation_study.py +++ b/synapse/adaptation_study.py @@ -63,13 +63,13 @@ def _learned_hash(agent): def _source_fingerprints(): - from .config import ARTIFACTS + from .config import tidal_checkpoint_path root = Path(__file__).resolve().parent names = sorted(p.name for p in root.glob('*.py')) names.extend(f'_vendor/graftbrain/graftbrain/{name}.py' for name in ('brain', 'plasticity', 'neuro_modules', 'world', 'connectomes', 'graft')) names.append('_vendor/poseidon/poseidon/core.py') values = {name: _file_hash(root/name) for name in names} - values['artifact:tidal_core.pt'] = _file_hash(ARTIFACTS/'tidal_core.pt') + values['artifact:tidal_core.pt'] = _file_hash(tidal_checkpoint_path()) return values diff --git a/synapse/agent.py b/synapse/agent.py index cc45f8615bbbd20436bfa179245897ad0c5464fd..6e3eb2c36c0f094fb30857ddb04ddf4265e3e53e 100644 --- a/synapse/agent.py +++ b/synapse/agent.py @@ -8,7 +8,7 @@ import torch from torch import nn from torch.nn import functional as F from . import sources -from .config import ARTIFACTS +from .config import tidal_checkpoint_path from graftbrain.brain import GraftedBrain from graftbrain.connectomes import make_proxy from graftbrain.graft import build @@ -74,7 +74,7 @@ class IntegratedAgent: # A small seeded projection gives camera input a measurable causal path. visual_generator=torch.Generator(device='cpu').manual_seed(config.seed+1907) nn.init.normal_(self.vis_to_sensory.weight,std=0.02,generator=visual_generator) - self.tidal,self.receipt=load_checkpoint(ARTIFACTS/'tidal_core.pt') + self.tidal,self.receipt=load_checkpoint(tidal_checkpoint_path()) h=self.tidal.config.hidden_size self.encoder=nn.Linear(155+16+2,len(self.brain.sensory_idx)) self.donor_to_graph=nn.Linear(h+6,len(self.brain.sensory_idx),bias=False) @@ -177,8 +177,12 @@ class IntegratedAgent: self.preparation_updates=0; self.bridge_updates=0; self.episodic=[]; self.tool_memory=[] self._camera_consumed_any=False self.neural_graft=None + self.frontier_hub=None self.programmed_prior_status={'enabled':False} self._setup_neural_graft() + if getattr(self.config, 'frontier', None) is not None: + from .frontier.bridge import attach_frontier_to_agent + attach_frontier_to_agent(self) self.reset_episode() def _setup_frontier_extensions(self): @@ -504,12 +508,19 @@ class IntegratedAgent: self.auditory_encoder = AuditorySpikeEncoder(seed=self.config.seed) self.chat_gateway = ConversationalChatGateway(embed_dim=64, seed=self.config.seed) + def _frontier_graft_optimizer(self): + spec = getattr(self.config, 'frontier', None) + if spec is not None and getattr(spec, 'enabled', False): + return getattr(spec, 'graft_optimizer', 'adam') + return 'adam' + def _setup_neural_graft(self): if not self.config.neural_graft: return from .neural_graft import NeuralResidualGraft if self.neural_graft is None: - self.neural_graft=NeuralResidualGraft(seed=self.config.seed) + self.neural_graft=NeuralResidualGraft(seed=self.config.seed, + optimizer_kind=self._frontier_graft_optimizer()) self.modules['neural_graft']=self.neural_graft.network if self.config.programmed_connectome and self.neural_graft.connectome is None: try: @@ -964,6 +975,9 @@ class IntegratedAgent: if getattr(self, 'neuroweave_channel', None) is not None: # No wall-clock: exact-replay receipts compare telemetry byte-for-byte. self.last_telemetry['neuroweave'] = self.neuroweave_channel.get_telemetry_dict(include_timing=False) + if getattr(self, 'frontier_hub', None) is not None and self.frontier_hub.enabled: + from .frontier.bridge import step_agent_frontier + step_agent_frontier(self) if getattr(self, 'dpo_engine', None) is not None: self.last_telemetry['verifiable_dpo']={'enabled':True,'pairs':len(self.dpo_engine.preference_buffer),'last_margin':getattr(self.dpo_engine,'last_margin',0.0)} if getattr(self, 'sancf_fabric', None) is not None: @@ -1495,6 +1509,8 @@ class IntegratedAgent: channels = fabric_state.get('channels') if isinstance(channels, dict): channels.pop('neuroweave', None) + if getattr(self, 'frontier_hub', None) is not None and self.frontier_hub.enabled: + state['frontier_v1'] = self.frontier_hub.export_state() state['neurowave_x2']=self.neurowave_x2.export_state() if getattr(self,'neurowave_x2',None) is not None else None state['overflow_mini_brain']=self.overflow_mini_brain.state_dict() if getattr(self,'overflow_mini_brain',None) is not None else None 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: self.modules['neural_graft']=self.neural_graft.network else: from .neural_graft import NeuralResidualGraft - self.neural_graft=NeuralResidualGraft(seed=self.config.seed) + self.neural_graft=NeuralResidualGraft(seed=self.config.seed, + optimizer_kind=self._frontier_graft_optimizer()) self.modules['neural_graft']=self.neural_graft.network if getattr(self,'dendritic_ltc',None) is not None and state.get('dendritic_ltc') is not None: self.dendritic_ltc.import_state(state['dendritic_ltc']) @@ -1695,6 +1712,9 @@ class IntegratedAgent: if state.get('neuroweave_v1') is not None: # Presence/config agreement was checked before any module was touched. self.neuroweave_channel.import_state(state['neuroweave_v1']) + if state.get('frontier_v1') is not None or getattr(self, 'frontier_hub', None) is not None: + from .frontier.bridge import import_agent_frontier + import_agent_frontier(self, state) if getattr(self,'neurowave_x2',None) is not None and state.get('neurowave_x2') is not None: self.neurowave_x2.import_state(state['neurowave_x2']) if getattr(self,'overflow_mini_brain',None) is not None and state.get('overflow_mini_brain') is not None: diff --git a/synapse/capabilities.py b/synapse/capabilities.py index 06919ed023ef75478f64224e3e796f5a151674c5..1d1759ce10901dc1e9f9fccb4377bd40348cadbe 100644 --- a/synapse/capabilities.py +++ b/synapse/capabilities.py @@ -14,7 +14,7 @@ from typing import Any, Dict, List, Optional, Tuple import numpy as np import torch from torch import nn -from .config import ARTIFACTS, PACKAGE, VENDOR +from .config import ARTIFACTS, PACKAGE, VENDOR, tidal_checkpoint_path from .sources import activate, manifest activate() @@ -281,7 +281,7 @@ def _handle_memory_nexus_search(payload: Dict[str, Any]) -> Dict[str, Any]: # 3. CORE & CONTROLLERS def _handle_core_scene(payload: Dict[str, Any]) -> Dict[str, Any]: from poseidon.core import load_checkpoint - tidal_path = ARTIFACTS / 'tidal_core.pt' + tidal_path = tidal_checkpoint_path() if not tidal_path.is_file(): return {'status': 'unavailable', 'error': 'Tidal core artifact tidal_core.pt not found'} tidal, _ = load_checkpoint(tidal_path) @@ -317,7 +317,7 @@ def _handle_core_scene(payload: Dict[str, Any]) -> Dict[str, Any]: def _handle_core_tidal(payload: Dict[str, Any]) -> Dict[str, Any]: from poseidon.core import load_checkpoint - tidal_path = ARTIFACTS / 'tidal_core.pt' + tidal_path = tidal_checkpoint_path() if not tidal_path.is_file(): return {'status': 'unavailable', 'error': 'Tidal core artifact tidal_core.pt not found'} tidal, receipt = load_checkpoint(tidal_path) diff --git a/synapse/cli.py b/synapse/cli.py index 2ee9a24279cb92e6de0d33102476d2184c8ee95b..ccaf28abb5d538f74db5c0e8db3547bb1123bfa4 100644 --- a/synapse/cli.py +++ b/synapse/cli.py @@ -3,10 +3,12 @@ import argparse import json from dataclasses import replace from pathlib import Path +from . import __version__ from .config import SynapseConfig, ARTIFACTS def main(argv=None): parser=argparse.ArgumentParser(description='SYNAPSE integrated connectome research lab') + parser.add_argument('--version',action='version',version=f'synapse-connectome-lab {__version__}') parser.add_argument('--output',type=Path,default=ARTIFACTS) parser.add_argument('--seed',type=int,default=7) 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): parser.add_argument('--dsag-config',type=Path,help='load an explicit DSAGSpecV1 YAML/JSON configuration') 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)') parser.add_argument('--neuroweave-config',dest='neuroweave_config',type=Path,help='load an explicit NeuroWeaveSpecV1 JSON configuration (sets SynapseConfig.neuroweave)') + from .frontier.cli_commands import register_frontier_cli + register_frontier_cli(parser) parser.add_argument('--programmed-connectome',action='store_true',help='bind the verified 128-neuron MaleCNS sparse prior') parser.add_argument('--connectome-mode',choices=['proxy','prefer_authentic','strict_authentic'],help='connectome source mode') size=parser.add_mutually_exclusive_group() @@ -49,6 +53,15 @@ def main(argv=None): nw_inspect=nw_sub.add_parser('inspect'); nw_inspect.add_argument('nw_file',type=Path) 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) 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) + fp=sub.add_parser('frontier',help='Frontier pack catalog, observers and experiments (opt-in; JSON to stdout)') + fp.add_argument('frontier_action',choices=('catalog','experiment','observe','laboratory'),nargs='?',default='catalog') + fp.add_argument('--id',dest='frontier_id',type=str,default='all',help='Experiment id to run (or "all")') + fp.add_argument('--quick',dest='frontier_quick',action='store_true',default=False,help='Run experiment(s) in fast quick mode') + fp.add_argument('--seeds',dest='frontier_seeds',type=str,default='0,1,2',help='Comma-separated integer seeds') + fp.add_argument('--modules',dest='frontier_sub_modules',type=str,default='all',help='Observer modules for observe/laboratory') + fp.add_argument('--steps',dest='frontier_steps',type=int,default=32,help='Synthetic observation steps for "frontier observe"') + fp.add_argument('--units',dest='frontier_units',type=int,default=32,help='Synthetic unit count for "frontier observe"') + fp.add_argument('--out',dest='frontier_out',type=Path,default=None,help='Optional path to write the JSON receipt') for name in ('run','train'): p=sub.add_parser(name); p.add_argument('--steps',type=int,default=100); p.add_argument('--save') 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): if args.neuroweave_enabled is not None or args.neuroweave_config is not None: from .neuroweave.cli_commands import cli_neuroweave_spec config=replace(config,neuroweave=cli_neuroweave_spec(args.neuroweave_enabled,args.neuroweave_config,args.seed)) + if (args.frontier_enabled is not None or args.frontier_config is not None + or args.frontier_modules is not None or args.frontier_graft_optimizer is not None): + from .frontier.cli_commands import cli_frontier_spec + frontier_spec=cli_frontier_spec( + args.frontier_enabled,args.frontier_config,args.seed, + modules=args.frontier_modules,graft_optimizer=args.frontier_graft_optimizer) + if frontier_spec is not None: + config=replace(config,frontier=frontier_spec) if args.command=='serve' and args.nodes is None and not getattr(args, 'frontier_all', False): import os config=replace(config, @@ -236,6 +257,9 @@ def main(argv=None): elif args.command=='neuroweave': from .neuroweave.cli_commands import run_neuroweave_command result=run_neuroweave_command(args,config) + elif args.command=='frontier': + from .frontier.cli_commands import run_frontier_command + result=run_frontier_command(args) elif args.command=='connectome-inventory': from .connectome_assets import get_source_inventory result={'sources':get_source_inventory()} @@ -636,7 +660,7 @@ def main(argv=None): result={**result,'measured':False,'evidence_kind':'illustrative', 'scope':'standalone synthetic inputs; no measured embodied performance; use planning-study or evidence for actual world trials'} print(json.dumps(result,indent=2,allow_nan=False,default=str)) - return 1 if (args.command in ('verify','adaptation-verify','planning-verify') and not result.get('ok',False)) or (args.command=='neuroweave' and result.get('ok') is False) else 0 + 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 except (ValueError,TypeError,KeyError,OSError,RuntimeError) as exc: parser.exit(2,f'Error: {exc}\n') diff --git a/synapse/config.py b/synapse/config.py index f5da02f25620ed105ef166869018aec443adf220..fe98e95a628032d1fa09a34ba69e910c259b277c 100644 --- a/synapse/config.py +++ b/synapse/config.py @@ -8,6 +8,26 @@ ROOT = Path(os.environ.get('SYNAPSE_HOME', str(PACKAGE.parent))).resolve() VENDOR = PACKAGE / '_vendor' ARTIFACTS = ROOT / 'artifacts' +def tidal_checkpoint_path() -> Path: + """Resolve the core in a source checkout, a configured home, or an installed wheel.""" + source = ARTIFACTS / 'tidal_core.pt' + if source.is_file() or 'SYNAPSE_HOME' in os.environ: + return source + + from importlib.metadata import PackageNotFoundError, distribution + relative = Path('share', 'synapse-connectome-lab', source.name) + target_install = PACKAGE.parent / relative + if target_install.is_file(): + return target_install + try: + installed = distribution('synapse-connectome-lab') + except PackageNotFoundError: + return source + for entry in installed.files or (): + if entry.parts[-3:] == relative.parts: + return Path(installed.locate_file(entry)) + return source + @dataclass(frozen=True) class SynapseConfig: seed: int = 7 @@ -120,8 +140,14 @@ class SynapseConfig: # NEUROWEAVE (synapse/neuroweave): same additive contract as DSAG. None is # the default and is omitted from to_dict(). neuroweave: object | None = None + # Frontier Pack (synapse/frontier): additive, default-off read-only + # observers and opt-in graft optimizer. Omitted from to_dict() when None. + frontier: object | None = None def __post_init__(self): + if self.frontier is not None: + from .frontier.bridge import coerce_frontier_spec + object.__setattr__(self, 'frontier', coerce_frontier_spec(self.frontier)) if self.neuroweave is not None: from .neuroweave.spec import NeuroWeaveSpecV1 if isinstance(self.neuroweave, dict): @@ -297,6 +323,7 @@ class SynapseConfig: def max_tandem(cls, total_neurons: int = 9000, seed: int = 7, task: str = 'continental_biosphere', **kwargs) -> 'SynapseConfig': """Maximum configuration with every optional subsystem enabled.""" from .dsag.config import DSAGSpecV1 + from .frontier.spec import FrontierSpecV1 from .neuroweave.spec import NeuroWeaveSpecV1 cfg_dict = dict( @@ -403,6 +430,8 @@ class SynapseConfig: # Bounded population: Max Mode stays within the machine budget. neuroweave=NeuroWeaveSpecV1.max_preset( seed=seed, neurons=min(256, max(48, int(total_neurons) // 32))), + # Read-only frontier observers: strictly trajectory-neutral. + frontier=FrontierSpecV1.max_preset(seed=seed), ) cfg_dict.update(kwargs) return cls(**cfg_dict) @@ -424,6 +453,10 @@ class SynapseConfig: d.pop('neuroweave') else: d['neuroweave'] = self.neuroweave.to_dict() + if self.frontier is None: + d.pop('frontier') + else: + d['frontier'] = self.frontier.to_dict() return d def max_tandem_feature_audit(self): @@ -453,6 +486,10 @@ class SynapseConfig: enabled.append('neuroweave_v1') enabled.extend(f'neuroweave_v1.{m}' for m in MECHANISM_IDS if m in neuroweave.mechanisms) disabled.extend(f'neuroweave_v1.{m}' for m in MECHANISM_IDS if m not in neuroweave.mechanisms) + from .frontier.bridge import frontier_audit_entries + fr_on, fr_off = frontier_audit_entries(self.frontier) + enabled.extend(fr_on) + disabled.extend(fr_off) return { 'schema': 'max-tandem-feature-audit-v1', 'enabled_count': len(enabled), @@ -468,6 +505,7 @@ class SynapseConfig: normalized = { 'dsag': None, 'neuroweave': None, + 'frontier': None, 'experience_planning': False, 'surprise_memory': True, 'experience_horizon': 1, 'experimental_cognition': False, 'continual_backprop': False, 'fast_weight_memory': False, 'dormant_lifecycle': True, @@ -527,6 +565,10 @@ class SynapseConfig: return False if not saved_nw_spec.enabled: normalized['neuroweave'] = self.neuroweave + # Frontier observers follow the same additive rule when graft_optimizer stays default. + from .frontier.bridge import normalize_saved_frontier + if not normalize_saved_frontier(self.frontier, normalized): + return False try: restored = type(self)(**normalized) except (TypeError, ValueError): diff --git a/synapse/energy_efficiency_assay.py b/synapse/energy_efficiency_assay.py index 905241f216c32b5cec0347ea8f0cfb2004ef989a..ec3a079bb6df01bac6eaf8b47db75d8138323522 100644 --- a/synapse/energy_efficiency_assay.py +++ b/synapse/energy_efficiency_assay.py @@ -45,7 +45,7 @@ class EnergyEfficiencyAssay: self.num_steps = num_steps self.seed = seed - def run_assay(self, thresholds: Optional[List[float]] = None) -> EnergyEfficiencyAssayReport: + def run_assay(self, thresholds: list[float] | None = None) -> EnergyEfficiencyAssayReport: if thresholds is None: thresholds = [0.01, 0.05, 0.1, 0.2] diff --git a/synapse/frontier/__init__.py b/synapse/frontier/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..193dc81f9048f6a1886756ad52ff592709f01376 --- /dev/null +++ b/synapse/frontier/__init__.py @@ -0,0 +1,7 @@ +"""Sonapse frontier pack: additive, default-off experimental modules (see ``spec.py``).""" +from .spec import (EVIDENCE_TIER, LAB_SCHEMA, MODULE_IDS, MODULES, OBSERVER_MODULE_IDS, FrontierSpecV1, + ModuleInfo, module_catalog) +from .extension import EXTENSION_INTERFACE_VERSION, EngineExtension, RandomTraceControl + +__all__ = ['EVIDENCE_TIER', 'LAB_SCHEMA', 'MODULE_IDS', 'MODULES', 'OBSERVER_MODULE_IDS', 'FrontierSpecV1', + 'ModuleInfo', 'module_catalog', 'EXTENSION_INTERFACE_VERSION', 'EngineExtension', 'RandomTraceControl'] diff --git a/synapse/frontier/anytime.py b/synapse/frontier/anytime.py new file mode 100644 index 0000000000000000000000000000000000000000..ea0249f8a1e49b2fe1bcd94d385c34b9478bb7b2 --- /dev/null +++ b/synapse/frontier/anytime.py @@ -0,0 +1,511 @@ +"""Anytime-valid inference (frontier module ``anytime_inference``). + +Inspired by Ian Waudby-Smith and Aaditya Ramdas, *Estimating means of bounded random variables by +betting*, J. R. Stat. Soc. B 86(1):1-27 (February 2024), doi:10.1093/jrsssb/qkad009, and by Aaditya +Ramdas, Peter Grünwald, Vladimir Vovk and Glenn Shafer, *Game-theoretic statistics and safe +anytime-valid inference*, Statistical Science 38(4):576-601 (November 2023), doi:10.1214/23-STS894. +This module is a synthetic computational abstraction: it implements two constructions from the first +paper and checks their stated guarantees in seeded simulations; it reproduces none of the papers' +experiments. Full, verified references: ``docs/frontier/modules/anytime_inference.md``. + +Betting confidence sequence (paper Sec. 4.4, Eqs. 24-26 and Theorem 3; section, equation and appendix +numbers follow arXiv:2010.09686v7, the version checked). Observations ``x_t`` in +``[lo, hi]`` are rescaled to ``X_t = (x_t - lo) / (hi - lo)`` in ``[0, 1]``; for each candidate mean ``m`` +on a grid:: + + 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)) + K±_t(m) = max{theta K+_t(m), (1 - theta) K-_t(m)} + lam+_t(m) = min(lam_t, c / m), lam-_t(m) = min(lam_t, c / (1 - m)) (Eq. 25) + lam_t = sqrt(2 log(2/alpha) / (sigma2_{t-1} t log(1 + t))) (Eq. 26) + 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) + CS_t = intersection_{i<=t} {m : K±_i(m) < 1/alpha} + +The set is an interval (Theorem 3), so the grid search returns a conservative superset: each bound is +the first *excluded* grid point outside the included run (when no grid point is included, the excluded +neighbours of the grid minimisers of ``K±``, which bracket the set because ``K±`` is quasiconvex in ``m``). + +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`` +and ``m = 1/2``, ``E_t = (K+_t + K-_t) / 2`` (the paper's mixture ``M±`` with ``theta = 1/2``). Both +one-sided processes bet with the approximate-GRAPA rule (paper App. B.3) computed from the Eq. 26 +estimators, split by sign: ``lam_t = clip((mu_{t-1} - m) / (sigma2_{t-1} + (mu_{t-1} - m)^2), -c/(1-m), c/m)``, +``lam+_t = max(lam_t, 0)``, ``lam-_t = max(-lam_t, 0)``. Every factor is at least ``1 - c > 0`` and the +bets are predictable, so under ``H0`` each one-sided process and their average are test martingales; +Ville's inequality gives ``P(exists t: E_t >= 1/alpha) <= alpha`` -- valid under optional stopping +(Ramdas et al. 2023). + +All randomness comes from ``numpy.random.default_rng(seed + offset)``. +""" +from __future__ import annotations + +import math +import time +from typing import Any, Mapping, Sequence + +import numpy as np + +from . import harness + +__all__ = ['MODULE_ID', 'SOURCE', 'EXPERIMENTS', 'betting_confidence_sequence', 'paired_e_process', + 'anytime_compare', 'naive_peeking_t_test', 'run_experiment'] + +MODULE_ID = 'anytime_inference' +SOURCE = ('Waudby-Smith & Ramdas, "Estimating means of bounded random variables by betting", J. R. Stat. Soc. B ' + '86(1):1-27, February 2024, doi:10.1093/jrsssb/qkad009; Ramdas, Grünwald, Vovk & Shafer, ' + '"Game-theoretic statistics and safe anytime-valid inference", Statistical Science 38(4):576-601, ' + 'November 2023, doi:10.1214/23-STS894') + +_NULL_BERNOULLI_OFFSET = 83_003 +_NULL_SKEWED_OFFSET = 83_011 +_EFFECT_OFFSET = 83_021 +_COVER_BETA_OFFSET = 83_029 +_COVER_BERNOULLI_OFFSET = 83_041 +_LOG_CAP = 690.0 # reported e-values are capped at exp(690) ~ 1e299, so every value stays finite +_MAX_N = 1_000_000 +_MAX_CS_WORK = 200_000_000 # observations x grid points per confidence-sequence call +_MAX_SIM_CELLS = 4_000_000 # replicates x horizon per simulated scenario (about 20 such float64 arrays at peak) +_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]) + + +# ====================================================================== validation helpers +def _int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _num(name: str, value: Any, low: float, high: float, *, open_low: bool = False, open_high: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + if (not math.isfinite(v) or v < low or v > high or (open_low and v <= low) or (open_high and v >= high)): + raise ValueError(f'{name} must be a finite number in {"(" if open_low else "["}{low}, {high}{")" if open_high else "]"}') + return v + + +def _series(name: str, x: Any) -> np.ndarray: + if isinstance(x, (str, bytes)) or isinstance(x, Mapping): + raise ValueError(f'{name} must be a 1-D sequence of finite numbers') + try: + a = np.asarray(x, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be a 1-D sequence of finite numbers') from exc + if a.ndim != 1 or a.size == 0 or a.size > _MAX_N or not np.all(np.isfinite(a)): + raise ValueError(f'{name} must be a non-empty 1-D sequence of at most {_MAX_N} finite numbers') + return a.copy() + + +def _alpha(alpha: Any) -> float: + return _num('alpha', alpha, 0.0, 1.0, open_low=True, open_high=True) + + +def _c(c: Any) -> float: + return _num('c', c, 0.0, 1.0, open_low=True, open_high=True) + + +# ====================================================================== core (batched over rows) +def _plugin_moments(x: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Predictable ``mu_{t-1}`` and ``sigma2_{t-1}`` (Eq. 26 estimators, priors 1/2 and 1/4) along the last axis.""" + n = x.shape[-1] + t = np.arange(1, n + 1, dtype=np.float64) + mu = (0.5 + np.cumsum(x, axis=-1)) / (t + 1.0) + sig = (0.25 + np.cumsum((x - mu) ** 2, axis=-1)) / (t + 1.0) + lead = x.shape[:-1] + (1,) + mu_prev = np.concatenate([np.full(lead, 0.5), mu[..., :-1]], axis=-1) + sig_prev = np.concatenate([np.full(lead, 0.25), sig[..., :-1]], axis=-1) + return mu_prev, sig_prev + + +def _hedged_bounds(x: np.ndarray, alpha: float, grid_size: int, c: float, + theta: float) -> tuple[np.ndarray, np.ndarray]: + """Per-time conservative bounds of ``{m : K±_t(m) < 1/alpha}`` for rows of ``x`` in [0, 1] (shape (R, n)).""" + rows, n = x.shape + grid = np.linspace(0.0, 1.0, grid_size + 1) + with np.errstate(divide='ignore'): + cap_plus = np.where(grid > 0.0, c / np.where(grid > 0.0, grid, 1.0), np.inf) + cap_minus = np.where(grid < 1.0, c / np.where(grid < 1.0, 1.0 - grid, 1.0), np.inf) + _, sig_prev = _plugin_moments(x) + t = np.arange(1, n + 1, dtype=np.float64) + lam = np.sqrt(2.0 * math.log(2.0 / alpha) / (sig_prev * t * np.log1p(t))) + log_kp = np.zeros((rows, grid.size)) + log_km = np.zeros((rows, grid.size)) + thresh = math.log(1.0 / alpha) + log_theta, log_rest = math.log(theta), math.log(1.0 - theta) + lower = np.empty((rows, n)) + upper = np.empty((rows, n)) + last = grid.size - 1 + rev = np.arange(grid.size)[::-1] + for i in range(n): + dev = x[:, i, None] - grid[None, :] + log_kp += np.log1p(np.minimum(lam[:, i, None], cap_plus) * dev) + log_km += np.log1p(-np.minimum(lam[:, i, None], cap_minus) * dev) + log_k = np.maximum(log_theta + log_kp, log_rest + log_km) + inside = log_k < thresh + any_in = inside.any(axis=1) + first = np.argmax(inside, axis=1) + final = last - np.argmax(inside[:, rev], axis=1) + # no grid point inside: bracket every grid minimiser (K± is quasiconvex in m, so the set lies there) + best_first = np.argmin(log_k, axis=1) + best_last = last - np.argmin(log_k[:, rev], axis=1) + lo_idx = np.where(any_in, first, best_first) - 1 + hi_idx = np.where(any_in, final, best_last) + 1 + lower[:, i] = grid[np.clip(lo_idx, 0, last)] + upper[:, i] = grid[np.clip(hi_idx, 0, last)] + return lower, upper + + +def _paired_log_capital(y: np.ndarray, c: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """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.""" + x = 0.5 * (1.0 + y) + m = 0.5 + mu_prev, sig_prev = _plugin_moments(x) + lam = np.clip((mu_prev - m) / (sig_prev + (mu_prev - m) ** 2), -c / (1.0 - m), c / m) + lam_plus = np.maximum(lam, 0.0) + lam_minus = np.maximum(-lam, 0.0) + log_kp = np.cumsum(np.log1p(lam_plus * (x - m)), axis=-1) + log_km = np.cumsum(np.log1p(-lam_minus * (x - m)), axis=-1) + log_e = np.logaddexp(log_kp, log_km) - math.log(2.0) + return log_kp, log_km, log_e + + +def _cap_exp(log_v: np.ndarray) -> np.ndarray: + return np.exp(np.minimum(log_v, _LOG_CAP)) + + +# ====================================================================== public API +def betting_confidence_sequence(x: Any, lo: float, hi: float, alpha: float = 0.05, *, grid_size: int = 1000, + c: float = 0.5, theta: float = 0.5) -> dict[str, Any]: + """Hedged-capital betting confidence sequence for the mean of ``x`` (values in ``[lo, hi]``). + + Returns ``lower``/``upper`` (running intersection, length ``n``), ``lower_raw``/``upper_raw`` (the set at + each time before intersecting), ``final`` = ``(lower[-1], upper[-1])`` and ``empty`` (the running + intersection became empty, which happens with probability at most ``alpha``). Bounds are conservative to + the grid resolution ``(hi - lo) / grid_size``.""" + a = _series('x', x) + lo_v = _num('lo', lo, -1e12, 1e12) + hi_v = _num('hi', hi, -1e12, 1e12) + if not hi_v > lo_v: + raise ValueError('hi must be greater than lo') + if np.any(a < lo_v) or np.any(a > hi_v): + raise ValueError('every observation must lie in [lo, hi]') + al = _alpha(alpha) + g = _int('grid_size', grid_size, 8, 100_000) + cc = _c(c) + th = _num('theta', theta, 0.0, 1.0, open_low=True, open_high=True) + if a.size * (g + 1) > _MAX_CS_WORK: + raise ValueError(f'len(x) * (grid_size + 1) must be at most {_MAX_CS_WORK}') + width = hi_v - lo_v + unit = np.clip((a - lo_v) / width, 0.0, 1.0) + lower_raw, upper_raw = _hedged_bounds(unit[None, :], al, g, cc, th) + lower = np.maximum.accumulate(lower_raw[0]) + upper = np.minimum.accumulate(upper_raw[0]) + scale = lambda v: lo_v + width * v # noqa: E731 + return {'n': int(a.size), 'alpha': al, 'lo': lo_v, 'hi': hi_v, 'grid_size': g, 'c': cc, 'theta': th, + 'lower': scale(lower), 'upper': scale(upper), 'lower_raw': scale(lower_raw[0]), + 'upper_raw': scale(upper_raw[0]), 'final': (float(scale(lower[-1])), float(scale(upper[-1]))), + 'empty': bool(lower[-1] > upper[-1]), 'method': 'hedged_capital_predictable_plugin'} + + +def paired_e_process(differences: Any, bound: float, *, c: float = 0.5) -> dict[str, Any]: + """Two-sided betting e-process for ``H0: E[D_t | past] = 0`` from paired differences ``|D_t| <= bound``. + + ``e_process[t]`` is ``(K+ + K-) / 2`` after ``t + 1`` observations; ``e_plus`` / ``e_minus`` are the one-sided + processes (evidence for a positive / negative mean). Values are capped at ``exp(690)`` to stay finite.""" + d = _series('differences', differences) + b = _num('bound', bound, 0.0, 1e12, open_low=True) + if np.any(np.abs(d) > b): + raise ValueError('every |difference| must be at most bound') + cc = _c(c) + log_kp, log_km, log_e = _paired_log_capital(np.clip(d / b, -1.0, 1.0)[None, :], cc) + return {'n': int(d.size), 'bound': b, 'c': cc, 'e_process': _cap_exp(log_e[0]), 'log_e_process': log_e[0], + 'e_plus': _cap_exp(log_kp[0]), 'e_minus': _cap_exp(log_km[0]), + 'method': 'two_sided_mixture_of_one_sided_agrapa_bets'} + + +def anytime_compare(candidate: Any, reference: Any, *, bound: float, alpha: float = 0.05, + higher_is_better: bool = True, c: float = 0.5, grid_size: int = 1000) -> dict[str, Any]: + """Anytime-valid paired comparison of two aligned score streams (``|candidate - reference| <= bound``). + + The e-process is monitored after every observation; ``rejected`` is true when it reaches ``1/alpha`` + (``stopped_at`` is that 1-based time and ``e_value`` the stopped value), so peeking never inflates the + type-I error beyond ``alpha`` provided ``E[D_t | past] = 0`` under the null. The direction comes from the + one-sided process that is at least ``1/alpha`` at the stopping time. ``cs_lower``/``cs_upper`` bound the + mean difference ``candidate - reference`` at the last observation (betting CS, level ``1 - alpha``).""" + a = _series('candidate', candidate) + r = _series('reference', reference) + if a.shape != r.shape: + raise ValueError('candidate and reference must have the same length') + if type(higher_is_better) is not bool: + raise ValueError('higher_is_better must be a boolean') + b = _num('bound', bound, 0.0, 1e12, open_low=True) + al = _alpha(alpha) + d = a - r + if np.any(np.abs(d) > b): + raise ValueError('every |candidate - reference| must be at most bound') + ep = paired_e_process(d, b, c=c) + cs = betting_confidence_sequence(d, -b, b, al, grid_size=grid_size, c=c) + log_e = ep['log_e_process'] + crossed = np.flatnonzero(log_e >= math.log(1.0 / al)) + rejected = bool(crossed.size) + stop = int(crossed[0]) if rejected else d.size - 1 + direction = None + if rejected: + direction = 'positive' if ep['e_plus'][stop] >= ep['e_minus'][stop] else 'negative' + if not rejected: + verdict = 'no_detectable_difference' + else: + verdict = 'improved' if (direction == 'positive') == higher_is_better else 'worse' + return {'n': int(d.size), 'alpha': al, 'bound': b, 'higher_is_better': higher_is_better, + 'mean_difference': float(d.mean()), 'e_value': float(ep['e_process'][stop]), + 'e_value_final': float(ep['e_process'][-1]), 'rejected': rejected, + 'stopped_at': stop + 1 if rejected else None, 'direction': direction, + 'cs_lower': float(cs['lower'][-1]), 'cs_upper': float(cs['upper'][-1]), + 'cs_excludes_zero': bool(cs['lower'][-1] > 0.0 or cs['upper'][-1] < 0.0), 'cs_empty': cs['empty'], + 'verdict': verdict, 'method': 'betting_e_process_and_hedged_confidence_sequence'} + + +def naive_peeking_t_test(differences: Any, alpha: float = 0.05, *, min_n: int = 2) -> dict[str, Any]: + """The invalid baseline: a two-sided one-sample t-test of mean 0 repeated after every observation. + + Returns whether any look at ``n >= min_n`` gave ``p < alpha`` and whether the single final look did.""" + d = _series('differences', differences) + al = _alpha(alpha) + mn = _int('min_n', min_n, 2, _MAX_N) + any_look, final_look = _naive_t_rejections(d[None, :], al, mn) + return {'n': int(d.size), 'alpha': al, 'min_n': mn, 'rejected_any_look': bool(any_look[0]), + 'rejected_final_look': bool(final_look[0])} + + +def _naive_t_rejections(d: np.ndarray, alpha: float, min_n: int) -> tuple[np.ndarray, np.ndarray]: + from scipy.special import stdtrit # Student-t quantile (lighter import than scipy.stats) + rows, n = d.shape + if n < 2: + return np.zeros(rows, dtype=bool), np.zeros(rows, dtype=bool) + t = np.arange(1, n + 1, dtype=np.float64) + s1 = np.cumsum(d, axis=1) + s2 = np.cumsum(d * d, axis=1) + mean = s1 / t + with np.errstate(divide='ignore', invalid='ignore'): + var = np.maximum(s2 - t * mean * mean, 0.0) / np.maximum(t - 1.0, 1.0) + se = np.sqrt(var / t) + stat = np.where(se > 0.0, np.abs(mean) / np.where(se > 0.0, se, 1.0), 0.0) + crit = np.full(n, np.inf) + df = np.arange(1, n) # look at t = 2..n has df = t - 1 + crit[1:] = stdtrit(df.astype(np.float64), 1.0 - alpha / 2.0) + looks = np.arange(1, n + 1) >= max(2, min_n) + reject = (stat > crit[None, :]) & looks[None, :] + return reject.any(axis=1), reject[:, -1] + + +# ====================================================================== validation experiment +_DEFAULTS: dict[str, Any] = {'alpha': 0.05, 'replicates': 400, 'horizon': 500, 'grid_size': 400, 'c': 0.5, + 'theta': 0.5, 'naive_min_n': 10, 'null_p': 0.6, 'effect_p': 0.75, 'effect_reference_p': 0.5, + 'cover_beta': (2.0, 5.0), 'cover_bernoulli_p': 0.3, 'power_min': 0.8, 'mc_z': 3.0} +_QUICK: dict[str, Any] = {'replicates': 100, 'horizon': 200, 'grid_size': 200} + + +def _seeds(seeds: Any) -> tuple[int, ...]: + if isinstance(seeds, (str, bytes, Mapping)): + raise ValueError('seeds must be an iterable of ints') + try: + out = tuple(_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + unknown = sorted(set(overrides) - set(_DEFAULTS)) + if unknown: + raise ValueError(f'unknown run_experiment parameters: {unknown}') + cfg = {**_DEFAULTS, **(_QUICK if quick else {}), **overrides} + cfg['alpha'] = _alpha(cfg['alpha']) + cfg['replicates'] = _int('replicates', cfg['replicates'], 10, 100_000) + cfg['horizon'] = _int('horizon', cfg['horizon'], 20, 100_000) + cfg['grid_size'] = _int('grid_size', cfg['grid_size'], 8, 100_000) + cfg['c'] = _c(cfg['c']) + cfg['theta'] = _num('theta', cfg['theta'], 0.0, 1.0, open_low=True, open_high=True) + cfg['naive_min_n'] = _int('naive_min_n', cfg['naive_min_n'], 2, cfg['horizon']) + for key in ('null_p', 'effect_p', 'effect_reference_p', 'cover_bernoulli_p'): + cfg[key] = _num(key, cfg[key], 0.0, 1.0, open_low=True, open_high=True) + if not cfg['effect_p'] > cfg['effect_reference_p']: + raise ValueError('effect_p must exceed effect_reference_p (the effect scenario is a positive difference)') + beta = cfg['cover_beta'] + if isinstance(beta, (str, bytes)) or len(tuple(beta)) != 2: + raise ValueError('cover_beta must be a pair of positive numbers') + cfg['cover_beta'] = tuple(_num('cover_beta', v, 0.0, 1000.0, open_low=True) for v in beta) + cfg['power_min'] = _num('power_min', cfg['power_min'], 0.0, 1.0) + cfg['mc_z'] = _num('mc_z', cfg['mc_z'], 0.0, 10.0) + if cfg['replicates'] * (cfg['grid_size'] + 1) > 20_000_000: + raise ValueError('replicates * (grid_size + 1) must be at most 20,000,000 (memory bound)') + if cfg['replicates'] * cfg['horizon'] > _MAX_SIM_CELLS: + raise ValueError(f'replicates * horizon must be at most {_MAX_SIM_CELLS:,} (memory bound)') + return cfg + + +def _paired_bernoulli(rng: np.random.Generator, shape: tuple[int, int], p_cand: float, p_ref: float) -> np.ndarray: + cand = (rng.random(shape) < p_cand).astype(np.float64) + ref = (rng.random(shape) < p_ref).astype(np.float64) + return cand - ref + + +def _seed_block(seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]: + r, n, al, cc = cfg['replicates'], cfg['horizon'], cfg['alpha'], cfg['c'] + thresh = math.log(1.0 / al) + out: dict[str, Any] = {'seed': int(seed)} + # ---- nulls: e-process under optional stopping vs repeated t-tests + nulls = { + 'paired_bernoulli': _paired_bernoulli(np.random.default_rng(seed + _NULL_BERNOULLI_OFFSET), (r, n), + cfg['null_p'], cfg['null_p']), + 'skewed_continuous': (np.random.default_rng(seed + _NULL_SKEWED_OFFSET).beta(_SKEW_A, _SKEW_B, (r, n)) + - _SKEW_A / (_SKEW_A + _SKEW_B)), + } + for name, d in nulls.items(): + _, _, log_e = _paired_log_capital(d, cc) + naive_any, naive_final = _naive_t_rejections(d, al, cfg['naive_min_n']) + final_e = _cap_exp(log_e[:, -1]) + out[f'null_{name}'] = { + 'e_process_rejections': int(np.sum(log_e.max(axis=1) >= thresh)), + 'naive_peeking_rejections': int(naive_any.sum()), 'fixed_n_t_rejections': int(naive_final.sum()), + 'final_e_sum': float(final_e.sum()), 'final_e_sq_sum': float(np.sum(final_e ** 2)), + 'final_e_max': float(final_e.max()), 'replicates': r} + # ---- power on a clear positive effect + d = _paired_bernoulli(np.random.default_rng(seed + _EFFECT_OFFSET), (r, n), cfg['effect_p'], + cfg['effect_reference_p']) + log_kp, log_km, log_e = _paired_log_capital(d, cc) + hit = log_e >= thresh + rejected = hit.any(axis=1) + stop = np.where(rejected, np.argmax(hit, axis=1), n - 1) + rows = np.arange(r) + positive = log_kp[rows, stop] >= log_km[rows, stop] + naive_any, _ = _naive_t_rejections(d, al, cfg['naive_min_n']) + out['effect'] = {'replicates': r, 'rejections': int(rejected.sum()), + 'wrong_direction_rejections': int(np.sum(rejected & ~positive)), + 'stopping_times': (stop[rejected] + 1).tolist(), + 'naive_peeking_rejections': int(naive_any.sum())} + # ---- uniform-in-time coverage of the betting CS + a_beta, b_beta = cfg['cover_beta'] + cover = { + 'beta': (np.random.default_rng(seed + _COVER_BETA_OFFSET).beta(a_beta, b_beta, (r, n)), a_beta / (a_beta + b_beta)), + 'bernoulli': ((np.random.default_rng(seed + _COVER_BERNOULLI_OFFSET).random((r, n)) + < cfg['cover_bernoulli_p']).astype(np.float64), cfg['cover_bernoulli_p']), + } + for name, (x, mu) in cover.items(): + lower_raw, upper_raw = _hedged_bounds(x, al, cfg['grid_size'], cc, cfg['theta']) + lower = np.maximum.accumulate(lower_raw, axis=1) + upper = np.minimum.accumulate(upper_raw, axis=1) + covered_all = np.all((lower <= mu) & (mu <= upper), axis=1) + early = min(n - 1, 19) + out[f'cover_{name}'] = {'replicates': r, 'true_mean': float(mu), 'covered_all_times': int(covered_all.sum()), + 'width_t20_sum': float(np.sum(upper[:, early] - lower[:, early])), + 'width_final_sum': float(np.sum(upper[:, -1] - lower[:, -1])), + 'empty_final': int(np.sum(lower[:, -1] > upper[:, -1]))} + return out + + +def _rate(k: int, n: int) -> dict[str, float]: + p = k / n + return {'rate': p, 'mc_se': math.sqrt(max(p * (1.0 - p), 1e-12) / n), 'count': int(k), 'n': int(n)} + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Seeded validation of the e-process and the betting CS under continuous monitoring. + + For every seed: ``replicates`` sequences of length ``horizon`` per scenario, with a look after every + observation. Checks (pooled over seeds; ``mc_z`` Monte-Carlo standard errors of slack): + + * type-I error of the e-process <= ``alpha`` under two nulls (paired Bernoulli, skewed continuous); + * the naive repeated two-sided t-test (looks from ``naive_min_n``) exceeds ``alpha`` clearly; + * the mean final e-value under each null is <= 1 + slack (it is a test martingale with expectation exactly 1; + the terminal value is heavy-tailed, so the sample mean usually falls below 1 and the check is one-sided); + * the running-intersection CS covers the true mean at every time with frequency >= ``1 - alpha`` + (Beta and Bernoulli data); + * power on a clear effect (paired Bernoulli ``effect_p`` vs ``effect_reference_p``) >= ``power_min`` and + wrong-direction rejections <= ``alpha``.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seeds(seeds) + cfg = _config(quick, overrides) + t0 = time.perf_counter() + blocks = [_seed_block(s, cfg) for s in seed_list] + wall = time.perf_counter() - t0 + al, z = cfg['alpha'], cfg['mc_z'] + total = cfg['replicates'] * len(seed_list) + results: dict[str, Any] = {} + checks: dict[str, bool] = {} + for name in ('paired_bernoulli', 'skewed_continuous'): + key = f'null_{name}' + e_rej = sum(b[key]['e_process_rejections'] for b in blocks) + naive = sum(b[key]['naive_peeking_rejections'] for b in blocks) + fixed = sum(b[key]['fixed_n_t_rejections'] for b in blocks) + e_sum = sum(b[key]['final_e_sum'] for b in blocks) + e_sq = sum(b[key]['final_e_sq_sum'] for b in blocks) + e_mean = e_sum / total + e_sd = math.sqrt(max(e_sq / total - e_mean ** 2, 0.0) * total / max(total - 1, 1)) + alpha_se = math.sqrt(al * (1.0 - al) / total) + results[key] = {'e_process_type1': _rate(e_rej, total), 'naive_peeking_t_type1': _rate(naive, total), + 'fixed_n_t_type1': _rate(fixed, total), + 'final_e_value': {'mean': e_mean, 'sd': e_sd, 'mc_se': e_sd / math.sqrt(total), + 'max': max(b[key]['final_e_max'] for b in blocks)}} + checks[f'e_process_type1_le_alpha_{name}'] = bool(e_rej / total <= al + z * alpha_se) + naive_rate = naive / total + naive_se = math.sqrt(max(naive_rate * (1.0 - naive_rate), 1e-12) / total) + checks[f'naive_peeking_t_exceeds_alpha_{name}'] = bool(naive_rate - z * naive_se > al) + checks[f'mean_final_e_value_le_1_{name}'] = bool(e_mean <= 1.0 + z * e_sd / math.sqrt(total)) + rej = sum(b['effect']['rejections'] for b in blocks) + wrong = sum(b['effect']['wrong_direction_rejections'] for b in blocks) + times = sorted(t for b in blocks for t in b['effect']['stopping_times']) + results['effect'] = {'power': _rate(rej, total), 'wrong_direction': _rate(wrong, total), + 'naive_peeking_t_rejections': _rate(sum(b['effect']['naive_peeking_rejections'] for b in blocks), total), + 'median_stopping_time': float(np.median(times)) if times else None, + 'mean_difference': cfg['effect_p'] - cfg['effect_reference_p']} + checks['power_on_clear_effect'] = bool(rej / total >= cfg['power_min']) + checks['wrong_direction_rate_le_alpha'] = bool(wrong / total <= al) + for name in ('beta', 'bernoulli'): + key = f'cover_{name}' + cov = sum(b[key]['covered_all_times'] for b in blocks) + results[key] = {'uniform_coverage': _rate(cov, total), 'true_mean': blocks[0][key]['true_mean'], + 'mean_width_t20': sum(b[key]['width_t20_sum'] for b in blocks) / total, + 'mean_width_final': sum(b[key]['width_final_sum'] for b in blocks) / total, + 'empty_final': int(sum(b[key]['empty_final'] for b in blocks))} + checks[f'cs_uniform_coverage_ge_1_minus_alpha_{name}'] = bool( + cov / total >= 1.0 - al - z * math.sqrt(al * (1.0 - al) / total)) + checks[f'cs_shrinks_{name}'] = bool(results[key]['mean_width_final'] < results[key]['mean_width_t20']) + n, g = cfg['horizon'], cfg['grid_size'] + receipt = harness.base_receipt(MODULE_ID, 'validation', { + **cfg, 'seeds': list(seed_list), 'quick': quick, 'looks': 'after every observation', + 'nulls': {'paired_bernoulli': f'D = Bern({cfg["null_p"]}) - Bern({cfg["null_p"]}), independent', + 'skewed_continuous': f'D = Beta({_SKEW_A}, {_SKEW_B}) - {_SKEW_A / (_SKEW_A + _SKEW_B):.6f}'}, + 'effect': f'D = Bern({cfg["effect_p"]}) - Bern({cfg["effect_reference_p"]}), independent, bound 1', + 'coverage': {'beta': f'X ~ Beta{tuple(cfg["cover_beta"])} on [0, 1]', + 'bernoulli': f'X ~ Bern({cfg["cover_bernoulli_p"]})'}, + 'e_process': 'mean of one-sided aGRAPA betting processes on X = (1 + D)/2 at m = 1/2; reject when E_t >= 1/alpha', + 'confidence_sequence': 'hedged capital (theta, c) with predictable plug-in bets; grid search; running intersection', + 'naive_baseline': 'two-sided one-sample t-test at every look n >= naive_min_n'}) + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['per_seed'] = [{k: v for k, v in b.items() if k != 'effect'} | {'effect': { + kk: vv for kk, vv in b['effect'].items() if kk != 'stopping_times'}} for b in blocks] + receipt['results'] = results + receipt['checks'] = checks + receipt['verdict'] = 'pass' if all(checks.values()) else 'fail' + receipt['verdict_basis'] = 'all_checks_pass' if receipt['verdict'] == 'pass' else 'failed_checks: ' + ', '.join( + k for k, v in checks.items() if not v) + receipt['estimated_cost'] = {'e_process_updates': 3 * total * n, 't_test_looks': 3 * total * n, + 'cs_capital_updates': 2 * 2 * total * n * (g + 1)} + receipt['measured_wallclock_s'] = wall + receipt['notes'] = ('Synthetic Monte-Carlo validation of two constructions from Waudby-Smith & Ramdas (2024): the ' + 'hedged-capital confidence sequence with predictable plug-in bets (grid search, conservative to ' + 'one grid step) and a two-sided e-process (mean of two one-sided aGRAPA betting processes). ' + 'Guarantees hold when E[D_t | past] = 0 (for the e-process) and observations are bounded with a ' + 'constant conditional mean (for the CS); serially dependent streams whose conditional mean ' + 'drifts are not covered. Rates are Monte-Carlo estimates with stated standard errors. The ' + 'terminal e-value under a null is heavy-tailed (rare large values carry its expectation of ' + '1), so its sample mean usually falls below 1 and its naive standard error understates the ' + 'spread; the exact expectation is checked by path enumeration in the tests. Nothing here ' + 'reproduces the papers\' experiments.') + return harness.seal(receipt) + + +EXPERIMENTS = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/bridge.py b/synapse/frontier/bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..2a7da844bb2b07b32d1ca71bd03e562095c2ee6a --- /dev/null +++ b/synapse/frontier/bridge.py @@ -0,0 +1,141 @@ +"""Sonapse host-integration bridge for the Frontier Pack (`SynapseConfig`, `IntegratedAgent`, `NeuralResidualGraft`). + +Centralises the config, checkpoint, observer-stepping and graft-optimizer hooks so host wiring stays minimal, +additive and strictly trajectory-neutral when read-only observers are active. +""" +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from .muon import make_graft_optimizer +from .runtime import FrontierObserverHub +from .spec import OBSERVER_MODULE_IDS, FrontierSpecV1 + +__all__ = [ + 'CHECKPOINT_NAMESPACE', + 'coerce_frontier_spec', + 'frontier_audit_entries', + 'normalize_saved_frontier', + 'attach_frontier_to_agent', + 'step_agent_frontier', + 'export_agent_frontier', + 'import_agent_frontier', +] + +CHECKPOINT_NAMESPACE = 'frontier_v1' + + +def coerce_frontier_spec(value: Any) -> FrontierSpecV1 | None: + """Validate/convert a ``SynapseConfig.frontier`` value (``None``, ``FrontierSpecV1`` or mapping).""" + if value is None: + return None + if isinstance(value, FrontierSpecV1): + return value + if isinstance(value, Mapping): + return FrontierSpecV1.from_dict(value) + raise ValueError('frontier must be None, a FrontierSpecV1 or a mapping') + + +def frontier_audit_entries(spec: FrontierSpecV1 | None) -> tuple[list[str], list[str]]: + """Return ``(enabled, disabled)`` feature-audit entries for ``SynapseConfig.max_tandem_feature_audit``.""" + if spec is None or not spec.enabled: + return [], ['frontier_v1'] + enabled = ['frontier_v1'] + disabled: list[str] = [] + for mod_id in OBSERVER_MODULE_IDS: + key = f'frontier_v1.{mod_id}' + if mod_id in spec.modules: + enabled.append(key) + else: + disabled.append(key) + return enabled, disabled + + +def normalize_saved_frontier(current_spec: FrontierSpecV1 | None, + normalized_saved: dict[str, Any]) -> bool: + """Apply the additive legacy-checkpoint rule (same as DSAG and NEUROWEAVE) in ``SynapseConfig.matches_saved``. + + Returns ``False`` only when ``normalized_saved['frontier']`` is malformed; otherwise updates + ``normalized_saved`` in place and returns ``True``.""" + normalized_saved.setdefault('frontier', None) + saved_frontier = normalized_saved.get('frontier') + saved_spec: FrontierSpecV1 | None = None + if isinstance(saved_frontier, FrontierSpecV1): + saved_spec = saved_frontier + elif isinstance(saved_frontier, Mapping): + try: + saved_spec = FrontierSpecV1.from_dict(saved_frontier) + except (TypeError, ValueError): + return False + normalized_saved['frontier'] = saved_spec + elif saved_frontier is not None: + return False + + # Read-only frontier observers can be additively enabled on a legacy checkpoint that had frontier disabled/None, + # provided graft_optimizer stays at its default ('adam'). + if (current_spec is not None and current_spec.enabled + and current_spec.graft_optimizer == 'adam' + and (saved_spec is None or not saved_spec.enabled)): + normalized_saved['frontier'] = current_spec + return True + + +def attach_frontier_to_agent(agent: Any, spec: FrontierSpecV1 | None = None) -> FrontierObserverHub | None: + """Attach a :class:`FrontierObserverHub` and optional Muon graft optimizer to an ``IntegratedAgent``.""" + active_spec = coerce_frontier_spec(getattr(getattr(agent, 'config', None), 'frontier', None) + if spec is None else spec) + if active_spec is None or not active_spec.enabled: + agent.frontier_hub = None + return None + n_units = int(agent.brain.n) + hub = FrontierObserverHub(active_spec, n_units=n_units) + agent.frontier_hub = hub + if active_spec.graft_optimizer == 'muon' and getattr(agent, 'neural_graft', None) is not None: + graft = agent.neural_graft + if graft.settings.get('optimizer_kind', 'adam') != 'muon': + lr = float(graft.settings.get('learning_rate', 3e-4)) + graft.settings['optimizer_kind'] = 'muon' + graft.optimizer = make_graft_optimizer(graft.network, kind='muon', lr=lr) + return hub + + +def step_agent_frontier(agent: Any) -> dict[str, Any] | None: + """Feed a read-only copy of ``agent.brain.r`` to ``agent.frontier_hub`` and update ``agent.last_telemetry``.""" + hub: FrontierObserverHub | None = getattr(agent, 'frontier_hub', None) + if hub is None or not hub.enabled: + return None + hub.observe(agent.brain.r) + summary = hub.telemetry() + if hasattr(agent, 'last_telemetry') and isinstance(agent.last_telemetry, dict): + agent.last_telemetry['frontier'] = summary + return summary + + +def export_agent_frontier(agent: Any, state: dict[str, Any]) -> None: + """Store ``state['frontier_v1']`` when an active ``frontier_hub`` is attached.""" + hub: FrontierObserverHub | None = getattr(agent, 'frontier_hub', None) + if hub is not None and hub.enabled: + state[CHECKPOINT_NAMESPACE] = hub.export_state() + + +def import_agent_frontier(agent: Any, state: Mapping[str, Any]) -> None: + """Validate and restore ``state['frontier_v1']`` (allowing additive enable on legacy checkpoints).""" + hub: FrontierObserverHub | None = getattr(agent, 'frontier_hub', None) + saved_config = state.get('config') + saved_frontier = saved_config.get('frontier') if isinstance(saved_config, Mapping) else None + saved_enabled = (isinstance(saved_frontier, Mapping) and saved_frontier.get('enabled') is True) or ( + isinstance(saved_frontier, FrontierSpecV1) and saved_frontier.enabled + ) + payload = state.get(CHECKPOINT_NAMESPACE) + if payload is not None: + if not saved_enabled: + raise ValueError('checkpoint contains frontier_v1 state but its saved config does not enable frontier') + if hub is None or not hub.enabled: + raise ValueError('checkpoint contains frontier_v1 state but this agent has no enabled frontier hub') + hub.import_state(payload) + elif saved_enabled and hub is not None and hub.enabled: + raise ValueError('frontier-enabled checkpoint is missing its frontier_v1 namespace') + elif hub is not None and hub.enabled: + # Legacy checkpoint without frontier_v1: reset observer hub to clean seeded initial state. + hub.reset() diff --git a/synapse/frontier/btsp.py b/synapse/frontier/btsp.py new file mode 100644 index 0000000000000000000000000000000000000000..27601d96e018c7de57e3d792bcaab45a2a04088c --- /dev/null +++ b/synapse/frontier/btsp.py @@ -0,0 +1,964 @@ +"""One-shot content-addressable memory with binary synapses and BTSP-style plasticity. + +Inspired by Wu & Maass, "A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides content +addressable memory with binary synapses and one-shot learning", Nature Communications 16, 342 (published online +2 January 2025), https://doi.org/10.1038/s41467-024-55563-6. It is a small synthetic abstraction of that model, not +a reproduction of the paper's networks, parameters or results, and it says nothing about hippocampal biology. + +Model (``BTSPMemory``) +---------------------- +``m = input_dim`` binary input units feed ``n = memory_dim`` binary memory units through a fixed random +connectivity mask ``C`` (``n x m``, connection probability ``density``) carrying binary weights ``W`` (initially 0). +Storing a binary pattern ``x`` is one-shot (paper Eq. 1): + +* every memory unit receives a plateau potential with probability ``plateau_prob``, independently of its firing; +* for every existing synapse ``(j, i)`` with a plateau in ``j`` and ``x_i = 1``, a weight at 0 flips to 1 with + probability ``p_ltp`` and a weight at 1 flips to 0 with probability ``p_ltd`` (the paper uses 0.5 for both); + nothing else changes. + +Memory units are McCulloch-Pitts units, ``z_j = 1[(W x)_j > threshold * density * |x|]``, so the threshold is a +fraction of the expected number of connected active inputs. (The paper grid-searches one absolute threshold for its +memory-trace experiments and, for input completion, sets both layers' thresholds by fitted linear functions of the +average fraction of 1's; a threshold proportional to the active count is this module's simplification.) +Reconstruction uses the paper's feedback pathway: a second random mask ``D`` (``m x n``, same density) carries binary +weights ``B`` that are set to 1, right after each store, on every existing synapse whose memory unit is in the new +trace ``z(x)`` and whose input unit is active in ``x`` (one-shot Hebbian rule saturating at 1). Recall of a cue +``c`` gives the trace ``z(c)`` and the reconstruction ``r_i = 1[(B z(c))_i > feedback_threshold * density * |z(c)|]``. + +``WillshawMemory`` is an auto-associative form of the classic clipped-Hebbian binary memory (Willshaw, Buneman & +Longuet-Higgins, Nature 222, 960-962, 1969; the paper does not compare BTSP with it, this module does) and +``RandomRecallControl`` returns a seeded random pattern (chance). +``run_capacity_benchmark`` compares them at the same synapse count; ``BTSPExtension`` attaches the memory to a +NEUROWEAVE engine as a readout-only extension. +""" +from __future__ import annotations + +import base64 +import binascii +import copy +import itertools +import math +import time +from typing import Any, Callable, Mapping, Sequence + +import numpy as np + +from .continuum_memory import _check_float, _check_int, _check_seeds, _grid_edges +from .extension import EngineExtension + +__all__ = ['MODULE_ID', 'CAPACITY_ID', 'SOURCE', 'EXPERIMENTS', 'CUE_KINDS', 'BTSPMemory', 'WillshawMemory', + 'RandomRecallControl', 'BTSPExtension', 'overlap', 'hamming', 'reconstruction_error', 'make_cue', + 'random_patterns', 'run_capacity_benchmark', 'run_experiment', 'CAPACITY_DEFAULTS', 'CAPACITY_QUICK'] + +MODULE_ID = 'btsp_memory' +CAPACITY_ID = 'btsp_memory_capacity' +SOURCE = ('Wu & Maass, "A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides content ' + 'addressable memory with binary synapses and one-shot learning", Nature Communications 16, 342 (2025), ' + 'doi:10.1038/s41467-024-55563-6; baseline: Willshaw, Buneman & Longuet-Higgins, "Non-holographic ' + 'associative memory", Nature 222, 960-962 (1969), doi:10.1038/222960a0') +CUE_KINDS = ('delete', 'flip') +_MAX_MATRIX = 4_000_000 +_MASK_OFFSET = 61_403 +_PLASTICITY_OFFSET = 61_417 +_PROJECTION_OFFSET = 61_429 +_PATTERN_OFFSET = 61_441 +_TEST_OFFSET = 61_453 +_CONTROL_OFFSET = 61_467 + + +# ====================================================================== binary helpers and metrics +def _binary(name: str, value: Any, size: int) -> np.ndarray: + """Validate a binary vector (bool or numbers in {0, 1}) of length ``size``; returns a new bool array.""" + try: + arr = np.asarray(value) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be a binary vector') from exc + if arr.shape != (size,): + raise ValueError(f'{name} must have shape ({size},), got {arr.shape}') + if arr.dtype == np.bool_: + return arr.copy() + if not np.issubdtype(arr.dtype, np.number) or np.issubdtype(arr.dtype, np.complexfloating): + raise ValueError(f'{name} must be a binary vector') + if not np.all((arr == 0) | (arr == 1)): + raise ValueError(f'{name} must contain only 0 and 1') + return arr.astype(bool) + + +def _pair(a: Any, b: Any) -> tuple[np.ndarray, np.ndarray]: + size = np.shape(a) + if len(size) != 1: + raise ValueError('expected two binary vectors of the same length') + return _binary('a', a, size[0]), _binary('b', b, size[0]) + + +def overlap(a: Any, b: Any) -> float: + """Normalised overlap ``|a & b| / sqrt(|a| |b|)`` of two binary vectors (cosine similarity; 0 if one is empty). + + This is the module's recall metric. It is not the paper's "overlap ratio" of two memory traces, which divides + the common 1's by the average number of 1's in a trace.""" + x, y = _pair(a, b) + nx, ny = int(np.count_nonzero(x)), int(np.count_nonzero(y)) + if nx == 0 or ny == 0: + return 0.0 + return float(np.count_nonzero(x & y) / math.sqrt(nx * ny)) + + +def hamming(a: Any, b: Any) -> int: + """Hamming distance between two binary vectors of the same length.""" + x, y = _pair(a, b) + return int(np.count_nonzero(x ^ y)) + + +def reconstruction_error(target: Any, cue: Any, reconstruction: Any) -> float | None: + """Wu & Maass's reconstruction error ``HD(r(x'), x) / HD(x, x')``: 0 is perfect, 1 is no better than the cue. + ``None`` when the cue equals the target (the ratio is undefined).""" + base = hamming(target, cue) + return None if base == 0 else hamming(reconstruction, target) / base + + +def _check_generator(rng: Any) -> np.random.Generator: + if not isinstance(rng, np.random.Generator): + raise ValueError('rng must be a numpy.random.Generator (e.g. numpy.random.default_rng(seed))') + return rng + + +def make_cue(pattern: Any, fraction: float, kind: str, rng: np.random.Generator) -> np.ndarray: + """Degraded copy of a binary pattern: ``round(fraction * |x|)`` active bits are switched off and, for + ``kind='flip'``, the same number of inactive bits are switched on (the number of ones is kept).""" + _check_generator(rng) + if len(np.shape(pattern)) != 1: + raise ValueError('pattern must be a binary vector') + x = _binary('pattern', pattern, np.shape(pattern)[0]) + frac = _check_float('fraction', fraction, 0.0, 1.0) + if kind not in CUE_KINDS: + raise ValueError(f'kind must be one of {CUE_KINDS}') + on, off = np.flatnonzero(x), np.flatnonzero(~x) + k = int(round(frac * on.size)) + if kind == 'flip' and k > off.size: + raise ValueError('not enough inactive bits to flip') + cue = x.copy() + if k: + cue[rng.choice(on, k, replace=False)] = False + if kind == 'flip': + cue[rng.choice(off, k, replace=False)] = True + return cue + + +def random_patterns(count: int, size: int, active: int, rng: np.random.Generator) -> np.ndarray: + """``count`` random binary patterns of length ``size`` with exactly ``active`` ones each, ``(count, size)``.""" + _check_int('count', count, 0, 1_000_000) + _check_int('size', size, 1, 1_000_000) + _check_int('active', active, 0, size) + _check_generator(rng) + if count * size > 200_000_000: # the capacity benchmark's largest workload (100,000 x 2,000) + raise ValueError('count * size must be <= 200,000,000') + out = np.zeros((count, size), dtype=bool) + for row in out: + row[rng.choice(size, active, replace=False)] = True + return out + + +def _pack(bits: np.ndarray) -> str: + return base64.b64encode(np.packbits(bits.astype(bool)).tobytes()).decode('ascii') + + +def _unpack(name: str, text: Any, count: int) -> np.ndarray: + if not isinstance(text, str): + raise ValueError(f'{name} must be a base64 string') + try: + raw = base64.b64decode(text.encode('ascii'), validate=True) + except (binascii.Error, UnicodeEncodeError, ValueError) as exc: + raise ValueError(f'{name} is not valid base64') from exc + if len(raw) != (count + 7) // 8: + raise ValueError(f'{name} has the wrong length') + bits = np.unpackbits(np.frombuffer(raw, dtype=np.uint8)) + if np.any(bits[count:]): + raise ValueError(f'{name} has non-zero padding bits') + return bits[:count].astype(bool) + + +def _rng_state(rng: np.random.Generator) -> dict[str, Any]: + return copy.deepcopy(rng.bit_generator.state) + + +def _restore_rng(state: Any) -> np.random.Generator: + if not isinstance(state, Mapping) or state.get('bit_generator') != 'PCG64': + raise ValueError('rng state must be a PCG64 state mapping') + inner = state.get('state') + if (not isinstance(inner, Mapping) or type(inner.get('state')) is not int or type(inner.get('inc')) is not int + or type(state.get('has_uint32')) is not int or type(state.get('uinteger')) is not int): + raise ValueError('malformed PCG64 state') + rng = np.random.Generator(np.random.PCG64()) + try: + rng.bit_generator.state = {'bit_generator': 'PCG64', 'state': {'state': inner['state'], 'inc': inner['inc']}, + 'has_uint32': state['has_uint32'], 'uinteger': state['uinteger']} + except (TypeError, ValueError, OverflowError) as exc: + raise ValueError('invalid PCG64 state') from exc + return rng + + +def _flip_probs(value: Any) -> tuple[float, float]: + if isinstance(value, (list, tuple, np.ndarray)): + if np.ndim(value) != 1 or len(value) != 2: + raise ValueError('flip_prob must be a number or a (p_ltp, p_ltd) pair') + return (_check_float('flip_prob[0] (p_ltp)', value[0], 0.0, 1.0), + _check_float('flip_prob[1] (p_ltd)', value[1], 0.0, 1.0)) + p = _check_float('flip_prob', value, 0.0, 1.0) + return p, p + + +# ====================================================================== BTSP memory +class BTSPMemory: + """Binary feed-forward + feedback memory trained one-shot by plateau-gated stochastic flips (module docstring). + + All randomness comes from ``seed``: the masks from ``default_rng(seed + 61403)`` and the plateau / flip draws + from ``default_rng(seed + 61417)``, so the same seed and the same store sequence give identical weights.""" + + def __init__(self, input_dim: int, memory_dim: int, *, density: float = 0.6, plateau_prob: float = 0.02, + flip_prob: float | Sequence[float] = 0.5, threshold: float = 0.35, feedback_threshold: float = 0.5, + seed: int = 0) -> None: + self.input_dim = _check_int('input_dim', input_dim, 1, 1_000_000) + self.memory_dim = _check_int('memory_dim', memory_dim, 1, 1_000_000) + if self.input_dim * self.memory_dim > _MAX_MATRIX: + raise ValueError(f'input_dim * memory_dim must be <= {_MAX_MATRIX:,}') + self.density = _check_float('density', density, 0.0, 1.0, low_open=True) + self.plateau_prob = _check_float('plateau_prob', plateau_prob, 0.0, 1.0) + self.p_ltp, self.p_ltd = _flip_probs(flip_prob) + self.threshold = _check_float('threshold', threshold, 0.0, 10.0) + self.feedback_threshold = _check_float('feedback_threshold', feedback_threshold, 0.0, 10.0) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + mask_rng = np.random.default_rng(self.seed + _MASK_OFFSET) + self._C = mask_rng.random((self.memory_dim, self.input_dim)) < self.density + self._D = mask_rng.random((self.input_dim, self.memory_dim)) < self.density + self.reset() + + # ------------------------------------------------------------------ state + def reset(self) -> None: + """Erase every memory (all weights 0) and restart the plasticity random stream.""" + self.W = np.zeros((self.memory_dim, self.input_dim), dtype=bool) + self.B = np.zeros((self.input_dim, self.memory_dim), dtype=bool) + self._rng = np.random.default_rng(self.seed + _PLASTICITY_OFFSET) + self.stores = 0 + self.plateaus = 0 + self.ltp_flips = 0 + self.ltd_flips = 0 + + @property + def forward_mask(self) -> np.ndarray: + return self._C.copy() + + @property + def feedback_mask(self) -> np.ndarray: + return self._D.copy() + + @property + def synapse_count(self) -> int: + """Existing plastic binary synapses (forward plus feedback).""" + return int(np.count_nonzero(self._C) + np.count_nonzero(self._D)) + + @property + def state_numbers(self) -> int: + """Stored numbers: binary weights and masks of both pathways plus four counters.""" + return int(self.W.size + self.B.size + self._C.size + self._D.size + 4) + + def weight_fractions(self) -> dict[str, float]: + """Fraction of existing synapses at weight 1 in each pathway.""" + c, d = max(1, int(np.count_nonzero(self._C))), max(1, int(np.count_nonzero(self._D))) + return {'forward': float(np.count_nonzero(self.W) / c), 'feedback': float(np.count_nonzero(self.B) / d)} + + def config(self) -> dict[str, Any]: + return {'input_dim': self.input_dim, 'memory_dim': self.memory_dim, 'density': self.density, + 'plateau_prob': self.plateau_prob, 'flip_prob': [self.p_ltp, self.p_ltd], 'threshold': self.threshold, + 'feedback_threshold': self.feedback_threshold, 'seed': self.seed} + + # ------------------------------------------------------------------ store / recall + def _code_idx(self, idx: np.ndarray) -> np.ndarray: + if idx.size == 0: + return np.zeros(self.memory_dim, dtype=bool) + drive = np.count_nonzero(self.W[:, idx], axis=1) + return drive > self.threshold * self.density * idx.size + + def _reconstruct_idx(self, zi: np.ndarray) -> np.ndarray: + if zi.size == 0: + return np.zeros(self.input_dim, dtype=bool) + drive = np.count_nonzero(self.B[:, zi], axis=1) + return drive > self.feedback_threshold * self.density * zi.size + + def store(self, pattern: Any, *, plateau_prob: float | None = None) -> dict[str, int]: + """One-shot store of a binary pattern (``plateau_prob`` overrides the configured probability for this store). + + Returns the number of plateau units, LTP (0 -> 1) and LTD (1 -> 0) flips, the new trace size and the number + of feedback synapses newly set to 1.""" + x = _binary('pattern', pattern, self.input_dim) + p = self.plateau_prob if plateau_prob is None else _check_float('plateau_prob', plateau_prob, 0.0, 1.0) + idx = np.flatnonzero(x) + rows = np.flatnonzero(self._rng.random(self.memory_dim) < p) + ltp = ltd = 0 + if rows.size and idx.size: + ix = np.ix_(rows, idx) + old = self.W[ix] + draw = self._rng.random(old.shape) + flip = self._C[ix] & (draw < np.where(old, self.p_ltd, self.p_ltp)) + ltp = int(np.count_nonzero(flip & ~old)) + ltd = int(np.count_nonzero(flip & old)) + self.W[ix] = old ^ flip + zi = np.flatnonzero(self._code_idx(idx)) + new_feedback = 0 + if zi.size and idx.size: + ix = np.ix_(idx, zi) + before = self.B[ix] + after = before | self._D[ix] + new_feedback = int(np.count_nonzero(after & ~before)) + self.B[ix] = after + self.stores += 1 + self.plateaus += int(rows.size) + self.ltp_flips += ltp + self.ltd_flips += ltd + return {'plateau_units': int(rows.size), 'ltp_flips': ltp, 'ltd_flips': ltd, 'trace_size': int(zi.size), + 'new_feedback_synapses': new_feedback} + + def drive(self, cue: Any) -> np.ndarray: + """Integer input of every memory unit, ``W c``.""" + idx = np.flatnonzero(_binary('cue', cue, self.input_dim)) + return np.count_nonzero(self.W[:, idx], axis=1).astype(np.int64) + + def code(self, cue: Any) -> np.ndarray: + """Memory trace ``z(c)`` (bool, length ``memory_dim``).""" + return self._code_idx(np.flatnonzero(_binary('cue', cue, self.input_dim))) + + def reconstruct(self, code: Any) -> np.ndarray: + """Feedback reconstruction ``r(z)`` of the input from a memory trace (bool, length ``input_dim``).""" + return self._reconstruct_idx(np.flatnonzero(_binary('code', code, self.memory_dim))) + + def recall(self, cue: Any) -> dict[str, np.ndarray]: + """``{'code': z(c), 'reconstruction': r(z(c))}`` (no state change).""" + z = self.code(cue) + return {'code': z, 'reconstruction': self._reconstruct_idx(np.flatnonzero(z))} + + # ------------------------------------------------------------------ persistence + def export_state(self) -> dict[str, Any]: + """JSON-safe state: weights on existing synapses (packed bits), counters and the plasticity RNG state.""" + return {'config': self.config(), 'W_bits': _pack(self.W[self._C]), 'B_bits': _pack(self.B[self._D]), + 'stores': int(self.stores), 'plateaus': int(self.plateaus), 'ltp_flips': int(self.ltp_flips), + 'ltd_flips': int(self.ltd_flips), 'rng': _rng_state(self._rng)} + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate everything, then replace weights, counters and RNG (the configuration must match).""" + if not isinstance(state, Mapping): + raise ValueError('BTSP memory state must be a mapping') + if state.get('config') != self.config(): + raise ValueError('BTSP memory state was made with a different configuration') + w_bits = _unpack('W_bits', state.get('W_bits'), int(np.count_nonzero(self._C))) + b_bits = _unpack('B_bits', state.get('B_bits'), int(np.count_nonzero(self._D))) + counters = {k: _check_int(k, state.get(k), 0, 2**62) for k in ('stores', 'plateaus', 'ltp_flips', 'ltd_flips')} + if counters['plateaus'] > counters['stores'] * self.memory_dim: + raise ValueError('plateau counter exceeds stores * memory_dim') + rng = _restore_rng(state.get('rng')) + W = np.zeros_like(self.W) + W[self._C] = w_bits + B = np.zeros_like(self.B) + B[self._D] = b_bits + self.W, self.B, self._rng = W, B, rng + self.stores, self.plateaus = counters['stores'], counters['plateaus'] + self.ltp_flips, self.ltd_flips = counters['ltp_flips'], counters['ltd_flips'] + + +# ====================================================================== comparison memories +class WillshawMemory: + """Clipped-Hebbian auto-associative binary memory (Willshaw et al., 1969) with ``input_dim**2`` synapses. + + ``store`` sets ``A_ij = 1`` for every co-active pair (including ``i = j``); ``recall`` returns + ``r_i = 1[(A c)_i >= threshold * |c|]`` (``threshold = 1`` is the classic all-cue-units rule).""" + + def __init__(self, input_dim: int, *, threshold: float = 1.0) -> None: + self.input_dim = _check_int('input_dim', input_dim, 1, 1_000_000) + if self.input_dim ** 2 > _MAX_MATRIX: + raise ValueError(f'input_dim**2 must be <= {_MAX_MATRIX:,}') + self.threshold = _check_float('threshold', threshold, 0.0, 1.0, low_open=True) + self.reset() + + def reset(self) -> None: + self.A = np.zeros((self.input_dim, self.input_dim), dtype=bool) + self.stores = 0 + + @property + def synapse_count(self) -> int: + return int(self.A.size) + + def store(self, pattern: Any) -> dict[str, int]: + idx = np.flatnonzero(_binary('pattern', pattern, self.input_dim)) + new = 0 + if idx.size: + ix = np.ix_(idx, idx) + new = int(idx.size * idx.size - np.count_nonzero(self.A[ix])) + self.A[ix] = True + self.stores += 1 + return {'new_synapses': new} + + def recall(self, cue: Any) -> np.ndarray: + idx = np.flatnonzero(_binary('cue', cue, self.input_dim)) + if idx.size == 0: + return np.zeros(self.input_dim, dtype=bool) + return np.count_nonzero(self.A[:, idx], axis=1) >= self.threshold * idx.size + + def export_state(self) -> dict[str, Any]: + return {'config': {'input_dim': self.input_dim, 'threshold': self.threshold}, 'A_bits': _pack(self.A.ravel()), + 'stores': int(self.stores)} + + def import_state(self, state: Mapping[str, Any]) -> None: + if not isinstance(state, Mapping) or state.get('config') != {'input_dim': self.input_dim, + 'threshold': self.threshold}: + raise ValueError('Willshaw state does not match this memory') + bits = _unpack('A_bits', state.get('A_bits'), self.input_dim ** 2).reshape(self.input_dim, self.input_dim) + if not np.array_equal(bits, bits.T): + raise ValueError('Willshaw matrix must be symmetric') + stores = _check_int('stores', state.get('stores'), 0, 2**62) + self.A, self.stores = bits, stores + + +class RandomRecallControl: + """Chance control: 'recalls' a seeded random pattern with ``active`` ones and ignores the cue. + Its expected normalised overlap with any pattern of ``active`` ones is ``active / input_dim``.""" + + def __init__(self, input_dim: int, active: int, seed: int = 0) -> None: + self.input_dim = _check_int('input_dim', input_dim, 1, 1_000_000) + self.active = _check_int('active', active, 0, self.input_dim) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + self._rng = np.random.default_rng(self.seed + _CONTROL_OFFSET) + + def store(self, pattern: Any) -> dict[str, int]: + _binary('pattern', pattern, self.input_dim) + return {} + + def recall(self, cue: Any) -> np.ndarray: + _binary('cue', cue, self.input_dim) + out = np.zeros(self.input_dim, dtype=bool) + out[self._rng.choice(self.input_dim, self.active, replace=False)] = True + return out + + +# ====================================================================== engine extension +class BTSPExtension(EngineExtension): + """Readout-only NEUROWEAVE extension around a :class:`BTSPMemory` over binarised brain output. + + After each engine step the brain output (fixed at the first ``n`` units seen at :meth:`bind`; units born later + are ignored) is binarised by top-``k`` (``k = max(1, round(active_fraction * n))``, ties to the lower index). + The current pattern is used as a recall cue *before* any store, giving the features + + * ``recall_overlap`` = ``overlap(x_t, r(z(x_t)))`` (familiarity of the current state), + * ``recall_confidence`` = ``min(1, |z(x_t)| / max(1, plateau_prob * memory_dim))`` (trace size relative to the + expected size of a stored trace), + * ``projection_dim`` fixed ``+-1`` projections of the trace, ``P z / sqrt(max(1, |z|))``. + + Then, only when ``ctx['learn']`` is true, the pattern is stored one-shot if its salience + ``max(|ctx['reward']|, 1 - recall_overlap)`` exceeds ``gate``, with plateau probability + ``plateau_prob * min(1, salience)``. The drive is never changed.""" + + id = MODULE_ID + + def __init__(self, memory_dim: int = 64, *, active_fraction: float = 0.25, density: float = 0.6, + plateau_prob: float = 0.1, flip_prob: float | Sequence[float] = 0.5, threshold: float = 0.35, + feedback_threshold: float = 0.5, gate: float = 0.5, projection_dim: int = 6, seed: int = 0) -> None: + self.memory_dim = _check_int('memory_dim', memory_dim, 1, 4096) + self.active_fraction = _check_float('active_fraction', active_fraction, 0.0, 1.0, low_open=True) + self.density = _check_float('density', density, 0.0, 1.0, low_open=True) + self.plateau_prob = _check_float('plateau_prob', plateau_prob, 0.0, 1.0) + self.flip_prob = list(_flip_probs(flip_prob)) + self.threshold = _check_float('threshold', threshold, 0.0, 10.0) + self.feedback_threshold = _check_float('feedback_threshold', feedback_threshold, 0.0, 10.0) + self.gate = _check_float('gate', gate, 0.0, 1.0) + self.projection_dim = _check_int('projection_dim', projection_dim, 0, 64) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + self.feature_dim = 2 + self.projection_dim + prng = np.random.default_rng(self.seed + _PROJECTION_OFFSET) + self._P = np.where(prng.random((self.projection_dim, self.memory_dim)) < 0.5, -1.0, 1.0) + self._expected_trace = max(1.0, self.plateau_prob * self.memory_dim) + self._n = 0 + self._k = 0 + self.memory: BTSPMemory | None = None + self._clear_counters() + + def _clear_counters(self) -> None: + self._features = np.zeros(self.feature_dim) + self._steps = 0 + self._frozen_steps = 0 + self._stores = 0 + self._last = {'overlap': 0.0, 'confidence': 0.0, 'salience': 0.0, 'stored': False} + + def _new_memory(self, n: int) -> BTSPMemory: + return BTSPMemory(n, self.memory_dim, density=self.density, plateau_prob=self.plateau_prob, + flip_prob=tuple(self.flip_prob), threshold=self.threshold, + feedback_threshold=self.feedback_threshold, seed=self.seed) + + def _build(self, n: int) -> None: + self._n = n + self._k = max(1, int(round(self.active_fraction * n))) + self.memory = self._new_memory(n) + + # ------------------------------------------------------------------ lifecycle + def bind(self, engine: Any) -> None: + """Size the memory from ``engine.n`` (copied); the memory starts empty.""" + n = getattr(engine, 'n', None) + if isinstance(n, (bool, np.bool_)) or not isinstance(n, (int, np.integer)): + raise ValueError('engine.n must be an int') + n = int(n) + if not 1 <= n <= 4096 or n * self.memory_dim > _MAX_MATRIX: + raise ValueError('engine size is out of range for the BTSP extension') + self._build(n) + self._clear_counters() + + def reset(self) -> None: + """Episode boundary: clear the current features (stored memories are kept).""" + self._features = np.zeros(self.feature_dim) + + # ------------------------------------------------------------------ hooks + def binarise(self, output: Any) -> np.ndarray: + """Top-``k`` binary pattern of the first ``n`` output values (zero-padded if the output is shorter).""" + if self.memory is None: + raise ValueError('BTSP extension is not bound to an engine') + try: + o = np.asarray(output, dtype=np.float64).ravel() + except (TypeError, ValueError) as exc: + raise ValueError('brain output must be numeric') from exc + if not np.all(np.isfinite(o)): + raise ValueError('brain output must be finite') + v = np.zeros(self._n) + m = min(self._n, o.size) + v[:m] = o[:m] + x = np.zeros(self._n, dtype=bool) + x[np.argsort(-v, kind='stable')[:self._k]] = True + return x + + def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None: + if not isinstance(ctx, Mapping): + raise ValueError('BTSP extension needs the engine step context') + learn = ctx.get('learn') + if type(learn) is not bool: + raise ValueError("ctx['learn'] must be a boolean") + reward = ctx.get('reward', 0.0) + if isinstance(reward, (bool, np.bool_)) or not isinstance(reward, (int, float, np.integer, np.floating)) \ + or not math.isfinite(float(reward)): + raise ValueError("ctx['reward'] must be a finite number") + x = self.binarise(output) + mem = self.memory + z = mem._code_idx(np.flatnonzero(x)) + zi = np.flatnonzero(z) + rec = mem._reconstruct_idx(zi) + ov = overlap(x, rec) + conf = min(1.0, zi.size / self._expected_trace) + proj = self._P @ z.astype(np.float64) / math.sqrt(max(1, zi.size)) if self.projection_dim else np.zeros(0) + self._features = np.clip(np.concatenate([[ov, conf], proj]), -10.0, 10.0) + salience = max(min(abs(float(reward)), 1.0), 1.0 - ov) + stored = False + if learn: + if salience > self.gate: + mem.store(x, plateau_prob=self.plateau_prob * min(1.0, salience)) + self._stores += 1 + stored = True + else: + self._frozen_steps += 1 + self._last = {'overlap': float(ov), 'confidence': float(conf), 'salience': float(salience), 'stored': stored} + self._steps += 1 + + def features(self) -> np.ndarray: + return self._features.copy() + + # ------------------------------------------------------------------ accounting / persistence + def parameter_count(self) -> int: + """Plastic binary synapses of the memory (0 before :meth:`bind`).""" + return 0 if self.memory is None else self.memory.synapse_count + + def state_numbers(self) -> int: + mem = 0 if self.memory is None else self.memory.state_numbers + return int(mem + self._P.size + self.feature_dim + 4) + + def telemetry(self) -> dict[str, Any]: + out: dict[str, Any] = {'id': self.id, 'n': self._n, 'k': self._k, 'memory_dim': self.memory_dim, + 'steps': self._steps, 'frozen_steps': self._frozen_steps, 'stores': self._stores, + 'last_overlap': self._last['overlap'], 'last_confidence': self._last['confidence'], + 'last_salience': self._last['salience'], 'last_stored': self._last['stored']} + if self.memory is not None: + out['weight_fractions'] = self.memory.weight_fractions() + out['synapses'] = self.memory.synapse_count + return out + + def config(self) -> dict[str, Any]: + return {'memory_dim': self.memory_dim, 'active_fraction': self.active_fraction, 'density': self.density, + 'plateau_prob': self.plateau_prob, 'flip_prob': list(self.flip_prob), 'threshold': self.threshold, + 'feedback_threshold': self.feedback_threshold, 'gate': self.gate, + 'projection_dim': self.projection_dim, 'seed': self.seed} + + def export_state(self) -> dict[str, Any]: + return {'id': self.id, 'config': self.config(), 'n': self._n, + 'memory': None if self.memory is None else self.memory.export_state(), + 'features': self._features.tolist(), 'steps': self._steps, 'frozen_steps': self._frozen_steps, + 'stores': self._stores, 'last': dict(self._last)} + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate fully, then restore. An unbound extension is sized from the state's ``n``.""" + super().import_state(state) + if state.get('config') != self.config(): + raise ValueError('BTSP extension state was made with a different configuration') + n = _check_int('n', state.get('n'), 0, 4096) + if self._n and n != self._n: + raise ValueError('BTSP extension state was made for a different engine size') + if n == 0: + if state.get('memory') is not None: + raise ValueError('unbound BTSP extension state cannot hold a memory') + memory = None + else: + if n * self.memory_dim > _MAX_MATRIX: + raise ValueError('engine size is out of range for the BTSP extension') + memory = self._new_memory(n) + memory.import_state(state.get('memory')) # validates fully before anything is replaced + try: + feats = np.asarray(state.get('features'), dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('features must be numeric') from exc + if feats.shape != (self.feature_dim,) or not np.all(np.isfinite(feats)) \ + or np.max(np.abs(feats), initial=0.0) > 10.0: + raise ValueError('features must be finite, in [-10, 10] and of length feature_dim') + steps = _check_int('steps', state.get('steps'), 0, 2**62) + frozen = _check_int('frozen_steps', state.get('frozen_steps'), 0, steps) + stores = _check_int('stores', state.get('stores'), 0, steps - frozen) + last = state.get('last') + if not isinstance(last, Mapping) or set(last) != {'overlap', 'confidence', 'salience', 'stored'} \ + or type(last['stored']) is not bool: + raise ValueError('last must hold overlap, confidence, salience and stored') + last = {'overlap': _check_float('last.overlap', last['overlap'], 0.0, 1.0), + 'confidence': _check_float('last.confidence', last['confidence'], 0.0, 1.0), + 'salience': _check_float('last.salience', last['salience'], 0.0, 1.0), 'stored': last['stored']} + if n == 0 and (steps or feats.any() or last['stored']): + raise ValueError('an unbound BTSP extension cannot have stepped') + if n: + self._n, self._k = n, max(1, int(round(self.active_fraction * n))) + self.memory = memory + self._features = feats.copy() + self._steps, self._frozen_steps, self._stores, self._last = steps, frozen, stores, last + + +# ====================================================================== capacity benchmark +# Both arms' tuned optimum lies inside its grid at these sizes (measured 2026-11-19); receipts flag a chosen value +# that sits on a grid edge, because an under-tuned arm would make the comparison unfair. +CAPACITY_DEFAULTS: dict[str, Any] = { + 'input_dim': 1000, 'active': 50, 'patterns': 400, 'checkpoints': 4, 'test_per_checkpoint': 64, + 'cue_fractions': (0.3, 0.5), 'cue_kinds': ('delete', 'flip'), 'density': 0.6, 'flip_prob': 0.5, + 'plateau_grid': (0.005, 0.01, 0.02, 0.04), 'threshold_grid': (0.25, 0.3, 0.35, 0.4), + 'feedback_grid': (0.35, 0.5, 0.65, 0.8), 'willshaw_grid': (0.5, 0.6, 0.7, 0.8, 0.9, 1.0), + 'tune_seeds': (1000, 1001)} +CAPACITY_QUICK: dict[str, Any] = { + 'input_dim': 400, 'active': 20, 'patterns': 120, 'test_per_checkpoint': 24, 'plateau_grid': (0.02, 0.04, 0.08), + '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), + 'tune_seeds': (1000,)} +_BTSP_NATURAL_BOUNDS = {'plateau_prob': (1.0,), 'threshold': (0.0,), 'feedback_threshold': (0.0,)} +_WILLSHAW_NATURAL_BOUNDS = {'threshold': (1.0,)} # 1 = the classic all-cue-units rule (and the largest allowed) + + +def _grid(name: str, value: Any, low: float, high: float, *, low_open: bool = False) -> tuple[float, ...]: + try: + out = tuple(value) + except TypeError as exc: + raise ValueError(f'{name} must be a sequence of numbers') from exc + if not 1 <= len(out) <= 16: + raise ValueError(f'{name} must hold 1..16 values') + return tuple(_check_float(f'{name} entry', v, low, high, low_open=low_open) for v in out) + + +def _test_sets(seed: int, patterns: np.ndarray, loads: Sequence[int], per: int, + conditions: Sequence[tuple[float, str]]) -> list[dict[str, Any]]: + """For each checkpoint: tested pattern indices and one cue per (condition, pattern), shared by every arm.""" + sets = [] + for j, load in enumerate(loads): + rng = np.random.default_rng(seed + _TEST_OFFSET + 7919 * j) + idx = np.sort(rng.choice(load, min(per, load), replace=False)) + cues = {cond: np.stack([make_cue(patterns[i], cond[0], cond[1], rng) for i in idx]) for cond in conditions} + sets.append({'load': int(load), 'idx': idx, 'cues': cues}) + return sets + + +def _cond_name(cond: tuple[float, str]) -> str: + return f'{cond[1]}_{cond[0]:g}' + + +def _score_recall(patterns: np.ndarray, test: Mapping[str, Any], recalls: Mapping[Any, Sequence[np.ndarray]] + ) -> dict[str, dict[str, float | None]]: + out: dict[str, dict[str, float | None]] = {} + for cond, recs in recalls.items(): + ovs, errs = [], [] + for i, cue, rec in zip(test['idx'], test['cues'][cond], recs): + ovs.append(overlap(patterns[i], rec)) + err = reconstruction_error(patterns[i], cue, rec) + if err is not None: + errs.append(err) + out[_cond_name(cond)] = {'overlap': float(np.mean(ovs)), + 'reconstruction_error': float(np.mean(errs)) if errs else None} + return out + + +def _curve(per_ckpt: Sequence[Mapping[str, Mapping[str, Any]]]) -> float: + return float(np.mean([v['overlap'] for ck in per_ckpt for v in ck.values()])) + + +def _run_btsp(patterns: np.ndarray, tests: Sequence[Mapping[str, Any]], *, memory_dim: int, density: float, + flip_prob: float, plateau: float, threshold: float, feedback_grid: Sequence[float], seed: int, + diagnostics: bool = False) -> dict[str, Any]: + """Store sequentially; at each checkpoint score every feedback threshold (it acts at recall only).""" + mem = BTSPMemory(patterns.shape[1], memory_dim, density=density, plateau_prob=plateau, flip_prob=flip_prob, + threshold=threshold, feedback_threshold=feedback_grid[0], seed=seed) + per_fb: dict[float, list[dict[str, Any]]] = {fb: [] for fb in feedback_grid} + diag = [] + stored = 0 + for test in tests: + while stored < test['load']: + mem.store(patterns[stored]) + stored += 1 + codes = {cond: [mem.code(c) for c in cues] for cond, cues in test['cues'].items()} + for fb in feedback_grid: + mem.feedback_threshold = fb + recs = {cond: [mem._reconstruct_idx(np.flatnonzero(z)) for z in zs] for cond, zs in codes.items()} + per_fb[fb].append(_score_recall(patterns, test, recs)) + if diagnostics: + full = [mem.code(patterns[i]) for i in test['idx']] + diag.append({'load': test['load'], 'weight_fractions': mem.weight_fractions(), + 'mean_trace_size': float(np.mean([np.count_nonzero(z) for z in full])), + 'trace_overlap': {_cond_name(cond): float(np.mean([overlap(a, b) for a, b in zip(full, zs)])) + for cond, zs in codes.items()}}) + return {'per_feedback': per_fb, 'diagnostics': diag, 'synapses': mem.synapse_count} + + +def _run_willshaw(patterns: np.ndarray, tests: Sequence[Mapping[str, Any]], grid: Sequence[float] + ) -> dict[float, list[dict[str, Any]]]: + mem = WillshawMemory(patterns.shape[1], threshold=grid[0]) + out: dict[float, list[dict[str, Any]]] = {th: [] for th in grid} + stored = 0 + for test in tests: + while stored < test['load']: + mem.store(patterns[stored]) + stored += 1 + for th in grid: + mem.threshold = th + recs = {cond: [mem.recall(c) for c in cues] for cond, cues in test['cues'].items()} + out[th].append(_score_recall(patterns, test, recs)) + return out + + +def _run_reference(patterns: np.ndarray, tests: Sequence[Mapping[str, Any]], *, active: int, seed: int + ) -> dict[str, list[dict[str, Any]]]: + control = RandomRecallControl(patterns.shape[1], active, seed=seed) + rand, cue_only = [], [] + for test in tests: + rand.append(_score_recall(patterns, test, {cond: [control.recall(c) for c in cues] + for cond, cues in test['cues'].items()})) + cue_only.append(_score_recall(patterns, test, {cond: list(cues) for cond, cues in test['cues'].items()})) + return {'random_recall': rand, 'cue_only': cue_only} + + +def run_capacity_benchmark(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any + ) -> dict[str, Any]: + """BTSP vs a Willshaw memory with the same synapse count vs a random-recall control. + + ``patterns`` random binary patterns with exactly ``active`` ones are stored one-shot, in order. At + ``checkpoints`` evenly spaced loads, ``test_per_checkpoint`` stored patterns are recalled from degraded cues + (every ``cue_fractions`` x ``cue_kinds`` condition; the same cues for every arm). Metric: normalised overlap + between the stored pattern and its reconstruction, averaged over checkpoints and conditions (the mean of the + capacity curve). BTSP uses ``memory_dim = round(input_dim / (2 * density))`` memory units, so its forward plus + feedback synapses match the Willshaw matrix's ``input_dim**2`` in expectation (exact counts are reported). + Free parameters are tuned per arm on ``tune_seeds`` (disjoint from ``seeds``) by the same metric: plateau + probability, threshold and feedback threshold for BTSP, the threshold for Willshaw. Verdict: paired 95 % t + interval over seeds, BTSP vs Willshaw (higher is better).""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds('seeds', seeds) + cfg = dict(CAPACITY_DEFAULTS) + if quick: + cfg.update(CAPACITY_QUICK) + unknown = sorted(set(overrides) - set(cfg)) + if unknown: + raise ValueError(f'unknown run_capacity_benchmark overrides: {unknown}') + cfg.update(overrides) + m = _check_int('input_dim', cfg['input_dim'], 8, 2000) + a = _check_int('active', cfg['active'], 1, m // 2) + n_pat = _check_int('patterns', cfg['patterns'], 1, 100_000) + n_ck = _check_int('checkpoints', cfg['checkpoints'], 1, min(16, n_pat)) + per = _check_int('test_per_checkpoint', cfg['test_per_checkpoint'], 1, 4096) + density = _check_float('density', cfg['density'], 0.0, 1.0, low_open=True) + flip = _check_float('flip_prob', cfg['flip_prob'], 0.0, 1.0) + fracs = _grid('cue_fractions', cfg['cue_fractions'], 0.0, 1.0) + try: + kinds = tuple(cfg['cue_kinds']) + except TypeError as exc: + raise ValueError(f'cue_kinds must be distinct values from {CUE_KINDS}') from exc + if not kinds or any(k not in CUE_KINDS for k in kinds) or len(set(kinds)) != len(kinds): + raise ValueError(f'cue_kinds must be distinct values from {CUE_KINDS}') + plateau_grid = _grid('plateau_grid', cfg['plateau_grid'], 0.0, 1.0, low_open=True) + threshold_grid = _grid('threshold_grid', cfg['threshold_grid'], 0.0, 10.0) + feedback_grid = _grid('feedback_grid', cfg['feedback_grid'], 0.0, 10.0) + willshaw_grid = _grid('willshaw_grid', cfg['willshaw_grid'], 0.0, 1.0, low_open=True) + tune_seeds = _check_seeds('tune_seeds', cfg['tune_seeds']) + if set(tune_seeds) & set(seeds): + raise ValueError('tune_seeds must be disjoint from seeds') + memory_dim = max(1, int(round(m / (2.0 * density)))) + if m * memory_dim > _MAX_MATRIX: + raise ValueError('input_dim / density gives a BTSP memory that is too large') + conditions = [(f, k) for k in kinds for f in fracs] + loads = sorted({max(1, int(round(n_pat * (j + 1) / n_ck))) for j in range(n_ck)}) + cfg.update({'input_dim': m, 'active': a, 'patterns': n_pat, 'checkpoints': n_ck, 'test_per_checkpoint': per, + 'density': density, 'flip_prob': flip, 'cue_fractions': fracs, 'cue_kinds': kinds, + 'plateau_grid': plateau_grid, 'threshold_grid': threshold_grid, 'feedback_grid': feedback_grid, + 'willshaw_grid': willshaw_grid, 'tune_seeds': tune_seeds}) + + def workload(seed: int) -> tuple[np.ndarray, list[dict[str, Any]]]: + pats = random_patterns(n_pat, m, a, np.random.default_rng(seed + _PATTERN_OFFSET)) + return pats, _test_sets(seed, pats, loads, per, conditions) + + t0 = time.perf_counter() + tune_work = {s: workload(s) for s in tune_seeds} + btsp_table: list[dict[str, Any]] = [] + for plateau, threshold in itertools.product(plateau_grid, threshold_grid): + runs = [_run_btsp(*tune_work[s], memory_dim=memory_dim, density=density, flip_prob=flip, plateau=plateau, + threshold=threshold, feedback_grid=feedback_grid, seed=s)['per_feedback'] + for s in tune_seeds] + for fb in feedback_grid: + btsp_table.append({'plateau_prob': plateau, 'threshold': threshold, 'feedback_threshold': fb, + 'tune_score': float(np.mean([_curve(r[fb]) for r in runs]))}) + will_runs = [_run_willshaw(*tune_work[s], willshaw_grid) for s in tune_seeds] + will_table = [{'threshold': th, 'tune_score': float(np.mean([_curve(r[th]) for r in will_runs]))} + for th in willshaw_grid] + b_best = btsp_table[max(range(len(btsp_table)), key=lambda i: (btsp_table[i]['tune_score'], -i))] + w_best = will_table[max(range(len(will_table)), key=lambda i: (will_table[i]['tune_score'], -i))] + b_chosen = {k: b_best[k] for k in ('plateau_prob', 'threshold', 'feedback_threshold')} + b_edges = _grid_edges(b_chosen, {'plateau_prob': plateau_grid, 'threshold': threshold_grid, + 'feedback_threshold': feedback_grid}, _BTSP_NATURAL_BOUNDS) + w_edges = _grid_edges({'threshold': w_best['threshold']}, {'threshold': willshaw_grid}, _WILLSHAW_NATURAL_BOUNDS) + tune_wall = time.perf_counter() - t0 + + t1 = time.perf_counter() + per_seed = [] + for s in seeds: + pats, tests = workload(s) + b = _run_btsp(pats, tests, memory_dim=memory_dim, density=density, flip_prob=flip, + plateau=b_best['plateau_prob'], threshold=b_best['threshold'], + feedback_grid=(b_best['feedback_threshold'],), seed=s, diagnostics=True) + w = _run_willshaw(pats, tests, (w_best['threshold'],))[w_best['threshold']] + ref = _run_reference(pats, tests, active=a, seed=s) + arms = {'btsp': b['per_feedback'][b_best['feedback_threshold']], 'willshaw': w, + 'random_recall': ref['random_recall'], 'cue_only': ref['cue_only']} + per_seed.append({'seed': int(s), 'btsp_synapses': b['synapses'], 'btsp_diagnostics': b['diagnostics'], + 'curve_mean_overlap': {arm: _curve(v) for arm, v in arms.items()}, + 'per_checkpoint': {arm: [{'load': t['load'], **ck} for t, ck in zip(tests, v)] + for arm, v in arms.items()}}) + eval_wall = time.perf_counter() - t1 + + def vals(arm: str) -> list[float]: + return [r['curve_mean_overlap'][arm] for r in per_seed] + + comparisons = {'btsp_vs_willshaw': harness.compare(vals('btsp'), vals('willshaw')), + 'btsp_vs_random_recall': harness.compare(vals('btsp'), vals('random_recall')), + 'willshaw_vs_random_recall': harness.compare(vals('willshaw'), vals('random_recall')), + 'btsp_vs_cue_only': harness.compare(vals('btsp'), vals('cue_only')), + 'willshaw_vs_cue_only': harness.compare(vals('willshaw'), vals('cue_only'))} + arm_names = ('btsp', 'willshaw', 'random_recall', 'cue_only') + summary = {arm: {'curve_mean_overlap': float(np.mean(vals(arm))), + 'overlap_by_load': [float(np.mean([r['per_checkpoint'][arm][j][_cond_name(c)]['overlap'] + for r in per_seed for c in conditions])) + for j in range(len(loads))]} + for arm in arm_names} + btsp_syn = [r['btsp_synapses'] for r in per_seed] + receipt = harness.base_receipt(CAPACITY_ID, 'memory_benchmark', { + **{k: (list(v) if isinstance(v, tuple) else v) for k, v in cfg.items()}, 'seeds': list(seeds), 'quick': quick, + 'loads': loads, 'conditions': [_cond_name(c) for c in conditions], 'memory_dim': memory_dim, + 'metric': 'normalised reconstruction overlap |x & r| / sqrt(|x| |r|), mean over checkpoints and conditions', + 'tuning_objective': 'the same metric on tune_seeds'}) + receipt.update({ + 'module': MODULE_ID, 'source': SOURCE, + 'arms': {'btsp': f'BTSP memory: {memory_dim} memory units, forward + feedback masks at density {density:g}, ' + 'plateau-gated stochastic flips, Hebbian feedback readout', + 'willshaw': f'Willshaw clipped-Hebbian auto-associative matrix, {m}x{m} binary synapses', + 'random_recall': f'seeded random pattern with {a} ones (chance; expected overlap {a / m:.4f})', + 'cue_only': 'reference without memory: the degraded cue itself is the reconstruction'}, + 'tuning': {'btsp': {'chosen': b_chosen, 'chosen_on_grid_edge': b_edges, 'table': btsp_table}, + 'willshaw': {'chosen': {'threshold': w_best['threshold']}, 'chosen_on_grid_edge': w_edges, + 'table': will_table}}, + 'per_seed': per_seed, 'summary': summary, 'comparisons': comparisons, + 'verdict': comparisons['btsp_vs_willshaw']['verdict'], + 'verdict_basis': ('btsp_vs_willshaw: paired 95% t interval over seeds on the capacity-curve mean ' + 'reconstruction overlap (higher is better), both arms tuned on disjoint tune_seeds'), + 'budget': {'willshaw_synapses': m * m, 'btsp_synapses_per_seed': btsp_syn, + 'btsp_synapses_expected': float(2.0 * density * m * memory_dim), + 'btsp_to_willshaw_synapse_ratio': float(np.mean(btsp_syn) / (m * m)), + 'btsp_state_numbers': int(4 * m * memory_dim + 4), 'willshaw_state_numbers': int(m * m + 1)}, + 'estimated_cost': {'stores_per_arm_run': n_pat, 'tuning_btsp_runs': len(plateau_grid) * len(threshold_grid) + * len(tune_seeds), 'recall_queries_per_run': len(loads) * len(conditions) * per, + 'estimated_synapse_reads': int((len(plateau_grid) * len(threshold_grid) * len(tune_seeds) + + len(seeds)) * (n_pat + len(loads) * len(conditions) * per) + * 2 * a * memory_dim)}, + 'measured_wallclock_s': {'tuning': tune_wall, 'evaluation': eval_wall}, + 'notes': ('Synthetic random sparse patterns stored once each, in order; recall is one feed-forward + feedback ' + 'pass for BTSP and one pass for Willshaw (no iteration). Thresholds are proportional to the cue / ' + 'trace size (the paper grid-searches an absolute memory threshold and, for input completion, uses ' + 'fitted linear functions of the average fraction of 1\'s). BTSP gets a larger tuning grid than ' + 'Willshaw (it has three free parameters, Willshaw one); tuning..chosen_on_grid_edge names any ' + 'parameter whose chosen value is a grid edge. The paper itself does not compare BTSP with a ' + 'Willshaw memory. The comparison is at equal synapse count, not equal bits of ' + 'state: Willshaw has no masks. BTSP feed-forward weights are a palimpsest (stochastic flips), but the ' + 'Hebbian feedback weights only saturate, as in the paper. The cue_only reference shows whether a ' + 'reconstruction beats the degraded cue. A small toy at one scale: it does not test the paper\'s ' + 'network sizes or claims.'), + }) + return harness.seal(receipt) + + +# ====================================================================== NEUROWEAVE extension experiment +_EXT_DEFAULTS: dict[str, Any] = {'memory_dim': 64, 'active_fraction': 0.25, 'density': 0.6, 'plateau_prob': 0.1, + 'flip_prob': 0.5, 'threshold': 0.35, 'feedback_threshold': 0.5, 'gate': 0.5, + 'projection_dim': 6} +_RUN_DEFAULTS: dict[str, Any] = {'task': 'delayed_recall', 'heldout_seeds': (100, 101), 'steps': 300, + 'heldout_steps': None, 'neurons': 48, 'topology': 'clustered', 'mechanisms': ()} + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Baseline vs ``BTSPExtension`` readout features vs the random-trace capacity control on a NEUROWEAVE + temporal task (default ``delayed_recall``), through ``harness.run_extension_experiment``. + + Extension overrides: the keys of ``_EXT_DEFAULTS``. Harness overrides: ``task``, ``heldout_seeds``, ``steps``, + ``heldout_steps``, ``neurons``, ``topology``, ``mechanisms``. Quick mode uses the harness ``QUICK_ARGS`` sizes + (the seeds stay the caller's).""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds('seeds', seeds) + ext_cfg, run_cfg = dict(_EXT_DEFAULTS), dict(_RUN_DEFAULTS) + if quick: + run_cfg.update({k: v for k, v in harness.QUICK_ARGS.items() if k != 'seeds'}) + unknown = sorted(set(overrides) - set(ext_cfg) - set(run_cfg)) + if unknown: + raise ValueError(f'unknown run_experiment overrides: {unknown}') + for key, value in overrides.items(): + (ext_cfg if key in ext_cfg else run_cfg)[key] = value + probe = BTSPExtension(seed=0, **ext_cfg) # validate before running anything + ext_cfg = {k: v for k, v in probe.config().items() if k != 'seed'} + + def factory(seed: int) -> BTSPExtension: + return BTSPExtension(seed=seed, **ext_cfg) + + t0 = time.perf_counter() + receipt = dict(harness.run_extension_experiment( + MODULE_ID, factory, seeds=seeds, control='random_trace', metric='accuracy', notes=( + f'Readout-only extension: the brain output is binarised by top-k (fraction {probe.active_fraction:g}) and ' + f'recalled from a {probe.memory_dim}-unit BTSP memory before any store; features are the recall overlap, ' + f'the recall confidence and {probe.projection_dim} fixed projections of the memory trace. While learning, ' + f'a pattern is stored one-shot when max(|reward|, novelty) exceeds {probe.gate:g}, with the plateau ' + 'probability scaled by that salience. It never changes the brain drive. The control gets the same number ' + 'of random leaky-trace features of the brain output. Small synthetic task; the verdict is a paired 95 % ' + 't interval over seeds.'), + **run_cfg)) + receipt.pop('digest', None) + receipt['config'] = {**receipt['config'], 'quick': quick, 'extension': ext_cfg} + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0} + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment, CAPACITY_ID: run_capacity_benchmark} diff --git a/synapse/frontier/causal_emergence.py b/synapse/frontier/causal_emergence.py new file mode 100644 index 0000000000000000000000000000000000000000..de432f81f9838e6bc455c69232812a512efd78fa --- /dev/null +++ b/synapse/frontier/causal_emergence.py @@ -0,0 +1,1365 @@ +"""Effective information and causal emergence (frontier module ``causal_emergence``). + +Inspired by effective information (EI) and causal emergence as defined by Hoel, Albantakis & Tononi (2013) and +Hoel (2017), and by the macro-vs-micro EI experiments of SONAPSE-ORIGIN (kai9987kai, +``sonapse_origin/theories/causal_emergence.py``). GhostInTheMachine (kai9987kai) measures emergence with the +Rosas et al. (2020) Psi criterion instead; its lesson that an emergence statistic must be read against a matched +null is applied here. This is a synthetic computational abstraction over discretised unit activity, not a measure +of consciousness, agency or biological causation. + +What is computed +---------------- +* **Effective information.** For a row-stochastic transition probability matrix (TPM) ``T`` over ``n`` states and + maximum-entropy (uniform) interventions on the current state, + ``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). + Equivalently ``EI = H(E_D) - (1/n) sum_i H(T_i)``, the mutual information between uniform interventions and + their effects. +* **Decomposition (Hoel 2017).** ``determinism = (1/n) sum_i D_KL(T_i || U) / log2 n``, + ``degeneracy = D_KL(E_D || U) / log2 n``, ``effectiveness = determinism - degeneracy`` and + ``EI = log2(n) * effectiveness`` (``U`` uniform). +* **Estimation.** Transition counts of a discretised state sequence, additive (Laplace, ``alpha = 1``) smoothing: + ``T_ij = (C_ij + alpha) / (sum_k C_ik + alpha n)``. +* **Coarse-graining.** A partition of micro states into macro states; the macro TPM is obtained by intervening + uniformly on the micro states inside each macro state and summing their effects over each macro state + (Hoel et al. 2013). Candidates are all proper set partitions of a small state space (``3 <= n <= 10``), or + partitions of binary units into groups whose macro variable is the group's count of active units. +* **Causal emergence.** ``CE = max_macro EI(macro) - EI(micro)`` over proper coarse-grainings (the micro + description itself is excluded, so ``CE`` can be negative). +* **Nulls.** Two references, both re-running the search for the best coarse-graining in every draw (so the null + includes the selection of the maximum), each reported as ``z = (CE - mean_null) / sd_null`` and the one-sided + rank p-value ``(1 + #{CE_null >= CE}) / (1 + draws)``: + + - *successor block permutation* (temporal-dependence null): the successor sequence is block-permuted against + the current-state sequence, which breaks lag-1 dependence but keeps how often each state was visited; + - *independent units* (multi-unit data only): every unit's bit sequence is circularly shifted by its own random + offset, which keeps each unit's own occupancy and autocorrelation but makes the units independent. + + Neither null tests "true macro EI > true micro EI". Smoothed EI estimates shrink the many-state micro TPM more + than a macro TPM, so with sparse counts the CE estimate rises above the successor null for *any* temporally + dependent data, including independent slow units whose exact CE is negative (a measured case is in the + receipt). Against the independent-units null, a large CE means the coarse-graining gains from coordination + between units beyond the units' own dynamics; the known-answer checks show where each null is calibrated. + +References (verified 2026-11-20; notes in ``docs/frontier/modules/causal_emergence.md``) +-------------------------------------------------------------------------------------- +* E. P. Hoel, L. Albantakis, G. Tononi, "Quantifying causal emergence shows that macro can beat micro", + PNAS 110(49):19790-19795, December 2013 (online 18 November 2013), https://doi.org/10.1073/pnas.1314922110 +* E. P. Hoel, "When the map is better than the territory", Entropy 19(5):188, published 26 April 2017, + https://doi.org/10.3390/e19050188 (preprint arXiv:1612.09592, whose v1 text was used to check printed values) +* F. E. Rosas, P. A. M. Mediano, H. J. Jensen, A. K. Seth, A. B. Barrett, R. L. Carhart-Harris, D. Bor, + "Reconciling emergences: an information-theoretic approach to identify causal emergence in multivariate data", + PLOS Comput. Biol. 16(12):e1008289, December 2020, https://doi.org/10.1371/journal.pcbi.1008289 (the Psi + criterion used by GhostInTheMachine; not implemented here) +""" +from __future__ import annotations + +import math +import time +from fractions import Fraction +from typing import Any, Callable, Mapping, Sequence + +import numpy as np + +from .connectomics import block_permutation +from .spec import EVIDENCE_TIER, FrontierSpecV1 + +__all__ = ['MODULE_ID', 'CausalEmergenceObserver', 'entropy_bits', 'as_tpm', 'effective_information', + 'ei_decomposition', 'transition_counts', 'estimate_tpm', 'median_binarize', 'encode_bits', + 'decode_states', 'coarse_grain_tpm', 'set_partitions', 'unit_sum_labels', 'unit_sum_candidates', + 'state_partition_candidates', 'macro_ei_batch', 'best_state_partition', 'best_unit_coarse_graining', + 'causal_emergence', 'successor_block_null', 'independent_units_null', 'hoel2017_examples', + 'and_gate_network', 'pair_count_copy_tpm', 'noisy_permutation_tpm', 'independent_flip_tpm', + 'PRINTED_VALUES', 'run_experiment', 'EXPERIMENTS'] + +MODULE_ID = 'causal_emergence' +OBSERVER_STATE_SCHEMA = 'CausalEmergenceObserverStateV1' +_PERM_OFFSET = 64_001 +_EST_OFFSET = 64_011 +_IID_OFFSET = 64_021 +_CHAIN_OFFSET = 64_031 +_NULL_OFFSET = 64_041 +_OBS_UNITS_OFFSET = 64_051 +_OBS_NULL_OFFSET = 64_061 +_INDEP_OFFSET = 64_071 +_OBS_INDEP_OFFSET = 64_081 +_PAIR_OFFSET = 64_091 +_SLOW_OFFSET = 64_101 +_UNIT_NULL_OFFSET = 64_111 +_PERM8_OFFSET = 64_121 +_EPS = 1e-12 +_MAX_STATES = 2048 +_MAX_SEARCH_STATES = 10 +_MAX_OBSERVER_UNITS = 6 +_CHUNK_CELLS = 1 << 20 # candidate chunks hold at most ~1M (candidate, i, j) cells +_SPEC_OBSERVER_PARAMS = frozenset({'sync_pairs', 'sae_features', 'sae_k', 'fc_window', 'max_observed_units', + 'observe_every'}) + + +# ====================================================================== validation helpers +def _check_int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _check_float(name: str, value: Any, low: float, high: float) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number in [{low}, {high}]') + v = float(value) + if not (math.isfinite(v) and low <= v <= high): + raise ValueError(f'{name} must be a finite number in [{low}, {high}]') + return v + + +def _check_seeds(seeds: Any) -> tuple[int, ...]: + try: + out = tuple(_check_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +def _int_vector(name: str, value: Any, *, min_len: int = 1) -> np.ndarray: + arr = np.asarray(value) + if arr.ndim != 1 or arr.size < min_len or (arr.size and arr.dtype.kind not in 'iu'): + raise ValueError(f'{name} must be a 1-D integer array with at least {min_len} entries') + return arr.astype(np.int64) + + +# ====================================================================== information measures +def _entropy(P: np.ndarray) -> np.ndarray: + """Shannon entropy in bits along the last axis (``0 log 0 = 0``).""" + L = np.zeros_like(P) + np.log2(P, out=L, where=P > 0.0) + return -(P * L).sum(axis=-1) + + +def entropy_bits(p: Any) -> float: + """Shannon entropy (bits) of a probability vector (finite, non-negative, summing to 1 within 1e-8).""" + try: + v = np.array(p, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('p must be numeric') from exc + 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: + raise ValueError('p must be a finite, non-negative 1-D probability vector') + return float(max(0.0, float(_entropy(v / v.sum())))) + + +def as_tpm(tpm: Any, *, atol: float = 1e-8) -> np.ndarray: + """A validated float64 copy of a row-stochastic ``(n, n)`` matrix, ``1 <= n <= 2048``. Rows must sum to 1 + within ``atol`` and are then renormalised exactly.""" + try: + T = np.array(tpm, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('tpm must be numeric') from exc + if T.ndim != 2 or T.shape[0] != T.shape[1] or not 1 <= T.shape[0] <= _MAX_STATES: + raise ValueError(f'tpm must be a square matrix with 1 to {_MAX_STATES} states') + if not np.all(np.isfinite(T)) or np.any(T < 0.0): + raise ValueError('tpm must be finite and non-negative') + s = T.sum(axis=1) + if np.any(np.abs(s - 1.0) > _check_float('atol', atol, 0.0, 1e-3)): + raise ValueError('every tpm row must sum to 1') + return T / s[:, None] + + +def _ei(T: np.ndarray) -> float: + """EI of a validated TPM: mean KL divergence (bits) of the rows from their mean.""" + m = T.mean(axis=0) + ratio = np.ones_like(T) + np.divide(T, m[None, :], out=ratio, where=T > 0.0) # T_ij > 0 implies m_j >= T_ij / n > 0 + return max(0.0, float((T * np.log2(ratio)).sum() / T.shape[0])) + + +def effective_information(tpm: Any) -> float: + """``EI = (1/n) sum_i D_KL(T_i || E_D)`` in bits under uniform interventions (Hoel et al., 2013).""" + return _ei(as_tpm(tpm)) + + +def _decomposition(T: np.ndarray) -> dict[str, Any]: + n = T.shape[0] + ei = _ei(T) + mean_h = float(_entropy(T).mean()) + h_eff = float(_entropy(T.mean(axis=0))) + size = math.log2(n) + out: dict[str, Any] = {'states': int(n), 'ei': ei, 'size_bits': size, 'mean_row_entropy': mean_h, + 'effect_entropy': h_eff, 'determinism': None, 'degeneracy': None, 'effectiveness': None} + if n > 1: + det = min(1.0, max(0.0, (size - mean_h) / size)) + deg = min(1.0, max(0.0, (size - h_eff) / size)) + out.update(determinism=det, degeneracy=deg, effectiveness=det - deg) + return out + + +def ei_decomposition(tpm: Any) -> dict[str, Any]: + """EI with Hoel's (2017) decomposition: ``determinism = (log2 n - mean_i H(T_i)) / log2 n``, + ``degeneracy = (log2 n - H(E_D)) / log2 n``, ``effectiveness = determinism - degeneracy``, so + ``EI = log2(n) * effectiveness``. The normalised terms are ``None`` for a single state.""" + return _decomposition(as_tpm(tpm)) + + +# ====================================================================== estimation from data +def _state_sequence(states: Any, n_states: int, *, min_len: int = 2) -> np.ndarray: + s = _int_vector('states', states, min_len=min_len) + if s.min() < 0 or s.max() >= n_states: + raise ValueError(f'states must lie in [0, {n_states})') + return s + + +def _counts(cur: np.ndarray, nxt: np.ndarray, n: int) -> np.ndarray: + return np.bincount(cur * n + nxt, minlength=n * n).reshape(n, n) + + +def transition_counts(states: Any, n_states: int, *, next_states: Any = None) -> np.ndarray: + """Counts ``C[i, j]`` of transitions ``i -> j`` (values in ``[0, n_states)``). + + Without ``next_states`` the transitions are the consecutive pairs of one state sequence. With ``next_states`` + (same length as ``states``) they are the pairs ``(states[t], next_states[t])``, e.g. interventional samples + in which the current state was set and its successor observed.""" + n = _check_int('n_states', n_states, 1, _MAX_STATES) + if next_states is None: + s = _state_sequence(states, n) + return _counts(s[:-1], s[1:], n) + cur = _state_sequence(states, n, min_len=1) + nxt = _state_sequence(next_states, n, min_len=1) + if nxt.size != cur.size: + raise ValueError('next_states must have the same length as states') + return _counts(cur, nxt, n) + + +def _smoothed(C: np.ndarray, alpha: float) -> np.ndarray: + n = C.shape[0] + A = C + alpha + tot = A.sum(axis=1, keepdims=True) + out = np.full(A.shape, 1.0 / n) + np.divide(A, tot, out=out, where=tot > 0.0) # unseen rows with alpha = 0 stay uniform + return out + + +def estimate_tpm(counts: Any, *, alpha: float = 1.0) -> np.ndarray: + """Additively smoothed TPM ``(C + alpha) / (row total + alpha n)``; ``alpha = 1`` is Laplace smoothing. + Rows without counts (possible only with ``alpha = 0``) are uniform: no evidence, maximum entropy.""" + try: + C = np.array(counts, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('counts must be numeric') from exc + if C.ndim != 2 or C.shape[0] != C.shape[1] or not 1 <= C.shape[0] <= _MAX_STATES: + raise ValueError('counts must be a square matrix') + if not np.all(np.isfinite(C)) or np.any(C < 0.0): + raise ValueError('counts must be finite and non-negative') + return _smoothed(C, _check_float('alpha', alpha, 0.0, 1e6)) + + +def _above_median(values: np.ndarray, reference: np.ndarray) -> np.ndarray: + """``values > median(reference)`` per column. A value tied with the median counts as on when more of the + reference lies strictly below the median than strictly above it, so a discrete unit whose upper value is the + majority (e.g. a 0/1 unit that is on 70 % of the time) is binarised as itself rather than as constant 0; + for continuous data ties have probability zero and the rule is plain ``x > median``.""" + med = np.median(reference, axis=0) + on = values > med + tie = values == med + if np.any(tie): + on |= tie & ((reference < med).sum(axis=0) > (reference > med).sum(axis=0)) + return on + + +def median_binarize(X: Any) -> np.ndarray: + """Offline per-column binarisation ``x > median(column)`` of a finite ``(T, k)`` array (boolean result); values + tied with the median go to the side of the median that holds less of the column (see the observer).""" + try: + A = np.array(X, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('X must be numeric') from exc + if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] < 1 or not np.all(np.isfinite(A)): + raise ValueError('X must be a finite 2-D array') + return _above_median(A, A) + + +def encode_bits(bits: Any) -> np.ndarray: + """Integer states ``sum_j bit_j 2^j`` of a ``(T, k)`` 0/1 array, ``1 <= k <= 30``.""" + b = np.asarray(bits) + 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)): + raise ValueError('bits must be a 2-D 0/1 array with 1 to 30 columns') + return (b.astype(np.int64) << np.arange(b.shape[1], dtype=np.int64)).sum(axis=1) + + +def decode_states(states: Any, n_bits: int) -> np.ndarray: + """Inverse of :func:`encode_bits`: a ``(T, n_bits)`` int8 array of bits.""" + k = _check_int('n_bits', n_bits, 1, 30) + s = _state_sequence(states, 2 ** k, min_len=1) + return ((s[:, None] >> np.arange(k, dtype=np.int64)) & 1).astype(np.int8) + + +# ====================================================================== coarse-graining +def _labels(labels: Any, n: int) -> tuple[np.ndarray, int]: + lab = _int_vector('labels', labels) + if lab.size != n or lab.min() < 0: + raise ValueError(f'labels must hold one non-negative macro label per micro state ({n})') + m = int(lab.max()) + 1 + if np.unique(lab).size != m: + raise ValueError('labels must use every macro state 0..m-1') + return lab, m + + +def coarse_grain_tpm(tpm: Any, labels: Any) -> np.ndarray: + """Macro TPM of a partition (Hoel et al., 2013): macro state ``A`` is entered by intervening uniformly on its + micro states, ``T_M[A, B] = (1/|A|) sum_{i in A} sum_{j in B} T[i, j]``.""" + T = as_tpm(tpm) + lab, m = _labels(labels, T.shape[0]) + Q = np.bincount((lab[:, None] * m + lab[None, :]).ravel(), weights=T.ravel(), minlength=m * m).reshape(m, m) + return Q / np.bincount(lab, minlength=m)[:, None] + + +def set_partitions(n: int) -> np.ndarray: + """Every set partition of ``n`` items (``1 <= n <= 10``) as restricted-growth label rows, shape ``(B_n, n)`` + (Bell number ``B_n``; 115975 rows for ``n = 10``).""" + n = _check_int('n', n, 1, _MAX_SEARCH_STATES) + rgs = np.zeros((1, 1), dtype=np.int64) + mx = np.zeros(1, dtype=np.int64) + for _ in range(1, n): + reps = mx + 2 # the next label is 0 .. max + 1 + start = np.repeat(np.cumsum(reps) - reps, reps) + vals = np.arange(int(reps.sum()), dtype=np.int64) - start + rgs = np.column_stack([np.repeat(rgs, reps, axis=0), vals]) + mx = np.maximum(np.repeat(mx, reps), vals) + return rgs + + +def unit_sum_labels(groups: Any) -> tuple[np.ndarray, int]: + """Macro labels of the ``2^u`` binary micro states when units are grouped by ``groups`` (one group label per + unit, every group ``0..G-1`` used) and each group's macro variable is its number of active units. Returns + ``(labels, m)`` with ``m = prod_g (|g| + 1)`` (mixed-radix encoding of the group counts).""" + g = _int_vector('groups', groups) + if not 1 <= g.size <= 12 or g.min() < 0 or np.unique(g).size != int(g.max()) + 1: + raise ValueError('groups must give 1 to 12 units a group label, using every group 0..G-1') + u, G = g.size, int(g.max()) + 1 + sizes = np.bincount(g, minlength=G) + bits = (np.arange(2 ** u, dtype=np.int64)[:, None] >> np.arange(u, dtype=np.int64)) & 1 + member = np.zeros((u, G), dtype=np.int64) + member[np.arange(u), g] = 1 + radix = np.cumprod(np.r_[1, sizes[:-1] + 1]).astype(np.int64) + return (bits @ member) @ radix, int(np.prod(sizes + 1)) + + +def unit_sum_candidates(n_units: int) -> dict[str, Any]: + """All partitions of ``n_units`` binary units (2..6) except all-singletons (the micro description), each + with its count-per-group macro labels. Keys ``groups (K, u)``, ``labels (K, 2^u)``, ``m (K,)``.""" + u = _check_int('n_units', n_units, 2, _MAX_OBSERVER_UNITS) + parts = set_partitions(u) + parts = parts[parts.max(axis=1) < u - 1] + labs, ms = zip(*(unit_sum_labels(p) for p in parts)) + return {'groups': parts, 'labels': np.stack(labs), 'm': np.asarray(ms, dtype=np.int64)} + + +def state_partition_candidates(n: int) -> dict[str, Any]: + """All proper partitions (``2 <= m < n`` macro states) of ``3 <= n <= 10`` micro states.""" + n = _check_int('n', n, 3, _MAX_SEARCH_STATES) + parts = set_partitions(n) + m = parts.max(axis=1) + 1 + keep = (m >= 2) & (m < n) + return {'labels': parts[keep], 'm': m[keep]} + + +class _Candidates: + """A chunk of ``K`` coarse-grainings of ``n`` micro states. The macro cells of candidate ``k`` form a compact + ``m_k x m_k`` block; a sparse 0/1 matrix maps the ``n^2`` micro TPM entries onto all blocks at once.""" + + def __init__(self, labels: np.ndarray, m: np.ndarray) -> None: + from scipy.sparse import csr_matrix + K, n = labels.shape + m = m.astype(np.int64) + self.labels, self.K, self.n, self.m = labels, K, n, m.astype(np.float64) + sq = m * m + off_cells = np.r_[0, np.cumsum(sq)[:-1]].astype(np.int64) + off_cols = np.r_[0, np.cumsum(m)[:-1]].astype(np.int64) + n_cells, n_cols = int(sq.sum()), int(m.sum()) + cell = off_cells[:, None, None] + labels[:, :, None] * m[:, None, None] + labels[:, None, :] + # 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 + sizes = np.bincount((off_cols[:, None] + labels).ravel(), minlength=n_cols).astype(np.float64) + inv_size = 1.0 / sizes[off_cols[:, None] + labels] # every macro state is non-empty + self.S = csr_matrix((np.repeat(inv_size.ravel(), n), + (cell.ravel(), np.tile(np.arange(n * n, dtype=np.int64), K))), shape=(n_cells, n * n)) + k_cell = np.repeat(np.arange(K, dtype=np.int64), sq) + m_cell = m[k_cell] + cell_col = off_cols[k_cell] + (np.arange(n_cells, dtype=np.int64) - off_cells[k_cell]) % m_cell + # column means of every macro TPM (its effect distribution under uniform macro interventions) + self.C = csr_matrix((1.0 / m_cell.astype(np.float64), (cell_col, np.arange(n_cells, dtype=np.int64))), + shape=(n_cols, n_cells)) + self.cell_starts, self.col_starts = off_cells, off_cols + + def macro_ei(self, T: np.ndarray) -> np.ndarray: + """``EI_k = H(mean row) - mean_A H(row A)`` (bits) of every candidate's macro TPM.""" + r = self.S @ T.ravel() # macro TPM entries, block by block + rlogr = np.add.reduceat(r * np.log2(np.where(r > 0.0, r, 1.0)), self.cell_starts) + col = self.C @ r # mean rows + h_mean = -np.add.reduceat(col * np.log2(np.where(col > 0.0, col, 1.0)), self.col_starts) + return np.maximum(h_mean + rlogr / self.m, 0.0) + + +def _candidate_chunks(labels_batch: Any, n: int, m: Any = None) -> list[_Candidates]: + L = np.asarray(labels_batch) + if L.ndim != 2 or L.shape[0] < 1 or L.shape[1] != n or L.dtype.kind not in 'iu': + raise ValueError(f'labels_batch must be a non-empty 2-D integer array with {n} columns') + L = L.astype(np.int64) + if L.min() < 0: + raise ValueError('labels must be non-negative') + mk = L.max(axis=1) + 1 + if m is None: + used = np.zeros((L.shape[0], int(mk.max())), dtype=bool) + used[np.repeat(np.arange(L.shape[0]), n), L.ravel()] = True + if not np.array_equal(used.sum(axis=1), mk): + raise ValueError('every labels row must use each macro state 0..m-1') + step = max(1, _CHUNK_CELLS // (n * n)) + return [_Candidates(L[i:i + step], mk[i:i + step]) for i in range(0, L.shape[0], step)] + + +def _batch_ei(T: np.ndarray, chunks: Sequence[_Candidates]) -> np.ndarray: + return np.concatenate([c.macro_ei(T) for c in chunks]) + + +def macro_ei_batch(tpm: Any, labels_batch: Any) -> np.ndarray: + """EI of the macro TPM of every coarse-graining in ``labels_batch`` (``(K, n)``, one partition per row).""" + T = as_tpm(tpm) + return _batch_ei(T, _candidate_chunks(labels_batch, T.shape[0])) + + +def best_state_partition(tpm: Any) -> dict[str, Any]: + """Exhaustive search over every proper partition of a ``3 <= n <= 10`` state TPM for the macro TPM with the + largest EI (ties: the first partition in restricted-growth order).""" + T = as_tpm(tpm) + cand = state_partition_candidates(T.shape[0]) + eis = _batch_ei(T, _candidate_chunks(cand['labels'], T.shape[0], cand['m'])) + k = int(np.argmax(eis)) + micro = _ei(T) + return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': float(eis[k]) - micro, + 'labels': cand['labels'][k].copy(), 'macro_states': int(cand['m'][k]), + 'partitions_evaluated': int(eis.size), 'macro_tpm': coarse_grain_tpm(T, cand['labels'][k])} + + +def best_unit_coarse_graining(tpm: Any, n_units: int) -> dict[str, Any]: + """Best count-per-group coarse-graining of a TPM over ``2^n_units`` binary micro states (``2 <= n_units <= 6``).""" + T = as_tpm(tpm) + cand = unit_sum_candidates(n_units) + if T.shape[0] != 2 ** int(n_units): + raise ValueError('tpm must have 2^n_units states') + eis = _batch_ei(T, _candidate_chunks(cand['labels'], T.shape[0], cand['m'])) + k = int(np.argmax(eis)) + micro = _ei(T) + return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': float(eis[k]) - micro, + 'groups': _groups(cand['groups'][k], np.arange(int(n_units))), 'labels': cand['labels'][k].copy(), + 'macro_states': int(cand['m'][k]), 'partitions_evaluated': int(eis.size)} + + +def _groups(rgs: np.ndarray, units: np.ndarray) -> list[list[int]]: + return [[int(units[j]) for j in np.flatnonzero(rgs == g)] for g in range(int(rgs.max()) + 1)] + + +def causal_emergence(tpm: Any, labels: Any) -> dict[str, Any]: + """Micro and macro EI (with decompositions) of one coarse-graining and ``CE = EI_macro - EI_micro``.""" + T = as_tpm(tpm) + M = coarse_grain_tpm(T, labels) + micro, macro = _decomposition(T), _decomposition(M) + return {'micro': micro, 'macro': macro, 'ce': macro['ei'] - micro['ei'], 'macro_tpm': M} + + +# ====================================================================== null distribution +def _default_block(transitions: int) -> int: + return max(1, int(round(transitions ** (1.0 / 3.0)))) if transitions >= 8 else 1 + + +def _ce_of_pairs(cur: np.ndarray, nxt: np.ndarray, n: int, alpha: float, + chunks: Sequence[_Candidates]) -> tuple[float, np.ndarray, int]: + T = _smoothed(_counts(cur, nxt, n), alpha) + eis = _batch_ei(T, chunks) + return _ei(T), eis, int(np.argmax(eis)) + + +def _null_stats(ce: float, null: np.ndarray) -> dict[str, Any]: + mu = float(null.mean()) + sd = float(null.std(ddof=1)) if null.size > 1 else 0.0 + return {'null_mean': mu, 'null_sd': sd, 'excess': ce - mu, 'z': (ce - mu) / sd if sd > _EPS else None, + 'p': float((1 + int((null >= ce - 1e-12).sum())) / (1 + null.size))} + + +def successor_block_null(states: Any, n_states: int, labels_batch: Any, *, alpha: float = 1.0, draws: int = 99, + block: int | None = None, seed: int = 0) -> dict[str, Any]: + """CE of a state sequence (best of the coarse-grainings in ``labels_batch``) against a successor + block-permutation null. + + The TPM is estimated from the pairs ``(s_t, s_{t+1})`` with smoothing ``alpha``. In each of ``draws`` null + draws the successor sequence ``s_{1..T}`` is block-permuted (blocks of ``block`` steps keep their order, + default ``round(transitions^(1/3))``) against the unchanged ``s_{0..T-1}``: every state keeps its visit count + and the successor marginal is kept, but lag-1 dependence is broken. The best coarse-graining is searched again + per draw. Returns observed EI/CE, the best partition, the null CE values and ``z`` / one-sided ``p``.""" + n = _check_int('n_states', n_states, 2, _MAX_STATES) + s = _state_sequence(states, n, min_len=3) + chunks = _candidate_chunks(labels_batch, n) + alpha = _check_float('alpha', alpha, 0.0, 1e6) + draws = _check_int('draws', draws, 2, 100_000) + block = None if block is None else _check_int('block', block, 1, s.size - 1) + return _successor_block_null(s, n, chunks, alpha, draws, block, _check_int('seed', seed, 0, 2**31 - 1)) + + +def _successor_null_values(cur: np.ndarray, nxt: np.ndarray, n: int, chunks: Sequence[_Candidates], alpha: float, + draws: int, block: int, rng: np.random.Generator) -> np.ndarray: + """Null CE values with the successor sequence block-permuted against the current-state sequence.""" + out = np.empty(draws) + for b in range(draws): + m_b, e_b, k_b = _ce_of_pairs(cur, nxt[block_permutation(cur.size, block, rng)], n, alpha, chunks) + out[b] = float(e_b[k_b]) - m_b + return out + + +def _successor_block_null(s: np.ndarray, n: int, chunks: Sequence[_Candidates], alpha: float, draws: int, + block: int | None, seed: int) -> dict[str, Any]: + """:func:`successor_block_null` on validated inputs and pre-built candidate chunks.""" + cur, nxt = s[:-1], s[1:] + block = _default_block(cur.size) if block is None else int(block) + rng = np.random.default_rng(seed + _NULL_OFFSET) + micro, eis, k = _ce_of_pairs(cur, nxt, n, alpha, chunks) + ce = float(eis[k]) - micro + null = _successor_null_values(cur, nxt, n, chunks, alpha, draws, block, rng) + labels = np.concatenate([c.labels for c in chunks]) + return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': ce, 'best_index': k, 'labels': labels[k].copy(), + 'null_ce': null, 'draws': draws, 'block': block, 'alpha': alpha, 'transitions': int(cur.size), + **_null_stats(ce, null)} + + +def _indep_null_values(states: np.ndarray, n_units: int, chunks: Sequence[_Candidates], alpha: float, draws: int, + rng: np.random.Generator) -> np.ndarray: + """Null CE values with every unit's bit sequence circularly shifted by its own offset in ``[1, L - 1]``.""" + L = int(states.size) + bits = (states[:, None] >> np.arange(n_units, dtype=np.int64)) & 1 + weights = np.left_shift(1, np.arange(n_units, dtype=np.int64)) + rows, cols = np.arange(L, dtype=np.int64)[:, None], np.arange(n_units, dtype=np.int64)[None, :] + out = np.empty(draws) + for b in range(draws): + shifted = bits[(rows - rng.integers(1, L, n_units)[None, :]) % L, cols] @ weights # np.roll per unit + micro, eis, k = _ce_of_pairs(shifted[:-1], shifted[1:], 2 ** n_units, alpha, chunks) + out[b] = float(eis[k]) - micro + return out + + +def independent_units_null(states: Any, n_units: int, labels_batch: Any, *, alpha: float = 1.0, draws: int = 99, + seed: int = 0) -> dict[str, Any]: + """CE of a binary-unit state sequence against an independent-units null. + + ``states`` encode ``n_units`` binary units (bit ``j`` of a state is unit ``j``, see :func:`encode_bits`). In + each of ``draws`` null draws every unit's bit sequence is circularly shifted by its own random offset in + ``[1, L - 1]``: each unit keeps its occupancy and autocorrelation (up to one wrap-around transition) while the + units become independent of each other. The best coarse-graining in ``labels_batch`` (``(K, 2^n_units)``) is + searched again per draw. A large ``z`` says the coarse-grained description gains from coordination between + units beyond what the units' own dynamics, and the estimator's finite-sample behaviour on them, give.""" + u = _check_int('n_units', n_units, 2, 11) + n = 2 ** u + s = _state_sequence(states, n, min_len=3) + chunks = _candidate_chunks(labels_batch, n) + alpha = _check_float('alpha', alpha, 0.0, 1e6) + draws = _check_int('draws', draws, 2, 100_000) + rng = np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _INDEP_OFFSET) + micro, eis, k = _ce_of_pairs(s[:-1], s[1:], n, alpha, chunks) + ce = float(eis[k]) - micro + null = _indep_null_values(s, u, chunks, alpha, draws, rng) + labels = np.concatenate([c.labels for c in chunks]) + return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': ce, 'best_index': k, 'labels': labels[k].copy(), + 'null_ce': null, 'draws': draws, 'alpha': alpha, 'transitions': int(s.size - 1), **_null_stats(ce, null)} + + +def _ce_and_nulls(seq: np.ndarray, n_units: int, chunks: Sequence[_Candidates], alpha: float, draws: int, + block: int | None, rng_successor: np.random.Generator, + rng_independent: np.random.Generator) -> dict[str, Any]: + """Observed CE of a binary-unit state sequence plus both null summaries (shared by the observer and the lab).""" + n = 2 ** n_units + cur, nxt = seq[:-1], seq[1:] + micro, eis, k = _ce_of_pairs(cur, nxt, n, alpha, chunks) + ce = float(eis[k]) - micro + blk = min(_default_block(cur.size) if block is None else int(block), int(cur.size)) + succ = _successor_null_values(cur, nxt, n, chunks, alpha, draws, blk, rng_successor) + indep = _indep_null_values(seq, n_units, chunks, alpha, draws, rng_independent) + return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'best_index': k, 'ce': ce, 'block': blk, + 'successor': _null_stats(ce, succ), 'independent': _null_stats(ce, indep)} + + +# ====================================================================== published toy systems +def hoel2017_examples() -> dict[str, np.ndarray]: + """The Markov chains printed in Hoel (2017): ``M1``, ``M2``, ``M3`` (EI 2, 1, 0 bits), the 8-state chain ``Sm`` + (seven states mix uniformly among themselves, the eighth is absorbing), its variant with unequal rows, and the + 4-state channel ``X -> Y`` of the channel-capacity section (three states mix uniformly, the fourth is + absorbing; printed EI 0.81 bits at the micro scale and 1 bit for the macro code {x1, x2, x3} -> 0, x4 -> 1).""" + third, F = 1.0 / 3.0, Fraction + chain = np.zeros((8, 8)) + chain[:7, :7] = 1.0 / 7.0 + chain[7, 7] = 1.0 + varied = [[F(1, 5)] * 5 + [0, 0, 0], + [F(1, 7), F(3, 7), F(1, 7), 0, F(1, 7), 0, F(1, 7), 0], + [0] + [F(1, 6)] * 6 + [0], + [F(1, 7), 0, F(1, 7), F(1, 7), F(1, 7), F(1, 7), F(2, 7), 0], + [F(1, 9), F(2, 9), F(2, 9), F(1, 9), 0, F(2, 9), F(1, 9), 0], + [F(1, 7)] * 7 + [0], + [F(1, 6), F(1, 6), 0, F(1, 6), F(1, 6), F(1, 6), F(1, 6), 0], + [0] * 7 + [1]] + return {'M1': np.array([[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]], dtype=np.float64), + 'M2': np.array([[third, third, third, 0], [third, third, third, 0], [0, 0, 0, 1], [0, 0, 0, 1]]), + 'M3': np.full((4, 4), 0.25), 'chain8': chain, + 'chain8_varied': np.array([[float(x) for x in row] for row in varied]), + 'channel4': np.array([[third, third, third, 0], [third, third, third, 0], [third, third, third, 0], + [0, 0, 0, 1]])} + + +def and_gate_network(pairs: int = 3) -> tuple[np.ndarray, np.ndarray]: + """Deterministic ring of ``2 * pairs`` AND gates in the spirit of Hoel et al. (2013, Fig. 4): both elements of + pair ``k`` compute AND of the two elements of pair ``k + 1`` (mod ``pairs``). Bit ``2k`` and ``2k + 1`` of a + state belong to pair ``k``. Returns the micro TPM and the macro labels that map each pair to one element that + is on only when both of its micro elements are on (the macro elements then copy each other around the ring).""" + p = _check_int('pairs', pairs, 1, 5) + u = 2 * p + states = np.arange(2 ** u, dtype=np.int64) + bits = (states[:, None] >> np.arange(u, dtype=np.int64)) & 1 + pair_and = bits[:, 0::2] & bits[:, 1::2] + nxt_bits = np.repeat(np.roll(pair_and, -1, axis=1), 2, axis=1) + nxt = (nxt_bits << np.arange(u, dtype=np.int64)).sum(axis=1) + T = np.zeros((2 ** u, 2 ** u)) + T[states, nxt] = 1.0 + return T, (pair_and << np.arange(p, dtype=np.int64)).sum(axis=1) + + +def pair_count_copy_tpm(pairs: int = 3, noise: float = 0.1) -> np.ndarray: + """Exact micro TPM of a ring of binary-unit pairs whose active-unit *counts* copy each other. + + Pair ``k`` (units ``2k`` and ``2k + 1``) takes the count of pair ``k + 1`` (mod ``pairs``) with probability + ``1 - noise`` and a uniformly random count in {0, 1, 2} otherwise; count 1 is realised as either unit alone + with probability 1/2. The pair counts follow near-deterministic macro dynamics over a degenerate, noisy micro + realisation, so the count-per-pair coarse-graining has higher EI than the micro TPM. This is a constructed + known-answer system in the spirit of Hoel et al. (2013), not an example printed there.""" + p = _check_int('pairs', pairs, 1, 5) + eps = _check_float('noise', noise, 0.0, 1.0) + u, n = 2 * p, 4 ** p + bits = decode_states(np.arange(n), u).astype(np.int64) + counts = bits[:, 0::2] + bits[:, 1::2] # (n, pairs) counts of the current state + p_count = (1.0 - eps) * (np.roll(counts, -1, axis=1)[:, :, None] == np.arange(3)) + eps / 3.0 + # P(pair micro state | count) for pair micro index b0 + 2 b1 = 00, 10, 01, 11 + 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]]) + T = np.ones((n, n)) + for k in range(p): + T *= p_count[:, k, :] @ realise[bits[:, 2 * k] + 2 * bits[:, 2 * k + 1]].T + return T + + +def noisy_permutation_tpm(n: int, noise: float, *, seed: int = 0) -> np.ndarray: + """``(1 - noise) P + noise / n`` for a seeded random ``n x n`` permutation matrix ``P``. + + Every row is a permutation of every other row and all column sums are 1, so the TPM is a weakly symmetric + channel. Uniform inputs achieve its capacity, and since a coarse-graining only changes the input distribution + (uniform over macro states) and post-processes inputs and outputs, no coarse-graining has a larger EI: the + exact CE of every partition is <= 0 (Hoel 2017: no causal emergence without asymmetry).""" + n = _check_int('n', n, 2, _MAX_STATES) + eps = _check_float('noise', noise, 0.0, 1.0) + P = np.eye(n)[np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _PERM8_OFFSET).permutation(n)] + return (1.0 - eps) * P + eps / n + + +def independent_flip_tpm(n_units: int, keep: float) -> np.ndarray: + """Exact micro TPM of ``n_units`` independent binary units that each keep their state with probability + ``keep`` and flip otherwise (bit ``j`` of a state is unit ``j``).""" + u = _check_int('n_units', n_units, 1, 11) + q = _check_float('keep', keep, 0.0, 1.0) + bits = decode_states(np.arange(2 ** u), u) + same = (bits[:, None, :] == bits[None, :, :]).sum(axis=2) + return q ** same * (1.0 - q) ** (u - same) + + +def _sample_pair_count_copy(pairs: int, noise: float, steps: int, rng: np.random.Generator) -> np.ndarray: + c = rng.integers(0, 3, pairs) + out = np.zeros((steps, 2 * pairs), dtype=np.int64) + for t in range(steps): + c = np.where(rng.random(pairs) < noise, rng.integers(0, 3, pairs), np.roll(c, -1)) + second = rng.integers(0, 2, pairs) == 1 # which unit realises a count of 1 + out[t, 0::2] = (c == 2) | ((c == 1) & ~second) + out[t, 1::2] = (c == 2) | ((c == 1) & second) + return out + + +def _sample_independent_flips(n_units: int, keep: float, steps: int, rng: np.random.Generator) -> np.ndarray: + start = rng.integers(0, 2, n_units) + return (start[None, :] + np.cumsum(rng.random((steps, n_units)) >= keep, axis=0)) % 2 + + +PRINTED_VALUES: dict[str, float] = { + # Hoel (2017), Entropy 19:188, as printed in its preprint arXiv:1612.09592v1 (usually 2 decimals) + 'hoel2017_M1_ei': 2.0, 'hoel2017_M2_ei': 1.0, 'hoel2017_M3_ei': 0.0, + 'hoel2017_chain8_ei_micro': 0.55, 'hoel2017_chain8_effectiveness': 0.18, 'hoel2017_chain8_ei_macro': 1.0, + 'hoel2017_chain8_ce': 0.45, 'hoel2017_chain8_varied_ei_micro': 0.81, 'hoel2017_chain8_varied_ei_macro': 1.0, + 'hoel2017_and_ei_micro': 2.43, 'hoel2017_and_effectiveness': 0.41, 'hoel2017_and_degeneracy': 0.59, + 'hoel2017_and_ei_macro': 3.0, 'hoel2017_channel4_ei_micro': 0.81, 'hoel2017_channel4_conditional_entropy': 1.19, + 'hoel2017_channel4_ei_macro': 1.0, + # Hoel, Albantakis & Tononi (2013), PNAS 110:19790, Fig. 4 (six AND gates -> three COPY gates) + 'hoel2013_and_ei_micro': 2.43, 'hoel2013_and_effectiveness': 0.4, 'hoel2013_and_determinism': 1.0, + 'hoel2013_and_degeneracy': 0.6, 'hoel2013_and_ei_macro': 3.0, 'hoel2013_and_ce': 0.57, +} + + +# ====================================================================== live observer +class CausalEmergenceObserver: + """Read-only live observer: EI and causal emergence of a few discretised units. + + * ``u = min(units, n_units)`` units (``2 <= u <= 6``; a seeded, sorted subset when ``n_units > units``) are + binarised online: each new value is compared with the median of that unit's last ``history`` raw values + (including the new one), so a unit is on when it is above its running median (a value tied with the median + is on when more of the window lies below the median than above it, which keeps discrete 0/1 units intact). + The ``2^u`` micro states of the last ``history`` observations are kept in a ring buffer (bounded transition + counts). With ``alpha = 1`` every row of the ``2^u``-state TPM receives ``2^u`` pseudo-counts, so until there + are many transitions per micro state (``transitions_per_micro_state``) EI estimates are shrunk far below the + exact values; the nulls below, not the raw ``ce``, carry the evidence. + * ``summary()`` estimates the micro TPM (smoothing ``alpha``; 1 = Laplace) from the buffered transitions and + reports micro EI with determinism/degeneracy, the best count-per-group coarse-graining over every partition + of the units (the micro description excluded) and ``ce = ei_macro - ei_micro``. Once ``min_transitions`` + transitions exist (default ``min(32, history - 1)``) it adds two nulls of ``null_draws`` draws each, seeded + by ``(seed, observed steps)``: the successor block permutation (``null_ce_mean``, ``null_ce_sd``, + ``ce_excess``, ``ce_z``, ``ce_p``: is CE above what temporally independent data give?) and the + independent-units circular shift (``indep_ce_mean``, ``indep_ce_sd``, ``ce_excess_indep``, ``ce_z_indep``, + ``ce_p_indep``: is CE above what the same units give when they are made independent?). The smallest + attainable p is ``1 / (null_draws + 1)`` (0.05 at the default 19 draws). With few transitions per micro + state the successor null flags any temporal dependence (see the module docstring); read emergence claims + against the independent-units null and the lab's known-answer checks. + * Results are a pure function of the buffered state and are cached per observed step, so they do not depend + on how often ``summary()`` is called. Unit indices refer to positions in the observed vector. FrontierSpecV1 + parameters meant for other observers are accepted and ignored.""" + + module_id = MODULE_ID + schema = OBSERVER_STATE_SCHEMA + + def __init__(self, n_units: int, *, seed: int = 7, history: int = 256, units: int = 6, alpha: float = 1.0, + null_draws: int = 19, block: int | None = None, min_transitions: int | None = None, + **params: Any) -> None: + unknown = sorted(set(params) - _SPEC_OBSERVER_PARAMS) + if unknown: + raise ValueError(f'unknown CausalEmergenceObserver parameters: {unknown}') + self.n_units = _check_int('n_units', n_units, 2, 1_000_000) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + self.history = _check_int('history', history, 16, 8192) + self.units = _check_int('units', units, 2, _MAX_OBSERVER_UNITS) + self.alpha = _check_float('alpha', alpha, 0.0, 100.0) + self.null_draws = _check_int('null_draws', null_draws, 2, 999) + self.block = None if block is None else _check_int('block', block, 1, self.history) + self.min_transitions = (min(32, self.history - 1) if min_transitions is None + else _check_int('min_transitions', min_transitions, 8, self.history - 1)) + m = self.m = min(self.units, self.n_units) + if m == self.n_units: + sample = np.arange(m, dtype=np.int64) + else: + sample = np.sort(np.random.default_rng(self.seed + _OBS_UNITS_OFFSET).choice(self.n_units, m, replace=False)) + self._units = sample.astype(np.int64) + self.n_states = 2 ** m + cand = unit_sum_candidates(m) + self._groups = cand['groups'] + self._chunks = _candidate_chunks(cand['labels'], self.n_states, cand['m']) + self._bit_weights = np.left_shift(1, np.arange(m, dtype=np.int64)) + self.reset() + + @classmethod + def from_spec(cls, n_units: int, spec: Any, **params: Any) -> 'CausalEmergenceObserver': + """Observer sized from a :class:`~synapse.frontier.spec.FrontierSpecV1` (``seed``, ``history``); ``params`` + are the observer's own keyword parameters (``units``, ``alpha``, ...).""" + if not isinstance(spec, FrontierSpecV1): + raise ValueError('spec must be a FrontierSpecV1') + return cls(n_units, seed=int(spec.seed), history=int(spec.history), **params) + + def config(self) -> dict[str, Any]: + return {'n_units': self.n_units, 'seed': self.seed, 'history': self.history, 'units': self.units, + 'alpha': self.alpha, 'null_draws': self.null_draws, 'block': self.block, + 'min_transitions': self.min_transitions} + + def reset(self) -> None: + self._raw = np.zeros((self.history, self.m)) + self._states = np.zeros(self.history, dtype=np.int64) + self._pos = 0 + self._filled = 0 + self._steps = 0 + self._cache: tuple[int, dict[str, Any]] | None = None + + @property + def observed_steps(self) -> int: + return int(self._steps) + + @property + def units_observed(self) -> np.ndarray: + return self._units.copy() + + def _encode(self, raw: np.ndarray, buffer: np.ndarray) -> int: + return int((_above_median(raw, buffer).astype(np.int64) * self._bit_weights).sum()) + + def observe(self, x: np.ndarray) -> None: + try: + v = np.asarray(x, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}') from exc + if v.shape != (self.n_units,) or not np.all(np.isfinite(v)): + raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}') + raw = v[self._units] # fancy indexing copies; the input is never written + p = self._pos + self._raw[p] = raw + self._filled = min(self.history, self._filled + 1) + self._states[p] = self._encode(raw, self._raw[:self._filled]) + self._pos = (p + 1) % self.history + self._steps += 1 + self._cache = None + + def _sequence(self) -> np.ndarray: + if self._filled < self.history: + return self._states[:self._filled].copy() + return np.concatenate([self._states[self._pos:], self._states[:self._pos]]) + + def _compute(self) -> dict[str, Any]: + seq = self._sequence() + cur, nxt = seq[:-1], seq[1:] + n = self.n_states + micro_T = _smoothed(_counts(cur, nxt, n), self.alpha) + micro = _decomposition(micro_T) + eis = _batch_ei(micro_T, self._chunks) + k = int(np.argmax(eis)) + labels = np.concatenate([c.labels for c in self._chunks])[k] + macro = _decomposition(coarse_grain_tpm(micro_T, labels)) + ce = float(eis[k]) - micro['ei'] + out: dict[str, Any] = { + 'visited_states': int(np.unique(cur).size), 'ei_micro': micro['ei'], + 'determinism_micro': micro['determinism'], 'degeneracy_micro': micro['degeneracy'], + 'effectiveness_micro': micro['effectiveness'], 'ei_macro': float(eis[k]), + 'determinism_macro': macro['determinism'], 'degeneracy_macro': macro['degeneracy'], + 'macro_partition': _groups(self._groups[k], self._units), 'macro_states': int(macro['states']), + 'ce': ce, 'null_ready': False, 'null_block': None, 'null_ce_mean': None, 'null_ce_sd': None, + 'ce_excess': None, 'ce_z': None, 'ce_p': None, 'indep_ce_mean': None, 'indep_ce_sd': None, + 'ce_excess_indep': None, 'ce_z_indep': None, 'ce_p_indep': None} + if cur.size >= self.min_transitions: + res = _ce_and_nulls(seq, self.m, self._chunks, self.alpha, self.null_draws, self.block, + np.random.default_rng([self.seed + _OBS_NULL_OFFSET, self._steps]), + np.random.default_rng([self.seed + _OBS_INDEP_OFFSET, self._steps])) + st, si = res['successor'], res['independent'] + out.update(null_ready=True, null_block=int(res['block']), null_ce_mean=st['null_mean'], + null_ce_sd=st['null_sd'], ce_excess=st['excess'], ce_z=st['z'], ce_p=st['p'], + indep_ce_mean=si['null_mean'], indep_ce_sd=si['null_sd'], ce_excess_indep=si['excess'], + ce_z_indep=si['z'], ce_p_indep=si['p']) + return out + + _METRIC_KEYS = ('visited_states', 'ei_micro', 'determinism_micro', 'degeneracy_micro', 'effectiveness_micro', + 'ei_macro', 'determinism_macro', 'degeneracy_macro', 'macro_partition', 'macro_states', 'ce', + 'null_ready', 'null_block', 'null_ce_mean', 'null_ce_sd', 'ce_excess', 'ce_z', 'ce_p', + 'indep_ce_mean', 'indep_ce_sd', 'ce_excess_indep', 'ce_z_indep', 'ce_p_indep') + + def summary(self) -> dict[str, Any]: + """JSON-safe metrics (``None`` until the first transition; null fields once ``min_transitions`` exist).""" + transitions = max(0, self._filled - 1) + out: dict[str, Any] = {'module': MODULE_ID, 'evidence_tier': EVIDENCE_TIER, 'n_units': self.n_units, + 'analysed_units': int(self.m), 'unit_sample': self._units.tolist(), + 'history': self.history, 'micro_states': int(self.n_states), 'alpha': self.alpha, + 'null_draws': self.null_draws, 'min_transitions': self.min_transitions, + 'observed_steps': int(self._steps), 'buffered': int(self._filled), + 'transitions': int(transitions), + 'transitions_per_micro_state': float(transitions / self.n_states)} + if transitions == 0: + out.update({k: None for k in self._METRIC_KEYS}) + out['null_ready'] = False + return out + if self._cache is None or self._cache[0] != self._steps: + self._cache = (self._steps, self._compute()) + metrics = self._cache[1] + out.update({k: ([list(g) for g in v] if k == 'macro_partition' else v) for k, v in metrics.items()}) + return out + + def export_state(self) -> dict[str, Any]: + return {'module': MODULE_ID, 'schema': self.schema, 'config': self.config(), 'units': self._units.tolist(), + 'raw': self._raw.tolist(), 'states': self._states.tolist(), 'pos': int(self._pos), + 'filled': int(self._filled), 'steps': int(self._steps)} + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate the whole state first (configuration, shapes, counters and, where the raw values are still + buffered, that every stored state is the median-binarisation of its raw values); then replace.""" + if not isinstance(state, Mapping) or state.get('module') != MODULE_ID or state.get('schema') != self.schema: + raise ValueError('state does not belong to a CausalEmergenceObserver') + try: + cfg = dict(state['config']) + units = state['units'] + raw = np.array(state['raw'], dtype=np.float64) + st = np.array(state['states']) + pos, filled, steps = state['pos'], state['filled'], state['steps'] + except (KeyError, TypeError, ValueError) as exc: + raise ValueError('CausalEmergenceObserver state is incomplete or malformed') from exc + if cfg != self.config() or units != self._units.tolist(): + raise ValueError('CausalEmergenceObserver state was made with a different configuration') + H = self.history + if raw.shape != (H, self.m) or not np.all(np.isfinite(raw)): + raise ValueError('raw buffer has the wrong shape or non-finite values') + 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): + raise ValueError('state buffer must hold one micro state in [0, 2^units) per history row') + if not all(type(v) is int for v in (pos, filled, steps)) or not (0 <= pos < H and 0 <= filled <= H + and filled == min(steps, H)): + raise ValueError('CausalEmergenceObserver counters are inconsistent') + if pos != steps % H: + raise ValueError('CausalEmergenceObserver ring-buffer position is inconsistent') + st = st.astype(np.int64) + if filled < H and (np.any(raw[filled:] != 0.0) or np.any(st[filled:] != 0)): + raise ValueError('buffers hold values beyond the observed steps') + if steps <= H: # every raw value is still buffered: check them all + ok = all(st[t] == self._encode(raw[t], raw[:t + 1]) for t in range(filled)) + else: # only the newest state's median is still known + last = (pos - 1) % H + ok = st[last] == self._encode(raw[last], raw) + if not ok: + raise ValueError('stored states are not the median-binarisation of the raw buffer') + self._raw, self._states = raw.copy(), st.copy() + self._pos, self._filled, self._steps = pos, filled, steps + self._cache = None + + +# ====================================================================== lab experiment +_MECH_DYNAMICS = ('sparse_code', 'synaptic_delays', 'membrane_dynamics') +_PAIR_GROUPS = [[0, 1], [2, 3], [4, 5]] +_SEVEN_PLUS_ONE = [0] * 7 + [1] +_DEFAULTS: dict[str, Any] = { + 'sizes': (2, 4, 8, 16, 32), 'alpha': 1.0, 'estimation_samples': 16_000, 'estimation_tolerance': 0.05, + 'null_steps': 512, 'null_draws': 199, 'null_replicates': 10, 'emergence_noise': 0.1, 'permutation_noise': 0.3, + 'unit_steps': 1024, 'unit_draws': 49, 'unit_replicates': 4, 'pair_copy_noise': 0.1, 'independent_keep': 0.9, + # 4 units (16 micro states) for the NEUROWEAVE report: ~11 (quick) / ~34 (default) transitions per micro + # state, against ~3 / ~9 with the observer's default of 6 units (64 states) + 'units': 4, 'topology': 'clustered', 'neurons': 32, 'nw_steps': 600, 'nw_burn_in': 50, 'nw_null_draws': 49, + 'mechanism_sets': {'baseline': (), 'dynamics': _MECH_DYNAMICS}, +} +_QUICK: dict[str, Any] = {'estimation_samples': 4000, 'null_steps': 384, 'null_draws': 39, 'null_replicates': 2, + 'unit_steps': 512, 'unit_draws': 19, 'unit_replicates': 1, 'neurons': 24, 'nw_steps': 200, + 'nw_burn_in': 24, 'nw_null_draws': 19} + + +def _validate_config(cfg: dict[str, Any]) -> dict[str, Any]: + from ..neuroweave.spec import MECHANISM_IDS, TOPOLOGIES + c = dict(cfg) + try: + sizes = tuple(c['sizes']) + except TypeError as exc: + raise ValueError('sizes must be a sequence of ints') from exc + if not sizes or len(set(sizes)) != len(sizes): + raise ValueError('sizes must be non-empty and distinct') + c['sizes'] = [_check_int('size', s, 2, 512) for s in sizes] + c['alpha'] = _check_float('alpha', c['alpha'], 0.0, 100.0) + c['estimation_samples'] = _check_int('estimation_samples', c['estimation_samples'], 200, 10_000_000) + c['estimation_tolerance'] = _check_float('estimation_tolerance', c['estimation_tolerance'], 1e-4, 1.0) + c['null_steps'] = _check_int('null_steps', c['null_steps'], 64, 1_000_000) + c['null_draws'] = _check_int('null_draws', c['null_draws'], 19, 100_000) + c['null_replicates'] = _check_int('null_replicates', c['null_replicates'], 1, 10_000) + c['emergence_noise'] = _check_float('emergence_noise', c['emergence_noise'], 0.01, 0.3) + c['permutation_noise'] = _check_float('permutation_noise', c['permutation_noise'], 0.01, 0.5) + c['unit_steps'] = _check_int('unit_steps', c['unit_steps'], 64, 1_000_000) + c['unit_draws'] = _check_int('unit_draws', c['unit_draws'], 19, 100_000) + c['unit_replicates'] = _check_int('unit_replicates', c['unit_replicates'], 1, 10_000) + c['pair_copy_noise'] = _check_float('pair_copy_noise', c['pair_copy_noise'], 0.0, 0.5) + c['independent_keep'] = _check_float('independent_keep', c['independent_keep'], 0.6, 0.99) + c['units'] = _check_int('units', c['units'], 2, _MAX_OBSERVER_UNITS) + if c['topology'] not in TOPOLOGIES: + raise ValueError(f'topology must be one of {TOPOLOGIES}') + c['neurons'] = _check_int('neurons', c['neurons'], 8, 512) + c['nw_steps'] = _check_int('nw_steps', c['nw_steps'], 64, 100_000) + c['nw_burn_in'] = _check_int('nw_burn_in', c['nw_burn_in'], 0, c['nw_steps'] - 48) + c['nw_null_draws'] = _check_int('nw_null_draws', c['nw_null_draws'], 2, 999) + sets = c['mechanism_sets'] + if not isinstance(sets, Mapping) or not 1 <= len(sets) <= 8: + raise ValueError('mechanism_sets must map 1 to 8 names to NEUROWEAVE mechanism tuples') + clean: dict[str, list[str]] = {} + for name, mechs in sets.items(): + if not isinstance(name, str) or not name or isinstance(mechs, str): + raise ValueError('mechanism_sets must map names to sequences of mechanism ids') + try: + mechs = list(mechs) + except TypeError as exc: + raise ValueError('mechanism_sets must map names to sequences of mechanism ids') from exc + if any(m not in MECHANISM_IDS for m in mechs) or len(set(mechs)) != len(mechs): + raise ValueError('mechanism_sets values must be distinct NEUROWEAVE mechanism ids') + clean[name] = mechs + c['mechanism_sets'] = clean + return c + + +def _close(a: float, b: float, tol: float) -> bool: + return bool(abs(float(a) - float(b)) <= tol) + + +def _exact_checks(c: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, bool]]: + """Seed-independent checks on exactly known TPMs (no sampling).""" + rng = np.random.default_rng(_PERM_OFFSET) + sizes = [] + for n in c['sizes']: + P = np.eye(n)[rng.permutation(n)] + d_id, d_perm, d_uni = ei_decomposition(np.eye(n)), ei_decomposition(P), ei_decomposition(np.full((n, n), 1.0 / n)) + sizes.append({'n': n, 'log2_n': math.log2(n), 'ei_identity': d_id['ei'], 'ei_permutation': d_perm['ei'], + 'ei_uniform': d_uni['ei'], 'identity_determinism': d_id['determinism'], + 'identity_degeneracy': d_id['degeneracy'], 'uniform_determinism': d_uni['determinism'], + 'uniform_degeneracy': d_uni['degeneracy']}) + ex = hoel2017_examples() + dec = {k: ei_decomposition(v) for k, v in ex.items()} + chain_exact = 3.0 - 7.0 / 8.0 * math.log2(7.0) + search = {k: best_state_partition(ex[k]) for k in ('chain8', 'chain8_varied')} + channel = best_state_partition(ex['channel4']) + T_and, lab_and = and_gate_network(3) + ce_and = causal_emergence(T_and, lab_and) + p = PRINTED_VALUES + hoel = { + 'M_ei': {k: dec[k]['ei'] for k in ('M1', 'M2', 'M3')}, + 'chain8': {'ei_micro': dec['chain8']['ei'], 'ei_micro_closed_form': chain_exact, + 'effectiveness': dec['chain8']['effectiveness'], 'ei_macro': search['chain8']['ei_macro'], + 'ce': search['chain8']['ce'], 'best_labels': search['chain8']['labels'], + 'partitions_evaluated': search['chain8']['partitions_evaluated']}, + 'chain8_varied': {'ei_micro': dec['chain8_varied']['ei'], 'ei_macro': search['chain8_varied']['ei_macro'], + 'ce': search['chain8_varied']['ce'], 'best_labels': search['chain8_varied']['labels']}, + 'channel4': {'ei_micro': dec['channel4']['ei'], 'conditional_entropy': 2.0 - dec['channel4']['ei'], + 'ei_macro': channel['ei_macro'], 'ce': channel['ce'], 'best_labels': channel['labels'], + 'partitions_evaluated': channel['partitions_evaluated']}, + 'and_gates': {'ei_micro': ce_and['micro']['ei'], 'determinism_micro': ce_and['micro']['determinism'], + 'degeneracy_micro': ce_and['micro']['degeneracy'], + 'effectiveness_micro': ce_and['micro']['effectiveness'], 'ei_macro': ce_and['macro']['ei'], + 'effectiveness_macro': ce_and['macro']['effectiveness'], 'ce': ce_and['ce'], + 'ei_micro_closed_form': 3.0 * entropy_bits([0.25, 0.75])}, + 'printed': dict(p), + } + symmetric = [] + for n in (5, 8): # weakly symmetric channels: no partition beats the micro scale + b = best_state_partition(noisy_permutation_tpm(n, c['permutation_noise'])) + symmetric.append({'n': n, 'noise': c['permutation_noise'], 'ei_micro': b['ei_micro'], + 'best_ei_macro': b['ei_macro'], 'best_ce': b['ce'], 'best_labels': b['labels'], + 'partitions_evaluated': b['partitions_evaluated']}) + pair = best_unit_coarse_graining(pair_count_copy_tpm(3, c['pair_copy_noise']), 6) + indep = best_unit_coarse_graining(independent_flip_tpm(6, c['independent_keep']), 6) + units = {'pair_copy': {'noise': c['pair_copy_noise'], **{k: pair[k] for k in ( + 'ei_micro', 'ei_macro', 'ce', 'groups', 'macro_states', 'partitions_evaluated')}}, + 'independent': {'keep': c['independent_keep'], **{k: indep[k] for k in ( + 'ei_micro', 'ei_macro', 'ce', 'groups', 'macro_states', 'partitions_evaluated')}}, + 'independent_ei_micro_closed_form': 6.0 * (1.0 - entropy_bits([c['independent_keep'], + 1.0 - c['independent_keep']]))} + every = [*(ex[k] for k in ex), T_and, np.eye(8), np.full((5, 5), 0.2)] + checks = { + 'identity_ei_equals_log2_n': all(_close(s['ei_identity'], s['log2_n'], 1e-9) and _close(s['identity_determinism'], 1.0, 1e-9) + and _close(s['identity_degeneracy'], 0.0, 1e-9) for s in sizes), + 'permutation_ei_equals_log2_n': all(_close(s['ei_permutation'], s['log2_n'], 1e-9) for s in sizes), + 'uniform_ei_is_zero': all(_close(s['ei_uniform'], 0.0, 1e-9) and _close(s['uniform_determinism'], 0.0, 1e-9) + and _close(s['uniform_degeneracy'], 0.0, 1e-9) for s in sizes), + 'ei_equals_size_times_effectiveness': all( + _close(d['ei'], d['size_bits'] * d['effectiveness'], 1e-9) + for d in (ei_decomposition(T) for T in every)), + 'hoel2017_M1_M2_M3_exact': all(_close(hoel['M_ei'][k], p[f'hoel2017_{k}_ei'], 1e-9) for k in ('M1', 'M2', 'M3')), + 'hoel2017_chain8_micro_closed_form': _close(hoel['chain8']['ei_micro'], chain_exact, 1e-9), + 'hoel2017_chain8_matches_printed': (_close(hoel['chain8']['ei_micro'], p['hoel2017_chain8_ei_micro'], 0.01) + and _close(hoel['chain8']['effectiveness'], p['hoel2017_chain8_effectiveness'], 0.005) + and _close(hoel['chain8']['ce'], p['hoel2017_chain8_ce'], 0.01)), + 'hoel2017_chain8_search_finds_1_bit_seven_plus_one': ( + _close(hoel['chain8']['ei_macro'], 1.0, 1e-9) and hoel['chain8']['best_labels'].tolist() == _SEVEN_PLUS_ONE), + 'hoel2017_chain8_varied_matches_printed': ( + _close(hoel['chain8_varied']['ei_micro'], p['hoel2017_chain8_varied_ei_micro'], 0.005) + and _close(hoel['chain8_varied']['ei_macro'], 1.0, 1e-9) + and hoel['chain8_varied']['best_labels'].tolist() == _SEVEN_PLUS_ONE), + 'hoel2017_channel4_matches_printed': ( + _close(hoel['channel4']['ei_micro'], p['hoel2017_channel4_ei_micro'], 0.005) + and _close(hoel['channel4']['conditional_entropy'], p['hoel2017_channel4_conditional_entropy'], 0.005) + and _close(hoel['channel4']['ei_macro'], p['hoel2017_channel4_ei_macro'], 1e-9) + and hoel['channel4']['best_labels'].tolist() == [0, 0, 0, 1]), + 'and_gate_network_matches_printed': ( + _close(hoel['and_gates']['ei_micro'], p['hoel2013_and_ei_micro'], 0.005) + and _close(hoel['and_gates']['determinism_micro'], 1.0, 1e-9) + and _close(hoel['and_gates']['degeneracy_micro'], p['hoel2017_and_degeneracy'], 0.005) + and _close(hoel['and_gates']['effectiveness_micro'], p['hoel2017_and_effectiveness'], 0.005) + and _close(hoel['and_gates']['ei_macro'], 3.0, 1e-9) + and _close(hoel['and_gates']['ce'], p['hoel2013_and_ce'], 0.005)), + 'weakly_symmetric_tpm_has_no_emergence': all(s['best_ce'] <= 1e-12 for s in symmetric), + 'unit_pair_copy_exact_ce_positive_for_pair_counts': bool(pair['ce'] > 0.0 and pair['groups'] == _PAIR_GROUPS), + 'unit_independent_exact_ce_negative': bool(indep['ce'] < 0.0 and _close( + indep['ei_micro'], units['independent_ei_micro_closed_form'], 1e-9)), + } + return {'sizes': sizes, 'hoel': hoel, 'weakly_symmetric': symmetric, 'units_exact': units}, checks + + +def _noisy_chain(eps: float) -> np.ndarray: + T = np.zeros((8, 8)) + T[:7, :7] = (1.0 - eps) / 7.0 + T[:7, 7] = eps + T[7, :7] = eps / 7.0 + T[7, 7] = 1.0 - eps + return T + + +def _sample_chain(T: np.ndarray, steps: int, rng: np.random.Generator) -> np.ndarray: + cum = np.cumsum(T, axis=1) + cum[:, -1] = 1.0 + u = rng.random(steps) + s = np.empty(steps, dtype=np.int64) + s[0] = int(rng.integers(T.shape[0])) + for t in range(1, steps): + s[t] = int(np.searchsorted(cum[s[t - 1]], u[t], side='right')) + return s + + +def _estimation(seed: int, c: Mapping[str, Any]) -> dict[str, Any]: + """Interventional samples of the Hoel (2017) 8-state chain: uniform current states, successors from the TPM.""" + T = hoel2017_examples()['chain8'] + rng = np.random.default_rng(seed + _EST_OFFSET) + N = c['estimation_samples'] + cur = rng.integers(0, 8, N) + cum = np.cumsum(T, axis=1) + cum[:, -1] = 1.0 + nxt = (rng.random(N)[:, None] >= cum[cur]).sum(axis=1) # inverse CDF (searchsorted side='right') + est = _smoothed(transition_counts(cur, 8, next_states=nxt).astype(np.float64), c['alpha']) + labels = np.array(_SEVEN_PLUS_ONE) + exact = causal_emergence(T, labels) + fit = causal_emergence(est, labels) + return {'seed': seed, 'samples': N, 'ei_micro_exact': exact['micro']['ei'], 'ei_micro_estimated': fit['micro']['ei'], + 'ce_exact': exact['ce'], 'ce_estimated': fit['ce'], + 'abs_error_ei_micro': abs(fit['micro']['ei'] - exact['micro']['ei']), + 'abs_error_ce': abs(fit['ce'] - exact['ce'])} + + +def _chain_record(out: Mapping[str, Any]) -> dict[str, Any]: + return {'ei_micro': out['ei_micro'], 'ei_macro': out['ei_macro'], 'ce': out['ce'], 'best_labels': out['labels'], + 'null_mean': out['null_mean'], 'null_sd': out['null_sd'], 'z': out['z'], 'p': out['p'], + 'block': out['block']} + + +def _null_runs(seed: int, c: Mapping[str, Any], chunks: Sequence[_Candidates]) -> dict[str, Any]: + """Successor block-permutation null on 8-state sequences: i.i.d. states (calibration), the noisy ergodic + version of the Hoel (2017) chain (exact CE > 0) and a weakly symmetric noisy permutation of the same length + (exact CE <= 0 for every partition).""" + iid = [] + for r in range(c['null_replicates']): + rng = np.random.default_rng([seed + _IID_OFFSET, r]) + out = _successor_block_null(rng.integers(0, 8, c['null_steps']), 8, chunks, c['alpha'], c['null_draws'], + None, (seed * 1009 + r) % (2**31 - 1)) + iid.append({'replicate': r, 'ce': out['ce'], 'null_mean': out['null_mean'], 'null_sd': out['null_sd'], + 'z': out['z'], 'p': out['p']}) + eps = c['emergence_noise'] + T = _noisy_chain(eps) + states = _sample_chain(T, c['null_steps'], np.random.default_rng(seed + _CHAIN_OFFSET)) + out = _successor_block_null(states, 8, chunks, c['alpha'], c['null_draws'], None, seed) + exact = causal_emergence(T, np.array(_SEVEN_PLUS_ONE)) + emerg = {'noise': eps, 'steps': c['null_steps'], 'ce_exact_seven_plus_one': exact['ce'], + 'ei_micro_exact': exact['micro']['ei'], 'ei_macro_exact': exact['macro']['ei'], **_chain_record(out)} + Tp = noisy_permutation_tpm(8, c['permutation_noise'], seed=seed) + sp = _sample_chain(Tp, c['null_steps'], np.random.default_rng([seed + _PERM8_OFFSET, 1])) + outp = _successor_block_null(sp, 8, chunks, c['alpha'], c['null_draws'], None, seed) + exact_p = best_state_partition(Tp) + control = {'noise': c['permutation_noise'], 'steps': c['null_steps'], 'ei_micro_exact': exact_p['ei_micro'], + 'best_ce_exact': exact_p['ce'], **_chain_record(outp)} + return {'seed': seed, 'iid': iid, 'emergence': emerg, 'permutation_control': control} + + +def _unit_runs(seed: int, c: Mapping[str, Any], chunks: Sequence[_Candidates], groups: np.ndarray) -> dict[str, Any]: + """Six binary units sampled from the pair-count copy ring (exact CE > 0) and from independent slow flips + (exact CE < 0), each scored with the observer's count-per-group search against both nulls.""" + weights = np.left_shift(1, np.arange(6, dtype=np.int64)) + out: dict[str, Any] = {'seed': seed, 'pair_copy': [], 'independent': []} + for r in range(c['unit_replicates']): + for name, offset in (('pair_copy', _PAIR_OFFSET), ('independent', _SLOW_OFFSET)): + rng = np.random.default_rng([seed + offset, r]) + if name == 'pair_copy': + bits = _sample_pair_count_copy(3, c['pair_copy_noise'], c['unit_steps'], rng) + else: + bits = _sample_independent_flips(6, c['independent_keep'], c['unit_steps'], rng) + seq = bits.astype(np.int64) @ weights + res = _ce_and_nulls(seq, 6, chunks, c['alpha'], c['unit_draws'], None, + np.random.default_rng([seed + _UNIT_NULL_OFFSET, r, 0]), + np.random.default_rng([seed + _UNIT_NULL_OFFSET, r, 1])) + part = _groups(groups[res['best_index']], np.arange(6)) + st, si = res['successor'], res['independent'] + out[name].append({'replicate': r, 'visited_states': int(np.unique(seq[:-1]).size), + 'ei_micro': res['ei_micro'], 'ei_macro': res['ei_macro'], 'ce': res['ce'], + 'best_partition': part, 'pairs_recovered': part == _PAIR_GROUPS, + 'successor_excess': st['excess'], 'successor_z': st['z'], 'successor_p': st['p'], + 'independent_excess': si['excess'], 'independent_z': si['z'], 'independent_p': si['p']}) + return out + + +def _neuroweave_activity(mechanisms: Sequence[str], seed: int, c: Mapping[str, Any]) -> np.ndarray: + from ..neuroweave.engine import NeuroWeaveEngine + from ..neuroweave.experiments import make_spec + from ..neuroweave.tasks import make_stream + steps = c['nw_steps'] + engine = NeuroWeaveEngine(make_spec(mechanisms, seed=seed, neurons=c['neurons'], topology=c['topology'], + steps=steps)) + stream = make_stream(seed, steps) + outs = [np.array(engine.step(stream.inputs[i], stream.sensory[i], reward=0.0, learn=False)['output'], + dtype=np.float64) for i in range(steps)] + return np.stack(outs)[c['nw_burn_in']:] + + +_NW_KEYS = ('unit_sample', 'transitions', 'transitions_per_micro_state', 'visited_states', 'ei_micro', + 'determinism_micro', 'degeneracy_micro', + 'ei_macro', 'macro_partition', 'macro_states', 'ce', 'null_ready', 'null_ce_mean', 'null_ce_sd', + 'ce_excess', 'ce_z', 'ce_p', 'indep_ce_mean', 'indep_ce_sd', 'ce_excess_indep', 'ce_z_indep', + 'ce_p_indep') + + +def _neuroweave_report(name: str, mechanisms: Sequence[str], seed: int, c: Mapping[str, Any]) -> dict[str, Any]: + X = _neuroweave_activity(mechanisms, seed, c) + obs = CausalEmergenceObserver(X.shape[1], seed=seed, history=min(8192, max(16, X.shape[0])), units=c['units'], + alpha=c['alpha'], null_draws=c['nw_null_draws'], + min_transitions=min(32, max(8, X.shape[0] - 2))) + for row in X: + obs.observe(row) + s = obs.summary() + return {'mechanism_set': name, 'seed': seed, 'neurons': int(X.shape[1]), **{k: s[k] for k in _NW_KEYS}} + + +def _finite_tree(obj: Any) -> bool: + if isinstance(obj, Mapping): + return all(_finite_tree(v) for v in obj.values()) + if isinstance(obj, (list, tuple)): + return all(_finite_tree(v) for v in obj) + if isinstance(obj, np.ndarray): + return bool(obj.dtype.kind not in 'fc' or np.all(np.isfinite(obj))) + if isinstance(obj, (float, np.floating)): + return math.isfinite(float(obj)) + return True + + +def _mean_of(values: Sequence[Any]) -> float | None: + v = [float(x) for x in values if x is not None] + return float(np.mean(v)) if v else None + + +def _rate(values: Sequence[Any], threshold: float = 0.05) -> float | None: + v = [float(x) for x in values if x is not None] + return float(np.mean([x <= threshold for x in v])) if v else None + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Known-answer validation of EI, its decomposition, coarse-graining search, TPM estimation and both nulls, + then a descriptive EI/CE report on NEUROWEAVE activity under each mechanism set. + + Exact checks (no sampling): identity and permutation TPMs give ``EI = log2 n`` (determinism 1, degeneracy 0), + uniform TPMs ``EI = 0``, and ``EI = log2(n) * effectiveness``; the printed values of Hoel (2017) (M1/M2/M3, + the 8-state chain with its closed form ``3 - (7/8) log2 7`` and the exhaustive search over its 4138 proper + partitions finding the 1-bit seven-plus-one macro, the unequal-row variant, the 4-state channel) and of the + six-AND-gate ring (Hoel et al. 2013, Fig. 4); weakly symmetric noisy permutations have no partition with + ``CE > 0``; the pair-count copy ring has exact ``CE > 0`` for the count-per-pair grouping and independent + slow units have exact ``CE < 0``. + + Sampled checks (every seed): Laplace-smoothed TPMs from interventional samples recover micro EI and CE within + ``estimation_tolerance``; the successor null is calibrated on i.i.d. states (at most 25 % of replicates with + ``p <= 0.05``, ``|mean z| < 1``); on 8-state sequences of the noisy chain the estimated CE is positive and + above the successor null (``z > 3``, ``p <= 0.05``), while a weakly symmetric noisy permutation of the same + length gives a negative CE that is not above it; on six binary units the pair-count copy ring is above the + independent-units null (``z > 3``, ``p <= 0.05``) with the pair grouping recovered, and the independent-units + null is calibrated on independent slow units (at most half of the replicates at ``p <= 0.05``, + ``|mean z| < 2``). How often the successor null flags those independent units (exact CE < 0) is reported, + not checked. The NEUROWEAVE part is descriptive (only finiteness is checked): for each mechanism set and seed the + frozen engine runs on the task stream and a :class:`CausalEmergenceObserver` over ``units`` (default 4) output + units reports micro/macro EI, CE and both nulls. + ``kind='validation'``, ``verdict`` in ``('pass', 'fail')``.""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds(seeds) + cfg = {k: (dict(v) if isinstance(v, Mapping) else v) for k, v in _DEFAULTS.items()} + if quick: + cfg.update(_QUICK) + unknown = sorted(set(overrides) - set(cfg)) + if unknown: + raise ValueError(f'unknown run_experiment overrides: {unknown}') + cfg.update(overrides) + c = _validate_config(cfg) + t0 = time.perf_counter() + exact, checks = _exact_checks(c) + estimation = [_estimation(s, c) for s in seeds] + cand = state_partition_candidates(8) + chunks8 = _candidate_chunks(cand['labels'], 8, cand['m']) + nulls = [_null_runs(s, c, chunks8) for s in seeds] + unit_cand = unit_sum_candidates(6) + unit_chunks = _candidate_chunks(unit_cand['labels'], 64, unit_cand['m']) + units = [_unit_runs(s, c, unit_chunks, unit_cand['groups']) for s in seeds] + t_val = time.perf_counter() - t0 + t1 = time.perf_counter() + nw: dict[str, Any] = {} + for name, mechs in c['mechanism_sets'].items(): + runs = [_neuroweave_report(name, mechs, s, c) for s in seeds] + nw[name] = {'mechanisms': list(mechs), 'per_seed': runs, + 'mean': {k: _mean_of([r[k] for r in runs]) for k in ( + 'ei_micro', 'ei_macro', 'ce', 'ce_excess', 'ce_z', 'ce_excess_indep', 'ce_z_indep', + 'visited_states')}} + t_nw = time.perf_counter() - t1 + iid = [r for n in nulls for r in n['iid']] + z_iid = [r['z'] for r in iid if r['z'] is not None] + fpr = float(np.mean([r['p'] <= 0.05 for r in iid])) + pair_rows = [r for u in units for r in u['pair_copy']] + ind_rows = [r for u in units for r in u['independent']] + ind_rate = _rate([r['independent_p'] for r in ind_rows]) + ind_mean_z = _mean_of([r['independent_z'] for r in ind_rows]) + unit_summary = { + 'pair_copy_replicates': len(pair_rows), + 'pair_copy_pairs_recovered_fraction': float(np.mean([r['pairs_recovered'] for r in pair_rows])), + 'pair_copy_min_independent_z': min((r['independent_z'] for r in pair_rows if r['independent_z'] is not None), + default=None), + 'pair_copy_mean_ce': _mean_of([r['ce'] for r in pair_rows]), + 'independent_replicates': len(ind_rows), + 'independent_units_null_flag_rate_p_le_0.05': ind_rate, + 'independent_units_null_mean_z': ind_mean_z, + 'independent_successor_null_flag_rate_p_le_0.05': _rate([r['successor_p'] for r in ind_rows]), + 'independent_successor_null_mean_z': _mean_of([r['successor_z'] for r in ind_rows]), + 'independent_mean_ce': _mean_of([r['ce'] for r in ind_rows]), + 'note': ('independent slow units have exact CE < 0, yet the successor null flags them when micro states ' + 'have few transitions each; the independent-units null does not'), + } + tol = c['estimation_tolerance'] + checks.update({ + 'estimated_tpm_recovers_ei_and_ce': all(e['abs_error_ei_micro'] <= tol and e['abs_error_ce'] <= tol + for e in estimation), + 'iid_null_false_positive_rate_at_most_0.25': bool(fpr <= 0.25), + 'iid_null_mean_z_within_1': bool(z_iid and abs(float(np.mean(z_iid))) < 1.0), + 'noisy_chain_ce_positive_and_above_successor_null': all( + n['emergence']['ce'] > 0.0 and n['emergence']['z'] is not None and n['emergence']['z'] > 3.0 + and n['emergence']['p'] <= 0.05 for n in nulls), + 'permutation_control_ce_negative_and_not_above_successor_null': all( + n['permutation_control']['ce'] < 0.0 and n['permutation_control']['p'] > 0.05 for n in nulls), + 'unit_pair_copy_above_independent_units_null_with_pairs_recovered': all( + r['independent_z'] is not None and r['independent_z'] > 3.0 and r['independent_p'] <= 0.05 + and r['pairs_recovered'] for r in pair_rows), + 'unit_independent_units_null_calibrated': bool(ind_rate is not None and ind_rate <= 0.5 + and ind_mean_z is not None and abs(ind_mean_z) < 2.0), + 'neuroweave_values_finite': _finite_tree(nw), + }) + receipt = harness.base_receipt(MODULE_ID, 'validation', {**c, 'quick': quick, 'seeds': list(seeds)}) + receipt['validations'] = { + **exact, 'estimation': estimation, + 'null_iid': {'replicates': len(iid), 'false_positive_rate_p_le_0.05': fpr, + 'mean_z': float(np.mean(z_iid)) if z_iid else None, 'per_replicate': iid}, + 'null_emergence': [n['emergence'] for n in nulls], + 'null_permutation_control': [n['permutation_control'] for n in nulls], + 'candidate_partitions': int(cand['labels'].shape[0]), + 'units': {'per_seed': units, 'summary': unit_summary, + 'candidate_coarse_grainings': int(unit_cand['labels'].shape[0])}} + receipt['neuroweave'] = {'per_mechanism_set': nw, 'topology': c['topology'], 'units': c['units'], + 'note': ('descriptive only: values are reported, no verdict is drawn from them; read CE ' + 'against the independent-units null (ce_excess_indep, ce_z_indep)')} + receipt['checks'] = checks + receipt['verdict'] = 'pass' if all(checks.values()) else 'fail' + receipt['verdict_basis'] = 'all_known_answer_checks' if receipt['verdict'] == 'pass' else 'failed_checks: ' + ', '.join( + k for k, v in checks.items() if not v) + n_null_runs = len(seeds) * (c['null_replicates'] + 2) + n_unit_runs = len(seeds) * c['unit_replicates'] * 2 + nw_cands = int(unit_sum_candidates(c['units'])['m'].size) + receipt['estimated_cost'] = { + 'tpm_evaluations_null': int(n_null_runs * (c['null_draws'] + 1) * (cand['labels'].shape[0] + 1)), + 'tpm_evaluations_units': int(n_unit_runs * (2 * c['unit_draws'] + 1) * (unit_cand['labels'].shape[0] + 1)), + 'engine_steps': int(len(c['mechanism_sets']) * len(seeds) * c['nw_steps']), + 'tpm_evaluations_neuroweave': int(len(c['mechanism_sets']) * len(seeds) * (2 * c['nw_null_draws'] + 1) + * (nw_cands + 1))} + receipt['measured_wallclock_s'] = {'validation': t_val, 'neuroweave': t_nw, 'total': time.perf_counter() - t0} + receipt['notes'] = ( + 'EI and causal emergence follow the definitions of Hoel et al. (2013) and Hoel (2017): uniform ' + '(maximum-entropy) interventions, macro TPMs by uniform interventions on the micro states of each macro ' + 'state. The six-AND-gate wiring is reconstructed from the papers\' text (pairs reading the next pair); its ' + 'exact values match the printed ones (2.43 bits, effectiveness 0.4/0.41, degeneracy 0.6/0.59, macro 3 bits, ' + 'CE 0.57 bits) at their printed precision. The 8-state chain has the closed form 3 - (7/8) log2 7 = 0.5436 ' + '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 ' + 'independent slow units are constructed known-answer systems, not examples from the papers. Estimated EI ' + 'from short discretised windows is dominated by Laplace smoothing and finite-sample effects (see ' + 'transitions_per_micro_state): with few transitions per micro state the successor null flags any temporal ' + 'dependence, so NEUROWEAVE CE is only meaningful against the independent-units null; the observer binarises ' + 'at a running median and only searches count-per-group coarse-grainings of 2 to 6 units. Nothing here is ' + 'evidence of consciousness, agency or biological causation.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/cli_commands.py b/synapse/frontier/cli_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..ab40391353f72f4d88d169a09d3536f8fbb72c21 --- /dev/null +++ b/synapse/frontier/cli_commands.py @@ -0,0 +1,223 @@ +"""Handlers for ``python -m synapse.cli frontier ...`` and global ``--frontier*`` CLI flags (opt-in only). + +Every subcommand handler returns a JSON-serialisable dict with an ``ok`` flag; nothing here changes any +Sonapse or NEUROWEAVE default. +""" +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path +from typing import Any + +import numpy as np + +from .harness import _jsonable +from .runtime import ( + FrontierObserverHub, + experiment_catalog, + run_all_frontier_experiments, + run_frontier_experiment, + run_frontier_laboratory, +) +from .spec import ( + EVIDENCE_TIER, + GRAFT_OPTIMIZERS, + MODULE_IDS, + OBSERVER_MODULE_IDS, + FrontierSpecV1, + module_catalog, +) + +__all__ = [ + 'parse_observer_modules', + 'parse_seeds', + 'cli_frontier_spec', + 'register_frontier_cli', + 'run_frontier_command', +] + +MAX_CLI_JSON_BYTES = 1_000_000 +MAX_CLI_OBSERVE_STEPS = 4096 +MAX_CLI_OBSERVE_UNITS = 4096 +_SYNTH_STREAM_OFFSET = 61_543 + + +def _read_json_file(path: Path, limit: int = MAX_CLI_JSON_BYTES) -> Any: + p = Path(path) + size = p.stat().st_size + if size > limit: + raise ValueError(f'{p} exceeds {limit} bytes (checked before reading)') + + def _reject(token: str) -> Any: + raise ValueError(f'non-standard JSON constant {token}') + + return json.loads(p.read_text(encoding='utf-8'), parse_constant=_reject) + + +def parse_observer_modules(text: str | None) -> tuple[str, ...]: + """``'all'`` -> every observer module, ``'none'``/``''`` -> ``()``, else a comma list of observer ids.""" + if text is None: + return () + t = text.strip() + if t.lower() == 'all': + return OBSERVER_MODULE_IDS + if t.lower() in ('', 'none'): + return () + items = [m.strip() for m in t.split(',') if m.strip()] + unknown = [m for m in items if m not in MODULE_IDS] + if unknown: + raise ValueError(f'unknown frontier modules: {unknown}') + non_obs = [m for m in items if m not in OBSERVER_MODULE_IDS] + if non_obs: + raise ValueError(f'modules without a live observer: {non_obs} (observers: {OBSERVER_MODULE_IDS})') + return tuple(m for m in OBSERVER_MODULE_IDS if m in set(items)) + + +def parse_seeds(text: str | None, default: tuple[int, ...] = (0, 1, 2), max_count: int = 16) -> tuple[int, ...]: + if text is None or not str(text).strip(): + return default + parts = [p.strip() for p in str(text).split(',') if p.strip()] + if not 1 <= len(parts) <= max_count: + raise ValueError(f'--seeds must list between 1 and {max_count} integers') + seeds: list[int] = [] + for p in parts: + try: + val = int(p) + except ValueError as exc: + raise ValueError(f'invalid seed {p!r}') from exc + if not 0 <= val <= 2**31 - 1: + raise ValueError('seeds must be non-negative 31-bit ints') + seeds.append(val) + if len(set(seeds)) != len(seeds): + raise ValueError('seeds must be unique') + return tuple(seeds) + + +def cli_frontier_spec(enabled: bool | None, config_path: Path | None, seed: int, *, + modules: str | None = None, graft_optimizer: str | None = None) -> FrontierSpecV1 | None: + """Build a :class:`FrontierSpecV1` from global CLI flags, or ``None`` when not requested.""" + if config_path is not None: + if enabled is False: + raise ValueError('--no-frontier conflicts with --frontier-config') + data = _read_json_file(Path(config_path)) + spec = FrontierSpecV1.from_dict(data) + if modules is not None: + spec = spec.with_modules(parse_observer_modules(modules)) + if graft_optimizer is not None: + spec = replace(spec, graft_optimizer=graft_optimizer) + return spec + has_opt_in = bool(enabled) or (modules is not None) or (graft_optimizer not in (None, 'adam')) + if not has_opt_in: + return None + if enabled is False: + raise ValueError('--no-frontier conflicts with frontier module or graft-optimizer options') + obs_mods = OBSERVER_MODULE_IDS if modules is None and enabled else parse_observer_modules(modules) + return FrontierSpecV1( + enabled=True, + seed=int(seed), + modules=obs_mods, + graft_optimizer='adam' if graft_optimizer is None else graft_optimizer, + ) + + +def register_frontier_cli(parser: Any, subparsers: Any = None) -> None: + """Add global ``--frontier*`` options to ``parser`` and optionally a ``frontier`` subcommand.""" + parser.add_argument('--frontier', dest='frontier_enabled', action='store_true', default=None, + help='Enable read-only live frontier observers on the brain') + parser.add_argument('--no-frontier', dest='frontier_enabled', action='store_false', + help='Disable live frontier observers') + parser.add_argument('--frontier-config', type=Path, default=None, + help='Path to a FrontierSpecV1 JSON file') + parser.add_argument('--frontier-modules', type=str, default=None, + help='Comma-separated observer modules (or "all" / "none")') + parser.add_argument('--frontier-graft-optimizer', choices=GRAFT_OPTIMIZERS, default=None, + help='Opt-in optimizer for the live neural-graft fit (adam or muon)') + if subparsers is not None: + fp = subparsers.add_parser('frontier', help='Frontier pack catalog, observers and experiments') + fp.add_argument('frontier_action', choices=('catalog', 'experiment', 'observe', 'laboratory'), + nargs='?', default='catalog') + fp.add_argument('--id', dest='frontier_id', type=str, default='all', + help='Experiment id to run (or "all")') + fp.add_argument('--quick', dest='frontier_quick', action='store_true', default=False, + help='Run experiment(s) in fast quick mode') + fp.add_argument('--seeds', dest='frontier_seeds', type=str, default='0,1,2', + help='Comma-separated integer seeds') + fp.add_argument('--modules', dest='frontier_sub_modules', type=str, default='all', + help='Observer modules for observe/laboratory') + fp.add_argument('--steps', dest='frontier_steps', type=int, default=32, + help='Synthetic observation steps for "frontier observe"') + fp.add_argument('--units', dest='frontier_units', type=int, default=32, + help='Synthetic unit count for "frontier observe"') + fp.add_argument('--out', dest='frontier_out', type=Path, default=None, + help='Optional path to write the JSON receipt') + + +def _write_optional(out_path: Path | None, payload: Any) -> dict[str, Any] | None: + if out_path is None: + return None + p = Path(out_path) + p.parent.mkdir(parents=True, exist_ok=True) + text = json.dumps(_jsonable(payload), indent=2, sort_keys=True) + p.write_text(text, encoding='utf-8') + return {'path': str(p), 'bytes': len(text.encode('utf-8'))} + + +def run_frontier_command(args: Any) -> dict[str, Any]: + """Execute ``python -m synapse.cli frontier `` and return a JSON-safe response.""" + action = getattr(args, 'frontier_action', 'catalog') + seed = int(getattr(args, 'seed', 7)) + out_path = getattr(args, 'frontier_out', None) + try: + if action == 'catalog': + res: dict[str, Any] = { + 'ok': True, + 'action': 'catalog', + 'evidence_tier': EVIDENCE_TIER, + 'modules': module_catalog(), + 'observer_module_ids': list(OBSERVER_MODULE_IDS), + 'experiments': experiment_catalog(include_unregistered=True), + } + elif action == 'experiment': + exp_id = str(getattr(args, 'frontier_id', 'all')).strip() + quick = bool(getattr(args, 'frontier_quick', False)) + seeds = parse_seeds(getattr(args, 'frontier_seeds', '0,1,2'), + default=(0, 1) if quick else (0, 1, 2)) + if exp_id.lower() == 'all': + receipts = run_all_frontier_experiments( + quick=quick, seeds=seeds, primary_only=True, include_unregistered=True) + res = {'ok': True, 'action': 'experiment', 'count': len(receipts), 'receipts': receipts} + else: + receipt = run_frontier_experiment(exp_id, quick=quick, seeds=seeds, include_unregistered=True) + res = {'ok': True, 'action': 'experiment', 'receipt': receipt} + elif action == 'observe': + steps = int(getattr(args, 'frontier_steps', 32)) + units = int(getattr(args, 'frontier_units', 32)) + if not 1 <= steps <= MAX_CLI_OBSERVE_STEPS: + raise ValueError(f'--steps must be in [1, {MAX_CLI_OBSERVE_STEPS}]') + if not 2 <= units <= MAX_CLI_OBSERVE_UNITS: + raise ValueError(f'--units must be in [2, {MAX_CLI_OBSERVE_UNITS}]') + mods = parse_observer_modules(getattr(args, 'frontier_sub_modules', 'all')) + spec = FrontierSpecV1(enabled=True, seed=seed, modules=mods, + history=max(16, min(256, steps * 2)), + fc_window=max(8, min(128, max(16, steps)))) + hub = FrontierObserverHub(spec, n_units=units) + rng = np.random.default_rng(seed + _SYNTH_STREAM_OFFSET) + for _ in range(steps): + hub.observe(np.tanh(rng.standard_normal(units))) + res = {'ok': True, 'action': 'observe', 'summary': hub.summary()} + elif action == 'laboratory': + quick = bool(getattr(args, 'frontier_quick', True)) + seeds = parse_seeds(getattr(args, 'frontier_seeds', '0,1'), default=(0, 1)) + mods = parse_observer_modules(getattr(args, 'frontier_sub_modules', 'all')) + spec = FrontierSpecV1(enabled=True, seed=seed, modules=mods) + lab = run_frontier_laboratory(spec, experiments=True, quick=quick, seeds=seeds) + res = {'ok': True, 'action': 'laboratory', 'receipt': lab} + else: + raise ValueError(f'unknown frontier action: {action!r}') + written = _write_optional(out_path, res) + if written is not None: + res['written'] = written + return _jsonable(res) + except Exception as exc: + return {'ok': False, 'action': action, 'error': str(exc)} diff --git a/synapse/frontier/connectomics.py b/synapse/frontier/connectomics.py new file mode 100644 index 0000000000000000000000000000000000000000..9cb503c5df3e572ea6e05ae6f6acff750861e2bc --- /dev/null +++ b/synapse/frontier/connectomics.py @@ -0,0 +1,1205 @@ +"""Structural, functional and effective connectivity (frontier module ``connectomics``). + +Inspired by the strictly separated structural / functional / effective connectomics of SONAPSE-CONNECTOME +(kai9987kai; ``sonapse_connectome/connectome/functional.py`` and ``effective.py``). This module re-implements +those ideas for NEUROWEAVE brains with known-answer validation. It is a synthetic computational abstraction: the +"structure" is a toy synapse table and the "function" is the activity of abstract units, not imaging data. + +What is computed +---------------- +* **Functional connectivity (FC).** Pearson and Spearman correlation matrices, and partial correlation from a + ridge-regularised precision matrix: ``Omega = (R + ridge * I)^-1`` on the correlation matrix ``R`` and + ``P_ij = -Omega_ij / sqrt(Omega_ii Omega_jj)``. Zero-variance units get zero rows and a zero diagonal. +* **Dynamic FC (dFC).** Sliding-window Pearson FC, k-means clustering of the windowed upper triangles into FC + states, the number of states chosen by the average silhouette width, and dwell times (run lengths of the state + sequence). In the spirit of Allen et al. (2014); see the doc for what differs. +* **Effective connectivity (EC).** A ridge VAR(1) (lagged regression, Granger-style predictive influence, not an + interventional effect): ``x_{t+1} = A x_t + e``, ``A[target, source]``. The significance mask comes from a + per-target conditional block-permutation null (each target keeps its own past; the other sources are + block-permuted jointly in time), a two-sided normal p-value from the null mean and spread, and + Benjamini-Hochberg FDR control over the off-diagonal edges. +* **Structure-function coupling.** Spearman correlation between symmetric structural weights and FC over node + pairs (all pairs and structurally connected pairs), and the same for weighted communicability + ``exp(D^-1/2 S D^-1/2)`` as an analytic predictor of FC. +* **FC modularity proxy.** Newman-Girvan modularity of the positive part of FC under a leading-eigenvector + partition (recursive bisection, no vertex-moving refinement), so it is a lower bound on the maximum modularity. + +References (verified 2026-11-19; full list and notes in ``docs/frontier/modules/connectomics.md``) +--------------------------------------------------------------------------------------------------- +* C. J. Honey, O. Sporns, L. Cammoun, X. Gigandet, J. P. Thiran, R. Meuli, P. Hagmann, "Predicting human + resting-state functional connectivity from structural connectivity", PNAS 106(6):2035-2040, February 2009, + https://doi.org/10.1073/pnas.0811168106 +* E. A. Allen, E. Damaraju, S. M. Plis, E. B. Erhardt, T. Eichele, V. D. Calhoun, "Tracking whole-brain + connectivity dynamics in the resting state", Cerebral Cortex 24(3):663-676, March 2014, + https://doi.org/10.1093/cercor/bhs352 +* E. Estrada, N. Hatano, "Communicability in complex networks", Phys. Rev. E 77:036111, March 2008, + https://doi.org/10.1103/PhysRevE.77.036111 +* J. J. Crofts, D. J. Higham, "A weighted communicability measure applied to complex brain networks", + J. R. Soc. Interface 6(33):411-414, April 2009, https://doi.org/10.1098/rsif.2008.0484 (eq. 2.2) +* M. E. J. Newman, "Modularity and community structure in networks", PNAS 103(23):8577-8582, June 2006, + https://doi.org/10.1073/pnas.0601602103 +* C. W. J. Granger, "Investigating causal relations by econometric models and cross-spectral methods", + Econometrica 37(3):424-438, August 1969, https://doi.org/10.2307/1912791 +* Y. Benjamini, Y. Hochberg, "Controlling the false discovery rate: a practical and powerful approach to multiple + testing", J. R. Stat. Soc. B 57(1):289-300, 1995, https://doi.org/10.1111/j.2517-6161.1995.tb02031.x +* P. J. Rousseeuw, "Silhouettes: a graphical aid to the interpretation and validation of cluster analysis", + J. Comput. Appl. Math. 20:53-65, November 1987, https://doi.org/10.1016/0377-0427(87)90125-7 +""" +from __future__ import annotations + +import math +import time +from typing import Any, Callable, Mapping, Sequence + +import numpy as np + +__all__ = ['MODULE_ID', 'ConnectivityObserver', 'pearson_fc', 'spearman_fc', 'partial_correlation', + 'partial_from_covariance', 'precision_to_partial', 'sliding_window_fc', 'kmeans', 'silhouette_score', + 'dwell_statistics', 'dynamic_fc_states', 'var1_fit', 'block_permutation', 'var1_permutation_null', + 'benjamini_hochberg', 'effective_connectivity', 'auroc', 'structural_matrix', 'weighted_communicability', + 'structure_function_coupling', 'modularity', 'fc_communities', 'run_experiment', 'EXPERIMENTS'] + +MODULE_ID = 'connectomics' +OBSERVER_STATE_SCHEMA = 'ConnectivityObserverStateV1' +_VAR_OFFSET = 63_001 +_CHAIN_OFFSET = 63_011 +_SWITCH_OFFSET = 63_021 +_KMEANS_OFFSET = 63_031 +_PERM_OFFSET = 63_041 +_OBS_UNITS_OFFSET = 63_051 +_OBS_PERM_OFFSET = 63_061 +_STATIONARY_OFFSET = 63_071 +_TOP_EDGES = 5 +_EPS = 1e-12 +_SPEC_OBSERVER_PARAMS = frozenset({'sync_pairs', 'sae_features', 'sae_k', 'fc_window', 'max_observed_units', + 'observe_every'}) + + +# ====================================================================== validation helpers +def _check_int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _check_float(name: str, value: Any, low: float, high: float) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number in [{low}, {high}]') + v = float(value) + if not (math.isfinite(v) and low <= v <= high): + raise ValueError(f'{name} must be a finite number in [{low}, {high}]') + return v + + +def _check_seeds(seeds: Any) -> tuple[int, ...]: + try: + out = tuple(_check_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +def _series(name: str, value: Any, *, min_rows: int = 3, min_cols: int = 2) -> np.ndarray: + """A private float64 copy of a finite ``(T, n)`` array with ``T >= min_rows`` and ``n >= min_cols``.""" + try: + arr = np.array(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + if arr.ndim != 2 or arr.shape[0] < min_rows or arr.shape[1] < min_cols: + raise ValueError(f'{name} must be a 2-D array with at least {min_rows} rows and {min_cols} columns') + if not np.all(np.isfinite(arr)): + raise ValueError(f'{name} must be finite') + return arr + + +def _square(name: str, value: Any, n: int | None = None) -> np.ndarray: + try: + arr = np.array(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + 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): + raise ValueError(f'{name} must be a square matrix' + ('' if n is None else f' of size {n}')) + if not np.all(np.isfinite(arr)): + raise ValueError(f'{name} must be finite') + return arr + + +# ====================================================================== functional connectivity +def _zscore_columns(X: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Column z-scores (population sd) and the mask of non-constant columns (constant columns become 0).""" + # A power-of-two rescaling keeps centering and squaring in range even + # when different units are recorded at very different amplitudes. + _, exponents = np.frexp(np.max(np.abs(X), axis=0)) + Z = np.ldexp(X, -exponents) + Z -= Z[0].copy() + Z -= Z.mean(axis=0) + sd = np.sqrt((Z * Z).mean(axis=0)) + ok = sd > 0.0 + out = np.zeros_like(Z) + out[:, ok] = Z[:, ok] / sd[ok] + return out, ok + + +def _pearson(X: np.ndarray) -> np.ndarray: + Z, ok = _zscore_columns(X) + C = np.clip((Z.T @ Z) / X.shape[0], -1.0, 1.0) + np.fill_diagonal(C, ok.astype(np.float64)) + return C + + +def pearson_fc(X: Any) -> np.ndarray: + """Pearson FC of a ``(T, n)`` series. Constant units get zero rows/columns and a zero diagonal entry.""" + return _pearson(_series('X', X)) + + +def spearman_fc(X: Any) -> np.ndarray: + """Spearman FC: Pearson correlation of per-unit ranks (average ranks for ties).""" + from scipy.stats import rankdata + return _pearson(rankdata(_series('X', X), axis=0)) + + +def precision_to_partial(precision: Any) -> np.ndarray: + """Partial correlations ``-Omega_ij / sqrt(Omega_ii Omega_jj)`` (unit diagonal) from a precision matrix.""" + Om = _square('precision', precision) + d = np.diag(Om) + if np.any(d <= 0.0): + raise ValueError('precision matrix must have a positive diagonal') + s = np.sqrt(d) + P = -Om / np.outer(s, s) + np.fill_diagonal(P, 1.0) + return np.clip(0.5 * (P + P.T), -1.0, 1.0) + + +def partial_from_covariance(cov: Any, *, ridge: float = 0.0) -> np.ndarray: + """Partial correlations from a covariance matrix through the ridge-regularised precision ``(R + ridge I)^-1`` + of its correlation matrix ``R``. Units with zero variance get zero rows and a zero diagonal entry. With + ``ridge = 0`` the result is exact; a singular ``R`` then raises ``ValueError``.""" + C = _square('cov', cov) + ridge = _check_float('ridge', ridge, 0.0, 1e6) + if not np.allclose(C, C.T, rtol=1e-9, atol=1e-12): + raise ValueError('cov must be symmetric') + C = 0.5 * (C + C.T) + d = np.diag(C).copy() + if np.any(d < 0): + raise ValueError('cov must have non-negative variances') + ok = d > 0 + if np.any(C[~ok] != 0): + raise ValueError('zero-variance units must have zero covariance') + n = C.shape[0] + R = np.eye(n) + s = np.sqrt(d[ok]) + R[np.ix_(ok, ok)] = C[np.ix_(ok, ok)] / np.outer(s, s) + np.fill_diagonal(R, 1.0) + S = R + ridge * np.eye(n) + w = np.linalg.eigvalsh(S) + if not w[0] > 1e-10 * max(1.0, float(w[-1])): + raise ValueError('correlation matrix is singular or not positive definite; use ridge > 0') + P = precision_to_partial(np.linalg.inv(S)) + P[~ok, :] = 0.0 + P[:, ~ok] = 0.0 + np.fill_diagonal(P, ok.astype(np.float64)) + return P + + +def partial_correlation(X: Any, *, ridge: float = 1e-2) -> np.ndarray: + """Partial correlations of a ``(T, n)`` series from the ridge-regularised precision of its correlation matrix.""" + X = _series('X', X) + return partial_from_covariance(_pearson(X), ridge=ridge) + + +# ====================================================================== dynamic FC +def sliding_window_fc(X: Any, window: int, step: int) -> tuple[np.ndarray, np.ndarray]: + """Window start indices and Pearson FC per window, shape ``(W, n, n)``.""" + X = _series('X', X) + T = X.shape[0] + window = _check_int('window', window, 3, T) + step = _check_int('step', step, 1, T) + starts = np.arange(0, T - window + 1, step, dtype=np.int64) + mats = np.stack([_pearson(X[s:s + window]) for s in starts]) + return starts, mats + + +def _sq_dists(V: np.ndarray, C: np.ndarray) -> np.ndarray: + d = (V * V).sum(1)[:, None] - 2.0 * (V @ C.T) + (C * C).sum(1)[None, :] + return np.maximum(d, 0.0) + + +def _canonical_labels(labels: np.ndarray, centers: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Relabel clusters in order of first appearance so labels do not depend on initialisation order.""" + order: list[int] = [] + for v in labels.tolist(): + if v not in order: + order.append(v) + order += [j for j in range(centers.shape[0]) if j not in order] + remap = np.empty(centers.shape[0], dtype=np.int64) + remap[np.asarray(order, dtype=np.int64)] = np.arange(centers.shape[0]) + return remap[labels], centers[np.asarray(order, dtype=np.int64)] + + +def kmeans(data: Any, k: int, *, seed: int = 0, n_init: int = 8, max_iter: int = 100) -> dict[str, Any]: + """Deterministic k-means (Lloyd iterations, D^2-weighted seeding, ``n_init`` restarts, best inertia kept). + + Seeding and restarts use ``numpy.random.default_rng(seed + offset)``. Empty clusters are re-seeded with the + point farthest from its centroid among clusters that keep at least one other member, so degenerate data + (repeated points) never leaves a cluster empty. Labels are canonicalised to order of first appearance.""" + V = _series('data', data, min_rows=1, min_cols=1) + W = V.shape[0] + k = _check_int('k', k, 1, W) + seed = _check_int('seed', seed, 0, 2**31 - 1) + n_init = _check_int('n_init', n_init, 1, 1000) + max_iter = _check_int('max_iter', max_iter, 1, 100_000) + rng = np.random.default_rng(seed + _KMEANS_OFFSET) + best: tuple[np.ndarray, np.ndarray, float] | None = None + for _ in range(n_init): + idx = [int(rng.integers(W))] + d2 = _sq_dists(V, V[idx])[:, 0] + for _j in range(1, k): + total = float(d2.sum()) + nxt = int(rng.integers(W)) if total <= 0.0 else int(rng.choice(W, p=d2 / total)) + idx.append(nxt) + d2 = np.minimum(d2, _sq_dists(V, V[[nxt]])[:, 0]) + C = V[idx].copy() + labels = np.full(W, -1, dtype=np.int64) + for _it in range(max_iter): + D = _sq_dists(V, C) + new = D.argmin(axis=1).astype(np.int64) + for j in range(k): # re-seed empty clusters deterministically + if not np.any(new == j): + # the point farthest from its centroid, taken only from a cluster with >= 2 members so + # that no other cluster is emptied (k <= W guarantees one exists); ties -> lowest index + sizes = np.bincount(new, minlength=k) + dist = np.where(sizes[new] > 1, D[np.arange(W), new], -np.inf) + far = int(dist.argmax()) + new[far] = j + D[far] = np.inf + D[far, j] = 0.0 + if np.array_equal(new, labels): + break + labels = new + for j in range(k): + C[j] = V[labels == j].mean(axis=0) + inertia = float(_sq_dists(V, C)[np.arange(W), labels].sum()) + if best is None or inertia < best[2] - 1e-12 * max(1.0, best[2]): + best = (labels.copy(), C.copy(), inertia) + assert best is not None + labels, C = _canonical_labels(best[0], best[1]) + return {'labels': labels, 'centroids': C, 'inertia': best[2], 'k': k} + + +def silhouette_score(data: Any, labels: Any) -> float | None: + """Mean silhouette width (Rousseeuw, 1987) with Euclidean distances; ``None`` unless 2 <= clusters < points. + Points alone in their cluster score 0.""" + V = _series('data', data, min_rows=1, min_cols=1) + lab = np.asarray(labels) + if lab.shape != (V.shape[0],) or lab.dtype.kind not in 'iu': + raise ValueError('labels must be one integer per row of data') + uniq, inv = np.unique(lab, return_inverse=True) + W, k = V.shape[0], uniq.size + if k < 2 or k >= W: + return None + D = np.sqrt(_sq_dists(V, V)) + onehot = np.zeros((W, k)) + onehot[np.arange(W), inv] = 1.0 + sums = D @ onehot + sizes = onehot.sum(0) + own_size = sizes[inv] + a = np.where(own_size > 1, sums[np.arange(W), inv] / np.maximum(own_size - 1.0, 1.0), 0.0) + mean_other = sums / sizes[None, :] + mean_other[np.arange(W), inv] = np.inf + b = mean_other.min(axis=1) + denom = np.maximum(a, b) + s = np.where((own_size > 1) & (denom > 0), (b - a) / np.where(denom > 0, denom, 1.0), 0.0) + return float(s.mean()) + + +def dwell_statistics(labels: Any, n_states: int | None = None) -> dict[str, Any]: + """Run lengths of a state sequence: per-state mean dwell, overall mean dwell, occupancy and transitions.""" + lab = np.asarray(labels) + if lab.ndim != 1 or lab.size == 0 or lab.dtype.kind not in 'iu' or lab.min() < 0: + raise ValueError('labels must be a non-empty 1-D array of non-negative integers') + k = int(lab.max()) + 1 if n_states is None else _check_int('n_states', n_states, int(lab.max()) + 1, 1_000_000) + change = np.flatnonzero(np.diff(lab) != 0) + starts = np.r_[0, change + 1] + lengths = np.diff(np.r_[starts, lab.size]) + run_state = lab[starts] + per_state = [] + for s in range(k): + r = lengths[run_state == s] + per_state.append(float(r.mean()) if r.size else None) + return {'n_states': k, 'runs': int(lengths.size), 'transitions': int(change.size), + 'mean_dwell': float(lengths.mean()), 'mean_dwell_per_state': per_state, + 'occupancy': (np.bincount(lab, minlength=k) / lab.size).tolist()} + + +def dynamic_fc_states(X: Any, *, window: int, step: int | None = None, k_max: int = 4, + min_silhouette: float = 0.25, seed: int = 0, n_init: int = 8) -> dict[str, Any]: + """Sliding-window FC states. + + Windowed FC upper triangles are clustered with :func:`kmeans` for ``k = 2 .. k_max``; the k with the largest + mean silhouette wins. When no k reaches ``min_silhouette`` (a heuristic default of 0.25) or there are fewer + than three windows, the series is reported as a single FC state. Dwell times are run lengths of the window + state sequence, in windows and in samples (``x step``).""" + X = _series('X', X) + T, n = X.shape + window = _check_int('window', window, 3, T) + step = max(1, window // 4) if step is None else _check_int('step', step, 1, T) + k_max = _check_int('k_max', k_max, 2, 16) + min_silhouette = _check_float('min_silhouette', min_silhouette, -1.0, 1.0) + seed = _check_int('seed', seed, 0, 2**31 - 1) + starts, mats = sliding_window_fc(X, window, step) + iu = np.triu_indices(n, 1) + V = mats[:, iu[0], iu[1]] + W = int(starts.size) + scores: dict[int, float | None] = {} + best_k, best_s, labels = 1, None, np.zeros(W, dtype=np.int64) + if W >= 3: + for k in range(2, min(k_max, W - 1) + 1): + # modulo keeps the derived seed valid for seeds near 2**31 - 1 (unchanged for all smaller seeds) + km = kmeans(V, k, seed=(seed + 101 * k) % 2**31, n_init=n_init) + s = silhouette_score(V, km['labels']) + scores[k] = s + if s is not None and (best_s is None or s > best_s + 1e-12): + best_k, best_s, labels = k, s, km['labels'] + if best_s is None or best_s < min_silhouette: + best_k, labels = 1, np.zeros(W, dtype=np.int64) + dw = dwell_statistics(labels, best_k) + centroids = np.stack([mats[labels == j].mean(axis=0) for j in range(best_k)]) + return {'n_states': best_k, 'labels': labels, 'starts': starts, 'window': window, 'step': step, 'windows': W, + 'silhouette': {int(k): v for k, v in scores.items()}, 'best_silhouette': best_s, + 'mean_dwell_windows': dw['mean_dwell'], 'mean_dwell_samples': dw['mean_dwell'] * step, + 'mean_dwell_per_state_windows': dw['mean_dwell_per_state'], 'occupancy': dw['occupancy'], + 'transitions': dw['transitions'], 'state_fc': centroids} + + +# ====================================================================== effective connectivity +def _var_design(X: Any, ridge: float, standardize: bool) -> tuple[np.ndarray, np.ndarray, float]: + X = _series('X', X, min_rows=4) + ridge = _check_float('ridge', ridge, 0.0, 1e6) + if type(standardize) is not bool: + raise ValueError('standardize must be a boolean') + if standardize: + X, _ok = _zscore_columns(X) + P = X[:-1] - X[:-1].mean(axis=0) + F = X[1:] - X[1:].mean(axis=0) + return P, F, ridge * P.shape[0] + + +def _solve(G: np.ndarray, R: np.ndarray) -> np.ndarray: + try: + return np.linalg.solve(G, R) + except np.linalg.LinAlgError as exc: + raise ValueError('lagged design is singular; use ridge > 0') from exc + + +def var1_fit(X: Any, *, ridge: float = 1e-2, standardize: bool = True) -> np.ndarray: + """Ridge VAR(1): ``A = argmin sum_t ||x_{t+1} - A x_t||^2 + lambda ||A||_F^2`` with ``lambda = ridge * (T-1)`` + on (optionally z-scored) series with intercepts. Returns ``A[target, source]``.""" + P, F, lam = _var_design(X, ridge, standardize) + n = P.shape[1] + return _solve(P.T @ P + lam * np.eye(n), P.T @ F).T + + +def block_permutation(length: int, block: int, rng: np.random.Generator) -> np.ndarray: + """A permutation of ``range(length)`` that reorders consecutive blocks of ``block`` indices (the last block + may be shorter) and keeps the order inside each block.""" + length = _check_int('length', length, 1, 2**40) + block = _check_int('block', block, 1, length) + nb = -(-length // block) + order = rng.permutation(nb) + idx = (order[:, None] * block + np.arange(block)[None, :]).ravel() + return idx[idx < length] + + +def _default_block(T: int) -> int: + return max(2, int(round(T ** (1.0 / 3.0)))) if T >= 8 else 1 + + +def _null_coefficients(P: np.ndarray, F: np.ndarray, lam: float, draws: int, block: int, + rng: np.random.Generator) -> np.ndarray: + """Per-target conditional block-permutation null for the ridge VAR(1). + + For draw b the rows of the source matrix are block-permuted (one permutation for all sources), except that + target i keeps its own unpermuted past. Each target's ridge system is assembled from shared cross-products and + all targets are solved in one batched call. Returns ``(draws, n, n)`` coefficients ``[target, source]``.""" + Tm, n = P.shape + ar = np.arange(n) + self_g = (P * P).sum(axis=0) + self_r = (P * F).sum(axis=0) + ridge_eye = lam * np.eye(n) + out = np.empty((draws, n, n)) + for b in range(draws): + Pp = P[block_permutation(Tm, block, rng)] + cpp = Pp.T @ Pp + cross = P.T @ Pp # cross[i, j] = P_i . Pp_j + rf = Pp.T @ F # rf[j, i] = Pp_j . F_i + G = np.repeat(cpp[None, :, :], n, axis=0) + G[ar, ar, :] = cross # row i of target i's Gram + G[ar, :, ar] = cross # column i of target i's Gram + G[ar, ar, ar] = self_g + r = rf.T.copy() + r[ar, ar] = self_r + out[b] = _solve(G + ridge_eye, r[..., None])[..., 0] + return out + + +def var1_permutation_null(X: Any, *, ridge: float = 1e-2, standardize: bool = True, draws: int = 99, + block: int | None = None, seed: int = 0) -> np.ndarray: + """Null coefficients ``(draws, n, n)`` of the per-target conditional block-permutation null (see + :func:`effective_connectivity`).""" + P, F, lam = _var_design(X, ridge, standardize) + draws = _check_int('draws', draws, 1, 100_000) + block = _default_block(P.shape[0]) if block is None else _check_int('block', block, 1, P.shape[0]) + rng = np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _PERM_OFFSET) + return _null_coefficients(P, F, lam, draws, block, rng) + + +def benjamini_hochberg(p_values: Any, alpha: float = 0.05) -> np.ndarray: + """Benjamini-Hochberg step-up rejections at FDR level ``alpha`` (boolean mask, same shape as the input).""" + p = np.asarray(p_values, dtype=np.float64) + alpha = _check_float('alpha', alpha, 0.0, 1.0) + if not np.all(np.isfinite(p)) or np.any(p < 0.0) or np.any(p > 1.0): + raise ValueError('p-values must be finite and in [0, 1]') + flat = p.ravel() + m = flat.size + reject = np.zeros(m, dtype=bool) + if m: + order = np.argsort(flat, kind='stable') + below = flat[order] <= alpha * np.arange(1, m + 1) / m + if below.any(): + reject[order[:int(np.flatnonzero(below).max()) + 1]] = True + return reject.reshape(p.shape) + + +def _ec_from_design(P: np.ndarray, F: np.ndarray, lam: float, draws: int, block: int, alpha: float, + rng: np.random.Generator) -> dict[str, Any]: + n = P.shape[1] + A = _solve(P.T @ P + lam * np.eye(n), P.T @ F).T + null = _null_coefficients(P, F, lam, draws, block, rng) + mu = null.mean(axis=0) + sd = null.std(axis=0, ddof=1) if draws > 1 else np.zeros((n, n)) + dev = A - mu + z = np.divide(dev, sd, out=np.zeros((n, n)), where=sd > _EPS) + p_norm = np.vectorize(lambda v: math.erfc(abs(v) / math.sqrt(2.0)))(z) if n else np.zeros((0, 0)) + p_rank = (1.0 + (np.abs(null - mu[None]) >= np.abs(dev)[None] - 1e-15).sum(axis=0)) / (1.0 + draws) + off = ~np.eye(n, dtype=bool) + mask = np.zeros((n, n), dtype=bool) + mask[off] = benjamini_hochberg(p_norm[off], alpha) + mask &= sd > _EPS + pairs = n * (n - 1) + return {'A': A, 'z': z, 'p': p_norm, 'p_rank': p_rank, 'mask': mask, 'null_mean': mu, 'null_sd': sd, + 'density': float(mask.sum() / pairs) if pairs else 0.0, 'significant': int(mask.sum()), + 'draws': int(draws), 'block': int(block), 'alpha': float(alpha)} + + +def effective_connectivity(X: Any, *, ridge: float = 1e-2, null_draws: int = 99, block: int | None = None, + alpha: float = 0.05, seed: int = 0, standardize: bool = True) -> dict[str, Any]: + """Ridge VAR(1) effective connectivity with a block-permutation significance mask. + + ``A[target, source]`` comes from :func:`var1_fit`. For every target the null refits its ridge regression with + its own past intact and the other sources block-permuted jointly in time (``null_draws`` draws, block length + ``round((T-1)^(1/3))`` by default), which keeps each source's autocorrelation inside blocks but breaks lagged + coupling. Each edge gets ``z = (A - mean_null) / sd_null`` and a two-sided normal p-value; the mask is + Benjamini-Hochberg at FDR ``alpha`` over the off-diagonal edges. Rank p-values ``(1 + #{|null| >= |A|}) / + (1 + draws)`` are reported too. Lagged regression measures predictive (Granger-style) influence only.""" + P, F, lam = _var_design(X, ridge, standardize) + draws = _check_int('null_draws', null_draws, 2, 100_000) + block = _default_block(P.shape[0]) if block is None else _check_int('block', block, 1, P.shape[0]) + alpha = _check_float('alpha', alpha, 0.0, 1.0) + rng = np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _PERM_OFFSET) + out = _ec_from_design(P, F, lam, draws, block, alpha, rng) + out['ridge'] = float(ridge) + return out + + +def auroc(scores: Any, labels: Any) -> float | None: + """Area under the ROC curve via the Mann-Whitney statistic (average ranks for ties); ``None`` if a class is empty.""" + from scipy.stats import rankdata + s = np.asarray(scores, dtype=np.float64).ravel() + y = np.asarray(labels).ravel().astype(bool) + if s.shape != y.shape or not np.all(np.isfinite(s)): + raise ValueError('scores must be finite and match labels') + pos, neg = int(y.sum()), int((~y).sum()) + if pos == 0 or neg == 0: + return None + r = rankdata(s) + return float((r[y].sum() - pos * (pos + 1) / 2.0) / (pos * neg)) + + +# ====================================================================== structure and coupling +def structural_matrix(n: int, src: Any, dst: Any, weight: Any, *, absolute: bool = True, + symmetric: bool = False) -> np.ndarray: + """Dense ``(n, n)`` structural matrix ``W[src, dst]`` (duplicate edges summed, diagonal zeroed). + ``absolute`` takes ``|w|``; ``symmetric`` returns ``W + W.T``.""" + n = _check_int('n', n, 1, 100_000) + s = np.asarray(src) + d = np.asarray(dst) + w = np.asarray(weight, dtype=np.float64) + 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')): + raise ValueError('src, dst and weight must be 1-D arrays of equal length (integer endpoints)') + if s.size and (s.min() < 0 or s.max() >= n or d.min() < 0 or d.max() >= n): + raise ValueError('edge endpoint out of range') + if not np.all(np.isfinite(w)): + raise ValueError('weights must be finite') + W = np.zeros((n, n)) + np.add.at(W, (s.astype(np.int64), d.astype(np.int64)), np.abs(w) if absolute else w) + np.fill_diagonal(W, 0.0) + return W + W.T if symmetric else W + + +def weighted_communicability(S: Any) -> np.ndarray: + """Weighted communicability ``exp(D^-1/2 S D^-1/2)`` (Crofts & Higham, 2009, eq. 2.2) of a symmetric + non-negative matrix, ``D = diag(sum_k S_ik)``; isolated nodes keep their (zero) rows.""" + S = _square('S', S) + if not np.allclose(S, S.T, rtol=1e-9, atol=1e-12) or np.any(S < 0.0): + raise ValueError('S must be symmetric and non-negative') + S = 0.5 * (S + S.T) + d = S.sum(axis=1) + inv = np.where(d > _EPS, 1.0 / np.sqrt(np.where(d > _EPS, d, 1.0)), 0.0) + N = inv[:, None] * S * inv[None, :] + vals, vecs = np.linalg.eigh(N) + return (vecs * np.exp(vals)[None, :]) @ vecs.T + + +def _spearman(a: np.ndarray, b: np.ndarray) -> float | None: + from scipy.stats import rankdata + if a.size < 3 or np.ptp(a) <= 0.0 or np.ptp(b) <= 0.0: + return None + ra, rb = rankdata(a), rankdata(b) + ra -= ra.mean() + rb -= rb.mean() + den = math.sqrt(float((ra * ra).sum() * (rb * rb).sum())) + return float(np.clip((ra * rb).sum() / den, -1.0, 1.0)) if den > 0 else None + + +def structure_function_coupling(structure: Any, fc: Any) -> dict[str, Any]: + """Spearman coupling between symmetric structural weights and FC over node pairs ``i < j``. + + ``structure`` is any non-negative ``(n, n)`` matrix (it is symmetrised as ``(S + S.T) / 2``). Reports the + coupling over all pairs and over structurally connected pairs, against signed and absolute FC, and the + same for weighted communicability (an analytic predictor that also credits indirect walks).""" + S = _square('structure', structure) + F = _square('fc', fc, S.shape[0]) + if np.any(S < 0.0): + raise ValueError('structure must be non-negative') + S = 0.5 * (S + S.T) + np.fill_diagonal(S, 0.0) + n = S.shape[0] + iu = np.triu_indices(n, 1) + s, f = S[iu], F[iu] + conn = s > 0.0 + G = weighted_communicability(S) + g = G[iu] + return {'pairs': int(s.size), 'connected_pairs': int(conn.sum()), + 'sc_fc_spearman': _spearman(s, f), 'sc_absfc_spearman': _spearman(s, np.abs(f)), + 'sc_fc_spearman_connected': _spearman(s[conn], f[conn]) if conn.sum() >= 3 else None, + 'communicability_fc_spearman': _spearman(g, f), + 'communicability_absfc_spearman': _spearman(g, np.abs(f)), + 'mean_fc_connected': float(f[conn].mean()) if conn.any() else None, + 'mean_fc_unconnected': float(f[~conn].mean()) if (~conn).any() else None} + + +def modularity(W: Any, labels: Any) -> float: + """Newman-Girvan modularity ``Q = (1/2m) sum_ij (W_ij - k_i k_j / 2m) [c_i == c_j]`` of a symmetric + non-negative weight matrix (0 for an empty graph).""" + A = _square('W', W) + if np.any(A < 0.0): + raise ValueError('W must be non-negative') + A = 0.5 * (A + A.T) + lab = np.asarray(labels) + if lab.shape != (A.shape[0],): + raise ValueError('labels must have one entry per node') + two_m = float(A.sum()) + if two_m <= _EPS: + return 0.0 + k = A.sum(axis=1) + same = lab[:, None] == lab[None, :] + return float(((A - np.outer(k, k) / two_m) * same).sum() / two_m) + + +def fc_communities(fc: Any, *, max_communities: int = 8) -> dict[str, Any]: + """Leading-eigenvector communities (Newman, 2006) of the positive part of an FC matrix. + + Recursive bisection: a group g splits by the signs of the leading eigenvector of its generalised modularity + matrix ``B^(g)_ij = B_ij - delta_ij sum_{l in g} B_il`` while the leading eigenvalue and the gain + ``s^T B^(g) s / 4m`` are positive and fewer than ``max_communities`` groups exist. No vertex-moving + refinement, so the reported modularity is a proxy (a lower bound on the maximum).""" + F = _square('fc', fc) + max_communities = _check_int('max_communities', max_communities, 1, 4096) + W = np.clip(0.5 * (F + F.T), 0.0, None) + np.fill_diagonal(W, 0.0) + n = W.shape[0] + two_m = float(W.sum()) + labels = np.zeros(n, dtype=np.int64) + if two_m <= _EPS or n < 2: + return {'labels': labels, 'communities': 1, 'modularity': 0.0} + k = W.sum(axis=1) + B = W - np.outer(k, k) / two_m + pending, final = [np.arange(n)], [] + while pending: + g = pending.pop(0) + if g.size < 2 or len(final) + len(pending) + 1 >= max_communities: + final.append(g) + continue + Bg = B[np.ix_(g, g)].copy() + Bg[np.diag_indices(g.size)] -= Bg.sum(axis=1) + vals, vecs = np.linalg.eigh(Bg) + lead = vecs[:, -1] + s = np.where(lead >= 0.0, 1.0, -1.0) + gain = float(s @ Bg @ s) / (2.0 * two_m) + tol = 1e-10 * (1.0 + float(np.abs(vals).max())) + if vals[-1] <= tol or gain <= 1e-12 or np.all(s == s[0]): + final.append(g) + continue + pending += [g[s > 0], g[s < 0]] + final.sort(key=lambda grp: int(grp.min())) + for c, grp in enumerate(final): + labels[grp] = c + return {'labels': labels, 'communities': len(final), 'modularity': modularity(W, labels)} + + +# ====================================================================== live observer +_METRIC_INT = ('computed_at', 'rows', 'constant_units') +_METRIC_OPT_INT = ('fc_communities', 'dfc_window', 'dfc_windows', 'dfc_states', 'dfc_transitions', 'ec_significant') +_METRIC_OPT_FLOAT = ('mean_abs_fc', 'fc_modularity', 'dfc_silhouette', 'dfc_mean_dwell_windows', + 'dfc_mean_dwell_steps', 'ec_density') +_METRIC_KEYS = _METRIC_INT + _METRIC_OPT_INT + _METRIC_OPT_FLOAT + ('ec_top_edges',) +_EDGE_KEYS = ('source', 'target', 'weight', 'z', 'significant') + + +class ConnectivityObserver: + """Read-only live observer: FC, dynamic FC states and ridge-VAR(1) EC over a bounded activity history. + + * A deterministic subset of at most ``max_units`` observed units (seeded) is kept in a ring buffer of + ``history`` rows. ``observe`` copies the values; it never writes to its input. + * Metrics are recomputed at most every ``max(8, window // 4)`` observations, once ``window`` rows exist: + static FC and EC on the last ``window`` rows, dynamic FC on the whole buffer (window ``max(8, window // 4)``, + step half of it). EC uses ``ec_null_draws`` per-target block-permutation draws seeded by + ``(seed, observed steps)``, so results do not depend on how often ``summary`` is called. + * ``summary()`` returns the cached metrics: mean |FC|, the FC modularity proxy and community count, the + number of dFC states with silhouette and mean dwell, EC density with the top-5 directed edges by |z|, and + the observed step count. Unit indices refer to positions in the observed vector. + * ``window`` defaults to 128; the FrontierSpecV1 name ``fc_window`` is accepted as the same parameter + (clipped to ``history``), and the spec parameters of other observers are accepted and ignored.""" + + module_id = MODULE_ID + + def __init__(self, n_units: int, *, seed: int = 7, history: int = 256, window: int | None = None, + max_units: int = 32, k_max: int = 4, ec_null_draws: int = 31, ridge: float = 0.05, + alpha: float = 0.05, min_silhouette: float = 0.25, **params: Any) -> None: + unknown = sorted(set(params) - _SPEC_OBSERVER_PARAMS) + if unknown: + raise ValueError(f'unknown ConnectivityObserver parameters: {unknown}') + self.n_units = _check_int('n_units', n_units, 2, 1_000_000) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + self.history = _check_int('history', history, 16, 8192) + fc_window = params.get('fc_window') # FrontierSpecV1 name of the static FC / EC window + if fc_window is not None: + fc_window = min(_check_int('fc_window', fc_window, 8, 1_000_000), self.history) + if window is not None and window != fc_window: + raise ValueError('window and fc_window disagree') + if window is None: + window = 128 if fc_window is None else fc_window + self.window = _check_int('window', window, 8, self.history) + self.max_units = _check_int('max_units', max_units, 2, 256) + self.k_max = _check_int('k_max', k_max, 2, 8) + self.ec_null_draws = _check_int('ec_null_draws', ec_null_draws, 2, 999) + self.ridge = _check_float('ridge', ridge, 1e-6, 1e3) + self.alpha = _check_float('alpha', alpha, 1e-6, 0.5) + self.min_silhouette = _check_float('min_silhouette', min_silhouette, 0.0, 1.0) + self.recompute_every = max(8, self.window // 4) + self.dfc_window = max(8, self.window // 4) + m = min(self.n_units, self.max_units) + if m == self.n_units: + units = np.arange(m, dtype=np.int64) + else: + units = np.sort(np.random.default_rng(self.seed + _OBS_UNITS_OFFSET).choice(self.n_units, m, replace=False)) + self._units = units.astype(np.int64) + self.reset() + + @classmethod + def from_spec(cls, n_units: int, spec: Any) -> 'ConnectivityObserver': + """Build from a ``FrontierSpecV1`` (``seed``, ``history``, ``fc_window`` clipped to ``history``).""" + from .spec import FrontierSpecV1 + if not isinstance(spec, FrontierSpecV1): + raise ValueError('spec must be a FrontierSpecV1') + return cls(n_units, seed=int(spec.seed), history=int(spec.history), + window=min(int(spec.fc_window), int(spec.history))) + + def reset(self) -> None: + self._buf = np.zeros((self.history, self._units.size)) + self._steps = 0 + self._last = -1 + self._metrics: dict[str, Any] | None = None + + @property + def observed_steps(self) -> int: + return self._steps + + @property + def units(self) -> np.ndarray: + return self._units.copy() + + def _rows(self) -> np.ndarray: + count = min(self._steps, self.history) + if self._steps <= self.history: + return self._buf[:count].copy() + pos = self._steps % self.history + return np.concatenate([self._buf[pos:], self._buf[:pos]]) + + def observe(self, x: np.ndarray) -> None: + try: + v = np.array(x, dtype=np.float64) # private copy: the caller's array is never touched + except (TypeError, ValueError) as exc: + raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}') from exc + if v.shape != (self.n_units,) or not np.all(np.isfinite(v)): + raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}') + self._buf[self._steps % self.history] = v[self._units] + self._steps += 1 + if self._steps >= self.window and (self._last < 0 or self._steps - self._last >= self.recompute_every): + self._metrics = self._compute() + self._last = self._steps + + def _compute(self) -> dict[str, Any]: + rows = self._rows() + static = rows[-self.window:] + fc = _pearson(static) + ok = np.diag(fc) > 0.5 + idx = np.flatnonzero(ok) + m: dict[str, Any] = {k: None for k in _METRIC_KEYS} + m.update(computed_at=int(self._steps), rows=int(rows.shape[0]), constant_units=int((~ok).sum()), + ec_top_edges=[]) + if idx.size < 2: + return m + sub = fc[np.ix_(idx, idx)] + iu = np.triu_indices(idx.size, 1) + m['mean_abs_fc'] = float(np.abs(sub[iu]).mean()) + com = fc_communities(sub) + m['fc_modularity'] = float(com['modularity']) + m['fc_communities'] = int(com['communities']) + data = rows[:, idx] + w = min(self.dfc_window, data.shape[0]) + step = max(1, w // 2) + n_win = (data.shape[0] - w) // step + 1 + if n_win >= 3: + d = dynamic_fc_states(data, window=w, step=step, k_max=self.k_max, min_silhouette=self.min_silhouette, + seed=self.seed, n_init=4) + m.update(dfc_window=int(w), dfc_windows=int(d['windows']), dfc_states=int(d['n_states']), + dfc_silhouette=None if d['best_silhouette'] is None else float(d['best_silhouette']), + dfc_mean_dwell_windows=float(d['mean_dwell_windows']), + dfc_mean_dwell_steps=float(d['mean_dwell_samples']), dfc_transitions=int(d['transitions'])) + Z, _ok = _zscore_columns(static[:, idx]) + P = Z[:-1] - Z[:-1].mean(axis=0) + F = Z[1:] - Z[1:].mean(axis=0) + rng = np.random.default_rng([self.seed + _OBS_PERM_OFFSET, self._steps]) + ec = _ec_from_design(P, F, self.ridge * P.shape[0], self.ec_null_draws, _default_block(P.shape[0]), + self.alpha, rng) + m['ec_density'] = float(ec['density']) + m['ec_significant'] = int(ec['significant']) + off = ~np.eye(idx.size, dtype=bool) + tgt, src = np.nonzero(off) + mag = np.abs(ec['z'][tgt, src]) + order = np.lexsort((src, tgt, -mag))[:_TOP_EDGES] + units = self._units[idx] + m['ec_top_edges'] = [{'source': int(units[src[e]]), 'target': int(units[tgt[e]]), + 'weight': float(ec['A'][tgt[e], src[e]]), 'z': float(ec['z'][tgt[e], src[e]]), + 'significant': bool(ec['mask'][tgt[e], src[e]])} for e in order] + return m + + def summary(self) -> dict[str, Any]: + out: dict[str, Any] = {'module': MODULE_ID, 'evidence_tier': 'synthetic_abstraction', + 'n_units': self.n_units, 'analysed_units': int(self._units.size), + 'unit_sample': self._units.tolist(), 'history': self.history, 'window': self.window, + 'recompute_every': self.recompute_every, 'observed_steps': self._steps, + 'buffered': min(self._steps, self.history), 'ready': self._metrics is not None} + metrics = self._metrics if self._metrics is not None else {k: None for k in _METRIC_KEYS} + for key in _METRIC_KEYS: + value = metrics[key] + out[key] = [dict(e) for e in value] if key == 'ec_top_edges' and value is not None else value + if out['ec_top_edges'] is None: + out['ec_top_edges'] = [] + return out + + def _config(self) -> dict[str, Any]: + return {'n_units': self.n_units, 'seed': self.seed, 'history': self.history, 'window': self.window, + 'max_units': self.max_units, 'k_max': self.k_max, 'ec_null_draws': self.ec_null_draws, + 'ridge': self.ridge, 'alpha': self.alpha, 'min_silhouette': self.min_silhouette} + + def export_state(self) -> dict[str, Any]: + metrics = None if self._metrics is None else { + k: ([dict(e) for e in v] if k == 'ec_top_edges' else v) for k, v in self._metrics.items()} + return {'module': MODULE_ID, 'schema': OBSERVER_STATE_SCHEMA, **self._config(), 'units': self._units.tolist(), + 'buffer': self._buf.tolist(), 'steps': self._steps, 'last': self._last, 'metrics': metrics} + + def _validate_metrics(self, metrics: Any, steps: int, last: int) -> dict[str, Any] | None: + if last < 0: + if metrics is not None: + raise ValueError('connectivity observer state has metrics but no recompute') + return None + if not isinstance(metrics, Mapping) or set(metrics) != set(_METRIC_KEYS): + raise ValueError('connectivity observer metrics have the wrong keys') + out: dict[str, Any] = {} + for key in _METRIC_INT: + out[key] = _check_int(f'metrics.{key}', metrics[key], 0, 2**62) + for key in _METRIC_OPT_INT: + out[key] = None if metrics[key] is None else _check_int(f'metrics.{key}', metrics[key], 0, 2**62) + for key in _METRIC_OPT_FLOAT: + out[key] = None if metrics[key] is None else _check_float(f'metrics.{key}', metrics[key], -1.0, 1e12) + if out['computed_at'] != last or out['rows'] != min(last, self.history) or out['constant_units'] > self._units.size: + raise ValueError('connectivity observer metrics do not match the recompute step') + for key in ('mean_abs_fc', 'ec_density'): + if out[key] is not None and not 0.0 <= out[key] <= 1.0: + raise ValueError(f'metrics.{key} must lie in [0, 1]') + edges = metrics['ec_top_edges'] + if not isinstance(edges, list) or len(edges) > _TOP_EDGES: + raise ValueError('metrics.ec_top_edges must be a list of at most 5 edges') + clean = [] + allowed = set(self._units.tolist()) + for e in edges: + if not isinstance(e, Mapping) or set(e) != set(_EDGE_KEYS): + raise ValueError('ec_top_edges entries have the wrong keys') + s = _check_int('edge.source', e['source'], 0, self.n_units - 1) + t = _check_int('edge.target', e['target'], 0, self.n_units - 1) + if s == t or s not in allowed or t not in allowed or type(e['significant']) is not bool: + raise ValueError('ec_top_edges entry is invalid') + clean.append({'source': s, 'target': t, 'weight': _check_float('edge.weight', e['weight'], -1e12, 1e12), + 'z': _check_float('edge.z', e['z'], -1e12, 1e12), 'significant': e['significant']}) + out['ec_top_edges'] = clean + return out + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate the whole state first; nothing changes unless every check passes.""" + if not isinstance(state, Mapping) or state.get('module') != MODULE_ID or state.get('schema') != OBSERVER_STATE_SCHEMA: + raise ValueError('state is not a connectivity observer state') + for key, value in self._config().items(): + if state.get(key) != value: + raise ValueError(f'connectivity observer state does not match this observer ({key})') + if state.get('units') != self._units.tolist(): + raise ValueError('connectivity observer state units do not match this observer') + try: + buf = np.array(state.get('buffer'), dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('buffer must be numeric') from exc + if buf.shape != self._buf.shape or not np.all(np.isfinite(buf)): + raise ValueError('connectivity observer buffer has the wrong shape or non-finite values') + steps = _check_int('steps', state.get('steps'), 0, 2**62) + last = state.get('last') + if last != -1: + last = _check_int('last', last, self.window, steps) + if steps >= self.window: + if last == -1 or steps - last >= self.recompute_every: + raise ValueError('connectivity observer state skipped a scheduled recompute') + if (last - self.window) % self.recompute_every: + raise ValueError('connectivity observer state recomputed off the schedule') + elif last != -1: + raise ValueError('connectivity observer state recomputed before the window filled') + if steps < self.history and np.any(buf[steps:] != 0.0): + raise ValueError('connectivity observer buffer has values beyond the observed steps') + metrics = self._validate_metrics(state.get('metrics'), steps, int(last)) + self._buf, self._steps, self._last, self._metrics = buf, steps, int(last), metrics + + +# ====================================================================== lab experiment +_DEFAULTS: dict[str, Any] = { + 'var_units': 8, 'var_steps': 3000, 'var_edge_prob': 0.15, 'var_spectral_radius': 0.8, + 'ec_ridge': 1e-2, 'ec_null_draws': 199, 'ec_alpha': 0.05, + 'chain_steps': 4000, 'chain_coupling': 0.8, 'pc_ridge': 1e-3, + 'switch_units': 6, 'switch_block': 150, 'switch_blocks': 8, 'switch_corr': 0.8, + 'dfc_window': 40, 'dfc_step': 8, 'dfc_k_max': 4, 'min_silhouette': 0.25, + 'topologies': ('clustered', 'ring_lattice', 'hub_skewed', 'multi_region'), 'neurons': 32, 'nw_steps': 600, + 'nw_burn_in': 50, 'mechanisms': (), 'nw_null_draws': 99, 'nw_pc_ridge': 0.1, +} +_QUICK: dict[str, Any] = {'var_steps': 1500, 'ec_null_draws': 99, 'chain_steps': 2000, 'switch_blocks': 6, + 'topologies': ('clustered', 'ring_lattice', 'hub_skewed'), 'neurons': 24, 'nw_steps': 240, + 'nw_burn_in': 40, 'nw_null_draws': 49} + + +def _validate_config(cfg: dict[str, Any]) -> dict[str, Any]: + from ..neuroweave.spec import MECHANISM_IDS, TOPOLOGIES + c = dict(cfg) + c['var_units'] = _check_int('var_units', c['var_units'], 3, 64) + c['var_steps'] = _check_int('var_steps', c['var_steps'], 100, 1_000_000) + c['var_edge_prob'] = _check_float('var_edge_prob', c['var_edge_prob'], 0.01, 0.9) + c['var_spectral_radius'] = _check_float('var_spectral_radius', c['var_spectral_radius'], 0.05, 0.99) + c['ec_ridge'] = _check_float('ec_ridge', c['ec_ridge'], 0.0, 1e3) + c['ec_null_draws'] = _check_int('ec_null_draws', c['ec_null_draws'], 2, 100_000) + c['ec_alpha'] = _check_float('ec_alpha', c['ec_alpha'], 1e-6, 0.5) + c['chain_steps'] = _check_int('chain_steps', c['chain_steps'], 100, 10_000_000) + c['chain_coupling'] = _check_float('chain_coupling', c['chain_coupling'], 0.1, 5.0) + c['pc_ridge'] = _check_float('pc_ridge', c['pc_ridge'], 0.0, 1.0) + c['switch_units'] = _check_int('switch_units', c['switch_units'], 4, 64) + c['switch_block'] = _check_int('switch_block', c['switch_block'], 20, 1_000_000) + c['switch_blocks'] = _check_int('switch_blocks', c['switch_blocks'], 4, 10_000) + c['switch_corr'] = _check_float('switch_corr', c['switch_corr'], 0.1, 0.95) + c['dfc_window'] = _check_int('dfc_window', c['dfc_window'], 8, c['switch_block']) + c['dfc_step'] = _check_int('dfc_step', c['dfc_step'], 1, c['dfc_window']) + c['dfc_k_max'] = _check_int('dfc_k_max', c['dfc_k_max'], 2, 8) + c['min_silhouette'] = _check_float('min_silhouette', c['min_silhouette'], 0.0, 1.0) + try: + topologies = tuple(c['topologies']) + mechanisms = tuple(c['mechanisms']) + except TypeError as exc: + raise ValueError('topologies and mechanisms must be sequences of names') from exc + if not topologies or len(set(topologies)) != len(topologies) or any(t not in TOPOLOGIES for t in topologies): + raise ValueError(f'topologies must be distinct names from {TOPOLOGIES}') + if any(m not in MECHANISM_IDS for m in mechanisms): + raise ValueError('mechanisms must be NEUROWEAVE mechanism ids') + c['topologies'], c['mechanisms'] = list(topologies), list(mechanisms) + c['neurons'] = _check_int('neurons', c['neurons'], 8, 512) + c['nw_steps'] = _check_int('nw_steps', c['nw_steps'], 40, 100_000) + c['nw_burn_in'] = _check_int('nw_burn_in', c['nw_burn_in'], 0, c['nw_steps'] - 30) + if c['nw_steps'] - c['nw_burn_in'] < c['dfc_window']: + raise ValueError('nw_steps - nw_burn_in must be at least dfc_window (the NEUROWEAVE dFC needs one window)') + c['nw_null_draws'] = _check_int('nw_null_draws', c['nw_null_draws'], 2, 100_000) + c['nw_pc_ridge'] = _check_float('nw_pc_ridge', c['nw_pc_ridge'], 1e-6, 10.0) + return c + + +def _simulate_sparse_var(rng: np.random.Generator, n: int, steps: int, edge_prob: float, + radius: float) -> tuple[np.ndarray, np.ndarray]: + off = ~np.eye(n, dtype=bool) + support = (rng.random((n, n)) < edge_prob) & off + if not support.any(): + i, j = np.argwhere(off)[int(rng.integers(n * (n - 1)))] + support[i, j] = True + A = np.zeros((n, n)) + k = int(support.sum()) + A[support] = rng.uniform(0.25, 0.5, k) * rng.choice(np.array([-1.0, 1.0]), k) + A[np.diag_indices(n)] = rng.uniform(0.2, 0.5, n) + rho = float(np.max(np.abs(np.linalg.eigvals(A)))) + if rho > radius: + A *= radius / rho + burn = 100 + noise = rng.standard_normal((steps + burn, n)) + X = np.empty((steps + burn, n)) + x = np.zeros(n) + for t in range(steps + burn): + x = A @ x + noise[t] + X[t] = x + return A, X[burn:] + + +def _validate_var(seed: int, c: Mapping[str, Any]) -> dict[str, Any]: + rng = np.random.default_rng(seed + _VAR_OFFSET) + A, X = _simulate_sparse_var(rng, c['var_units'], c['var_steps'], c['var_edge_prob'], c['var_spectral_radius']) + ec = effective_connectivity(X, ridge=c['ec_ridge'], null_draws=c['ec_null_draws'], alpha=c['ec_alpha'], + seed=seed, standardize=False) + n = A.shape[0] + off = ~np.eye(n, dtype=bool) + truth = (A != 0.0)[off] + est = ec['A'][off] + mask = ec['mask'][off] + tp, fp = int((mask & truth).sum()), int((mask & ~truth).sum()) + return {'seed': seed, 'units': n, 'steps': c['var_steps'], 'true_edges': int(truth.sum()), + 'spectral_radius': float(np.max(np.abs(np.linalg.eigvals(A)))), + 'support_auroc': auroc(np.abs(est), truth), + 'sign_accuracy': float((np.sign(est[truth]) == np.sign(A[off][truth])).mean()), + 'max_abs_coefficient_error': float(np.max(np.abs(ec['A'] - A))), + 'mask_true_positives': tp, 'mask_false_positives': fp, + 'mask_precision': float(tp / (tp + fp)) if tp + fp else None, + 'mask_recall': float(tp / max(1, int(truth.sum()))), 'ec_density': ec['density'], 'block': ec['block']} + + +def _validate_chain(seed: int, c: Mapping[str, Any]) -> dict[str, Any]: + rng = np.random.default_rng(seed + _CHAIN_OFFSET) + T, a = c['chain_steps'], c['chain_coupling'] + x = rng.standard_normal(T) + y = a * x + rng.standard_normal(T) + z = a * y + rng.standard_normal(T) + X = np.column_stack([x, y, z]) + fc = pearson_fc(X) + pc = partial_correlation(X, ridge=c['pc_ridge']) + exact = {'xy': a / (1.0 + a * a), 'yz': a / math.sqrt(1.0 + a * a), 'xz': 0.0, + 'fc_xz': a * a / math.sqrt(a * a * (a * a + 1.0) + 1.0)} + tol = 4.0 / math.sqrt(T) + est = {'xy': float(pc[0, 1]), 'yz': float(pc[1, 2]), 'xz': float(pc[0, 2])} + return {'seed': seed, 'steps': T, 'tolerance': tol, 'partial': est, 'exact_partial': exact, + 'fc_xz': float(fc[0, 2]), 'spearman_xz': float(spearman_fc(X)[0, 2]), + 'max_partial_error': float(max(abs(est[k] - exact[k]) for k in ('xy', 'yz', 'xz')))} + + +def _two_state_cov(n: int, r: float) -> tuple[np.ndarray, np.ndarray]: + h = n // 2 + A, B = np.eye(n), np.eye(n) + A[:h, :h] = r + B[h:, h:] = r + np.fill_diagonal(A, 1.0) + np.fill_diagonal(B, 1.0) + return A, B + + +def _validate_switching(seed: int, c: Mapping[str, Any]) -> dict[str, Any]: + rng = np.random.default_rng(seed + _SWITCH_OFFSET) + n, L, nb = c['switch_units'], c['switch_block'], c['switch_blocks'] + CA, CB = _two_state_cov(n, c['switch_corr']) + chol = [np.linalg.cholesky(CA), np.linalg.cholesky(CB)] + X = np.vstack([rng.standard_normal((L, n)) @ chol[b % 2].T for b in range(nb)]) + w, step = c['dfc_window'], c['dfc_step'] + kw = dict(window=w, step=step, k_max=c['dfc_k_max'], min_silhouette=c['min_silhouette'], seed=seed) + d = dynamic_fc_states(X, **kw) + starts = d['starts'] + pure = (starts // L) == ((starts + w - 1) // L) + truth = (starts // L) % 2 + accuracy = None + if d['n_states'] == 2 and pure.any(): + lab = d['labels'][pure] + accuracy = float(max((lab == truth[pure]).mean(), (lab != truth[pure]).mean())) + rng2 = np.random.default_rng(seed + _STATIONARY_OFFSET) + Xs = rng2.standard_normal((L * nb, n)) @ np.linalg.cholesky(0.5 * (CA + CB)).T + ds = dynamic_fc_states(Xs, **kw) + return {'seed': seed, 'units': n, 'block': L, 'blocks': nb, 'windows': d['windows'], 'n_states': d['n_states'], + 'silhouette': d['silhouette'], 'pure_windows': int(pure.sum()), 'pure_window_accuracy': accuracy, + 'mean_dwell_samples': d['mean_dwell_samples'], 'expected_dwell_samples_upper': float(L), + 'stationary_control_states': ds['n_states'], 'stationary_control_silhouette': ds['silhouette']} + + +def _neuroweave_run(topology: str, seed: int, c: Mapping[str, Any]) -> dict[str, Any]: + from ..neuroweave.engine import NeuroWeaveEngine + from ..neuroweave.experiments import engine_topology, make_spec + from ..neuroweave.tasks import make_stream + from ..neuroweave.topology import topology_metrics + steps = c['nw_steps'] + engine = NeuroWeaveEngine(make_spec(c['mechanisms'], seed=seed, neurons=c['neurons'], topology=topology, + steps=steps)) + stream = make_stream(seed, steps) + outs = [] + for i in range(steps): # frozen dynamics: the structure that generates the activity stays fixed + outs.append(np.array(engine.step(stream.inputs[i], stream.sensory[i], reward=0.0, learn=False)['output'])) + X = np.stack(outs)[c['nw_burn_in']:] + topo = engine_topology(engine) + n = int(topo.n) + W = structural_matrix(n, topo.src, topo.dst, topo.weight, absolute=False) + S = np.abs(W) + np.abs(W).T + fc = pearson_fc(X) + pc = partial_correlation(X, ridge=c['nw_pc_ridge']) + ok = np.diag(fc) > 0.5 + iu = np.triu_indices(n, 1) + both = ok[iu[0]] & ok[iu[1]] + coupling = structure_function_coupling(S, fc) + ec = effective_connectivity(X, ridge=c['ec_ridge'], null_draws=c['nw_null_draws'], alpha=c['ec_alpha'], + seed=seed) + off = ~np.eye(n, dtype=bool) + present = (W.T != 0.0) # present[target, source]: a synapse source -> target exists + sig = ec['mask'] & off + sign_ok = np.sign(ec['A'][sig & present]) == np.sign(W.T[sig & present]) + d = dynamic_fc_states(X, window=c['dfc_window'], step=c['dfc_step'], k_max=c['dfc_k_max'], + min_silhouette=c['min_silhouette'], seed=seed) + com = fc_communities(fc[np.ix_(ok, ok)]) if ok.sum() >= 2 else {'modularity': 0.0, 'communities': 1} + tm = topology_metrics(topo) + return { + 'seed': seed, 'neurons': n, 'samples': int(X.shape[0]), 'synapses': int(topo.edges), + 'constant_units': int((~ok).sum()), + 'structure': {k: tm[k] for k in ('density', 'clustering_mean', 'modularity', 'mean_shortest_path', + 'global_efficiency', 'inter_region_edge_fraction')}, + 'mean_abs_fc': float(np.abs(fc[iu][both]).mean()) if both.any() else None, + 'mean_abs_partial': float(np.abs(pc[iu][both]).mean()) if both.any() else None, + 'fc_modularity_proxy': float(com['modularity']), 'fc_communities': int(com['communities']), + 'coupling': coupling, + 'ec': {'density': ec['density'], 'significant': ec['significant'], 'block': ec['block'], + 'structure_auroc': auroc(np.abs(ec['A'][off]), present[off]), + 'significant_on_synapses_fraction': float((sig & present).sum() / sig.sum()) if sig.any() else None, + 'sign_agreement_on_synapses': float(sign_ok.mean()) if sign_ok.size else None}, + 'dfc': {'n_states': d['n_states'], 'best_silhouette': d['best_silhouette'], 'windows': d['windows'], + 'mean_dwell_samples': d['mean_dwell_samples']}, + } + + +def _finite_tree(obj: Any) -> bool: + if isinstance(obj, Mapping): + return all(_finite_tree(v) for v in obj.values()) + if isinstance(obj, (list, tuple)): + return all(_finite_tree(v) for v in obj) + if isinstance(obj, (float, np.floating)): + return math.isfinite(float(obj)) + return True + + +def _mean_of(values: Sequence[Any]) -> float | None: + v = [float(x) for x in values if x is not None] + return float(np.mean(v)) if v else None + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Known-answer validation of the connectivity estimators, then a descriptive NEUROWEAVE report. + + Validation (per seed, checks must hold for every seed): (1) a sparse stable VAR(1) with known ``A``: EC support + AUROC > 0.9, sign accuracy on true edges >= 0.9 and pooled mask precision >= 0.8; (2) a Gaussian chain + X -> Y -> Z: partial correlations within ``4 / sqrt(T)`` of their exact values (X-Z exactly 0) while + FC(X, Z) stays clearly non-zero; (3) a two-state switching process: dFC finds 2 states with pure-window + accuracy >= 0.9, and a stationary control with the averaged covariance gives 1 state. Then (4) NEUROWEAVE: for + each topology the frozen engine runs on the task stream and the module reports structure-function coupling, + communicability coupling, EC/structure agreement and dFC/FC summaries. Part (4) is descriptive: no verdict is + drawn from it beyond finiteness. ``kind='validation'``, ``verdict`` in ``('pass', 'fail')``.""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds(seeds) + cfg = dict(_DEFAULTS) + if quick: + cfg.update(_QUICK) + unknown = sorted(set(overrides) - set(cfg)) + if unknown: + raise ValueError(f'unknown run_experiment overrides: {unknown}') + cfg.update(overrides) + c = _validate_config(cfg) + t0 = time.perf_counter() + var = [_validate_var(s, c) for s in seeds] + chain = [_validate_chain(s, c) for s in seeds] + switch = [_validate_switching(s, c) for s in seeds] + t_val = time.perf_counter() - t0 + t1 = time.perf_counter() + nw: dict[str, Any] = {} + for topo in c['topologies']: + runs = [_neuroweave_run(topo, s, c) for s in seeds] + nw[topo] = {'per_seed': runs, 'mean': { + 'sc_fc_spearman': _mean_of([r['coupling']['sc_fc_spearman'] for r in runs]), + 'sc_fc_spearman_connected': _mean_of([r['coupling']['sc_fc_spearman_connected'] for r in runs]), + 'communicability_fc_spearman': _mean_of([r['coupling']['communicability_fc_spearman'] for r in runs]), + 'communicability_absfc_spearman': _mean_of([r['coupling']['communicability_absfc_spearman'] for r in runs]), + 'mean_abs_fc': _mean_of([r['mean_abs_fc'] for r in runs]), + 'ec_structure_auroc': _mean_of([r['ec']['structure_auroc'] for r in runs]), + 'ec_density': _mean_of([r['ec']['density'] for r in runs]), + 'dfc_states': _mean_of([r['dfc']['n_states'] for r in runs])}} + t_nw = time.perf_counter() - t1 + tp = sum(v['mask_true_positives'] for v in var) + fp = sum(v['mask_false_positives'] for v in var) + pooled_precision = tp / (tp + fp) if tp + fp else 0.0 + checks = { + 'var_support_auroc_above_0.9': all(v['support_auroc'] is not None and v['support_auroc'] > 0.9 for v in var), + 'var_sign_accuracy_at_least_0.9': all(v['sign_accuracy'] >= 0.9 for v in var), + 'var_mask_pooled_precision_at_least_0.8': bool(pooled_precision >= 0.8), + 'chain_partials_match_exact_values': all(ch['max_partial_error'] <= ch['tolerance'] for ch in chain), + 'chain_fc_xz_clearly_nonzero': all(abs(ch['fc_xz']) > 0.3 for ch in chain), + 'switching_two_states_recovered': all(s['n_states'] == 2 for s in switch), + 'switching_pure_window_accuracy_at_least_0.9': all( + s['pure_window_accuracy'] is not None and s['pure_window_accuracy'] >= 0.9 for s in switch), + 'stationary_control_single_state': all(s['stationary_control_states'] == 1 for s in switch), + 'neuroweave_values_finite': _finite_tree(nw), + } + receipt = harness.base_receipt(MODULE_ID, 'validation', {**c, 'quick': quick, 'seeds': list(seeds)}) + receipt['validations'] = {'var_recovery': var, 'var_pooled_mask_precision': pooled_precision, + 'chain_partial_correlation': chain, 'dfc_switching': switch} + receipt['neuroweave'] = {'per_topology': nw, 'mechanisms': list(c['mechanisms']), + 'note': 'descriptive only: values are reported, no verdict is drawn from them'} + receipt['checks'] = checks + receipt['verdict'] = 'pass' if all(checks.values()) else 'fail' + receipt['verdict_basis'] = 'all_known_answer_checks' if receipt['verdict'] == 'pass' else 'failed_checks: ' + ', '.join( + k for k, v in checks.items() if not v) + nets = len(c['topologies']) * len(seeds) + receipt['estimated_cost'] = { + 'engine_steps': int(nets * c['nw_steps']), + 'ec_null_ridge_solves': int(len(seeds) * c['ec_null_draws'] * c['var_units'] + + nets * c['nw_null_draws'] * c['neurons']), + 'fc_windows': int(sum(s['windows'] for s in switch) * 2)} + receipt['measured_wallclock_s'] = {'validation': t_val, 'neuroweave': t_nw, 'total': time.perf_counter() - t0} + receipt['notes'] = ( + 'Synthetic validation of FC, partial correlation, dFC states and ridge VAR(1) EC on processes with known ' + 'answers, then a descriptive structure-function report on frozen NEUROWEAVE brains (the synapse table ' + 'that generated the activity). EC is lagged predictive influence (Granger-style), not an interventional ' + 'effect; the dFC state count uses a silhouette heuristic (0.25 by default); the FC modularity is a ' + 'leading-eigenvector proxy. Nothing here is imaging data or evidence of biological fidelity.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/continuum_memory.py b/synapse/frontier/continuum_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb5021afc5bd0b17d75f5a2f43c468187b23cdc --- /dev/null +++ b/synapse/frontier/continuum_memory.py @@ -0,0 +1,767 @@ +"""Continuum memory: linear associative memories updated at geometrically spaced periods. + +Inspired by the *continuum memory system* (CMS) of Nested Learning (Behrouz, Razaviyayn, Zhong & Mirrokni, +"Nested Learning: The Illusion of Deep Learning Architectures", NeurIPS 2025; arXiv:2512.24695, Dec 2025) and by +the neural long-term memory of Titans (Behrouz, Zhong & Mirrokni, "Titans: Learning to Memorize at Test Time", +NeurIPS 2025; arXiv:2501.00663, Dec 2024). It is a small synthetic abstraction, not a reproduction of either paper: +linear memories instead of MLP blocks, fixed instead of learned data-dependent gates, no attention and no language +modelling. + +Model +----- +``levels`` linear associative memories ``M_l`` (``value_dim x key_dim``) form an *independent (head-wise)* CMS +(Nested Learning Eq. 74) with a sum aggregation. Level ``l`` reads its own key ``k_l`` (one key per level, i.e. +a level-specific key projection, or one key shared by every level):: + + read: r_l = M_l k_l (``read`` returns every r_l) y = sum_l r_l (``predict``) + loss: L_t = ||y_t - v_t||^2 grad_l = dL_t/dM_l = 2 (y_t - v_t) k_{l,t}^T + +Level ``l`` has period ``P_l = base_period * 2**l``. It accumulates ``grad_l`` over its chunk of ``P_l`` writes, +each evaluated with the memories as they are at that write, and applies the chunk gradient ``G_l`` only when the +chunk closes (Nested Learning Eq. 71). ``G_l`` is the chunk *sum* (Eq. 71 with a constant learning rate) or, with +``chunk_reduce='mean'``, the chunk mean (Eq. 71 with ``lr / P_l``). The update uses Titans' surprise momentum and +forgetting gate (Titans Eqs. 10 and 13) with constant ``momentum`` (Titans' ``eta``) and ``lr`` (``theta``):: + + S_l <- momentum * S_l - lr * G_l + M_l <- (1 - alpha_l) * M_l + S_l + alpha_l = min(max_forget, forget + surprise_forget * mean_chunk_surprise) + +Titans learns ``alpha_t`` as a function of the input; here it is a fixed number, optionally raised by this module's +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 +for an empty memory, towards 1 for a confidently wrong read; Titans' "momentary surprise" is the gradient term +itself). ``M`` and ``S`` are clipped to ``[-bound, bound]`` and every array has a fixed shape, so the state stays +finite and bounded. + +Engine extension +---------------- +``ContinuumMemoryExtension`` stores the predictive association *previous fused task+sensory context -> current +sensory frame* (only when ``ctx['learn']``) and exposes a fixed random projection of the per-level reads for the +current context (a multi-timescale forecast of the next frame) as readout features. It never changes the drive. + +Benchmark +--------- +``run_recall_benchmark`` streams key -> value associations: some recur after short gaps, some after long gaps, +and one-off associations fill the remaining steps as interference. It compares the CMS with a single-level +Titans-style memory holding the same number of entries (one ``value_dim x (levels * key_dim)`` memory reading the +concatenated key) and with a no-memory predictor (running mean of the values), with hyperparameters tuned per +arm on separate tuning seeds. +""" +from __future__ import annotations + +import copy +import itertools +import math +import time +from typing import Any, Callable, Mapping, Sequence + +import numpy as np + +from ..neuroweave.spec import SENSORY_DIM, TASK_INPUT_DIM +from .extension import EngineExtension + +__all__ = ['MODULE_ID', 'RECALL_ID', 'SOURCE', 'EXPERIMENTS', 'CHUNK_REDUCTIONS', 'KIND_CODES', 'ContinuumMemory', + 'ContinuumMemoryExtension', 'make_recall_stream', 'run_recall_benchmark', 'run_experiment', + 'RECALL_DEFAULTS', 'RECALL_QUICK'] + +MODULE_ID = 'continuum_memory' +RECALL_ID = 'continuum_memory_recall' +SOURCE = ('Behrouz, Razaviyayn, Zhong & Mirrokni, "Nested Learning: The Illusion of Deep Learning Architectures", ' + 'NeurIPS 2025, arXiv:2512.24695 (continuum memory system); Behrouz, Zhong & Mirrokni, "Titans: Learning to ' + 'Memorize at Test Time", NeurIPS 2025, arXiv:2501.00663 (surprise momentum and forgetting gate)') +CONTEXT_DIM = TASK_INPUT_DIM + SENSORY_DIM +CHUNK_REDUCTIONS = ('sum', 'mean') +KIND_CODES = {'fresh': 0, 'first': 1, 'short': 2, 'long': 3, 'remap': 4} +_KEY_OFFSET = 51_407 +_FEATURE_OFFSET = 51_419 +_STREAM_OFFSET = 51_431 +_MAX_ABS_INPUT = 1e6 +# Far above any accumulator reachable from valid writes (inputs <= 1e6, |M| <= bound <= 1e6, chunks <= 2**23 writes +# give |acc| < 1e30) and far below float64 overflow, so an imported accumulator can never turn the state into inf/NaN. +_MAX_ACCUMULATOR = 1e100 + + +# ====================================================================== validation helpers +def _check_int(name: str, value: Any, low: int, high: int) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return value + + +def _check_float(name: str, value: Any, low: float, high: float, *, high_open: bool = False, + low_open: bool = False) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + ok = math.isfinite(v) and (v > low if low_open else v >= low) and (v < high if high_open else v <= high) + if not ok: + raise ValueError(f'{name} must be in {"(" if low_open else "["}{low}, {high}{")" if high_open else "]"}') + return v + + +def _finite(name: str, value: Any) -> np.ndarray: + try: + arr = np.asarray(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + if not np.all(np.isfinite(arr)) or float(np.max(np.abs(arr), initial=0.0)) > _MAX_ABS_INPUT: + raise ValueError(f'{name} must be finite with magnitude <= {_MAX_ABS_INPUT:g}') + return arr + + +def _vector(name: str, value: Any, size: int) -> np.ndarray: + arr = _finite(name, value) + if arr.shape != (size,): + raise ValueError(f'{name} must have shape ({size},), got {arr.shape}') + return arr + + +def _array(name: str, value: Any, shape: tuple[int, ...]) -> np.ndarray: + try: + arr = np.asarray(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be a numeric array') from exc + if arr.shape != shape or not np.all(np.isfinite(arr)): + raise ValueError(f'{name} must be a finite array of shape {shape}') + return arr + + +def _check_seeds(name: str, seeds: Any) -> tuple[int, ...]: + try: + out = tuple(seeds) + except TypeError as exc: + raise ValueError(f'{name} must be a sequence of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError(f'{name} must be non-empty and unique') + for s in out: + _check_int(f'{name} entry', s, 0, 2**31 - 1) + return out + + +def _check_pair(name: str, value: Any, low: int, high: int) -> tuple[int, int]: + try: + lo, hi = value + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be a (low, high) pair of ints') from exc + _check_int(f'{name}[0]', lo, low, high) + _check_int(f'{name}[1]', hi, lo, high) + return int(lo), int(hi) + + +def _check_grid(name: str, value: Any, low: float, high: float, *, high_open: bool = False) -> tuple[float, ...]: + try: + out = tuple(value) + except TypeError as exc: + raise ValueError(f'{name} must be a sequence of numbers') from exc + if not 1 <= len(out) <= 16: + raise ValueError(f'{name} must hold 1..16 values') + return tuple(_check_float(f'{name} entry', v, low, high, high_open=high_open) for v in out) + + +def _grid_edges(chosen: Mapping[str, float], grids: Mapping[str, Sequence[float]], + natural: Mapping[str, Sequence[float]] | None = None) -> list[str]: + """Tuned hyperparameters (grids with at least two distinct values) whose chosen value is the smallest or largest + grid value, so the best setting may lie outside the grid. A value in ``natural[name]`` (a natural bound such as + momentum 0 = no momentum) is not counted as an edge.""" + natural = natural or {} + out = [] + for name, grid in grids.items(): + values = sorted({float(v) for v in grid}) + value = float(chosen[name]) + if len(values) >= 2 and value in (values[0], values[-1]) and value not in {float(v) for v in natural.get(name, ())}: + out.append(name) + return out + + +# ====================================================================== memory +class ContinuumMemory: + """``levels`` linear associative memories with periods ``base_period * 2**l`` (see the module docstring). + + Keys may be one ``(key_dim,)`` vector shared by every level or a ``(levels, key_dim)`` array with one key + per level. With a shared key and ``chunk_reduce='sum'`` several levels can apply the same error in one + write, so a smaller ``lr`` (about ``1 / levels`` of the per-level-key value) keeps the joint update stable; + the ``bound`` clip keeps the state finite either way. The memory has no randomness.""" + + def __init__(self, key_dim: int, value_dim: int, levels: int = 4, base_period: int = 1, lr: float = 0.5, + momentum: float = 0.0, forget: float = 0.01, *, surprise_forget: float = 0.0, + max_forget: float = 0.5, chunk_reduce: str = 'sum', bound: float = 100.0) -> None: + self.key_dim = _check_int('key_dim', key_dim, 1, 4096) + self.value_dim = _check_int('value_dim', value_dim, 1, 4096) + self.levels = _check_int('levels', levels, 1, 12) + self.base_period = _check_int('base_period', base_period, 1, 4096) + if self.key_dim * self.value_dim * self.levels > 4_000_000: + raise ValueError('levels * key_dim * value_dim must be <= 4,000,000') + self.lr = _check_float('lr', lr, 0.0, 10.0) + self.momentum = _check_float('momentum', momentum, 0.0, 1.0, high_open=True) + self.forget = _check_float('forget', forget, 0.0, 1.0, high_open=True) + self.surprise_forget = _check_float('surprise_forget', surprise_forget, 0.0, 1.0) + self.max_forget = _check_float('max_forget', max_forget, 0.0, 1.0, high_open=True) + if self.max_forget < self.forget: + raise ValueError('max_forget must be >= forget') + if chunk_reduce not in CHUNK_REDUCTIONS: + raise ValueError(f'chunk_reduce must be one of {CHUNK_REDUCTIONS}') + self.chunk_reduce = chunk_reduce + self.bound = _check_float('bound', bound, 0.0, 1e6, low_open=True) + self.periods: tuple[int, ...] = tuple(self.base_period * 2 ** level for level in range(self.levels)) + self.reset() + + # ------------------------------------------------------------------ state + def reset(self) -> None: + """Empty memories, momentum and chunk accumulators (a fresh memory).""" + shape = (self.levels, self.value_dim, self.key_dim) + self.M = np.zeros(shape) + self.S = np.zeros(shape) + self._acc = np.zeros(shape) + self._acc_surprise = np.zeros(self.levels) + self._acc_count = np.zeros(self.levels, dtype=np.int64) + self.writes = 0 + self.update_counts = np.zeros(self.levels, dtype=np.int64) + self.last_alpha = np.full(self.levels, self.forget) + self.last_surprise = 0.0 + self.last_error = 0.0 + + @property + def parameter_count(self) -> int: + """Number of memory entries (the fast weights ``M``).""" + return int(self.M.size) + + @property + def state_numbers(self) -> int: + """All stored numbers: memories, momentum, chunk accumulators and counters.""" + return int(self.M.size + self.S.size + self._acc.size + self._acc_surprise.size + self._acc_count.size + + self.update_counts.size + self.last_alpha.size + 3) + + def config(self) -> dict[str, Any]: + return {'key_dim': self.key_dim, 'value_dim': self.value_dim, 'levels': self.levels, + 'base_period': self.base_period, 'lr': self.lr, 'momentum': self.momentum, 'forget': self.forget, + 'surprise_forget': self.surprise_forget, 'max_forget': self.max_forget, + 'chunk_reduce': self.chunk_reduce, 'bound': self.bound} + + # ------------------------------------------------------------------ read / write + def _keys(self, name: str, key: Any) -> np.ndarray: + arr = _finite(name, key) + if arr.shape == (self.key_dim,): + return np.broadcast_to(arr, (self.levels, self.key_dim)) + if arr.shape != (self.levels, self.key_dim): + raise ValueError(f'{name} must have shape ({self.key_dim},) or ({self.levels}, {self.key_dim}), ' + f'got {arr.shape}') + return arr + + def read(self, query: Any) -> np.ndarray: + """Every level's read ``M_l q_l`` as a ``(levels, value_dim)`` array (no state change).""" + return np.einsum('lvk,lk->lv', self.M, self._keys('query', query)) + + def predict(self, query: Any) -> np.ndarray: + """Combined read ``sum_l M_l q_l``.""" + return self.read(query).sum(axis=0) + + def write(self, key: Any, value: Any) -> dict[str, Any]: + """One write: score the joint read, accumulate every level's gradient, apply the levels that are due.""" + ks = self._keys('key', key) + v = _vector('value', value, self.value_dim) + err = np.einsum('lvk,lk->v', self.M, ks) - v + e = float(err @ err) + surprise = e / (e + float(v @ v)) if e > 0.0 else 0.0 + self._acc += 2.0 * err[None, :, None] * ks[:, None, :] + self._acc_surprise += surprise + self._acc_count += 1 + self.writes += 1 + updated: list[int] = [] + for level, period in enumerate(self.periods): + if self.writes % period: + continue + n = int(self._acc_count[level]) + grad = self._acc[level] / n if self.chunk_reduce == 'mean' else self._acc[level] + alpha = min(self.max_forget, self.forget + self.surprise_forget * float(self._acc_surprise[level]) / n) + self.S[level] = np.clip(self.momentum * self.S[level] - self.lr * grad, -self.bound, self.bound) + self.M[level] = np.clip((1.0 - alpha) * self.M[level] + self.S[level], -self.bound, self.bound) + self._acc[level] = 0.0 + self._acc_surprise[level] = 0.0 + self._acc_count[level] = 0 + self.update_counts[level] += 1 + self.last_alpha[level] = alpha + updated.append(level) + self.last_surprise = surprise + self.last_error = e / self.value_dim + return {'error': self.last_error, 'surprise': surprise, 'updated_levels': updated} + + # ------------------------------------------------------------------ persistence + def export_state(self) -> dict[str, Any]: + return {'config': self.config(), 'M': self.M.tolist(), 'S': self.S.tolist(), 'acc': self._acc.tolist(), + 'acc_surprise': self._acc_surprise.tolist(), 'acc_count': self._acc_count.tolist(), + 'writes': int(self.writes), 'update_counts': self.update_counts.tolist(), + 'last_alpha': self.last_alpha.tolist(), 'last_surprise': float(self.last_surprise), + 'last_error': float(self.last_error)} + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate everything first, then replace the state (the configuration must match).""" + if not isinstance(state, Mapping): + raise ValueError('continuum memory state must be a mapping') + if state.get('config') != self.config(): + raise ValueError('continuum memory state was made with a different configuration') + shape = (self.levels, self.value_dim, self.key_dim) + M = _array('M', state.get('M'), shape) + S = _array('S', state.get('S'), shape) + acc = _array('acc', state.get('acc'), shape) + acc_s = _array('acc_surprise', state.get('acc_surprise'), (self.levels,)) + alpha = _array('last_alpha', state.get('last_alpha'), (self.levels,)) + if np.max(np.abs(M), initial=0.0) > self.bound or np.max(np.abs(S), initial=0.0) > self.bound: + raise ValueError('memory state exceeds the configured bound') + if np.max(np.abs(acc), initial=0.0) > _MAX_ACCUMULATOR: + raise ValueError('gradient accumulator is out of range') + writes = _check_int('writes', state.get('writes'), 0, 2**62) + raw_counters = (state.get('acc_count'), state.get('update_counts')) + if not all(isinstance(c, (list, tuple, np.ndarray)) and np.ndim(c) == 1 and all( + isinstance(x, (int, np.integer)) and not isinstance(x, (bool, np.bool_)) for x in c) + for c in raw_counters): + raise ValueError('counters must be one-dimensional sequences of ints') + try: + counts = np.asarray(raw_counters[0], dtype=np.int64) + upd = np.asarray(raw_counters[1], dtype=np.int64) + except (TypeError, ValueError, OverflowError) as exc: + raise ValueError('counters must be integer arrays') from exc + expected_counts = np.array([writes % p for p in self.periods], dtype=np.int64) + expected_upd = np.array([writes // p for p in self.periods], dtype=np.int64) + if counts.shape != (self.levels,) or not np.array_equal(counts, expected_counts): + raise ValueError('chunk counters do not match the write count') + if upd.shape != (self.levels,) or not np.array_equal(upd, expected_upd): + raise ValueError('update counters do not match the write count') + 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): + raise ValueError('surprise accumulators / forgetting gates out of range') + if np.any(acc[counts == 0] != 0.0): + raise ValueError('a level with an empty chunk must have a zero gradient accumulator') + ls = _check_float('last_surprise', state.get('last_surprise'), 0.0, 1.0) + le = _check_float('last_error', state.get('last_error'), 0.0, 1e300) + self.M, self.S, self._acc = M.copy(), S.copy(), acc.copy() + self._acc_surprise, self._acc_count, self.update_counts = acc_s.copy(), counts.copy(), upd.copy() + self.last_alpha = alpha.copy() + self.writes = int(writes) + self.last_surprise, self.last_error = ls, le + + +# ====================================================================== engine extension +def _fit(vec: np.ndarray, size: int) -> np.ndarray: + out = np.zeros(size) + m = min(size, vec.size) + out[:m] = vec[:m] + return out + + +class ContinuumMemoryExtension(EngineExtension): + """Readout-only NEUROWEAVE extension around a :class:`ContinuumMemory`. + + Context ``c_t`` = task input (fitted to ``TASK_INPUT_DIM``; zeros when absent) followed by the fused sensory + frame. The key is a fixed binary random-feature map ``k = sign(R c + b) / sqrt(levels * key_dim)`` split + into one ``key_dim`` block per level (unit norm overall). After every engine step the extension writes + ``key(c_{t-1}) -> sensory_t`` (only when ``ctx['learn']``; never before a previous context exists, e.g. + right after :meth:`reset`) and then reads every level with ``key(c_t)``. ``features()`` are + ``features_per_level`` fixed unit-norm projections of each level's 16-channel read, clipped to [-10, 10]. + The brain output is not used and the drive is never changed.""" + + id = MODULE_ID + + def __init__(self, levels: int = 4, key_dim: int = 8, base_period: int = 1, lr: float = 0.25, + momentum: float = 0.0, forget: float = 0.01, *, features_per_level: int = 2, + surprise_forget: float = 0.0, max_forget: float = 0.5, chunk_reduce: str = 'sum', + seed: int = 0) -> None: + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + self.features_per_level = _check_int('features_per_level', features_per_level, 1, 64) + self.memory = ContinuumMemory(key_dim, SENSORY_DIM, levels, base_period, lr, momentum, forget, + surprise_forget=surprise_forget, max_forget=max_forget, + chunk_reduce=chunk_reduce) + self.levels = self.memory.levels + self.key_dim = self.memory.key_dim + self.feature_dim = self.levels * self.features_per_level + if self.feature_dim > 4096: + raise ValueError('levels * features_per_level must be <= 4096') + rng = np.random.default_rng(self.seed + _KEY_OFFSET) + self._R = rng.standard_normal((self.levels * self.key_dim, CONTEXT_DIM)) + self._b = 0.5 * rng.standard_normal(self.levels * self.key_dim) + prng = np.random.default_rng(self.seed + _FEATURE_OFFSET) + proj = prng.standard_normal((self.levels, self.features_per_level, SENSORY_DIM)) + self._P = proj / np.linalg.norm(proj, axis=2, keepdims=True) + self._key_scale = 1.0 / math.sqrt(self.levels * self.key_dim) + self._prev_key: np.ndarray | None = None + self._features = np.zeros(self.feature_dim) + self._steps = 0 + self._frozen_steps = 0 + + # ------------------------------------------------------------------ lifecycle + def bind(self, engine: Any) -> None: + """Nothing is sized from the engine (the context has a fixed width); start a fresh episode.""" + self.reset() + + def reset(self) -> None: + self._prev_key = None + self._features = np.zeros(self.feature_dim) + + # ------------------------------------------------------------------ hooks + def key(self, context: Any) -> np.ndarray: + """``(levels, key_dim)`` binary random-feature key of a ``CONTEXT_DIM`` context vector.""" + c = _vector('context', context, CONTEXT_DIM) + z = self._R @ c + self._b + return (np.where(z >= 0.0, 1.0, -1.0) * self._key_scale).reshape(self.levels, self.key_dim) + + def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None: + if not isinstance(ctx, Mapping): + raise ValueError('continuum memory needs the engine step context') + learn = ctx.get('learn') + if type(learn) is not bool: + raise ValueError("ctx['learn'] must be a boolean") + sensory = _vector("ctx['sensory']", ctx.get('sensory'), SENSORY_DIM) + task = ctx.get('task_input') + task_vec = np.zeros(TASK_INPUT_DIM) if task is None else _fit(_finite("ctx['task_input']", task).ravel(), + TASK_INPUT_DIM) + key = self.key(np.concatenate([task_vec, sensory])) + if learn and self._prev_key is not None: + self.memory.write(self._prev_key, sensory) + elif not learn: + self._frozen_steps += 1 + reads = self.memory.read(key) + self._features = np.clip(np.einsum('lfv,lv->lf', self._P, reads).ravel(), -10.0, 10.0) + self._prev_key = key + self._steps += 1 + + def features(self) -> np.ndarray: + return self._features.copy() + + # ------------------------------------------------------------------ accounting / persistence + def parameter_count(self) -> int: + return self.memory.parameter_count + + def state_numbers(self) -> int: + return int(self.memory.state_numbers + self._R.size + self._b.size + self._P.size + + self.levels * self.key_dim + self.feature_dim + 2) + + def telemetry(self) -> dict[str, Any]: + mem = self.memory + return {'id': self.id, 'levels': self.levels, 'periods': list(mem.periods), 'writes': int(mem.writes), + 'update_counts': mem.update_counts.tolist(), 'steps': self._steps, 'frozen_steps': self._frozen_steps, + 'last_surprise': float(mem.last_surprise), 'last_error': float(mem.last_error), + 'last_alpha': mem.last_alpha.tolist(), + 'level_norms': [float(np.linalg.norm(mem.M[level])) for level in range(self.levels)]} + + def _config(self) -> dict[str, Any]: + mem = self.memory + return {'levels': self.levels, 'key_dim': self.key_dim, 'base_period': mem.base_period, 'lr': mem.lr, + 'momentum': mem.momentum, 'forget': mem.forget, 'features_per_level': self.features_per_level, + 'surprise_forget': mem.surprise_forget, 'max_forget': mem.max_forget, + 'chunk_reduce': mem.chunk_reduce, 'seed': self.seed} + + def export_state(self) -> dict[str, Any]: + return {'id': self.id, 'config': self._config(), 'memory': self.memory.export_state(), + 'prev_key': None if self._prev_key is None else self._prev_key.tolist(), + 'features': self._features.tolist(), 'steps': self._steps, 'frozen_steps': self._frozen_steps} + + def import_state(self, state: Mapping[str, Any]) -> None: + super().import_state(state) + if state.get('config') != self._config(): + raise ValueError('continuum memory extension state was made with a different configuration') + memory = copy.deepcopy(self.memory) + memory.import_state(state.get('memory')) # validates fully before anything is replaced + prev = state.get('prev_key') + if prev is not None: + prev = _array('prev_key', prev, (self.levels, self.key_dim)) + if not np.allclose(np.abs(prev), self._key_scale, rtol=0.0, atol=1e-12): + raise ValueError('prev_key is not a binary random-feature key') + feats = _array('features', state.get('features'), (self.feature_dim,)) + if np.max(np.abs(feats), initial=0.0) > 10.0: + raise ValueError('features out of range') + steps = _check_int('steps', state.get('steps'), 0, 2**62) + frozen = _check_int('frozen_steps', state.get('frozen_steps'), 0, steps) + self.memory = memory + self._prev_key = None if prev is None else np.where(prev > 0.0, self._key_scale, -self._key_scale) + self._features = feats.copy() + self._steps, self._frozen_steps = steps, frozen + + +# ====================================================================== recall benchmark +def make_recall_stream(seed: int, steps: int, *, key_dim: int = 128, value_dim: int = 8, n_short: int = 4, + n_long: int = 8, short_gap: Sequence[int] = (3, 10), long_gap: Sequence[int] = (40, 80), + remap_prob: float = 0.0) -> dict[str, np.ndarray]: + """Deterministic key -> value stream with recurring associations and one-off interference. + + ``n_short`` items recur after gaps drawn from ``short_gap`` and ``n_long`` items after gaps from + ``long_gap`` (inclusive, in steps). When several items are due, the earliest-due one is presented (ties: lowest + index) and the others wait, so realised gaps can be longer than drawn. Steps without a due item present a fresh + one-off association. With ``remap_prob`` a short-gap item gets a new value at a recurrence (kind ``remap``: + a write of a changed association, not a recall query). Keys are random unit vectors, values standard normal. + Returns ``keys (T, key_dim)``, ``values (T, value_dim)``, ``kind (T,)`` (codes in ``KIND_CODES``), + ``item (T,)`` (-1 for fresh) and ``gap (T,)`` (0 unless the step is a recurrence).""" + _check_int('seed', seed, 0, 2**31 - 1) + _check_int('steps', steps, 1, 1_000_000) + _check_int('key_dim', key_dim, 1, 65_536) + _check_int('value_dim', value_dim, 1, 4096) + _check_int('n_short', n_short, 0, 1024) + _check_int('n_long', n_long, 0, 1024) + sg = _check_pair('short_gap', short_gap, 1, 1_000_000) + lg = _check_pair('long_gap', long_gap, 1, 1_000_000) + p_remap = _check_float('remap_prob', remap_prob, 0.0, 1.0) + rng = np.random.default_rng(seed + _STREAM_OFFSET) + n_items = n_short + n_long + item_keys = rng.standard_normal((n_items, key_dim)) + item_keys /= np.linalg.norm(item_keys, axis=1, keepdims=True) + item_values = rng.standard_normal((n_items, value_dim)) + gaps = [sg] * n_short + [lg] * n_long + due = np.array([int(rng.integers(0, g[1])) for g in gaps], dtype=np.int64) + last = np.full(n_items, -1, dtype=np.int64) + keys = np.zeros((steps, key_dim)) + values = np.zeros((steps, value_dim)) + kind = np.zeros(steps, dtype=np.int8) + item = np.full(steps, -1, dtype=np.int64) + gap = np.zeros(steps, dtype=np.int64) + for t in range(steps): + cand = np.flatnonzero(due <= t) if n_items else np.zeros(0, dtype=np.int64) + if cand.size: + i = int(cand[np.argmin(due[cand])]) + if last[i] < 0: + code = KIND_CODES['first'] + elif i < n_short: + code = KIND_CODES['short'] + if p_remap > 0.0 and rng.random() < p_remap: + item_values[i] = rng.standard_normal(value_dim) + code = KIND_CODES['remap'] + else: + code = KIND_CODES['long'] + keys[t], values[t], kind[t], item[t] = item_keys[i], item_values[i], code, i + gap[t] = t - last[i] if last[i] >= 0 else 0 + last[i] = t + due[i] = t + int(rng.integers(gaps[i][0], gaps[i][1] + 1)) + else: + k = rng.standard_normal(key_dim) + keys[t] = k / np.linalg.norm(k) + values[t] = rng.standard_normal(value_dim) + return {'keys': keys, 'values': values, 'kind': kind, 'item': item, 'gap': gap} + + +def _score(preds_err: list[float], kinds: list[int]) -> dict[str, Any]: + err = np.asarray(preds_err) + kd = np.asarray(kinds) + out: dict[str, Any] = {} + for name in ('short', 'long'): + sel = err[kd == KIND_CODES[name]] + out[f'{name}_mse'] = float(sel.mean()) if sel.size else None + out[f'{name}_queries'] = int(sel.size) + return out + + +def _run_memory(memory: ContinuumMemory, stream: Mapping[str, np.ndarray], split: bool) -> dict[str, Any]: + """Prequential: predict the value from the key, score recurring items, then write.""" + errs, kinds = [], [] + shape = (memory.levels, memory.key_dim) + for key, value, code in zip(stream['keys'], stream['values'], stream['kind']): + k = key.reshape(shape) if split else key + pred = memory.predict(k) + if code in (KIND_CODES['short'], KIND_CODES['long']): + errs.append(float(np.mean((pred - value) ** 2))) + kinds.append(int(code)) + memory.write(k, value) + return _score(errs, kinds) + + +def _run_mean_predictor(stream: Mapping[str, np.ndarray]) -> dict[str, Any]: + """No memory: predict the running mean of the values seen so far.""" + mean = np.zeros(stream['values'].shape[1]) + errs, kinds = [], [] + for n, (value, code) in enumerate(zip(stream['values'], stream['kind']), start=1): + if code in (KIND_CODES['short'], KIND_CODES['long']): + errs.append(float(np.mean((mean - value) ** 2))) + kinds.append(int(code)) + mean = mean + (value - mean) / n + return _score(errs, kinds) + + +def _overall(score: Mapping[str, Any]) -> float: + vals = [score[k] for k in ('short_mse', 'long_mse') if score[k] is not None] + return float(np.mean(vals)) if vals else float('inf') + + +# The grids bracket both arms' tuned optimum (measured 2026-11-19): learning rate and momentum trade off along a +# ridge of nearly equal effective step lr / (1 - momentum), and a grid that stops short of one arm's optimum on that +# ridge can hand the other arm a spurious win. Receipts flag a chosen value that sits on a grid edge. +RECALL_DEFAULTS: dict[str, Any] = { + 'steps': 800, 'levels': 4, 'key_dim': 32, 'value_dim': 8, 'base_period': 1, + 'n_short': 4, 'n_long': 8, 'short_gap': (3, 10), 'long_gap': (40, 80), 'remap_prob': 0.0, + 'chunk_reduce': 'sum', 'surprise_forget': 0.0, 'max_forget': 0.5, + '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), + 'forget_grid': (0.0, 0.01), 'tune_seeds': (1000, 1001)} +RECALL_QUICK: dict[str, Any] = {'steps': 240, 'lr_grid': (0.125, 0.25, 0.5), 'momentum_grid': (0.0, 0.25, 0.5), + 'forget_grid': (0.0, 0.02), 'tune_seeds': (1000,)} +_NATURAL_BOUNDS = {'lr': (0.0,), 'momentum': (0.0,), 'forget': (0.0,)} + + +def run_recall_benchmark(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """CMS vs a single-level Titans-style memory with the same number of entries vs no memory. + + Both memories use the same keys (random unit vectors in ``levels * key_dim`` dimensions): CMS level ``l`` reads + block ``l`` of the key, the single-level memory reads all of it, so both read functions are linear maps of the + same key with ``value_dim * levels * key_dim`` entries and differ only in the update schedule. For each memory + arm, ``(lr, momentum, forget)`` is chosen from the same grid by the mean of short- and long-gap recall MSE on + ``tune_seeds`` (disjoint from ``seeds``); the chosen values are then evaluated on every seed. Verdict: paired + 95 % t interval on long-gap recall MSE (lower is better), CMS vs single-level memory.""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds('seeds', seeds) + cfg = dict(RECALL_DEFAULTS) + if quick: + cfg.update(RECALL_QUICK) + unknown = sorted(set(overrides) - set(cfg)) + if unknown: + raise ValueError(f'unknown run_recall_benchmark overrides: {unknown}') + cfg.update(overrides) + _check_int('steps', cfg['steps'], 16, 200_000) + tune_seeds = _check_seeds('tune_seeds', cfg['tune_seeds']) + if set(tune_seeds) & set(seeds): + raise ValueError('tune_seeds must be disjoint from seeds') + for name, lo, hi, open_hi in (('lr_grid', 0.0, 10.0, False), ('momentum_grid', 0.0, 1.0, True), + ('forget_grid', 0.0, 1.0, True)): + cfg[name] = _check_grid(name, cfg[name], lo, hi, high_open=open_hi) + cfg['short_gap'] = _check_pair('short_gap', cfg['short_gap'], 1, 1_000_000) + cfg['long_gap'] = _check_pair('long_gap', cfg['long_gap'], 1, 1_000_000) + cfg['max_forget'] = _check_float('max_forget', cfg['max_forget'], 0.0, 1.0, high_open=True) # used in max() + cfg['tune_seeds'] = tune_seeds + levels, key_dim, value_dim = cfg['levels'], cfg['key_dim'], cfg['value_dim'] + + def make(arm: str, lr: float, momentum: float, forget: float) -> ContinuumMemory: + common = dict(surprise_forget=cfg['surprise_forget'], max_forget=max(cfg['max_forget'], forget), + chunk_reduce=cfg['chunk_reduce']) + if arm == 'cms': + return ContinuumMemory(key_dim, value_dim, levels, cfg['base_period'], lr, momentum, forget, **common) + return ContinuumMemory(levels * key_dim, value_dim, 1, 1, lr, momentum, forget, **common) + + probe_cms, probe_single = make('cms', 0.5, 0.0, 0.0), make('single', 0.5, 0.0, 0.0) # validates sizes + if probe_cms.parameter_count != probe_single.parameter_count: + raise AssertionError('capacity matching failed') + stream_kw = dict(key_dim=levels * key_dim, value_dim=value_dim, n_short=cfg['n_short'], n_long=cfg['n_long'], + short_gap=cfg['short_gap'], long_gap=cfg['long_gap'], remap_prob=cfg['remap_prob']) + t0 = time.perf_counter() + tune_streams = [make_recall_stream(s, cfg['steps'], **stream_kw) for s in tune_seeds] + grid = list(itertools.product(cfg['lr_grid'], cfg['momentum_grid'], cfg['forget_grid'])) + tuning: dict[str, Any] = {} + chosen: dict[str, tuple[float, float, float]] = {} + for arm in ('cms', 'single'): + table = [] + for lr, momentum, forget in grid: + score = float(np.mean([_overall(_run_memory(make(arm, lr, momentum, forget), st, arm == 'cms')) + for st in tune_streams])) + table.append({'lr': lr, 'momentum': momentum, 'forget': forget, 'tune_score': score}) + best = min(range(len(table)), key=lambda i: (table[i]['tune_score'], i)) + chosen[arm] = (table[best]['lr'], table[best]['momentum'], table[best]['forget']) + picked = dict(zip(('lr', 'momentum', 'forget'), chosen[arm])) + edges = _grid_edges(picked, {'lr': cfg['lr_grid'], 'momentum': cfg['momentum_grid'], + 'forget': cfg['forget_grid']}, _NATURAL_BOUNDS) + tuning[arm] = {'chosen': picked, 'chosen_on_grid_edge': edges, 'table': table} + tune_wall = time.perf_counter() - t0 + + t1 = time.perf_counter() + per_seed = [] + for s in seeds: + stream = make_recall_stream(s, cfg['steps'], **stream_kw) + row = {'seed': int(s), + 'cms': _run_memory(make('cms', *chosen['cms']), stream, True), + 'single': _run_memory(make('single', *chosen['single']), stream, False), + 'none': _run_mean_predictor(stream), + 'kinds': {name: int(np.sum(stream['kind'] == code)) for name, code in KIND_CODES.items()}} + per_seed.append(row) + eval_wall = time.perf_counter() - t1 + + def vals(arm: str, metric: str) -> list[float]: + return [float('nan') if r[arm][metric] is None else r[arm][metric] for r in per_seed] + + comparisons = { + 'cms_vs_single_long_gap': harness.compare(vals('cms', 'long_mse'), vals('single', 'long_mse'), + higher_is_better=False), + 'cms_vs_single_short_gap': harness.compare(vals('cms', 'short_mse'), vals('single', 'short_mse'), + higher_is_better=False), + 'cms_vs_none_long_gap': harness.compare(vals('cms', 'long_mse'), vals('none', 'long_mse'), + higher_is_better=False), + 'single_vs_none_long_gap': harness.compare(vals('single', 'long_mse'), vals('none', 'long_mse'), + higher_is_better=False), + } + summary = {arm: {m: float(np.nanmean(vals(arm, m))) for m in ('short_mse', 'long_mse')} + for arm in ('cms', 'single', 'none')} + entries = probe_cms.parameter_count + runs = len(grid) * len(tune_seeds) * 2 + 2 * len(seeds) + receipt = harness.base_receipt(RECALL_ID, 'memory_benchmark', { + **{k: (list(v) if isinstance(v, tuple) else v) for k, v in cfg.items()}, + 'seeds': list(seeds), 'quick': quick, 'scored_kinds': ['short', 'long'], + 'tuning_objective': 'mean of short- and long-gap recall MSE on tune_seeds'}) + receipt.update({ + 'module': MODULE_ID, 'source': SOURCE, + 'arms': {'cms': f'{levels}-level continuum memory, periods {list(probe_cms.periods)}, per-level key blocks', + 'single': 'one Titans-style memory (momentum + forgetting) reading the full key, period 1', + 'none': 'running mean of the values seen so far'}, + 'tuning': tuning, 'per_seed': per_seed, 'summary': summary, 'comparisons': comparisons, + 'verdict': comparisons['cms_vs_single_long_gap']['verdict'], + 'verdict_basis': ('cms_vs_single_level_memory: paired 95% t interval over seeds on long-gap recall MSE ' + '(lower is better); hyperparameters tuned per arm on disjoint tune_seeds'), + 'budget': {'cms_memory_entries': entries, 'single_memory_entries': probe_single.parameter_count, + 'cms_state_numbers': probe_cms.state_numbers, 'single_state_numbers': probe_single.state_numbers}, + 'estimated_cost': {'memory_runs': runs, 'steps_per_run': cfg['steps'], + 'estimated_multiply_adds': int(runs * cfg['steps'] * 4 * entries)}, + 'measured_wallclock_s': {'tuning': tune_wall, 'evaluation': eval_wall}, + 'notes': ('Synthetic stream of random unit keys and Gaussian values; recall is scored prequentially (read ' + 'before write) at short-gap and long-gap recurrences only. The two memory arms hold the same ' + 'number of entries and read the same keys, so they differ only in the multi-period update ' + 'schedule (and per-level forgetting); the gates are fixed numbers, not the learned ' + 'data-dependent gates of Titans or Hope. Each memory arm gets its best point of the same grid on ' + 'separate tuning seeds; tuning..chosen_on_grid_edge names any hyperparameter whose chosen ' + 'value is a grid edge (the optimum may then lie outside the grid). A linear toy: it says nothing ' + 'about language modelling or the published results.'), + }) + return harness.seal(receipt) + + +# ====================================================================== NEUROWEAVE extension experiment +_EXT_DEFAULTS: dict[str, Any] = {'levels': 4, 'key_dim': 8, 'base_period': 1, 'lr': 0.25, 'momentum': 0.0, + 'forget': 0.01, 'features_per_level': 2, 'surprise_forget': 0.0, 'max_forget': 0.5, + 'chunk_reduce': 'sum'} +_RUN_DEFAULTS: dict[str, Any] = {'task': 'delayed_recall', 'heldout_seeds': (100, 101), 'steps': 300, + 'heldout_steps': None, 'neurons': 48, 'topology': 'clustered', 'mechanisms': ()} + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Baseline vs ``ContinuumMemoryExtension`` readout features vs the random-trace capacity control on a + NEUROWEAVE temporal task (default ``delayed_recall``), through ``harness.run_extension_experiment``. + + Extension overrides: the keys of ``_EXT_DEFAULTS``. Harness overrides: ``task``, ``heldout_seeds``, ``steps``, + ``heldout_steps``, ``neurons``, ``topology``, ``mechanisms``. Quick mode uses the harness ``QUICK_ARGS`` sizes + (the seeds stay the caller's).""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds('seeds', seeds) + ext_cfg, run_cfg = dict(_EXT_DEFAULTS), dict(_RUN_DEFAULTS) + if quick: + run_cfg.update({k: v for k, v in harness.QUICK_ARGS.items() if k != 'seeds'}) + unknown = sorted(set(overrides) - set(ext_cfg) - set(run_cfg)) + if unknown: + raise ValueError(f'unknown run_experiment overrides: {unknown}') + for key, value in overrides.items(): + (ext_cfg if key in ext_cfg else run_cfg)[key] = value + ContinuumMemoryExtension(seed=0, **ext_cfg) # validate before running anything + + def factory(seed: int) -> ContinuumMemoryExtension: + return ContinuumMemoryExtension(seed=seed, **ext_cfg) + + t0 = time.perf_counter() + receipt = harness.run_extension_experiment( + MODULE_ID, factory, seeds=seeds, control='random_trace', metric='accuracy', notes=( + f'Readout-only extension: a {ext_cfg["levels"]}-level continuum memory stores previous task+sensory ' + 'context -> current ' + 'sensory frame (writes only while learning) and its per-level reads of the current context (a ' + 'multi-timescale forecast of the next frame) are projected to readout features. It never changes the ' + 'brain drive and does not read the brain output. The control gets the same number of random ' + 'leaky-trace features of the brain output. Small synthetic task; the verdict is a paired 95 % t ' + 'interval over seeds.'), + **run_cfg) + receipt = dict(receipt) + receipt.pop('digest', None) + receipt['config'] = {**receipt['config'], 'quick': quick, 'extension': ext_cfg} + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0} + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment, RECALL_ID: run_recall_benchmark} diff --git a/synapse/frontier/dendritic.py b/synapse/frontier/dendritic.py new file mode 100644 index 0000000000000000000000000000000000000000..d4019162192ca0a0108de3e0d84c97c392c09a39 --- /dev/null +++ b/synapse/frontier/dendritic.py @@ -0,0 +1,592 @@ +"""Structured dendritic layer (dANN) compared with a dense MLP at matched trainable parameters. + +Inspired by (not a reproduction of): S. Chavlis and P. Poirazi, "Dendrites endow artificial +neural networks with accurate, robust and parameter-efficient learning", Nature +Communications 16, 943 (22 January 2025), https://doi.org/10.1038/s41467-025-56297-9 +(preprint arXiv:2404.03708). + +What is implemented +------------------- +``DendriticLayer`` is a two-stage sparse layer: ``somas * dendrites_per_soma`` dendrites each +receive exactly ``synapses_per_dendrite`` inputs through a *fixed* binary synaptic mask +(``W <- W * M``, applied in the forward pass so masked weights get no gradient, and re-applied +after every optimiser step as in the paper's Eq. 1/3); each dendrite applies a leaky ReLU +(slope 0.1, as in the paper); each soma sums its own dendrites through trainable cable weights +(every dendrite belongs to exactly one soma) and applies a second leaky ReLU:: + + d_k = lrelu(sum_i M_ki W_ki x_i + b_k) (dendrite k) + s_j = lrelu(sum_{k in dendrites(j)} c_jk d_k + a_j) (soma j) + +Input sampling (fixed at construction from a seeded NumPy generator): + +* ``random``: each dendrite samples ``synapses_per_dendrite`` distinct inputs uniformly; +* ``local``: each dendrite gets a uniformly drawn centre pixel and samples the nearest pixels + (its 3x3 block, subsampled, or expanded ring by ring with random fill), following the + authors' released ``receptive_fields.py``; +* ``global``: each soma gets a centre pixel; its dendrites' centres are drawn from the + neighbourhood of that centre by the same ring rule, and each dendrite then samples + locally around its own centre. + +``parameter_count()`` counts only unmasked synapses plus biases and cable weights. + +Benchmark (``run_experiment``) +------------------------------ +Procedurally generated 12x12 glyphs (10 stroke-drawn classes, no downloads) with random +translation, scale, small rotation, stroke-thickness jitter and Gaussian pixel noise. Arms: +one dANN per sampling mode and a dense two-hidden-layer MLP whose width is chosen so its +trainable parameters match the dANN's (within ``param_tolerance``). All arms share data, +minibatch order, optimiser (Adam) and number of updates. Metrics: held-out accuracy and +held-out accuracy under extra pixel noise. The best dANN is chosen by mean *validation* +accuracy; the verdict is ``harness.compare`` (paired 95 % t interval over seeds) of that dANN +against the dense MLP on held-out accuracy; robustness gets its own comparison. + +Synthetic abstraction only: the paper's datasets (MNIST variants, CIFAR-10), sizes and +efficiency scores are not reproduced. +""" +from __future__ import annotations + +import contextlib +import functools +import math +import time +from typing import Any, Callable, Iterable, Iterator, Mapping + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from . import harness + +__all__ = ['MODULE_ID', 'EXPERIMENTS', 'SAMPLING_MODES', 'GLYPHS', 'GLYPH_NAMES', 'GLYPH_SIDE', 'DEFAULTS', 'QUICK', + 'sample_receptive_fields', 'DendriticLayer', 'DendriticNet', 'DenseMLP', 'dense_parameter_count', + 'dann_parameter_count', 'matched_dense_hidden', 'render_glyph', 'make_glyph_dataset', 'train_classifier', + 'accuracy', 'run_experiment'] + +MODULE_ID = 'dendritic_layer' +SAMPLING_MODES = ('random', 'local', 'global') +NEGATIVE_SLOPE = 0.1 # leaky ReLU slope used for dendrites and somata in the paper +GLYPH_SIDE = 12 + +_MASK_OFFSET = 41_011 +_INIT_OFFSET = 41_113 +_DATA_OFFSET = 41_201 +_NOISE_OFFSET = 41_303 +_STREAM_OFFSET = 41_407 + +# Ten stroke glyphs as polylines in the unit square (x to the right, y downwards). +GLYPHS: dict[str, tuple[tuple[tuple[float, float], ...], ...]] = { + 'box': (((0, 0), (1, 0), (1, 1), (0, 1), (0, 0)),), + 'bar': (((0.5, 0), (0.5, 1)),), + 'plus': (((0.5, 0), (0.5, 1)), ((0, 0.5), (1, 0.5))), + 'cross': (((0, 0), (1, 1)), ((1, 0), (0, 1))), + 'ell': (((0, 0), (0, 1), (1, 1)),), + 'tee': (((0, 0), (1, 0)), ((0.5, 0), (0.5, 1))), + 'zed': (((0, 0), (1, 0), (0, 1), (1, 1)),), + 'caret': (((0, 1), (0.5, 0), (1, 1)),), + 'aitch': (((0, 0), (0, 1)), ((1, 0), (1, 1)), ((0, 0.5), (1, 0.5))), + 'cup': (((0, 0), (0, 1), (1, 1), (1, 0)),), +} +GLYPH_NAMES: tuple[str, ...] = tuple(GLYPHS) + + +def _segments(name: str) -> np.ndarray: + segs = [(a, b) for line in GLYPHS[name] for a, b in zip(line[:-1], line[1:])] + return np.asarray(segs, dtype=np.float64) # (K, 2 endpoints, 2 coords) + + +_SEGMENTS = {name: _segments(name) for name in GLYPH_NAMES} + + +def _check_int(name: str, value: Any, low: int, high: int) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return value + + +# ====================================================================== receptive fields +def _ring(center: tuple[int, int], radius: int, shape: tuple[int, int]) -> list[int]: + """Flat indices at Chebyshev distance exactly ``radius`` (0 = the centre) inside the image.""" + r0, c0 = center + h, w = shape + out = [] + for r in range(max(0, r0 - radius), min(h, r0 + radius + 1)): + for c in range(max(0, c0 - radius), min(w, c0 + radius + 1)): + if max(abs(r - r0), abs(c - c0)) == radius: + out.append(r * w + c) + return out + + +def _neighbourhood(center: tuple[int, int], count: int, shape: tuple[int, int], rng: np.random.Generator) -> list[int]: + """``count`` distinct pixels nearest ``center``: its 3x3 block (subsampled when larger than needed), + then rings at Chebyshev radius 2, 3, ... with a random subset of the last ring needed.""" + h, w = shape + if count > h * w: + raise ValueError('neighbourhood larger than the image') + block = _ring(center, 0, shape) + _ring(center, 1, shape) + if len(block) >= count: + return sorted(int(i) for i in rng.choice(block, size=count, replace=False)) + chosen = list(block) + radius = 2 + while len(chosen) < count: + ring = _ring(center, radius, shape) + need = count - len(chosen) + chosen.extend(ring if len(ring) <= need else (int(i) for i in rng.choice(ring, size=need, replace=False))) + radius += 1 + return sorted(chosen) + + +def sample_receptive_fields(in_features: int, somas: int, dendrites_per_soma: int, synapses_per_dendrite: int, + sampling: str, *, image_shape: tuple[int, int] | None = None, + rng: np.random.Generator) -> np.ndarray: + """Input indices per dendrite, shape ``(somas * dendrites_per_soma, synapses_per_dendrite)``, sorted per row. + + Dendrites ``j * dendrites_per_soma ... (j + 1) * dendrites_per_soma - 1`` belong to soma ``j``.""" + _check_int('in_features', in_features, 1, 1 << 20) + _check_int('somas', somas, 1, 1 << 16) + _check_int('dendrites_per_soma', dendrites_per_soma, 1, 1 << 12) + _check_int('synapses_per_dendrite', synapses_per_dendrite, 1, in_features) + if sampling not in SAMPLING_MODES: + raise ValueError(f'sampling must be one of {SAMPLING_MODES}') + shape = _image_shape(in_features, image_shape) + if sampling == 'global' and dendrites_per_soma > in_features: + raise ValueError('global sampling needs dendrites_per_soma <= in_features (distinct dendrite centres)') + n_dend = somas * dendrites_per_soma + fields = np.zeros((n_dend, synapses_per_dendrite), dtype=np.int64) + h, w = shape + if sampling == 'random': + for k in range(n_dend): + fields[k] = np.sort(rng.choice(in_features, size=synapses_per_dendrite, replace=False)) + elif sampling == 'local': + for k in range(n_dend): + c = int(rng.integers(in_features)) + fields[k] = _neighbourhood((c // w, c % w), synapses_per_dendrite, shape, rng) + else: + for j in range(somas): + c = int(rng.integers(in_features)) + centres = _neighbourhood((c // w, c % w), dendrites_per_soma, shape, rng) + order = rng.permutation(len(centres)) + for i, ci in enumerate(order): + cc = centres[int(ci)] + fields[j * dendrites_per_soma + i] = _neighbourhood((cc // w, cc % w), synapses_per_dendrite, shape, rng) + return fields + + +def _image_shape(in_features: int, image_shape: tuple[int, int] | None) -> tuple[int, int]: + if image_shape is None: + side = math.isqrt(in_features) + return (side, side) if side * side == in_features else (1, in_features) + if (not isinstance(image_shape, (tuple, list)) or len(image_shape) != 2 + or any(type(v) is not int or v < 1 for v in image_shape) or image_shape[0] * image_shape[1] != in_features): + raise ValueError('image_shape must be two positive ints whose product is in_features') + return int(image_shape[0]), int(image_shape[1]) + + +# ====================================================================== models +class _Linear(nn.Module): + """Affine map initialised like ``nn.Linear`` but from an explicit generator (never the global RNG).""" + + def __init__(self, in_features: int, out_features: int, generator: torch.Generator) -> None: + super().__init__() + bound = 1.0 / math.sqrt(in_features) + self.weight = nn.Parameter(torch.empty(out_features, in_features).uniform_(-bound, bound, generator=generator)) + self.bias = nn.Parameter(torch.empty(out_features).uniform_(-bound, bound, generator=generator)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return F.linear(x, self.weight, self.bias) + + +class DendriticLayer(nn.Module): + """Dendrites with fixed sparse receptive fields feeding somata that sum their own dendrites. + + ``synaptic_mask`` (buffer, 0/1, shape ``(somas * dendrites_per_soma, in_features)``) has exactly + ``synapses_per_dendrite`` ones per row and never changes; ``cable_weight`` has shape + ``(somas, dendrites_per_soma)`` (each dendrite connects to one soma).""" + + def __init__(self, in_features: int, somas: int, dendrites_per_soma: int, synapses_per_dendrite: int, + sampling: str = 'random', *, image_shape: tuple[int, int] | None = None, seed: int = 0, + negative_slope: float = NEGATIVE_SLOPE) -> None: + super().__init__() + _check_int('seed', seed, 0, 2**31 - 1) + if isinstance(negative_slope, bool) or not isinstance(negative_slope, (int, float)) or not 0.0 <= negative_slope < 1.0: + raise ValueError('negative_slope must be in [0, 1)') + fields = sample_receptive_fields(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling, + image_shape=image_shape, rng=np.random.default_rng(seed + _MASK_OFFSET)) + self.in_features, self.somas = in_features, somas + self.dendrites_per_soma, self.synapses_per_dendrite = dendrites_per_soma, synapses_per_dendrite + self.sampling, self.seed, self.negative_slope = sampling, seed, float(negative_slope) + self.image_shape = _image_shape(in_features, image_shape) + n_dend = somas * dendrites_per_soma + mask = torch.zeros(n_dend, in_features) + mask[torch.arange(n_dend).unsqueeze(1), torch.from_numpy(fields)] = 1.0 + self.register_buffer('synaptic_mask', mask) + self.register_buffer('fields', torch.from_numpy(fields)) + g = torch.Generator().manual_seed(seed + _INIT_OFFSET) + bs, bc = 1.0 / math.sqrt(synapses_per_dendrite), 1.0 / math.sqrt(dendrites_per_soma) + self.synaptic_weight = nn.Parameter(torch.empty(n_dend, in_features).uniform_(-bs, bs, generator=g) * mask) + self.dendritic_bias = nn.Parameter(torch.empty(n_dend).uniform_(-bs, bs, generator=g)) + self.cable_weight = nn.Parameter(torch.empty(somas, dendrites_per_soma).uniform_(-bc, bc, generator=g)) + self.soma_bias = nn.Parameter(torch.empty(somas).uniform_(-bc, bc, generator=g)) + + def dendritic_activity(self, x: torch.Tensor) -> torch.Tensor: + if not isinstance(x, torch.Tensor) or x.ndim != 2 or x.shape[1] != self.in_features: + raise ValueError(f'x must be a tensor of shape (batch, {self.in_features})') + return F.leaky_relu(F.linear(x, self.synaptic_weight * self.synaptic_mask, self.dendritic_bias), + self.negative_slope) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + d = self.dendritic_activity(x).view(-1, self.somas, self.dendrites_per_soma) + return F.leaky_relu((d * self.cable_weight).sum(-1) + self.soma_bias, self.negative_slope) + + @torch.no_grad() + def enforce_mask(self) -> None: + """Re-apply ``W <- W * M`` (a no-op unless something wrote into masked weights).""" + self.synaptic_weight.mul_(self.synaptic_mask) + + def cable_mask(self) -> torch.Tensor: + """Dense 0/1 soma-by-dendrite connectivity implied by the tree (each dendrite -> one soma).""" + return torch.repeat_interleave(torch.eye(self.somas), self.dendrites_per_soma, dim=1) + + def parameter_count(self) -> int: + """Trainable parameters that exist in the model: unmasked synapses, biases, cable weights.""" + return int(self.synaptic_mask.sum().item()) + self.dendritic_bias.numel() + self.cable_weight.numel() \ + + self.soma_bias.numel() + + def mask_density(self) -> float: + return float(self.synaptic_mask.mean().item()) + + def macs(self) -> int: + """Multiply-accumulates per example that a sparse implementation would need (masked entries excluded).""" + return int(self.synaptic_mask.sum().item()) + self.cable_weight.numel() + + +class DendriticNet(nn.Module): + """``DendriticLayer`` followed by a dense linear read-out over the somata.""" + + def __init__(self, in_features: int, classes: int, somas: int, dendrites_per_soma: int, synapses_per_dendrite: int, + sampling: str = 'random', *, image_shape: tuple[int, int] | None = None, seed: int = 0) -> None: + super().__init__() + _check_int('classes', classes, 2, 1 << 16) + self.dendritic = DendriticLayer(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling, + image_shape=image_shape, seed=seed) + g = torch.Generator().manual_seed(seed + _INIT_OFFSET + 1) + self.readout = _Linear(somas, classes, g) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.readout(self.dendritic(x)) + + def enforce_mask(self) -> None: + self.dendritic.enforce_mask() + + def parameter_count(self) -> int: + return self.dendritic.parameter_count() + self.readout.weight.numel() + self.readout.bias.numel() + + def macs(self) -> int: + return self.dendritic.macs() + self.readout.weight.numel() + + +def dense_parameter_count(in_features: int, classes: int, hidden: int) -> int: + """Trainable parameters of ``DenseMLP(in_features, classes, hidden)``.""" + return in_features * hidden + hidden + hidden * hidden + hidden + hidden * classes + classes + + +def dann_parameter_count(somas: int, dendrites_per_soma: int, synapses_per_dendrite: int, classes: int) -> int: + """Trainable parameters of ``DendriticNet`` (existing synapses, dendritic biases, cable weights, somatic + biases, read-out); independent of the input size and of the sampling mode.""" + dendrites = somas * dendrites_per_soma + return dendrites * synapses_per_dendrite + 2 * dendrites + somas + somas * classes + classes + + +class DenseMLP(nn.Module): + """Dense control: two hidden layers of width ``hidden`` with the same leaky ReLU, then a linear read-out.""" + + def __init__(self, in_features: int, classes: int, hidden: int, *, seed: int = 0) -> None: + super().__init__() + self.in_features = _check_int('in_features', in_features, 1, 1 << 20) + _check_int('classes', classes, 2, 1 << 16) + self.hidden = _check_int('hidden', hidden, 1, 1 << 14) + _check_int('seed', seed, 0, 2**31 - 1) + g = torch.Generator().manual_seed(seed + _INIT_OFFSET + 2) + self.fc1, self.fc2, self.readout = _Linear(in_features, hidden, g), _Linear(hidden, hidden, g), _Linear(hidden, classes, g) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if not isinstance(x, torch.Tensor) or x.ndim != 2 or x.shape[1] != self.in_features: + raise ValueError(f'x must be a tensor of shape (batch, {self.in_features})') + h = F.leaky_relu(self.fc1(x), NEGATIVE_SLOPE) + return self.readout(F.leaky_relu(self.fc2(h), NEGATIVE_SLOPE)) + + def parameter_count(self) -> int: + return int(sum(p.numel() for p in self.parameters() if p.requires_grad)) + + def macs(self) -> int: + return int(self.fc1.weight.numel() + self.fc2.weight.numel() + self.readout.weight.numel()) + + +def matched_dense_hidden(target_params: int, in_features: int, classes: int) -> int: + """Width whose ``DenseMLP`` parameter count is closest to ``target_params``.""" + _check_int('target_params', target_params, 1, 1 << 40) + best, gap = 1, None + for h in range(1, 1 << 14): + n = dense_parameter_count(in_features, classes, h) + if gap is None or abs(n - target_params) < gap: + best, gap = h, abs(n - target_params) + if n > target_params: + break + return best + + +# ====================================================================== glyph data +def _segment_distance(points: np.ndarray, segs: np.ndarray) -> np.ndarray: + """Distance from each point (P, 2) to the nearest segment (K, 2, 2).""" + a, b = segs[:, 0][None], segs[:, 1][None] # (1, K, 2) + p = points[:, None, :] # (P, 1, 2) + ab = b - a + t = np.clip(((p - a) * ab).sum(-1) / np.maximum((ab * ab).sum(-1), 1e-12), 0.0, 1.0) + proj = a + t[..., None] * ab + return np.sqrt(((p - proj) ** 2).sum(-1)).min(axis=1) + + +_PIXELS = np.stack(np.meshgrid(np.arange(GLYPH_SIDE) + 0.5, np.arange(GLYPH_SIDE) + 0.5, indexing='xy'), -1).reshape(-1, 2) + + +def render_glyph(label: int, rng: np.random.Generator, *, noise: float = 0.0, shift: float = 2.0, + size: tuple[float, float] = (6.0, 8.5), thickness: tuple[float, float] = (0.35, 0.9), + rotation: float = 0.25) -> np.ndarray: + """One anti-aliased 12x12 glyph (flattened, float64) with random placement, scale, rotation (radians), + half stroke width and additive Gaussian pixel noise.""" + _check_int('label', label, 0, len(GLYPH_NAMES) - 1) + segs = _SEGMENTS[GLYPH_NAMES[label]] + s = rng.uniform(*size) + theta = rng.uniform(-rotation, rotation) + cx, cy = GLYPH_SIDE / 2 + rng.uniform(-shift, shift, size=2) + half = rng.uniform(*thickness) + rot = np.array([[math.cos(theta), -math.sin(theta)], [math.sin(theta), math.cos(theta)]]) + placed = ((segs - 0.5) * s) @ rot.T + np.array([cx, cy]) + img = np.clip(half + 0.5 - _segment_distance(_PIXELS, placed), 0.0, 1.0) + if noise > 0: + img = img + rng.normal(0.0, noise, size=img.shape) + return img + + +def make_glyph_dataset(n_per_class: int, *, seed: int, noise: float = 0.2, **render_kw: Any + ) -> tuple[torch.Tensor, torch.Tensor]: + """Balanced, shuffled glyph set: ``x`` float32 ``(10 * n_per_class, 144)``, ``y`` int64 labels.""" + _check_int('n_per_class', n_per_class, 1, 1 << 20) + _check_int('seed', seed, 0, 2**40) + if isinstance(noise, bool) or not isinstance(noise, (int, float)) or not 0.0 <= noise <= 10.0: + raise ValueError('noise must be in [0, 10]') + rng = np.random.default_rng(seed) + labels = np.repeat(np.arange(len(GLYPH_NAMES)), n_per_class) + labels = labels[rng.permutation(labels.size)] + x = np.stack([render_glyph(int(c), rng, noise=float(noise), **render_kw) for c in labels]) + return torch.from_numpy(x.astype(np.float32)), torch.from_numpy(labels.astype(np.int64)) + + +# ====================================================================== training / evaluation +@torch.no_grad() +def accuracy(model: nn.Module, x: torch.Tensor, y: torch.Tensor) -> float: + model.eval() + return float((model(x).argmax(-1) == y).float().mean()) + + +@functools.lru_cache(maxsize=1) +def _fused_adam_available() -> bool: + """Whether this torch build runs the fused CPU Adam kernel (several times faster for tiny models).""" + try: + p = nn.Parameter(torch.zeros(2)) + p.grad = torch.ones(2) + torch.optim.Adam([p], lr=1e-3, fused=True).step() + return bool(torch.isfinite(p).all()) + except (RuntimeError, TypeError, ValueError): + return False + + +def train_classifier(model: nn.Module, x: torch.Tensor, y: torch.Tensor, *, updates: int, batch_size: int, lr: float, + generator: torch.Generator) -> dict[str, Any]: + """Adam on cross-entropy over a deterministic shuffled minibatch stream; masks re-applied after each step.""" + _check_int('updates', updates, 1, 1 << 20) + _check_int('batch_size', batch_size, 1, 1 << 16) + if not isinstance(lr, (int, float)) or isinstance(lr, bool) or not 0.0 < float(lr) <= 1.0: + raise ValueError('lr must be a number in (0, 1]') + if x.ndim != 2 or y.ndim != 1 or x.shape[0] != y.shape[0] or x.shape[0] < 1: + raise ValueError('x must be (n, features) and y (n,) with n >= 1') + opt = torch.optim.Adam(model.parameters(), lr=float(lr), **({'fused': True} if _fused_adam_available() else {})) + enforce = getattr(model, 'enforce_mask', None) + order = torch.empty(0, dtype=torch.long) + losses = [] + model.train() + for _ in range(updates): + if order.numel() < batch_size: + order = torch.cat([order, torch.randperm(x.shape[0], generator=generator)]) + idx, order = order[:batch_size], order[batch_size:] + loss = F.cross_entropy(model(x[idx]), y[idx]) + opt.zero_grad(set_to_none=True) + loss.backward() + opt.step() + if enforce is not None: + enforce() + losses.append(float(loss.detach())) + return {'updates': updates, 'final_loss': float(np.mean(losses[-max(1, len(losses) // 10):]))} + + +# ====================================================================== experiment +DEFAULTS: dict[str, Any] = { + 'train_per_class': 60, 'val_per_class': 50, 'test_per_class': 200, 'noise': 0.2, 'extra_noise': 0.5, + 'somas': 16, 'dendrites_per_soma': 8, 'synapses_per_dendrite': 9, + 'updates': 1000, 'batch_size': 64, 'lr': 3e-3, 'param_tolerance': 0.10, +} +QUICK: dict[str, Any] = {**DEFAULTS, 'train_per_class': 40, 'val_per_class': 20, 'test_per_class': 50, 'updates': 250} +_INT_KEYS = {'train_per_class': (2, 100_000), 'val_per_class': (2, 100_000), 'test_per_class': (2, 100_000), + 'somas': (1, 4096), 'dendrites_per_soma': (1, GLYPH_SIDE ** 2), + 'synapses_per_dendrite': (1, GLYPH_SIDE ** 2), 'updates': (1, 1_000_000), 'batch_size': (1, 65_536)} +_FLOAT_KEYS = {'noise': (0.0, 5.0), 'extra_noise': (0.0, 5.0), 'lr': (1e-6, 1.0), 'param_tolerance': (0.0, 1.0)} + + +def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + cfg = dict(QUICK if quick else DEFAULTS) + unknown = set(overrides) - set(cfg) + if unknown: + raise ValueError(f'unknown dendritic_layer options: {sorted(unknown)}') + cfg.update(overrides) + for k, (lo, hi) in _INT_KEYS.items(): + _check_int(k, cfg[k], lo, hi) + for k, (lo, hi) in _FLOAT_KEYS.items(): + v = cfg[k] + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)) or not lo <= v <= hi: + raise ValueError(f'{k} must be a number in [{lo}, {hi}]') + cfg[k] = float(v) + return cfg + + +@contextlib.contextmanager +def _single_thread() -> Iterator[None]: + previous = torch.get_num_threads() + try: + if previous != 1: + torch.set_num_threads(1) + yield + finally: + if torch.get_num_threads() != previous: + torch.set_num_threads(previous) + + +def _seed_data(seed: int, cfg: Mapping[str, Any]) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: + base = seed * 10 + _DATA_OFFSET + data = {'train': make_glyph_dataset(cfg['train_per_class'], seed=base, noise=cfg['noise']), + 'val': make_glyph_dataset(cfg['val_per_class'], seed=base + 1, noise=cfg['noise']), + 'test': make_glyph_dataset(cfg['test_per_class'], seed=base + 2, noise=cfg['noise'])} + xt, yt = data['test'] + g = torch.Generator().manual_seed(seed + _NOISE_OFFSET) + data['test_noisy'] = (xt + cfg['extra_noise'] * torch.randn(xt.shape, generator=g), yt) + return data + + +def _budget(cfg: Mapping[str, Any]) -> dict[str, Any]: + """Parameter budget of every arm, computed before any training; ``ValueError`` when the dense control + cannot be matched within ``param_tolerance`` (e.g. a dANN smaller than the narrowest dense MLP).""" + in_features, classes = GLYPH_SIDE ** 2, len(GLYPH_NAMES) + target = dann_parameter_count(cfg['somas'], cfg['dendrites_per_soma'], cfg['synapses_per_dendrite'], classes) + hidden = matched_dense_hidden(target, in_features, classes) + dense = dense_parameter_count(in_features, classes, hidden) + gap = abs(dense - target) / target + if gap > cfg['param_tolerance']: + raise ValueError(f'the dense MLP cannot match the dANN budget: {dense} vs {target} parameters ' + f'(gap {gap:.3f} > param_tolerance {cfg["param_tolerance"]})') + params = {f'dann_{m}': target for m in SAMPLING_MODES} + params['dense_mlp'] = dense + return {'trainable_parameters': params, 'dense_hidden': hidden, 'max_relative_gap': gap} + + +def _run_seed(seed: int, cfg: dict[str, Any], hidden: int) -> dict[str, Any]: + data = _seed_data(seed, cfg) + x_train, y_train = data['train'] + in_features, classes = x_train.shape[1], len(GLYPH_NAMES) + shape = dict(somas=cfg['somas'], dendrites_per_soma=cfg['dendrites_per_soma'], + synapses_per_dendrite=cfg['synapses_per_dendrite']) + models: dict[str, nn.Module] = {f'dann_{m}': DendriticNet(in_features, classes, sampling=m, seed=seed, **shape) + for m in SAMPLING_MODES} + models['dense_mlp'] = DenseMLP(in_features, classes, hidden, seed=seed) + arms = {} + for name, model in models.items(): + gen = torch.Generator().manual_seed(seed + _STREAM_OFFSET) # same minibatch order for every arm + t0 = time.perf_counter() + log = train_classifier(model, x_train, y_train, updates=cfg['updates'], batch_size=cfg['batch_size'], + lr=cfg['lr'], generator=gen) + t1 = time.perf_counter() + metrics = {split: accuracy(model, *data[split]) for split in ('train', 'val', 'test', 'test_noisy')} + arm = {'seed': int(seed), 'parameters': model.parameter_count(), 'estimated_macs_per_example': model.macs(), + 'training': log, 'train_accuracy': metrics['train'], 'val_accuracy': metrics['val'], + 'heldout_accuracy': metrics['test'], 'heldout_noisy_accuracy': metrics['test_noisy'], + 'measured_wallclock_s': {'train': t1 - t0, 'eval': time.perf_counter() - t1}} + if isinstance(model, DendriticNet): + layer = model.dendritic + arm['mask_density'] = layer.mask_density() + arm['masked_weights_nonzero'] = int((layer.synaptic_weight.detach() * (1 - layer.synaptic_mask)).ne(0).sum()) + arms[name] = arm + return {'arms': arms} + + +def _summary(per_seed: list[dict[str, Any]]) -> dict[str, float]: + keys = ('train_accuracy', 'val_accuracy', 'heldout_accuracy', 'heldout_noisy_accuracy') + return {k: float(np.mean([a[k] for a in per_seed])) for k in keys} + + +def run_experiment(*, quick: bool = False, seeds: Iterable[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """dANN (random / local / global sampling) vs a parameter-matched dense MLP on procedural glyphs. + + Returns a sealed frontier receipt. ``overrides`` may change any key of ``DEFAULTS``.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = tuple(seeds) + 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): + raise ValueError('seeds must be unique non-negative ints') + cfg = _config(quick, overrides) + budget = _budget(cfg) # ValueError before any training + params, gap = budget['trainable_parameters'], budget['max_relative_gap'] + t_start = time.perf_counter() + with _single_thread(): + runs = [_run_seed(s, cfg, budget['dense_hidden']) for s in seeds] + names = [f'dann_{m}' for m in SAMPLING_MODES] + ['dense_mlp'] + per_arm = {n: [r['arms'][n] for r in runs] for n in names} + if any(a['parameters'] != params[n] for n in names for a in per_arm[n]): + raise RuntimeError('built models do not match the computed parameter budget') + summaries = {n: _summary(per_arm[n]) for n in names} + dann_names = names[:-1] + best = max(dann_names, key=lambda n: (summaries[n]['val_accuracy'], -dann_names.index(n))) + acc = {n: [a['heldout_accuracy'] for a in per_arm[n]] for n in names} + noisy = {n: [a['heldout_noisy_accuracy'] for a in per_arm[n]] for n in names} + comparisons = {'best_dann_vs_dense': harness.compare(acc[best], acc['dense_mlp']), + 'best_dann_vs_dense_noisy': harness.compare(noisy[best], noisy['dense_mlp'])} + for n in dann_names: + comparisons[f'{n}_vs_dense'] = harness.compare(acc[n], acc['dense_mlp']) + comparisons[f'{n}_vs_dense_noisy'] = harness.compare(noisy[n], noisy['dense_mlp']) + receipt = harness.base_receipt(MODULE_ID, 'model_comparison', { + **cfg, 'quick': quick, 'seeds': list(seeds), 'task': 'procedural_glyphs_12x12_10_classes', + 'glyphs': list(GLYPH_NAMES), 'metric': 'heldout_accuracy', 'robustness_metric': 'heldout_noisy_accuracy', + 'render': {'shift_px': 2.0, 'size_px': [6.0, 8.5], 'half_thickness_px': [0.35, 0.9], 'rotation_rad': 0.25}, + 'optimizer': 'Adam', 'nonlinearity': f'leaky_relu({NEGATIVE_SLOPE})', 'torch_threads': 1}) + receipt['parameter_budget'] = {'trainable_parameters': params, 'dense_hidden': budget['dense_hidden'], + 'max_relative_gap': gap, 'tolerance': cfg['param_tolerance'], + 'within_tolerance': bool(gap <= cfg['param_tolerance']), + 'dann_mask_density': per_arm['dann_random'][0]['mask_density'], + 'counting': 'dANN counts only unmasked synapses + biases + cable + read-out'} + receipt['arms'] = {n: {'per_seed': per_arm[n], 'summary': summaries[n]} for n in names} + receipt['best_dann'] = {'arm': best, 'selected_by': 'highest mean validation accuracy (held-out set unused)'} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['best_dann_vs_dense']['verdict'] + receipt['verdict_basis'] = f'best_dann({best})_vs_dense_mlp: paired 95% t interval on held-out accuracy over seeds' + receipt['robustness_verdict'] = comparisons['best_dann_vs_dense_noisy']['verdict'] + receipt['estimated_cost'] = {'macs_per_example': {n: per_arm[n][0]['estimated_macs_per_example'] for n in names}, + 'optimizer_updates_per_arm': cfg['updates'], + 'implementation': 'dense masked matmul; sparsity is not exploited for speed'} + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t_start} + receipt['notes'] = ( + 'Synthetic glyph benchmark inspired by dendritic ANNs (Chavlis & Poirazi, Nat. Commun. 2025); not a ' + 'reproduction (no MNIST/CIFAR, no efficiency scores, no sparse-ANN control). All arms: same data, same ' + 'minibatch order, same Adam updates; the dense MLP width is chosen to match trainable parameters. The best ' + 'dANN is picked on a separate validation set before the held-out comparison. With few seeds the paired t ' + 'interval is wide.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/experiment_design.py b/synapse/frontier/experiment_design.py new file mode 100644 index 0000000000000000000000000000000000000000..9ebd9899c2efda011368a4030ef4b0b1ae033c9a --- /dev/null +++ b/synapse/frontier/experiment_design.py @@ -0,0 +1,560 @@ +"""Decision-sensitive experiment selection (frontier module ``experiment_design``). + +Inspired by COUNTERFORM's decision-risk acquisition and Mnemorph (kai9987kai) +and by Bayesian decision-theoretic experimental design (Lindley, 1956; +Chaloner & Verdinelli, 1995). Nothing here reproduces a published result. + +Setting: a finite set of hypotheses ``k`` with prior weights ``w``; a finite +menu of experiments ``e`` whose outcome under hypothesis ``k`` is Gaussian +``y ~ N(mu[k, e], sigma[k, e]^2)``; a finite set of downstream decisions ``d`` +with a loss matrix ``L[d, k]`` and optional per-experiment costs ``c[e]``. + +* Bayes risk of a belief: ``R(w) = min_d sum_k w_k L[d, k]``. +* Decision-sensitive value of experiment ``e``: the expected reduction in Bayes + risk ``R(w) - E_y[R(w'(y))]`` where ``y`` follows the posterior predictive and + ``w'`` is the Bayes update. The expectation uses deterministic Gauss-Hermite + quadrature per mixture component (no Monte-Carlo noise). +* The selector picks the experiment with the largest net value + ``value - cost`` and **abstains** (recommends stopping) when that net value + does not exceed ``abstain_threshold``. +* Baselines: expected information gain (Lindley's mutual information + ``H(w) - E_y[H(w'(y))]``, in nats) and a seeded random selector. + +The value of information is greedy (one step). Greedy decision-risk acquisition +can stop too early when only a *combination* of experiments would change the +decision; receipts record abstentions so this is visible. +""" +from __future__ import annotations + +import math +import time +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any + +import numpy as np + +from . import harness + +__all__ = ['MODULE_ID', 'SELECTORS', 'DecisionProblem', 'DecisionSensitiveSelector', 'InformationGainSelector', + 'RandomSelector', 'make_selector', 'make_study', 'simulate_study', 'run_experiment', 'run_costed_experiment', + 'EXPERIMENTS', 'DEFAULTS'] + +MODULE_ID = 'experiment_design' +SELECTORS = ('decision_risk', 'information_gain', 'random') + +MAX_HYPOTHESES = 64 +MAX_EXPERIMENTS = 64 +MAX_DECISIONS = 32 +MAX_QUADRATURE = 64 +MAX_BUDGET = 64 +_STUDY_OFFSET = 7_919 +_TRUTH_OFFSET = 15_485_863 +_NOISE_OFFSET = 32_452_843 +_RANDOM_SELECT_OFFSET = 104_729 +_EPS = 1e-300 + + +def _finite_array(name: str, value: Any, ndim: int) -> np.ndarray: + try: + arr = np.array(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + if arr.ndim != ndim: + raise ValueError(f'{name} must be {ndim}-dimensional') + if arr.size == 0 or not np.all(np.isfinite(arr)): + raise ValueError(f'{name} must be non-empty and finite') + return arr + + +def _entropy(w: np.ndarray) -> np.ndarray: + """Shannon entropy (nats) along the last axis; 0 log 0 = 0.""" + safe = np.where(w > 0.0, w, 1.0) + return -np.sum(np.where(w > 0.0, w * np.log(safe), 0.0), axis=-1) + + +class DecisionProblem: + """Finite hypotheses x Gaussian experiments x decisions with a loss matrix (immutable after construction).""" + + def __init__(self, prior: Sequence[float], means: Any, sigmas: Any, loss: Any, costs: Sequence[float] | None = None, + *, quadrature: int = 20) -> None: + prior_a = _finite_array('prior', prior, 1) + means_a = _finite_array('means', means, 2) + loss_a = _finite_array('loss', loss, 2) + k, m = means_a.shape + if not 1 <= k <= MAX_HYPOTHESES or not 1 <= m <= MAX_EXPERIMENTS: + raise ValueError(f'means must be (hypotheses<= {MAX_HYPOTHESES}, experiments<= {MAX_EXPERIMENTS})') + if prior_a.shape != (k,) or np.any(prior_a < 0.0) or not prior_a.sum() > 0.0: + raise ValueError('prior must be non-negative, match the hypotheses and have positive mass') + sig = np.array(sigmas, dtype=np.float64) if not np.isscalar(sigmas) else np.full(m, float(sigmas)) + if sig.ndim == 1: + if sig.shape != (m,): + raise ValueError('sigmas must have one value per experiment or shape (hypotheses, experiments)') + sig = np.broadcast_to(sig, (k, m)).copy() + if sig.shape != (k, m) or not np.all(np.isfinite(sig)) or np.any(sig <= 0.0): + raise ValueError('sigmas must be positive and finite with shape (experiments,) or (hypotheses, experiments)') + if loss_a.shape[1] != k or not 1 <= loss_a.shape[0] <= MAX_DECISIONS: + raise ValueError(f'loss must be (decisions<= {MAX_DECISIONS}, hypotheses)') + cost_a = np.zeros(m) if costs is None else _finite_array('costs', costs, 1) + if cost_a.shape != (m,) or np.any(cost_a < 0.0): + raise ValueError('costs must be non-negative with one value per experiment') + if type(quadrature) is not int or not 2 <= quadrature <= MAX_QUADRATURE: + raise ValueError(f'quadrature must be an int in [2, {MAX_QUADRATURE}]') + self.prior = prior_a / prior_a.sum() + self.means = means_a + self.sigmas = sig + self.loss = loss_a + self.costs = cost_a + self.quadrature = quadrature + nodes, weights = np.polynomial.hermite.hermgauss(quadrature) + self._nodes = nodes * math.sqrt(2.0) # N(0, 1) abscissae + self._weights = weights / math.sqrt(math.pi) # sum to 1 + for arr in (self.prior, self.means, self.sigmas, self.loss, self.costs, self._nodes, self._weights): + arr.setflags(write=False) + + # ------------------------------------------------------------------ shapes + @property + def n_hypotheses(self) -> int: + return int(self.means.shape[0]) + + @property + def n_experiments(self) -> int: + return int(self.means.shape[1]) + + @property + def n_decisions(self) -> int: + return int(self.loss.shape[0]) + + def _belief(self, w: Any) -> np.ndarray: + arr = _finite_array('belief', w, 1) + if arr.shape != (self.n_hypotheses,) or np.any(arr < 0.0) or not arr.sum() > 0.0: + raise ValueError('belief must be a non-negative vector over the hypotheses with positive mass') + return arr / arr.sum() + + def _experiment(self, e: Any) -> int: + if type(e) not in (int, np.int64, np.int32) or not 0 <= int(e) < self.n_experiments: + raise ValueError('experiment index out of range') + return int(e) + + # ------------------------------------------------------------------ inference + def log_likelihood(self, e: int, y: Any) -> np.ndarray: + """``log p(y | k, e)`` for every hypothesis (``y`` scalar -> (K,), array (n,) -> (n, K)).""" + e = self._experiment(e) + y_arr = np.asarray(y, dtype=np.float64) + if not np.all(np.isfinite(y_arr)): + raise ValueError('outcome must be finite') + mu, sd = self.means[:, e], self.sigmas[:, e] + z = (y_arr[..., None] - mu) / sd + return -0.5 * z * z - np.log(sd) - 0.5 * math.log(2.0 * math.pi) + + def update(self, w: Any, e: int, y: float) -> np.ndarray: + """Bayes posterior after observing ``y`` from experiment ``e`` (computed in log space).""" + belief = self._belief(w) + logp = np.log(np.maximum(belief, _EPS)) + self.log_likelihood(e, y) + logp = np.where(belief > 0.0, logp, -np.inf) + logp -= logp.max() + post = np.exp(logp) + return post / post.sum() + + def decision(self, w: Any) -> tuple[int, float]: + """Bayes decision (lowest index on ties) and its expected loss.""" + risks = self.loss @ self._belief(w) + d = int(np.argmin(risks)) + return d, float(risks[d]) + + def bayes_risk(self, w: Any) -> float: + return self.decision(w)[1] + + def _fantasies(self, w: np.ndarray, e: int) -> tuple[np.ndarray, np.ndarray]: + """Quadrature outcomes from the posterior predictive: probabilities (K*Q,) and posteriors (K*Q, K).""" + mu, sd = self.means[:, e], self.sigmas[:, e] + ys = (mu[:, None] + sd[:, None] * self._nodes[None, :]).ravel() # (K*Q,) + probs = (w[:, None] * self._weights[None, :]).ravel() + loglik = self.log_likelihood(e, ys) # (K*Q, K) + logp = np.where(w > 0.0, np.log(np.maximum(w, _EPS)), -np.inf)[None, :] + loglik + logp -= logp.max(axis=1, keepdims=True) + post = np.exp(logp) + post /= post.sum(axis=1, keepdims=True) + return probs, post + + def risk_reduction(self, w: Any) -> np.ndarray: + """Expected reduction in Bayes risk for every experiment (clipped at 0 against quadrature error).""" + belief = self._belief(w) + base = self.bayes_risk(belief) + out = np.empty(self.n_experiments) + for e in range(self.n_experiments): + probs, post = self._fantasies(belief, e) + out[e] = base - float(probs @ np.min(post @ self.loss.T, axis=1)) + return np.maximum(out, 0.0) + + def information_gain(self, w: Any) -> np.ndarray: + """Expected information gain (mutual information, nats) for every experiment (clipped at 0).""" + belief = self._belief(w) + base = float(_entropy(belief)) + out = np.empty(self.n_experiments) + for e in range(self.n_experiments): + probs, post = self._fantasies(belief, e) + out[e] = base - float(probs @ _entropy(post)) + return np.maximum(out, 0.0) + + def to_dict(self) -> dict[str, Any]: + return {'prior': self.prior.tolist(), 'means': self.means.tolist(), 'sigmas': self.sigmas.tolist(), + 'loss': self.loss.tolist(), 'costs': self.costs.tolist(), 'quadrature': self.quadrature} + + +# ---------------------------------------------------------------------- selectors + +def _argmax_lowest(x: np.ndarray) -> int: + return int(np.flatnonzero(x == x.max())[0]) + + +class DecisionSensitiveSelector: + """Choose the experiment with the largest expected Bayes-risk reduction net of cost, or abstain.""" + + name = 'decision_risk' + + def __init__(self, problem: DecisionProblem, *, abstain_threshold: float = 1e-9) -> None: + if not isinstance(problem, DecisionProblem): + raise ValueError('problem must be a DecisionProblem') + if not isinstance(abstain_threshold, (int, float)) or not math.isfinite(abstain_threshold) \ + or abstain_threshold < 0.0: + raise ValueError('abstain_threshold must be a finite non-negative number') + self.problem = problem + self.abstain_threshold = float(abstain_threshold) + + def scores(self, w: Any) -> np.ndarray: + return self.problem.risk_reduction(w) - self.problem.costs + + def choose(self, w: Any) -> int | None: + net = self.scores(w) + best = _argmax_lowest(net) + return None if net[best] <= self.abstain_threshold else best + + +class InformationGainSelector: + """Expected-information-gain baseline (stops only when no experiment carries information).""" + + name = 'information_gain' + + def __init__(self, problem: DecisionProblem, *, abstain_threshold: float = 1e-12) -> None: + if not isinstance(problem, DecisionProblem): + raise ValueError('problem must be a DecisionProblem') + if not isinstance(abstain_threshold, (int, float)) or not math.isfinite(abstain_threshold) \ + or abstain_threshold < 0.0: + raise ValueError('abstain_threshold must be a finite non-negative number') + self.problem = problem + self.abstain_threshold = float(abstain_threshold) + + def scores(self, w: Any) -> np.ndarray: + return self.problem.information_gain(w) + + def choose(self, w: Any) -> int | None: + ig = self.scores(w) + best = _argmax_lowest(ig) + return None if ig[best] <= self.abstain_threshold else best + + +class RandomSelector: + """Seeded uniform choice over experiments (never abstains).""" + + name = 'random' + + def __init__(self, problem: DecisionProblem, *, seed: int = 0) -> None: + if not isinstance(problem, DecisionProblem): + raise ValueError('problem must be a DecisionProblem') + if type(seed) is not int or seed < 0: + raise ValueError('seed must be a non-negative int') + self.problem = problem + self._rng = np.random.default_rng(seed + _RANDOM_SELECT_OFFSET) + + def choose(self, w: Any) -> int | None: + self.problem._belief(w) + return int(self._rng.integers(self.problem.n_experiments)) + + +def make_selector(name: str, problem: DecisionProblem, *, seed: int = 0, abstain: bool = True): + """Build a selector by name; ``abstain=False`` gives the decision-risk ranking without its stopping rule.""" + if name == 'decision_risk': + return DecisionSensitiveSelector(problem) if abstain else _NoAbstainDecisionSelector(problem) + if name == 'information_gain': + return InformationGainSelector(problem) + if name == 'random': + return RandomSelector(problem, seed=seed) + raise ValueError(f'selector must be one of {SELECTORS}') + + +class _NoAbstainDecisionSelector(DecisionSensitiveSelector): + """Ablation: decision-risk ranking but always runs an experiment (lowest index when all values are zero).""" + + name = 'decision_risk_no_abstain' + + def choose(self, w: Any) -> int | None: + return _argmax_lowest(self.scores(w)) + + +# ---------------------------------------------------------------------- synthetic studies + +def make_study(seed: int, *, hypotheses: int = 6, experiments: int = 8, decisions: int = 2, distractors: int = 3, + noise: float = 1.0, cost_range: tuple[float, float] = (0.0, 0.0), quadrature: int = 20) -> DecisionProblem: + """Seeded synthetic study where information and decision relevance diverge. + + Hypotheses are split into ``decisions`` groups; decision ``d`` is right for group ``d`` and costs an + asymmetric loss otherwise. *Relevant* experiments separate groups with modest effects. *Distractor* + experiments repeat the same large within-group pattern in every group, so they are very informative about + which hypothesis holds but nearly useless for the decision.""" + if type(seed) is not int or seed < 0: + raise ValueError('seed must be a non-negative int') + for name, value, low, high in (('hypotheses', hypotheses, 2, MAX_HYPOTHESES), + ('experiments', experiments, 1, MAX_EXPERIMENTS), + ('decisions', decisions, 2, MAX_DECISIONS)): + if type(value) is not int or not low <= value <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + if decisions > hypotheses: + raise ValueError('decisions must not exceed hypotheses') + if type(distractors) is not int or not 0 <= distractors < experiments: + raise ValueError('distractors must be an int in [0, experiments)') + if not isinstance(noise, (int, float)) or not math.isfinite(noise) or noise <= 0.0: + raise ValueError('noise must be a positive finite number') + lo, hi = (float(cost_range[0]), float(cost_range[1])) + if not (math.isfinite(lo) and math.isfinite(hi)) or lo < 0.0 or hi < lo: + raise ValueError('cost_range must be finite with 0 <= low <= high') + rng = np.random.default_rng(seed + _STUDY_OFFSET) + group = np.arange(hypotheses) % decisions + rank = np.array([int(np.sum(group[:k] == group[k])) for k in range(hypotheses)]) + size = np.bincount(group, minlength=decisions) + prior = rng.dirichlet(np.full(hypotheses, 4.0)) + wrong = rng.uniform(0.5, 2.0, size=hypotheses) + loss = np.where(np.arange(decisions)[:, None] == group[None, :], 0.0, wrong[None, :]) + relevant = experiments - distractors + means = np.empty((hypotheses, experiments)) + group_effect = rng.normal(0.0, 1.0, size=(decisions, relevant)) + means[:, :relevant] = group_effect[group] + rng.normal(0.0, 0.15, size=(hypotheses, relevant)) + for j in range(distractors): + amp = rng.uniform(2.0, 4.0) + pos = np.where(size[group] > 1, rank / np.maximum(size[group] - 1, 1), 0.5) # same pattern in every group + means[:, relevant + j] = amp * (2.0 * pos - 1.0) + order = rng.permutation(experiments) # hide which experiments are distractors + means = means[:, order] + sigmas = rng.uniform(0.8, 1.2, size=experiments) * float(noise) + costs = rng.uniform(lo, hi, size=experiments) if hi > 0.0 else np.zeros(experiments) + return DecisionProblem(prior, means, sigmas, loss, costs, quadrature=quadrature) + + +def simulate_study(problem: DecisionProblem, truth: int, selector: Any, budget: int, noise: Sequence[float]) -> dict[str, Any]: + """Run ``selector`` for up to ``budget`` experiments against the hidden ``truth``. + + ``noise[t]`` is the standard-normal draw used for the t-th experiment, shared across selectors (common random + numbers). Returns the regret curve after 0..budget experiments, the chosen experiments and the total cost.""" + if type(truth) not in (int, np.int64) or not 0 <= int(truth) < problem.n_hypotheses: + raise ValueError('truth out of range') + if type(budget) is not int or not 0 <= budget <= MAX_BUDGET: + raise ValueError(f'budget must be an int in [0, {MAX_BUDGET}]') + z = np.asarray(noise, dtype=np.float64) + if z.shape != (budget,) or not np.all(np.isfinite(z)): + raise ValueError('noise must hold one finite draw per budget step') + truth = int(truth) + best_loss = float(problem.loss[:, truth].min()) + w = problem.prior.copy() + + def regret() -> float: + d, _ = problem.decision(w) + return float(problem.loss[d, truth]) - best_loss + + curve = [regret()] + chosen: list[int] = [] + cost = 0.0 + abstained_at = None + for t in range(budget): + e = selector.choose(w) if abstained_at is None else None + if e is None: + abstained_at = t if abstained_at is None else abstained_at + curve.append(curve[-1]) + continue + y = float(problem.means[truth, e] + problem.sigmas[truth, e] * z[t]) + w = problem.update(w, e, y) + chosen.append(int(e)) + cost += float(problem.costs[e]) + curve.append(regret()) + d_final, _ = problem.decision(w) + return {'regret_curve': curve, 'final_regret': curve[-1], 'correct': bool(curve[-1] == 0.0), + 'decision': int(d_final), 'experiments': chosen, 'cost': cost, 'abstained_at': abstained_at, + 'final_entropy': float(_entropy(w))} + + +# ---------------------------------------------------------------------- experiments + +DEFAULTS: dict[str, Any] = {'studies': 300, 'budget': 4, 'hypotheses': 6, 'experiments': 8, 'decisions': 2, + 'distractors': 3, 'noise': 1.0, 'quadrature': 20} +_QUICK: dict[str, Any] = {'studies': 60, 'budget': 3} +COSTED_DEFAULTS: dict[str, Any] = {**DEFAULTS, 'budget': 6, 'cost_low': 0.02, 'cost_high': 0.08} +_COSTED_QUICK: dict[str, Any] = {'studies': 60, 'budget': 4} + + +def _check_seeds(seeds: Iterable[int]) -> tuple[int, ...]: + out = tuple(seeds) + if not out or any(type(s) is not int or not 0 <= s <= 2**31 - 1 for s in out) or len(set(out)) != len(out): + raise ValueError('seeds must be unique non-negative ints') + return out + + +def _config(defaults: Mapping[str, Any], quick_over: Mapping[str, Any], quick: bool, + overrides: Mapping[str, Any]) -> dict[str, Any]: + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + unknown = set(overrides) - set(defaults) + if unknown: + raise ValueError(f'unknown overrides: {sorted(unknown)}') + cfg = {**defaults, **(quick_over if quick else {}), **overrides} + if type(cfg['studies']) is not int or not 2 <= cfg['studies'] <= 100_000: + raise ValueError('studies must be an int in [2, 100000]') + if type(cfg['budget']) is not int or not 1 <= cfg['budget'] <= MAX_BUDGET: + raise ValueError(f'budget must be an int in [1, {MAX_BUDGET}]') + return cfg + + +def _study_args(cfg: Mapping[str, Any], costed: bool) -> dict[str, Any]: + args = {k: cfg[k] for k in ('hypotheses', 'experiments', 'decisions', 'distractors', 'noise', 'quadrature')} + if costed: + args['cost_range'] = (float(cfg['cost_low']), float(cfg['cost_high'])) + return args + + +def _run_seed(seed: int, cfg: Mapping[str, Any], arms: Sequence[str], *, costed: bool) -> dict[str, Any]: + truth_rng = np.random.default_rng(seed + _TRUTH_OFFSET) + noise_rng = np.random.default_rng(seed + _NOISE_OFFSET) + budget = int(cfg['budget']) + per_arm: dict[str, dict[str, list]] = {a: {'curves': [], 'costs': [], 'abstentions': [], 'correct': [], + 'experiments_run': [], 'entropy': []} for a in arms} + study_args = _study_args(cfg, costed) + for i in range(int(cfg['studies'])): + problem = make_study(seed * 100_003 + i, **study_args) + truth = int(truth_rng.choice(problem.n_hypotheses, p=problem.prior)) + z = noise_rng.standard_normal(budget) + for a in arms: + if a == 'decision_risk': + sel = DecisionSensitiveSelector(problem) + elif a == 'decision_risk_no_abstain': + sel = _NoAbstainDecisionSelector(problem) + elif a == 'information_gain': + sel = InformationGainSelector(problem) + else: + sel = RandomSelector(problem, seed=seed * 100_003 + i) + res = simulate_study(problem, truth, sel, budget, z) + rec = per_arm[a] + rec['curves'].append(res['regret_curve']) + rec['costs'].append(res['cost']) + rec['abstentions'].append(res['abstained_at'] is not None) + rec['correct'].append(res['correct']) + rec['experiments_run'].append(len(res['experiments'])) + rec['entropy'].append(res['final_entropy']) + out = {} + for a, rec in per_arm.items(): + curves = np.asarray(rec['curves']) + regret = curves[:, -1] + cost = np.asarray(rec['costs']) + out[a] = {'seed': int(seed), 'mean_regret_by_budget': curves.mean(axis=0).tolist(), + 'final_regret': float(regret.mean()), 'decision_accuracy': float(np.mean(rec['correct'])), + 'mean_cost': float(cost.mean()), 'total_loss': float((regret + cost).mean()), + 'abstention_rate': float(np.mean(rec['abstentions'])), + 'mean_experiments_run': float(np.mean(rec['experiments_run'])), + 'final_entropy_nats': float(np.mean(rec['entropy']))} + return out + + +def _summary(per_seed: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + keys = ('final_regret', 'decision_accuracy', 'mean_cost', 'total_loss', 'abstention_rate', + 'mean_experiments_run', 'final_entropy_nats') + out = {k: float(np.mean([p[k] for p in per_seed])) for k in keys} + out['mean_regret_by_budget'] = np.mean([p['mean_regret_by_budget'] for p in per_seed], axis=0).tolist() + return out + + +def _estimated_cost(cfg: Mapping[str, Any], n_arms: int, seeds: int) -> dict[str, Any]: + k, m, q = cfg['hypotheses'], cfg['experiments'], cfg['quadrature'] + per_selection = m * (k * q) * k * 4 # likelihood, posterior, risk/entropy per fantasy outcome + selections = seeds * cfg['studies'] * cfg['budget'] * n_arms + return {'estimated_flops_per_selection': int(per_selection), 'estimated_selections_upper_bound': int(selections), + 'estimated_total_flops_upper_bound': int(per_selection * selections)} + + +def run_experiment(*, quick: bool = False, seeds: Iterable[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Decision-sensitive vs information-gain vs random acquisition at a fixed experiment budget. + + Each seed runs ``studies`` synthetic studies with a hidden true hypothesis; all selectors see the same study, + truth and observation noise. Metric: mean final decision regret (lower is better).""" + seeds = _check_seeds(seeds) + cfg = _config(DEFAULTS, _QUICK, quick, overrides) + make_study(0, **_study_args(cfg, False)) # validate study settings before running + arms = ('decision_risk', 'information_gain', 'random') + t0 = time.perf_counter() + runs = [_run_seed(s, cfg, arms, costed=False) for s in seeds] + per_arm = {a: [r[a] for r in runs] for a in arms} + regret = {a: [p['final_regret'] for p in per_arm[a]] for a in arms} + comparisons = { + 'decision_risk_vs_information_gain': harness.compare(regret['decision_risk'], regret['information_gain'], + higher_is_better=False), + 'decision_risk_vs_random': harness.compare(regret['decision_risk'], regret['random'], higher_is_better=False), + 'information_gain_vs_random': harness.compare(regret['information_gain'], regret['random'], + higher_is_better=False), + } + receipt = harness.base_receipt(MODULE_ID, 'methodology_comparison', { + **cfg, 'quick': quick, 'seeds': list(seeds), 'metric': 'mean_final_decision_regret', + 'higher_is_better': False, 'abstain_threshold': 1e-9, 'quadrature_rule': 'gauss_hermite_per_component', + 'noise_sharing': 'common_random_numbers_across_selectors'}) + receipt['arms'] = {a: {'per_seed': per_arm[a], 'summary': _summary(per_arm[a])} for a in arms} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['decision_risk_vs_information_gain']['verdict'] + receipt['verdict_basis'] = ('decision_risk_vs_information_gain: paired 95% t interval over seeds on mean final ' + 'decision regret (lower is better)') + receipt['parameter_budget'] = {'trainable_parameters': 0, 'experiment_budget_per_study': cfg['budget'], + 'note': 'selectors have no trained parameters; all arms share the same budget'} + receipt['estimated_cost'] = _estimated_cost(cfg, len(arms), len(seeds)) + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0} + receipt['notes'] = ( + 'Synthetic finite-hypothesis studies with Gaussian outcomes, inspired by COUNTERFORM decision-risk acquisition ' + 'and Bayesian decision-theoretic design (Lindley 1956; Chaloner & Verdinelli 1995). Distractor experiments are ' + 'built to be informative about the hypothesis but nearly irrelevant to the decision, which favours a ' + 'decision-sensitive criterion by construction; the result says how much, not whether it generalises. Values ' + 'are one-step (greedy); abstention is rare at the default threshold and is recorded per arm.') + return harness.seal(receipt) + + +def run_costed_experiment(*, quick: bool = False, seeds: Iterable[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """With per-experiment costs: decision-sensitive selection that may abstain vs information gain that always + spends the budget. Metric: mean total loss = final regret + experiment cost (lower is better).""" + seeds = _check_seeds(seeds) + cfg = _config(COSTED_DEFAULTS, _COSTED_QUICK, quick, overrides) + if not 0.0 <= cfg['cost_low'] <= cfg['cost_high'] or not math.isfinite(cfg['cost_high']): + raise ValueError('cost_low/cost_high must satisfy 0 <= low <= high (finite)') + make_study(0, **_study_args(cfg, True)) + arms = ('decision_risk', 'decision_risk_no_abstain', 'information_gain') + t0 = time.perf_counter() + runs = [_run_seed(s, cfg, arms, costed=True) for s in seeds] + per_arm = {a: [r[a] for r in runs] for a in arms} + total = {a: [p['total_loss'] for p in per_arm[a]] for a in arms} + comparisons = { + 'decision_risk_vs_information_gain': harness.compare(total['decision_risk'], total['information_gain'], + higher_is_better=False), + 'decision_risk_vs_no_abstain_ablation': harness.compare(total['decision_risk'], + total['decision_risk_no_abstain'], + higher_is_better=False), + } + receipt = harness.base_receipt(MODULE_ID + '_costed', 'methodology_comparison', { + **cfg, 'quick': quick, 'seeds': list(seeds), 'metric': 'mean_total_loss_regret_plus_cost', + 'higher_is_better': False, 'abstain_threshold': 1e-9, 'quadrature_rule': 'gauss_hermite_per_component', + 'noise_sharing': 'common_random_numbers_across_selectors'}) + receipt['arms'] = {a: {'per_seed': per_arm[a], 'summary': _summary(per_arm[a])} for a in arms} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['decision_risk_vs_information_gain']['verdict'] + receipt['verdict_basis'] = ('decision_risk_vs_information_gain: paired 95% t interval over seeds on mean total ' + 'loss (regret + cost, lower is better)') + receipt['parameter_budget'] = {'trainable_parameters': 0, 'max_experiments_per_study': cfg['budget']} + receipt['estimated_cost'] = _estimated_cost(cfg, len(arms), len(seeds)) + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0} + receipt['notes'] = ( + 'Costs are synthetic and uniform per experiment. The information-gain baseline has no stopping rule, so part of ' + 'any advantage is the abstention rule itself; the no-abstain ablation separates ranking from stopping.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment, + MODULE_ID + '_costed': run_costed_experiment} diff --git a/synapse/frontier/extension.py b/synapse/frontier/extension.py new file mode 100644 index 0000000000000000000000000000000000000000..e66d8814cd2c40b262d6b265eef0e6b6053bb993 --- /dev/null +++ b/synapse/frontier/extension.py @@ -0,0 +1,142 @@ +"""Engine-extension interface (v1) between the frontier pack and the NEUROWEAVE engine. + +``NeuroWeaveEngine.attach_extension`` accepts any object with this shape. Every +hook on the base class is neutral, so a subclass only overrides what it uses. + +Step context +------------ +``ctx`` is a mapping the engine builds once per step: + +``step`` (int), ``learn`` (bool), ``reward`` (float; the effective reward given +to the brain this step), ``raw_reward`` (float), ``task_input`` +(``np.ndarray | None``), ``sensory`` (``np.ndarray`` of 16 fused channels), +``controls`` (the neuromodulatory controls mapping) and ``flags`` +(``frozenset`` of enabled NEUROWEAVE mechanisms). + +Rules +----- +* ``transform_drive`` may change the *values* of the external drive but must + return the same shape (and ``None`` when it receives ``None``). The engine + rejects anything else. +* An extension must not keep a reference to the engine: ``bind`` copies what it + needs. ``copy.deepcopy(extension)`` must give an independent clone. +* All state is finite and bounded; randomness comes from a + ``numpy.random.default_rng`` seeded in ``bind``/``__init__``. +* ``features()`` returns exactly ``feature_dim`` finite values in ``[-10, 10]``. +* With ``ctx['learn']`` false an extension must not adapt (frozen evaluation). +""" +from __future__ import annotations + +from typing import Any, Mapping + +import numpy as np + +EXTENSION_INTERFACE_VERSION = 1 + + +class EngineExtension: + """Neutral base class for NEUROWEAVE engine extensions.""" + + id: str = 'extension' + interface_version: int = EXTENSION_INTERFACE_VERSION + feature_dim: int = 0 + + # ------------------------------------------------------------------ lifecycle + def bind(self, engine: Any) -> None: + """Size the extension from the engine (``engine.n``, regions, seed). Must not keep ``engine``.""" + + def reset(self) -> None: + """Forget cross-step transients (episode boundary).""" + + # ------------------------------------------------------------------ hooks + def transform_drive(self, external: np.ndarray | None, ctx: Mapping[str, Any]) -> np.ndarray | None: + return external + + def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None: + """Called after the brain step with the brain output (a copy).""" + + def features(self) -> np.ndarray: + """Extra readout features (length ``feature_dim``).""" + return np.zeros(self.feature_dim) + + # ------------------------------------------------------------------ accounting / persistence + def parameter_count(self) -> int: + """Trainable parameters, for budget matching.""" + return 0 + + def state_numbers(self) -> int: + """Total stored numbers (parameters + state), for budget matching.""" + return 0 + + def telemetry(self) -> dict[str, Any]: + return {'id': self.id} + + def export_state(self) -> dict[str, Any]: + return {'id': self.id} + + def import_state(self, state: Mapping[str, Any]) -> None: + if not isinstance(state, Mapping) or state.get('id') != self.id: + raise ValueError(f'state does not belong to extension {self.id!r}') + + +class RandomTraceControl(EngineExtension): + """Capacity-matched control: random leaky traces of the brain output. + + It gives the readout the same number of extra features (and comparable + temporal memory) as a candidate extension, without the candidate's + mechanism. A candidate is only credited when it beats this control. + """ + + id = 'random_trace_control' + + def __init__(self, feature_dim: int, seed: int = 0, *, decay_range: tuple[float, float] = (0.5, 0.98)) -> None: + if type(feature_dim) is not int or not 1 <= feature_dim <= 4096: + raise ValueError('feature_dim must be an int in [1, 4096]') + lo, hi = float(decay_range[0]), float(decay_range[1]) + if not 0.0 <= lo <= hi < 1.0: + raise ValueError('decay_range must satisfy 0 <= lo <= hi < 1') + self.feature_dim = feature_dim + self.seed = int(seed) + self.decay_range = (lo, hi) + self._n = 0 + self._proj = np.zeros((feature_dim, 0)) + self._decay = np.linspace(lo, hi, feature_dim) + self._trace = np.zeros(feature_dim) + + def bind(self, engine: Any) -> None: + self._n = int(engine.n) + rng = np.random.default_rng(self.seed + 40_009) + self._proj = rng.standard_normal((self.feature_dim, self._n)) / np.sqrt(max(1, self._n)) + self._trace = np.zeros(self.feature_dim) + + def reset(self) -> None: + self._trace = np.zeros(self.feature_dim) + + def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None: + o = np.zeros(self._n) + m = min(self._n, output.size) # neurons born later are ignored (fixed shape) + o[:m] = output[:m] + self._trace = self._decay * self._trace + (1.0 - self._decay) * np.tanh(self._proj @ o) + + def features(self) -> np.ndarray: + return np.clip(self._trace, -10.0, 10.0) + + def state_numbers(self) -> int: + return int(self._proj.size + self._decay.size + self._trace.size) + + def telemetry(self) -> dict[str, Any]: + return {'id': self.id, 'feature_dim': self.feature_dim, 'trace_norm': float(np.linalg.norm(self._trace))} + + def export_state(self) -> dict[str, Any]: + return {'id': self.id, 'feature_dim': self.feature_dim, 'seed': self.seed, 'n': self._n, + 'decay_range': list(self.decay_range), 'trace': self._trace.tolist()} + + def import_state(self, state: Mapping[str, Any]) -> None: + super().import_state(state) + trace = np.asarray(state.get('trace'), dtype=np.float64) + if (state.get('feature_dim') != self.feature_dim or state.get('n') != self._n + or state.get('seed') != self.seed or state.get('decay_range') != list(self.decay_range) + or trace.shape != (self.feature_dim,) or not np.all(np.isfinite(trace)) + or np.any(np.abs(trace) > 1.0)): + raise ValueError('random_trace_control state does not match this extension') + self._trace = trace.copy() diff --git a/synapse/frontier/harness.py b/synapse/frontier/harness.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5dcc6c2b8027ec3fb8ae6ac4ac5a0a276eb691 --- /dev/null +++ b/synapse/frontier/harness.py @@ -0,0 +1,225 @@ +"""Shared experiment harness for frontier modules. + +Every frontier experiment reports the same things so results are comparable +and hard to over-read: + +* a **baseline** arm (the unmodified system), +* a **candidate** arm (the module under test), +* where the candidate adds capacity, a **capacity-matched control** arm, +* paired differences over seeds with a 95 % t interval and a verdict that is + ``improved`` only when the interval excludes zero, +* frozen held-out evaluation, parameter/state budgets, estimated cost kept + apart from measured wall-clock, and a SHA-256 digest that ignores wall-clock. + +The statistics and receipt helpers are the NEUROWEAVE lab's, reused unchanged. +""" +from __future__ import annotations + +import copy +import time +from typing import Any, Callable, Iterable, Mapping, Sequence + +import numpy as np + +from ..neuroweave.engine import NeuroWeaveEngine +from ..neuroweave.experiments import (ReadoutHead, _HEAD_OFFSET, _budget, _estimated_cost, _finalise, _jsonable, _mean, + clone_engine, make_spec, paired_stats, receipt_digest, run_task_phase, + verdict_from_stats, verify_receipt, VERDICTS) +from ..neuroweave.tasks import make_stream +from .extension import EngineExtension, RandomTraceControl +from .spec import EVIDENCE_TIER, LAB_SCHEMA + +__all__ = ['ExtendedHead', 'clone_with_extensions', 'compare', 'base_receipt', 'seal', 'verify_receipt', + 'receipt_digest', 'run_extension_experiment', 'headline_verdict', 'VERDICTS', 'QUICK_ARGS'] + +TASKS = ('delayed_recall', 'xor', 'rhythm', 'context_switch') +QUICK_ARGS: dict[str, Any] = {'seeds': (0, 1), 'heldout_seeds': (100,), 'steps': 24, 'neurons': 24, + 'heldout_steps': 12} +ExtensionFactory = Callable[[int], 'EngineExtension | Sequence[EngineExtension]'] + + +class ExtendedHead(ReadoutHead): + """The lab's logistic readout plus the attached extensions' features. + + The shared features keep the baseline head's initial weights (same generator + stream), so the only difference from the baseline readout is the extra block.""" + + def __init__(self, n0: int, seed: int, extra_dim: int = 0, lr: float = 0.05) -> None: + super().__init__(n0, seed, lr) + self.extra_dim = int(extra_dim) + if self.extra_dim: + base = self.w + rng = np.random.default_rng(int(seed) + _HEAD_OFFSET) # ReadoutHead's stream: same first draws + self.w = (rng.random(self.dim + self.extra_dim) - 0.5) * 0.02 + assert np.array_equal(self.w[:self.dim], base) + self.dim += self.extra_dim + + def features(self, engine: NeuroWeaveEngine, out: np.ndarray) -> np.ndarray: + x = super().features(engine, out) + if not self.extra_dim: + return x + parts = [np.asarray(e.features(), dtype=np.float64).ravel() for e in engine.extensions] + extra = np.concatenate(parts) if parts else np.zeros(0) + if extra.size != self.extra_dim or not np.all(np.isfinite(extra)): + raise ValueError('extension features do not match the head (size or non-finite values)') + return np.concatenate([x, np.clip(extra, -10.0, 10.0)]) + + +def clone_with_extensions(engine: NeuroWeaveEngine) -> NeuroWeaveEngine: + """Independent copy of an engine and deep copies of its attached extensions.""" + other = clone_engine(engine) + for ext in engine.extensions: + other.attach_extension(copy.deepcopy(ext), bind=False) + return other + + +def compare(candidate: Sequence[float], reference: Sequence[float], *, higher_is_better: bool = True) -> dict[str, Any]: + """Paired statistics plus the CI-only verdict used across the lab.""" + stats = paired_stats(candidate, reference) + return {**stats, **verdict_from_stats(stats, higher_is_better=higher_is_better), + 'higher_is_better': bool(higher_is_better)} + + +def headline_verdict(vs_baseline: Mapping[str, Any], vs_control: Mapping[str, Any] | None) -> dict[str, str]: + """``improved`` needs a win over the baseline *and* (when present) over the capacity-matched control.""" + if vs_baseline['verdict'] == 'worse': + return {'verdict': 'worse', 'basis': 'candidate_vs_baseline'} + if vs_baseline['verdict'] == 'improved' and (vs_control is None or vs_control['verdict'] == 'improved'): + return {'verdict': 'improved', 'basis': 'candidate_vs_baseline' if vs_control is None + else 'candidate_vs_baseline_and_control'} + if vs_baseline['verdict'] == 'improved': + return {'verdict': 'no_detectable_difference', 'basis': 'not_better_than_capacity_matched_control'} + return {'verdict': 'no_detectable_difference', 'basis': 'candidate_vs_baseline'} + + +def base_receipt(experiment_id: str, kind: str, config: Mapping[str, Any]) -> dict[str, Any]: + return {'schema': LAB_SCHEMA, 'schema_version': 1, 'experiment_id': str(experiment_id), 'kind': str(kind), + 'config': _jsonable(dict(config)), 'evidence_tier': EVIDENCE_TIER} + + +def seal(receipt: dict[str, Any]) -> dict[str, Any]: + """JSON-normalise the receipt and add its wall-clock-independent SHA-256 digest.""" + if receipt.get('schema') != LAB_SCHEMA: + raise ValueError('not a frontier lab receipt') + return _finalise(receipt) + + +def _as_list(value: Any) -> list[EngineExtension]: + if value is None: + return [] + return [value] if isinstance(value, EngineExtension) or not isinstance(value, (list, tuple)) else list(value) + + +def _arm(factory: ExtensionFactory | None, seed: int, *, task: str, steps: int, heldout_seeds: Sequence[int], + heldout_steps: int, neurons: int, topology: str, mechanisms: Sequence[str]) -> dict[str, Any]: + spec = make_spec(mechanisms, seed=seed, neurons=neurons, topology=topology, steps=steps) + engine = NeuroWeaveEngine(spec) + exts = _as_list(None if factory is None else factory(seed)) + for ext in exts: + engine.attach_extension(ext) + extra = int(sum(int(e.feature_dim) for e in exts)) + head = ExtendedHead(engine.n, seed, extra) + stream = make_stream(seed, steps) + t0 = time.perf_counter() + train = run_task_phase(engine, {task: head}, stream, learn=True) + train_wall = time.perf_counter() - t0 + held = [] + t1 = time.perf_counter() + for hs in heldout_seeds: + held.append(run_task_phase(clone_with_extensions(engine), {task: head.copy()}, + make_stream(hs, heldout_steps), learn=False)) + held_wall = time.perf_counter() - t1 + tm = train['tasks'][task] + budget = _budget(engine, head) + budget['extension_parameters'] = int(sum(int(e.parameter_count()) for e in exts)) + budget['extension_state_numbers'] = int(sum(int(e.state_numbers()) for e in exts)) + budget['extension_features'] = extra + return { + 'seed': int(seed), 'extensions': [e.id for e in exts], 'train_stream_digest': stream.digest, + 'train': {k: tm[k] for k in ('accuracy', 'log_loss', 'brier', 'chance_accuracy')}, + 'heldout': {k: _mean(h['tasks'][task][k] for h in held) + for k in ('accuracy', 'log_loss', 'brier', 'chance_accuracy')}, + 'telemetry': [_jsonable(e.telemetry()) for e in exts], + 'budget': budget, 'estimated_cost': _estimated_cost(engine, steps, head.dim), + 'measured_wallclock_s': {'train': train_wall, 'heldout': held_wall}, + } + + +def _summary(per_seed: list[dict[str, Any]]) -> dict[str, Any]: + return {'train_accuracy': _mean(a['train']['accuracy'] for a in per_seed), + 'heldout_accuracy': _mean(a['heldout']['accuracy'] for a in per_seed), + 'heldout_log_loss': _mean(a['heldout']['log_loss'] for a in per_seed), + 'heldout_chance_accuracy': _mean(a['heldout']['chance_accuracy'] for a in per_seed)} + + +def run_extension_experiment(experiment_id: str, candidate: ExtensionFactory, *, task: str = 'xor', + seeds: Iterable[int] = (0, 1, 2), heldout_seeds: Iterable[int] = (100, 101), + steps: int = 300, heldout_steps: int | None = None, neurons: int = 48, + topology: str = 'clustered', mechanisms: Iterable[str] = (), + control: ExtensionFactory | str | None = 'random_trace', + metric: str = 'accuracy', notes: str = '') -> dict[str, Any]: + """Baseline vs candidate vs capacity-matched control on a NEUROWEAVE temporal task. + + ``candidate(seed)`` returns the extension(s) to attach for that seed. ``control`` is a factory, ``None`` + (no control arm) or ``'random_trace'`` (random leaky traces with the candidate's feature count; skipped + when the candidate adds no readout features). All arms share seeds, streams, the NEUROWEAVE mechanism + set and the readout protocol; held-out streams are evaluated frozen.""" + seeds, heldout_seeds = tuple(seeds), tuple(heldout_seeds) + for group in (seeds, heldout_seeds): + if not group or any(isinstance(s, bool) or not isinstance(s, (int, np.integer)) + or not 0 <= s < 2**31 for s in group): + raise ValueError('seeds and heldout_seeds must contain non-negative 31-bit integers') + if len(set(group)) != len(group): + raise ValueError('seeds and heldout_seeds must each be unique') + seeds, heldout_seeds = tuple(map(int, seeds)), tuple(map(int, heldout_seeds)) + if set(seeds) & set(heldout_seeds): + raise ValueError('heldout_seeds must be disjoint from seeds') + if task not in TASKS: + raise ValueError(f'task must be one of {TASKS}') + if metric not in ('accuracy', 'log_loss', 'brier'): + raise ValueError("metric must be 'accuracy', 'log_loss' or 'brier'") + if type(steps) is not int or not 4 <= steps <= 100_000: + raise ValueError('steps must be an int in [4, 100000]') + heldout_steps = max(4, steps // 2) if heldout_steps is None else heldout_steps + if type(heldout_steps) is not int or not 1 <= heldout_steps <= 1_000_000: + raise ValueError('heldout_steps must be an int in [1, 1000000]') + mechanisms = tuple(mechanisms) + kw = dict(task=task, steps=steps, heldout_seeds=heldout_seeds, heldout_steps=heldout_steps, neurons=int(neurons), + topology=topology, mechanisms=mechanisms) + probe = _as_list(candidate(seeds[0])) + feature_dim = int(sum(int(e.feature_dim) for e in probe)) + control_factory: ExtensionFactory | None + if control == 'random_trace': + control_factory = (lambda s: RandomTraceControl(feature_dim, seed=s)) if feature_dim > 0 else None + elif control is None or callable(control): + control_factory = control + else: + raise ValueError("control must be a factory, None or 'random_trace'") + + arms: dict[str, list[dict[str, Any]]] = {'baseline': [], 'candidate': []} + if control_factory is not None: + arms['control'] = [] + for s in seeds: + arms['baseline'].append(_arm(None, s, **kw)) + arms['candidate'].append(_arm(candidate, s, **kw)) + if control_factory is not None: + arms['control'].append(_arm(control_factory, s, **kw)) + + higher = metric == 'accuracy' + vals = {name: [a['heldout'][metric] for a in per_seed] for name, per_seed in arms.items()} + vs_baseline = compare(vals['candidate'], vals['baseline'], higher_is_better=higher) + vs_control = compare(vals['candidate'], vals['control'], higher_is_better=higher) if 'control' in arms else None + head = headline_verdict(vs_baseline, vs_control) + receipt = base_receipt(experiment_id, 'extension_task', { + 'task': task, 'seeds': list(seeds), 'heldout_seeds': list(heldout_seeds), 'steps': steps, + 'heldout_steps': heldout_steps, 'neurons': int(neurons), 'topology': topology, + 'mechanisms': list(mechanisms), 'metric': f'heldout_{metric}', 'candidate_feature_dim': feature_dim, + 'control': None if control_factory is None else ('random_trace' if control == 'random_trace' else 'custom')}) + receipt['arms'] = {name: {'per_seed': per_seed, 'summary': _summary(per_seed)} for name, per_seed in arms.items()} + receipt['comparisons'] = {'candidate_vs_baseline': vs_baseline} + if vs_control is not None: + receipt['comparisons']['candidate_vs_control'] = vs_control + receipt['verdict'] = head['verdict'] + receipt['verdict_basis'] = head['basis'] + receipt['notes'] = str(notes) + return seal(receipt) diff --git a/synapse/frontier/hh_cable.py b/synapse/frontier/hh_cable.py new file mode 100644 index 0000000000000000000000000000000000000000..0335b68f0873f03ca3a10a8529793d6e1bcbb3a0 --- /dev/null +++ b/synapse/frontier/hh_cable.py @@ -0,0 +1,1102 @@ +"""Hodgkin-Huxley cable reference (frontier module ``hh_cable``). + +Inspired by NeuroPulse-CableLab (kai9987kai), a browser multi-compartment Hodgkin-Huxley workbench, and built +on the membrane equations of A. L. Hodgkin and A. F. Huxley, "A quantitative description of membrane current +and its application to conduction and excitation in nerve", J. Physiol. 117(4):500-544, August 1952, +doi:10.1113/jphysiol.1952.sp004764. This is a synthetic computational reference: it integrates the 1952 +equations on a discretised, uniform, sealed-end cable. It does not reproduce the paper's numerical procedure +(HH solved a travelling-wave ODE by shooting) and it is not a validated neuron simulator. Full, verified +references: ``docs/frontier/modules/hh_cable.md``. + +Model (``v`` in mV, rest near -65 mV; HH's own variable is the displacement ``V = -(v + 65)``, depolarisation +negative):: + + 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) + dx/dt = phi (alpha_x(v) (1 - x) - beta_x(v) x), x in {m, h, n}, phi = 3 ** ((T - 6.3) / 10) + g_ax = a / (2 Ra dx^2) (HH eqn 28, central differences) + +Sealed ends: no axial current leaves the first or the last compartment. The rate functions are HH eqns 12, 13, +20, 21, 23 and 24 (p. 519) rewritten for ``v``; Table 3 (p. 520) gives the constants (ENa = 50, EK = -77 and +EL = -54.387 mV here). The stimulus is a current density (uA/cm^2) on the membrane of compartment 0. + +Integrators: ``'rk4'`` (classical Runge-Kutta; ``__init__`` rejects time steps beyond a conservative linear +stability bound) and ``'exp_euler'`` (gates integrated exactly for frozen voltage, as in Rush-Larsen; the voltage +takes an exponential step with frozen conductances and neighbour voltages; first order, stable for any step). + +Spike times are upward crossings of 0 mV (re-armed below -30 mV) located inside the step with cubic Hermite +interpolation, so they keep the integrator's order. All randomness-free; nothing here touches global state. +""" +from __future__ import annotations + +import math +import time +from typing import Any, Callable, Mapping, Sequence + +import numpy as np + +__all__ = ['MODULE_ID', 'SOURCE', 'EXPERIMENTS', 'HH_REST_MV', 'HH1952_REFERENCE_AXON', 'METHODS', 'HHCable', + 'vtrap', 'hh_rates', 'steady_state_gates', 'temperature_factor', 'neuroweave_fi_curve', + 'neuroweave_threshold', 'adaptation_index', 'average_ranks', 'spearman_rho', 'compare_fi_curves', + 'run_experiment'] + +MODULE_ID = 'hh_cable' +SOURCE = ('Hodgkin & Huxley, "A quantitative description of membrane current and its application to conduction and ' + 'excitation in nerve", J. Physiol. 117(4):500-544, August 1952, doi:10.1113/jphysiol.1952.sp004764; ' + 'NeuroPulse-CableLab (kai9987kai)') +METHODS = ('rk4', 'exp_euler') +HH_REST_MV = -65.0 # rest of the shifted convention (HH chose V_l so the ionic current is 0 at V = 0) +REFERENCE_TEMPERATURE_C = 6.3 # HH rate constants are for 6.3 C and scale with a Q10 of 3 (p. 519) +Q10 = 3.0 +# HH 1952, p. 528: K = 10.47 /ms at 18.5 C, a = 238 um, R2 = 35.4 ohm cm, Cm = 1 uF/cm^2 -> 18.8 m/s (observed 21.2). +HH1952_REFERENCE_AXON: dict[str, float] = {'diameter_um': 476.0, 'Ra_ohm_cm': 35.4, 'Cm_uF_cm2': 1.0, + 'temperature_c': 18.5, 'computed_velocity_m_s': 18.8, + 'observed_velocity_m_s': 21.2} + +SPIKE_THRESHOLD_MV = 0.0 +REARM_MV = -30.0 +_RK4_STABILITY = 2.5 # dt * lambda_max must stay below this (RK4 real-axis limit is ~2.785) +_MAX_STEPS = 2_000_000 +_MAX_BATCH = 4096 +_MAX_TRACE = 200_000 +_FINITE_CHECK_EVERY = 256 +_E = math.e + +# fused-kernel constants in u = v + 65 (HH's V = -u); rates are stacked as rows (alpha_m, alpha_h, alpha_n, +# beta_m, beta_h, beta_n) so the three gate equations are one vectorised expression +_AH_K, _AH_C = -1.0 / 20.0, math.log(0.07) # alpha_h = 0.07 exp(-u/20) +_BETA_K = np.array([-1.0 / 18.0, -0.1, -1.0 / 80.0])[:, None, None] # beta_m, beta_h argument, beta_n +_BETA_C = np.array([math.log(4.0), 3.0, math.log(0.125)])[:, None, None] # 4 e^(-u/18), e^(-(u-30)/10), ... +_TRAP_SHIFT = np.array([25.0, 10.0])[:, None, None] # alpha_m: u - 25, alpha_n: u - 10 +_TRAP_SCALE = np.array([-0.1, -0.01])[:, None, None] + + +# ====================================================================== validation helpers +def _int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _num(name: str, value: Any, low: float, high: float, *, open_low: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + if not math.isfinite(v) or v < low or v > high or (open_low and v <= low): + raise ValueError(f'{name} must be a finite number in {"(" if open_low else "["}{low}, {high}]') + return v + + +def _vector(name: str, value: Any, *, low: float = -math.inf, high: float = math.inf, min_size: int = 1, + max_size: int = _MAX_BATCH) -> np.ndarray: + try: + arr = np.asarray(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + if arr.ndim != 1 or not min_size <= arr.size <= max_size: + raise ValueError(f'{name} must be a 1-D sequence of {min_size}..{max_size} numbers') + if not np.all(np.isfinite(arr)) or np.any(arr < low) or np.any(arr > high): + raise ValueError(f'{name} must be finite and within [{low}, {high}]') + return arr + + +# ====================================================================== HH rate functions (6.3 C) +def vtrap(x: Any, y: float) -> np.ndarray: + """``x / (1 - exp(-x / y))`` evaluated stably; equals ``y + x / 2`` to first order near ``x = 0``.""" + x = np.asarray(x, dtype=np.float64) + y = float(y) + den = -np.expm1(-x / y) + small = np.abs(x) < 1e-7 + with np.errstate(divide='ignore', invalid='ignore'): + out = x / np.where(small, 1.0, den) + return np.where(small, y + 0.5 * x, out) + + +def hh_rates(v: Any) -> tuple[np.ndarray, ...]: + """``(alpha_m, beta_m, alpha_h, beta_h, alpha_n, beta_n)`` in 1/ms at 6.3 C for membrane potential ``v`` (mV). + + HH eqns 12, 13, 20, 21, 23, 24 with ``V = -(v + 65)``.""" + v = np.asarray(v, dtype=np.float64) + if not np.all(np.isfinite(v)): + raise ValueError('v must be finite') + u = v + 65.0 + return (0.1 * vtrap(v + 40.0, 10.0), 4.0 * np.exp(-u / 18.0), 0.07 * np.exp(-u / 20.0), + 1.0 / (1.0 + np.exp(-(v + 35.0) / 10.0)), 0.01 * vtrap(v + 55.0, 10.0), 0.125 * np.exp(-u / 80.0)) + + +def steady_state_gates(v: Any) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``(m_inf, h_inf, n_inf)`` at voltage ``v`` (temperature independent: ``phi`` scales alpha and beta alike).""" + am, bm, ah, bh, an, bn = hh_rates(v) + return am / (am + bm), ah / (ah + bh), an / (an + bn) + + +def temperature_factor(temperature_c: float) -> float: + """``phi = 3 ** ((T - 6.3) / 10)`` (HH p. 519: rate constants are for 6.3 C and scale with a Q10 of 3).""" + t = _num('temperature_c', temperature_c, -5.0, 45.0) + return float(Q10 ** ((t - REFERENCE_TEMPERATURE_C) / 10.0)) + + +def _gate_rate_bound(v_low: float, v_high: float) -> float: + """max over v in [v_low, v_high] of alpha_x + beta_x for the three gates (6.3 C).""" + v = np.linspace(v_low, v_high, 2001) + am, bm, ah, bh, an, bn = hh_rates(v) + return float(max(np.max(am + bm), np.max(ah + bh), np.max(an + bn))) + + +def _hermite_crossing(v0: float, v1: float, d0: float, d1: float, dt: float, level: float) -> float: + """Fraction ``s`` in [0, 1] of the step at which the cubic Hermite interpolant reaches ``level``.""" + if v1 == v0: + return 1.0 + def p(s: float) -> float: + s2, s3 = s * s, s * s * s + return ((2 * s3 - 3 * s2 + 1) * v0 + (s3 - 2 * s2 + s) * dt * d0 + (-2 * s3 + 3 * s2) * v1 + + (s3 - s2) * dt * d1) + lo, hi = 0.0, 1.0 + if p(lo) >= level: + return 0.0 + for _ in range(60): + mid = 0.5 * (lo + hi) + if p(mid) >= level: + hi = mid + else: + lo = mid + return 0.5 * (lo + hi) + + +def _first_success(flags: Sequence[bool]) -> int | None: + for i, f in enumerate(flags): + if f: + return i + return None + + +def _monotone(flags: Sequence[bool]) -> bool: + """True when every evaluation after the first success also succeeded.""" + i = _first_success(flags) + return i is None or all(flags[i:]) + + +def _batched_bisection(fires: Callable[[np.ndarray], list[bool]], lo: float, hi: float, *, rounds: int, batch: int, + integer: bool = False) -> dict[str, Any]: + """Smallest value in ``[lo, hi]`` for which ``fires`` holds, assuming a monotone response. + + Round 1 evaluates ``batch`` points including both ends (one batched simulation); every further round evaluates + ``batch`` interior points of the current bracket. ``bracket = [a, b]``: ``a`` is the largest value seen silent and + ``b`` the smallest seen firing. ``status`` is ``'resolved'``, ``'lower_fires'`` or ``'upper_silent'``; + ``lower_fires``/``upper_fires`` are the first grid's two ends and ``monotone`` reports whether every evaluated + grid agreed with the monotonicity assumption.""" + grid = np.linspace(lo, hi, batch) + if integer: + grid = np.unique(np.rint(grid)).astype(np.int64) + ok = fires(grid) + monotone = _monotone(ok) + evaluations = int(grid.size) + ends = {'lower_fires': bool(ok[0]), 'upper_fires': bool(ok[-1])} + if ok[0]: + return {'status': 'lower_fires', 'bracket': [grid[0].item(), grid[0].item()], 'monotone': monotone, + 'evaluations': evaluations, **ends} + i = _first_success(ok) + if i is None: + return {'status': 'upper_silent', 'bracket': [grid[-1].item(), None], 'monotone': monotone, + 'evaluations': evaluations, **ends} + a, b = grid[i - 1].item(), grid[i].item() + for _ in range(rounds - 1): + inner = np.linspace(a, b, batch + 2)[1:-1] + if integer: + inner = np.unique(np.rint(inner)).astype(np.int64) + inner = inner[(inner > a) & (inner < b)] + if inner.size == 0: + break + ok = fires(inner) + monotone = monotone and _monotone(ok) + evaluations += int(inner.size) + i = _first_success(ok) + if i is None: + a = inner[-1].item() + else: + b = inner[i].item() + a = inner[i - 1].item() if i > 0 else a + return {'status': 'resolved', 'bracket': [a, b], 'monotone': monotone, 'evaluations': evaluations, **ends} + + +# ====================================================================== cable +class HHCable: + """Uniform multi-compartment Hodgkin-Huxley cable with sealed ends and a step stimulus at compartment 0. + + Units: lengths in um, ``Ra`` in ohm cm, ``Cm`` in uF/cm^2, conductances in mS/cm^2, potentials in mV, + ``dt_ms`` in ms, stimulus current densities in uA/cm^2. Every simulation starts from the resting state.""" + + def __init__(self, compartments: int = 1, length_um: float = 100.0, diameter_um: float = 476.0, + Ra: float = 35.4, Cm: float = 1.0, gNa: float = 120.0, gK: float = 36.0, gL: float = 0.3, + ENa: float = 50.0, EK: float = -77.0, EL: float = -54.387, dt_ms: float = 0.01, + method: str = 'rk4', temperature_c: float = REFERENCE_TEMPERATURE_C) -> None: + self.compartments = _int('compartments', compartments, 1, 4000) + self.length_um = _num('length_um', length_um, 1.0, 1e6) + self.diameter_um = _num('diameter_um', diameter_um, 0.05, 5000.0) + self.Ra = _num('Ra', Ra, 1.0, 1e5) + self.Cm = _num('Cm', Cm, 0.01, 100.0) + self.gNa = _num('gNa', gNa, 0.0, 1e4) + self.gK = _num('gK', gK, 0.0, 1e4) + self.gL = _num('gL', gL, 0.0, 1e4) + self.ENa = _num('ENa', ENa, -200.0, 200.0) + self.EK = _num('EK', EK, -200.0, 200.0) + self.EL = _num('EL', EL, -200.0, 200.0) + self.dt_ms = _num('dt_ms', dt_ms, 0.0, 0.1, open_low=True) + if method not in METHODS: + raise ValueError(f'method must be one of {METHODS}') + self.method = method + self.temperature_c = _num('temperature_c', temperature_c, -5.0, 45.0) + self.phi = temperature_factor(self.temperature_c) + if self.gNa + self.gK + self.gL <= 0.0: + raise ValueError('at least one membrane conductance must be positive') + self._gax = self.axial_conductance(self.diameter_um) + bound = self.stability_bound(self._gax) + if self.method == 'rk4' and self.dt_ms * bound > _RK4_STABILITY: + raise ValueError(f'dt_ms={self.dt_ms} exceeds the conservative RK4 stability limit ' + f'{_RK4_STABILITY / bound:.6g} ms for this cable; reduce dt_ms or use method="exp_euler"') + self._rest: float | None = None + + # ------------------------------------------------------------------ derived quantities + @property + def dx_um(self) -> float: + return self.length_um / self.compartments + + def axial_conductance(self, diameter_um: float) -> float: + """``a / (2 Ra dx^2)`` between neighbouring compartments, in mS/cm^2 (0 for a single compartment).""" + if self.compartments == 1: + return 0.0 + a_cm = 0.5 * float(diameter_um) * 1e-4 + dx_cm = self.dx_um * 1e-4 + return 1e3 * a_cm / (2.0 * self.Ra * dx_cm * dx_cm) + + def stability_bound(self, gax: float) -> float: + """Conservative bound (1/ms) on the stiffness: voltage ``(4 g_ax + gNa + gK + gL) / Cm`` (all channels + open, worst Laplacian mode) and the fastest gate rate ``phi (alpha + beta)`` over a wide voltage range.""" + lap = 0.0 if self.compartments == 1 else (2.0 if self.compartments == 2 else 4.0) * gax + v_lo = min(self.EK, self.EL, self.ENa) - 30.0 + v_hi = max(self.EK, self.EL, self.ENa) + 30.0 + return max((lap + self.gNa + self.gK + self.gL) / self.Cm, self.phi * _gate_rate_bound(v_lo, v_hi)) + + def config(self) -> dict[str, Any]: + return {'compartments': self.compartments, 'length_um': self.length_um, 'diameter_um': self.diameter_um, + 'Ra': self.Ra, 'Cm': self.Cm, 'gNa': self.gNa, 'gK': self.gK, 'gL': self.gL, 'ENa': self.ENa, + 'EK': self.EK, 'EL': self.EL, 'dt_ms': self.dt_ms, 'method': self.method, + 'temperature_c': self.temperature_c} + + def replace(self, **changes: Any) -> 'HHCable': + """A new, fully validated cable with some parameters changed.""" + unknown = sorted(set(changes) - set(self.config())) + if unknown: + raise ValueError(f'unknown HHCable parameters: {unknown}') + return HHCable(**{**self.config(), **changes}) + + # ------------------------------------------------------------------ resting state + def _ionic_ss(self, v: np.ndarray) -> np.ndarray: + m, h, n = steady_state_gates(v) + return self.gNa * m ** 3 * h * (v - self.ENa) + self.gK * n ** 4 * (v - self.EK) + self.gL * (v - self.EL) + + def resting_potential(self) -> float: + """Most negative stable zero of the steady-state ionic current (bisection to 1e-10 mV).""" + if self._rest is None: + grid = np.linspace(-150.0, 100.0, 2501) + f = self._ionic_ss(grid) + idx = np.flatnonzero((f[:-1] < 0.0) & (f[1:] >= 0.0)) + if idx.size == 0: + raise ValueError('no stable resting potential in [-150, 100] mV for these parameters') + lo, hi = float(grid[idx[0]]), float(grid[idx[0] + 1]) + for _ in range(100): + mid = 0.5 * (lo + hi) + if float(self._ionic_ss(np.array(mid))) < 0.0: + lo = mid + else: + hi = mid + if hi - lo < 1e-10: + break + self._rest = 0.5 * (lo + hi) + return self._rest + + # ------------------------------------------------------------------ integrator + def _rhs(self, S: np.ndarray, stim0: np.ndarray, gcol: np.ndarray) -> np.ndarray: + """Time derivative of the stacked state ``S = [v, m, h, n]`` of shape (4, B, N).""" + v = S[0] + u = v + 65.0 + R = np.empty((6,) + v.shape) # alpha_m, alpha_h, alpha_n, beta_m, beta_h, beta_n + np.exp(_BETA_K * u + _BETA_C, out=R[3:]) # 4 e^(-u/18), e^(-(u-30)/10), 0.125 e^(-u/80) + R[4] += 1.0 + np.reciprocal(R[4], out=R[4]) # beta_h = 1 / (1 + e^(-(u-30)/10)) + np.exp(_AH_K * u + _AH_C, out=R[1]) # alpha_h = 0.07 e^(-u/20) + x = u - _TRAP_SHIFT # alpha_m and alpha_n arguments + with np.errstate(divide='ignore', invalid='ignore'): + trap = (_TRAP_SCALE * x) / np.expm1(-0.1 * x) # 0.1 x / (1 - e^(-x/10)), 0.01 x / (1 - e^(-x/10)) + if not math.isfinite(trap.sum()): # x == 0 exactly (0/0): use the limit y + x/2 + trap = np.where(np.isfinite(trap), trap, -_TRAP_SCALE * (10.0 + 0.5 * x)) + R[0:3:2] = trap + D = np.empty_like(S) + np.multiply(self.phi, R[:3] - (R[:3] + R[3:]) * S[1:], out=D[1:]) # phi (alpha (1 - x) - beta x) + m, h, n = S[1], S[2], S[3] + n2 = n * n + dv = -(self.gNa * (m * m * m) * h * (v - self.ENa) + self.gK * (n2 * n2) * (v - self.EK) + + self.gL * (v - self.EL)) + if v.shape[1] > 1: + d = gcol * (v[:, 1:] - v[:, :-1]) + dv[:, :-1] += d + dv[:, 1:] -= d + dv[:, 0] += stim0 + D[0] = dv / self.Cm + return D + + def _step_rk4(self, S: np.ndarray, stim0: np.ndarray, gcol: np.ndarray) -> np.ndarray: + dt = self.dt_ms + k1 = self._rhs(S, stim0, gcol) + k2 = self._rhs(S + (0.5 * dt) * k1, stim0, gcol) + k3 = self._rhs(S + (0.5 * dt) * k2, stim0, gcol) + k4 = self._rhs(S + dt * k3, stim0, gcol) + return S + (dt / 6.0) * (k1 + 2.0 * (k2 + k3) + k4) + + def _step_exp_euler(self, S: np.ndarray, stim0: np.ndarray, gcol: np.ndarray, deg: np.ndarray) -> np.ndarray: + dt, phi = self.dt_ms, self.phi + v = S[0] + am, bm, ah, bh, an, bn = hh_rates(v) + out = np.empty_like(S) + for i, (a, b) in enumerate(((am, bm), (ah, bh), (an, bn)), start=1): + s = a + b + inf = a / s + out[i] = inf + (S[i] - inf) * np.exp(-dt * phi * s) + m, h, n = out[1], out[2], out[3] + gna = self.gNa * m * m * m * h + n2 = n * n + gk = self.gK * n2 * n2 + drive = gna * self.ENa + gk * self.EK + self.gL * self.EL + if v.shape[1] > 1: + nb = np.zeros_like(v) + nb[:, 1:] += v[:, :-1] + nb[:, :-1] += v[:, 1:] + drive = drive + gcol * nb + drive[:, 0] += stim0 + G = gna + gk + self.gL + gcol * deg + vinf = drive / G + out[0] = vinf + (v - vinf) * np.exp(-dt * G / self.Cm) + return out + + def _simulate(self, on: np.ndarray, end: np.ndarray, amp: np.ndarray, n_steps: int, rec: np.ndarray, *, + gax: np.ndarray | None = None, trace_site: int | None = None, + trace_every: int = 1) -> dict[str, Any]: + """Integrate a batch. ``on``/``end``/``amp`` have shape (B, P): pulse ``p`` of element ``b`` injects + ``amp`` into compartment 0 during steps ``on <= k < end``. Returns spike times (ms) per element and + recorded compartment, peak voltages and (optionally) a decimated voltage trace.""" + B = amp.shape[0] + N = self.compartments + g = np.full(B, self._gax) if gax is None else np.asarray(gax, dtype=np.float64) + gcol = g[:, None] + deg = np.full(N, 2.0) + if N == 1: + deg[:] = 0.0 + else: + deg[0] = deg[-1] = 1.0 + v0 = self.resting_potential() + m0, h0, n0 = (float(x) for x in steady_state_gates(np.array(v0))) + S = np.empty((4, B, N)) + S[0], S[1], S[2], S[3] = v0, m0, h0, n0 + changes = np.unique(np.concatenate([on.ravel(), end.ravel()])) + changes = [int(c) for c in changes if 0 < c < n_steps] + stim0 = (amp * ((on <= 0) & (end > 0))).sum(axis=1) + prev = S[0][:, rec].copy() + armed = prev < REARM_MV + peak = prev.copy() + times: list[list[list[float]]] = [[[] for _ in range(rec.size)] for _ in range(B)] + trace = None + if trace_site is not None: + samples = n_steps // trace_every + 1 + trace = np.empty((B, samples)) + trace[:, 0] = S[0][:, trace_site] + dt = self.dt_ms + ci = 0 + for k in range(n_steps): + if ci < len(changes) and k == changes[ci]: + stim0 = (amp * ((on <= k) & (end > k))).sum(axis=1) + ci += 1 + if self.method == 'rk4': + S_new = self._step_rk4(S, stim0, gcol) + else: + S_new = self._step_exp_euler(S, stim0, gcol, deg) + cur = S_new[0][:, rec] + up = armed & (cur >= SPIKE_THRESHOLD_MV) + if up.any(): + d0 = self._rhs(S, stim0, gcol)[0][:, rec] + d1 = self._rhs(S_new, stim0, gcol)[0][:, rec] + for b, s in zip(*np.nonzero(up)): + frac = _hermite_crossing(float(prev[b, s]), float(cur[b, s]), float(d0[b, s]), float(d1[b, s]), + dt, SPIKE_THRESHOLD_MV) + times[int(b)][int(s)].append((k + frac) * dt) + armed &= ~up + armed |= cur < REARM_MV + np.maximum(peak, cur, out=peak) + if trace is not None and (k + 1) % trace_every == 0: + trace[:, (k + 1) // trace_every] = S_new[0][:, trace_site] + if (k + 1) % _FINITE_CHECK_EVERY == 0 and not np.all(np.isfinite(S_new)): + raise FloatingPointError('HH cable integration diverged (non-finite state)') + prev = cur + S = S_new + if not np.all(np.isfinite(S)): + raise FloatingPointError('HH cable integration diverged (non-finite state)') + out: dict[str, Any] = {'spike_times_ms': times, 'peak_mv': peak, 'final_v_mv': S[0].copy()} + if trace is not None: + out['trace_mv'] = trace + out['trace_dt_ms'] = dt * trace_every + return out + + def _pulses_to_steps(self, pulses: Any) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + try: + arr = np.asarray(pulses, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('pulses must be numeric (onset_ms, duration_ms, amplitude) rows') from exc + if arr.ndim == 2: + arr = arr[None] + if arr.ndim != 3 or arr.shape[2] != 3 or not 1 <= arr.shape[0] <= _MAX_BATCH or not 1 <= arr.shape[1] <= 64: + raise ValueError('pulses must have shape (P, 3) or (B, P, 3) with 1 <= B <= 4096 and 1 <= P <= 64') + if not np.all(np.isfinite(arr)): + raise ValueError('pulses must be finite') + if np.any(arr[..., 0] < 0.0) or np.any(arr[..., 1] < 0.0) or np.any(np.abs(arr[..., 2]) > 1e7): + raise ValueError('pulse onsets and durations must be >= 0 and |amplitude| <= 1e7 uA/cm^2') + on = np.rint(arr[..., 0] / self.dt_ms).astype(np.int64) + end = on + np.rint(arr[..., 1] / self.dt_ms).astype(np.int64) + return on, end, arr[..., 2].copy() + + def _steps(self, t_ms: float) -> int: + t = _num('t_stop_ms', t_ms, 0.0, 1e5, open_low=True) + n = int(round(t / self.dt_ms)) + if not 1 <= n <= _MAX_STEPS: + raise ValueError(f't_stop_ms / dt_ms must give 1..{_MAX_STEPS} steps') + return n + + def _sites(self, record: Any) -> np.ndarray: + if record is None: + return np.arange(self.compartments, dtype=np.int64) + idx = np.asarray(record) + if idx.ndim != 1 or idx.size == 0 or idx.dtype.kind not in 'iu': + raise ValueError('record must be a non-empty 1-D sequence of compartment indices') + if idx.min() < 0 or idx.max() >= self.compartments: + raise ValueError('record index out of range') + return idx.astype(np.int64) + + def run(self, pulses: Any, *, t_stop_ms: float, record: Any = None, trace_site: int | None = None, + trace_every: int = 1) -> dict[str, Any]: + """Simulate from rest. ``pulses`` rows are ``(onset_ms, duration_ms, amplitude_uA_cm2)`` applied to + compartment 0 (shape (P, 3) for one run or (B, P, 3) for a batch); onsets and durations are rounded to + the time grid. Returns ``spike_times_ms[b][site]``, ``peak_mv`` (B, sites), ``final_v_mv`` and, with + ``trace_site``, ``trace_mv`` (B, samples) every ``trace_every`` steps.""" + on, end, amp = self._pulses_to_steps(pulses) + n = self._steps(t_stop_ms) + rec = self._sites(record) + if trace_site is not None: + trace_site = _int('trace_site', trace_site, 0, self.compartments - 1) + trace_every = _int('trace_every', trace_every, 1, _MAX_STEPS) + if (n // trace_every + 1) * amp.shape[0] > _MAX_TRACE: + raise ValueError(f'trace would exceed {_MAX_TRACE} samples; increase trace_every') + out = self._simulate(on, end, amp, n, rec, trace_site=trace_site, trace_every=trace_every) + out['record'] = rec.tolist() + out['pulse_steps'] = {'onset': on.tolist(), 'end': end.tolist()} + return out + + # ------------------------------------------------------------------ measurements + def _step_batch(self, amplitudes: np.ndarray, onset_ms: float, duration_ms: float) -> np.ndarray: + rows = np.zeros((amplitudes.size, 1, 3)) + rows[:, 0, 0] = onset_ms + rows[:, 0, 1] = duration_ms + rows[:, 0, 2] = amplitudes + return rows + + def _default_site(self) -> int: + return self.compartments - 1 + + def threshold_current(self, duration_ms: float, *, onset_ms: float = 1.0, window_ms: float | None = None, + site: int | None = None, bracket: tuple[float, float] = (0.0, 50.0), rounds: int = 2, + batch: int = 32) -> dict[str, Any]: + """Smallest step amplitude (uA/cm^2) giving at least one spike at ``site`` (default: the last compartment, + i.e. a spike that reached the far end) within ``window_ms`` of the onset. + + Batched search with ``rounds`` batched simulations of ``batch`` amplitudes each (the first includes both + ends of ``bracket``). Returns the final bracket, its midpoint as ``threshold`` and ``resolved``.""" + duration_ms = _num('duration_ms', duration_ms, 0.0, 1e5, open_low=True) + onset_ms = _num('onset_ms', onset_ms, 0.0, 1e5) + window_ms = duration_ms + 10.0 if window_ms is None else _num('window_ms', window_ms, 0.0, 1e5, open_low=True) + rounds = _int('rounds', rounds, 1, 12) + batch = _int('batch', batch, 3, 1024) + site = self._default_site() if site is None else _int('site', site, 0, self.compartments - 1) + lo, hi = (_num('bracket', b, 0.0, 1e7) for b in bracket) + if not hi > lo: + raise ValueError('bracket must be (low, high) with high > low') + n = self._steps(onset_ms + window_ms) + rec = np.array([site], dtype=np.int64) + + def fires(amps: np.ndarray) -> list[bool]: + on, end, amp = self._pulses_to_steps(self._step_batch(amps, onset_ms, duration_ms)) + res = self._simulate(on, end, amp, n, rec) + return [len(res['spike_times_ms'][b][0]) > 0 for b in range(amps.size)] + + res = _batched_bisection(fires, lo, hi, rounds=rounds, batch=batch) + a, b = res['bracket'] + resolved = res['status'] == 'resolved' + return {'threshold': 0.5 * (a + b) if resolved else None, 'bracket': [a, b], 'resolved': resolved, + 'reason': None if resolved else res['status'], 'monotone': res['monotone'], + 'evaluations': res['evaluations']} + + def fi_curve(self, amplitudes: Any, *, window_ms: float = 200.0, transient_ms: float = 50.0, + onset_ms: float = 1.0, site: int | None = None) -> dict[str, Any]: + """Steady firing rate for constant steps of each amplitude (one batched run). + + Spikes after ``onset + transient`` count; the rate is ``(k - 1) / (t_last - t_first)`` (Hz) for ``k >= 2`` + such spikes and 0 otherwise, so a lone onset spike does not count as repetitive firing.""" + amps = _vector('amplitudes', amplitudes, low=-1e6, high=1e6) + window_ms = _num('window_ms', window_ms, 0.0, 1e5, open_low=True) + transient_ms = _num('transient_ms', transient_ms, 0.0, window_ms) + onset_ms = _num('onset_ms', onset_ms, 0.0, 1e5) + site = self._default_site() if site is None else _int('site', site, 0, self.compartments - 1) + n = self._steps(onset_ms + window_ms) + on, end, amp = self._pulses_to_steps(self._step_batch(amps, onset_ms, window_ms)) + res = self._simulate(on, end, amp, n, np.array([site], dtype=np.int64)) + t0 = onset_ms + transient_ms + rates, counts, isis = [], [], [] + for b in range(amps.size): + st = res['spike_times_ms'][b][0] + steady = [t for t in st if t >= t0] + counts.append(len(st)) + rates.append((len(steady) - 1) * 1000.0 / (steady[-1] - steady[0]) if len(steady) >= 2 else 0.0) + isis.append(np.diff(st).tolist()) + return {'amplitudes': amps.tolist(), 'rates_hz': rates, 'spike_counts': counts, 'isis_ms': isis, + 'peak_mv': res['peak_mv'][:, 0].tolist(), 'final_v_mv': res['final_v_mv'][:, site].tolist(), + 'window_ms': window_ms, 'transient_ms': transient_ms} + + def conduction_velocity(self, *, amplitude: float = 3000.0, duration_ms: float = 0.2, t_stop_ms: float = 2.0, + sites: tuple[int, int] | None = None, + diameters_um: Sequence[float] | None = None) -> dict[str, Any]: + """Conduction velocity (m/s) from first-spike arrival times at two compartments (default at 1/3 and 2/3 + of the cable). The stimulated end and the sealed far end both bias the local velocity over a few + millimetres for squid-sized axons (the wave speeds up as it approaches the sealed end), so the cable + should be long compared with that range; ``run_experiment`` uses 40 mm. With ``diameters_um`` the run + is batched over diameters (each one checked against the RK4 stability bound).""" + if self.compartments < 4: + raise ValueError('conduction velocity needs at least 4 compartments') + amplitude = _num('amplitude', amplitude, 0.0, 1e7, open_low=True) + duration_ms = _num('duration_ms', duration_ms, 0.0, 1e5, open_low=True) + if sites is None: + sites = (self.compartments // 3, (2 * self.compartments) // 3) + i1, i2 = (_int('site', s, 0, self.compartments - 1) for s in sites) + if not i2 > i1: + raise ValueError('sites must be increasing') + diam = (np.array([self.diameter_um]) if diameters_um is None + else _vector('diameters_um', diameters_um, low=0.05, high=5000.0, max_size=64)) + gax = np.array([self.axial_conductance(d) for d in diam]) + if self.method == 'rk4' and self.dt_ms * self.stability_bound(float(gax.max())) > _RK4_STABILITY: + raise ValueError('dt_ms exceeds the RK4 stability limit for the largest diameter') + n = self._steps(t_stop_ms) + on, end, amp = self._pulses_to_steps(self._step_batch(np.full(diam.size, amplitude), 0.0, duration_ms)) + mid = self.compartments // 2 + res = self._simulate(on, end, amp, n, np.array([i1, mid, i2], dtype=np.int64), gax=gax) + dist_um = (i2 - i1) * self.dx_um + rows = [] + for b, d in enumerate(diam): + st = res['spike_times_ms'][b] + t1 = st[0][0] if st[0] else None + t2 = st[2][0] if st[2] else None + ok = t1 is not None and t2 is not None and t2 > t1 + rows.append({'diameter_um': float(d), 'axial_conductance_mS_cm2': float(gax[b]), + 'arrival_ms': [t1, t2], 'velocity_m_s': dist_um / (t2 - t1) * 1e-3 if ok else None, + 'mid_peak_mv': float(res['peak_mv'][b, 1])}) + return {'sites': [i1, i2], 'distance_um': dist_um, 'rows': rows} + + def refractory_period(self, *, pulse_ms: float = 0.5, threshold: float | None = None, + conditioning_multiple: float = 2.0, test_multiple: float = 4.0, max_interval_ms: float = 20.0, + onset_ms: float = 1.0, rounds: int = 2, batch: int = 32, site: int | None = None, + threshold_bracket: tuple[float, float] = (0.0, 500.0), threshold_rounds: int = 2, + tail_ms: float = 10.0) -> dict[str, Any]: + """Paired-pulse refractory period: the smallest onset-to-onset interval at which a test pulse of + ``test_multiple`` x the single-pulse threshold evokes a second spike after a conditioning spike. + + Batched search over intervals on the time grid (``rounds`` batched simulations of ``batch`` intervals; + the first includes the shortest interval, one pulse width, and ``max_interval_ms``); each run lasts until + ``tail_ms`` after the latest test pulse. With a strong test pulse this is an operational estimate of the + absolute refractory period (recovery assumed monotone near the transition; ``monotone`` reports whether + every evaluated grid agreed). Without ``threshold`` the single-pulse threshold is searched first + (``threshold_rounds`` batched simulations) and the upper end of its bracket is used.""" + pulse_ms = _num('pulse_ms', pulse_ms, 0.0, 100.0, open_low=True) + conditioning_multiple = _num('conditioning_multiple', conditioning_multiple, 1.0, 1e3, open_low=True) + test_multiple = _num('test_multiple', test_multiple, 1.0, 1e3, open_low=True) + max_interval_ms = _num('max_interval_ms', max_interval_ms, pulse_ms, 1e4, open_low=True) + onset_ms = _num('onset_ms', onset_ms, 0.0, 1e4) + tail_ms = _num('tail_ms', tail_ms, 1.0, 1e4) + rounds = _int('rounds', rounds, 1, 12) + threshold_rounds = _int('threshold_rounds', threshold_rounds, 1, 12) + batch = _int('batch', batch, 3, 1024) + site = self._default_site() if site is None else _int('site', site, 0, self.compartments - 1) + thr_info = None + if threshold is None: + thr_info = self.threshold_current(pulse_ms, onset_ms=onset_ms, site=site, bracket=threshold_bracket, + rounds=threshold_rounds, batch=batch) + if not thr_info['resolved']: + raise ValueError(f'single-pulse threshold not found in {threshold_bracket}') + threshold = thr_info['bracket'][1] # upper end: certainly suprathreshold + threshold = _num('threshold', threshold, 0.0, 1e7, open_low=True) + dt = self.dt_ms + pulse_steps = max(1, int(round(pulse_ms / dt))) + lo, hi = pulse_steps, int(round(max_interval_ms / dt)) + if not hi > lo: + raise ValueError('max_interval_ms must exceed the pulse width by at least one time step') + n = self._steps(onset_ms + max_interval_ms + pulse_ms + tail_ms) + rec = np.array([site], dtype=np.int64) + on0 = int(round(onset_ms / dt)) + + def second_spike(intervals: np.ndarray) -> list[bool]: + B = intervals.size + on = np.empty((B, 2), dtype=np.int64) + on[:, 0] = on0 + on[:, 1] = on0 + intervals + end = on + pulse_steps + amp = np.empty((B, 2)) + amp[:, 0] = conditioning_multiple * threshold + amp[:, 1] = test_multiple * threshold + res = self._simulate(on, end, amp, n, rec) + out = [] + for b in range(B): + st = res['spike_times_ms'][b][0] + t_test = (on0 + intervals[b]) * dt + out.append(len(st) >= 2 and st[0] < t_test and st[-1] >= t_test) + return out + + res = _batched_bisection(second_spike, lo, hi, rounds=rounds, batch=batch, integer=True) + info: dict[str, Any] = {'pulse_ms': pulse_steps * dt, 'threshold_uA_cm2': threshold, + 'threshold_search': thr_info, 'test_amplitude': test_multiple * threshold, + 'conditioning_amplitude': conditioning_multiple * threshold, + 'fails_at_min_interval': not res['lower_fires'], + 'succeeds_at_max_interval': res['upper_fires'], + 'evaluations': res['evaluations']} + if res['status'] != 'resolved': + info.update({'refractory_ms': None, 'bracket_ms': None, 'monotone': res['monotone']}) + return info + a, b = res['bracket'] + info.update({'refractory_ms': b * dt, 'bracket_ms': [a * dt, b * dt], 'monotone': res['monotone']}) + return info + + +# ====================================================================== NEUROWEAVE cell (abstract) reference +def neuroweave_fi_curve(drives: Any, *, steps: int = 400, transient: int = 100, seed: int = 0, + flags: Sequence[str] = ('membrane_dynamics',)) -> dict[str, Any]: + """Spike counts and steady rates of isolated NEUROWEAVE cells (``CellPopulation``) under constant external drive. + + One cell per drive value, no recurrent input, neutral controls. The rate is ``(k - 1) / (t_last - t_first)`` + spikes per step over the spikes after ``transient`` (0 for fewer than two), as for the HH curve.""" + from ..neuroweave.cells import NEURON_FLAGS, CellPopulation, CompartmentDrive + u = _vector('drives', drives, low=-100.0, high=100.0) + steps = _int('steps', steps, 2, 1_000_000) + transient = _int('transient', transient, 0, steps - 1) + seed = _int('seed', seed, 0, 2**31 - 1) + flags = frozenset(flags) + if not flags <= set(NEURON_FLAGS): + raise ValueError(f'flags must be NEUROWEAVE neuron flags {NEURON_FLAGS}') + k = u.size + cells = CellPopulation(k, seed=seed, regions=np.zeros(k, dtype=np.int64), signs=np.ones(k, dtype=np.int64)) + zero = np.zeros(k) + spikes = np.zeros((steps, k), dtype=bool) + for t in range(steps): + cells.step(CompartmentDrive(zero.copy(), zero.copy(), zero.copy(), zero.copy(), u.copy()), flags) + spikes[t] = cells.spike > 0 + rates, counts, isis = [], [], [] + for j in range(k): + st = np.flatnonzero(spikes[:, j]) + steady = st[st >= transient] + counts.append(int(st.size)) + rates.append(float((steady.size - 1) / (steady[-1] - steady[0])) if steady.size >= 2 else 0.0) + isis.append(np.diff(st).astype(float).tolist()) + return {'drives': u.tolist(), 'rates_per_step': rates, 'spike_counts': counts, 'isis_steps': isis, + 'steps': steps, 'transient': transient, 'flags': sorted(flags)} + + +def neuroweave_threshold(*, steps: int = 400, seed: int = 0, bracket: tuple[float, float] = (0.0, 2.0), + rounds: int = 2, batch: int = 64, flags: Sequence[str] = ('membrane_dynamics',)) -> dict[str, Any]: + """Smallest constant external drive that makes an isolated NEUROWEAVE cell spike within ``steps`` steps. + + Same batched search as :meth:`HHCable.threshold_current`: ``rounds`` populations of ``batch`` cells, the + first including both ends of ``bracket``.""" + lo, hi = (_num('bracket', b, -100.0, 100.0) for b in bracket) + if not hi > lo: + raise ValueError('bracket must be (low, high) with high > low') + rounds = _int('rounds', rounds, 1, 12) + batch = _int('batch', batch, 3, 4096) + + def fires(values: np.ndarray) -> list[bool]: + res = neuroweave_fi_curve(values, steps=steps, transient=0, seed=seed, flags=flags) + return [c > 0 for c in res['spike_counts']] + + res = _batched_bisection(fires, lo, hi, rounds=rounds, batch=batch) + a, b = res['bracket'] + resolved = res['status'] == 'resolved' + return {'threshold': 0.5 * (a + b) if resolved else None, 'bracket': [a, b], 'resolved': resolved, + 'reason': None if resolved else res['status'], 'monotone': res['monotone'], + 'evaluations': res['evaluations']} + + +def adaptation_index(isis: Sequence[float]) -> float | None: + """Mean of ``(ISI_{k+1} - ISI_k) / (ISI_{k+1} + ISI_k)``: 0 for regular firing, > 0 when firing slows down. + ``None`` with fewer than two intervals.""" + x = np.asarray(list(isis), dtype=np.float64) + if x.size < 2 or not np.all(np.isfinite(x)) or np.any(x <= 0.0): + return None + return float(np.mean((x[1:] - x[:-1]) / (x[1:] + x[:-1]))) + + +def average_ranks(x: Any) -> np.ndarray: + """Ranks 1..n of a 1-D sequence with tied values sharing their average rank.""" + a = np.asarray(x, dtype=np.float64) + if a.ndim != 1 or not np.all(np.isfinite(a)): + raise ValueError('average_ranks needs a finite 1-D sequence') + order = np.argsort(a, kind='mergesort') + s = a[order] + starts = np.flatnonzero(np.r_[True, s[1:] != s[:-1]]) # first index of each run of equal values + ends = np.r_[starts[1:], s.size] + ranks = np.empty(a.size) + ranks[order] = np.repeat(0.5 * (starts + ends - 1) + 1.0, ends - starts) + return ranks + + +def spearman_rho(a: Any, b: Any) -> float | None: + """Spearman rank correlation (Pearson correlation of average ranks); ``None`` when either side is constant.""" + ra, rb = average_ranks(a), average_ranks(b) + if ra.size != rb.size or ra.size < 2: + raise ValueError('spearman_rho needs two sequences of equal length >= 2') + ra -= ra.mean() + rb -= rb.mean() + den = math.sqrt(float(ra @ ra) * float(rb @ rb)) + return None if den == 0.0 else float(ra @ rb) / den + + +def compare_fi_curves(levels: Sequence[float], hh_rates: Sequence[float], + nw_rates: Sequence[float]) -> dict[str, Any]: + """Max-normalised curves on shared threshold-normalised drive levels and their Spearman rank correlation + (over the suprathreshold levels, ``level >= 1``). Descriptive only.""" + lv = np.asarray(levels, dtype=np.float64) + a = np.asarray(hh_rates, dtype=np.float64) + b = np.asarray(nw_rates, dtype=np.float64) + if not (lv.shape == a.shape == b.shape) or lv.ndim != 1: + raise ValueError('levels and rates must be 1-D sequences of equal length') + na = a / a.max() if a.max() > 0 else np.zeros_like(a) + nb = b / b.max() if b.max() > 0 else np.zeros_like(b) + sel = lv >= 1.0 + rho = None + if sel.sum() >= 3 and np.ptp(na[sel]) > 0 and np.ptp(nb[sel]) > 0: + rho = spearman_rho(na[sel], nb[sel]) + + def onset(x: np.ndarray) -> float | None: + i = _first_success(list(x > 0)) + return None if i is None else float(lv[i]) + + return {'levels': lv.tolist(), 'hh_normalised': na.tolist(), 'neuroweave_normalised': nb.tolist(), + 'spearman_suprathreshold': rho, 'hh_repetitive_onset_level': onset(a), + 'neuroweave_repetitive_onset_level': onset(b), + 'hh_first_nonzero_normalised_rate': None if onset(a) is None else float(na[a > 0][0]), + 'neuroweave_first_nonzero_normalised_rate': None if onset(b) is None else float(nb[b > 0][0]), + 'mean_abs_difference': float(np.mean(np.abs(na - nb)))} + + +# ====================================================================== validation experiment +_DEFAULTS: dict[str, Any] = { + 'patch_dt_ms': 0.0125, 'patch_temperature_c': 6.3, 'fi_window_ms': 200.0, 'fi_transient_ms': 50.0, + 'fi_levels': (0.0, 0.5, 0.9, 1.1, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 5.0, 6.0, 8.0, 10.0, 15.0, 20.0), + 'threshold_bracket': (0.0, 20.0), 'threshold_window_ms': 40.0, 'threshold_rounds': 2, 'search_batch': 32, + 'pulse_ms': 0.5, 'pulse_bracket': (0.0, 100.0), 'refractory_test_multiple': 4.0, 'refractory_rounds': 2, + 'refractory_max_interval_ms': 20.0, 'refractory_tail_ms': 10.0, 'convergence_amplitude': 20.0, + 'convergence_dts': (0.0125, 0.00625, 0.003125), 'convergence_t_stop_ms': 4.0, 'convergence_floor_ms': 1e-6, + # 40 mm cable, velocity between 1/3 and 2/3 of its length: both ends bias the local speed over several mm + 'cable_temperature_c': 18.5, 'cable_length_um': 40000.0, 'cable_compartments': 200, 'cable_dt_ms': 0.0006, + 'cable_diameters_um': (119.0, 238.0, 476.0), 'cable_Ra': 35.4, 'cable_amplitude': 3000.0, + 'cable_pulse_ms': 0.2, 'cable_t_stop_ms': 3.4, 'reference_tolerance': 0.02, 'scaling_tolerance': 0.03, + 'neuroweave_steps': 600, 'neuroweave_transient': 150, 'adaptation_level': 4.0, +} +_QUICK: dict[str, Any] = {'fi_window_ms': 40.0, 'fi_transient_ms': 10.0, 'threshold_window_ms': 15.0, + 'threshold_rounds': 1, 'refractory_rounds': 1, 'search_batch': 64, + 'threshold_bracket': (0.0, 5.0), 'pulse_bracket': (0.0, 40.0), + 'fi_levels': (0.0, 0.5, 0.9, 1.1, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0), + 'refractory_max_interval_ms': 12.0, 'refractory_tail_ms': 4.0, 'convergence_t_stop_ms': 2.5, + 'cable_compartments': 60, 'cable_dt_ms': 0.005, + 'neuroweave_steps': 150, 'neuroweave_transient': 40} + + +def _seeds(seeds: Any) -> tuple[int, ...]: + try: + out = tuple(_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +def _validate_config(cfg: Mapping[str, Any]) -> dict[str, Any]: + c = dict(cfg) + for key in ('patch_dt_ms', 'cable_dt_ms'): + c[key] = _num(key, c[key], 0.0, 0.1, open_low=True) + for key in ('patch_temperature_c', 'cable_temperature_c'): + c[key] = _num(key, c[key], -5.0, 45.0) + c['fi_window_ms'] = _num('fi_window_ms', c['fi_window_ms'], 10.0, 5000.0) + c['fi_transient_ms'] = _num('fi_transient_ms', c['fi_transient_ms'], 0.0, c['fi_window_ms'] / 2) + c['fi_levels'] = tuple(float(x) for x in _vector('fi_levels', c['fi_levels'], low=0.0, high=1000.0, min_size=3, + max_size=128)) + if sorted(set(c['fi_levels'])) != list(c['fi_levels']) or sum(1 for x in c['fi_levels'] if x >= 1.0) < 3: + raise ValueError('fi_levels must be increasing with at least three levels >= 1') + if c['fi_levels'][-1] < 1.1: + raise ValueError('fi_levels must include a suprathreshold level >= 1.1') + for key in ('threshold_bracket', 'pulse_bracket'): + b = tuple(float(x) for x in _vector(key, c[key], low=0.0, high=1e7, min_size=2, max_size=2)) + if not b[1] > b[0]: + raise ValueError(f'{key} must be increasing') + c[key] = b + c['threshold_window_ms'] = _num('threshold_window_ms', c['threshold_window_ms'], 5.0, c['fi_window_ms']) + c['threshold_rounds'] = _int('threshold_rounds', c['threshold_rounds'], 1, 12) + c['search_batch'] = _int('search_batch', c['search_batch'], 4, 256) + c['pulse_ms'] = _num('pulse_ms', c['pulse_ms'], 0.0, 10.0, open_low=True) + c['refractory_test_multiple'] = _num('refractory_test_multiple', c['refractory_test_multiple'], 1.0, 100.0, + open_low=True) + c['refractory_rounds'] = _int('refractory_rounds', c['refractory_rounds'], 1, 12) + c['refractory_max_interval_ms'] = _num('refractory_max_interval_ms', c['refractory_max_interval_ms'], + c['pulse_ms'], 500.0, open_low=True) + c['refractory_tail_ms'] = _num('refractory_tail_ms', c['refractory_tail_ms'], 2.0, 100.0) + c['convergence_amplitude'] = _num('convergence_amplitude', c['convergence_amplitude'], 0.0, 1e5, open_low=True) + dts = tuple(float(x) for x in _vector('convergence_dts', c['convergence_dts'], low=1e-6, high=0.1, + min_size=3, max_size=3)) + if not all(math.isclose(coarse, 2.0 * fine) for coarse, fine in zip(dts, dts[1:])): + raise ValueError('convergence_dts must halve at each refinement') + c['convergence_dts'] = dts + c['convergence_t_stop_ms'] = _num('convergence_t_stop_ms', c['convergence_t_stop_ms'], 2.0, 100.0) + c['convergence_floor_ms'] = _num('convergence_floor_ms', c['convergence_floor_ms'], 0.0, 1e-3, open_low=True) + c['cable_length_um'] = _num('cable_length_um', c['cable_length_um'], 100.0, 1e6) + c['cable_compartments'] = _int('cable_compartments', c['cable_compartments'], 8, 4000) + diam = tuple(float(x) for x in _vector('cable_diameters_um', c['cable_diameters_um'], low=0.05, high=5000.0, + min_size=2, max_size=16)) + if sorted(set(diam)) != list(diam): + raise ValueError('cable_diameters_um must be strictly increasing') + c['cable_diameters_um'] = diam + c['cable_Ra'] = _num('cable_Ra', c['cable_Ra'], 1.0, 1e5) + c['cable_amplitude'] = _num('cable_amplitude', c['cable_amplitude'], 0.0, 1e7, open_low=True) + c['cable_pulse_ms'] = _num('cable_pulse_ms', c['cable_pulse_ms'], 0.0, 10.0, open_low=True) + c['cable_t_stop_ms'] = _num('cable_t_stop_ms', c['cable_t_stop_ms'], 0.1, 100.0) + c['reference_tolerance'] = _num('reference_tolerance', c['reference_tolerance'], 0.0, 1.0, open_low=True) + c['scaling_tolerance'] = _num('scaling_tolerance', c['scaling_tolerance'], 0.0, 0.5, open_low=True) + c['neuroweave_steps'] = _int('neuroweave_steps', c['neuroweave_steps'], 20, 100_000) + c['neuroweave_transient'] = _int('neuroweave_transient', c['neuroweave_transient'], 0, c['neuroweave_steps'] // 2) + c['adaptation_level'] = _num('adaptation_level', c['adaptation_level'], 1.0, 1000.0) + return c + + +def _convergence(c: Mapping[str, Any]) -> dict[str, Any]: + """First-spike time of the patch for a strong 1 ms step at three time steps (RK4 and exponential Euler).""" + out: dict[str, Any] = {} + for method in METHODS: + times = [] + for dt in c['convergence_dts']: + cable = HHCable(dt_ms=dt, method=method, temperature_c=c['patch_temperature_c']) + res = cable.run([[0.5, 1.0, c['convergence_amplitude']]], t_stop_ms=c['convergence_t_stop_ms'], record=[0]) + st = res['spike_times_ms'][0][0] + times.append(st[0] if st else None) + if any(t is None for t in times): + out[method] = {'spike_times_ms': times, 'error_coarse': None, 'error_fine': None, 'observed_order': None} + continue + e1, e2 = abs(times[0] - times[1]), abs(times[1] - times[2]) + ratio = c['convergence_dts'][0] / c['convergence_dts'][1] + order = math.log(e1 / e2) / math.log(ratio) if e1 > 0 and e2 > 0 else None + out[method] = {'spike_times_ms': times, 'error_coarse': e1, 'error_fine': e2, 'observed_order': order} + return out + + +def _estimated_cost(c: Mapping[str, Any], n_seeds: int, refr: Mapping[str, Any]) -> dict[str, int]: + """Sequential integration steps (each batched over its amplitudes/intervals/diameters) and cell updates.""" + dt = c['patch_dt_ms'] + steps = lambda t_ms, step=dt: int(round(t_ms / step)) + pulse_rounds = c['threshold_rounds'] if refr.get('threshold_search') else 0 + patch = (c['threshold_rounds'] * steps(1.0 + c['threshold_window_ms']) + steps(1.0 + c['fi_window_ms']) + + pulse_rounds * steps(1.0 + c['pulse_ms'] + 10.0) + + c['refractory_rounds'] * steps(1.0 + c['refractory_max_interval_ms'] + c['pulse_ms'] + + c['refractory_tail_ms'])) + convergence = 2 * sum(steps(c['convergence_t_stop_ms'], h) for h in c['convergence_dts']) + cable = 3 * steps(c['cable_t_stop_ms'], c['cable_dt_ms']) # dt and dt/2 runs + nw_sequential = 2 * c['neuroweave_steps'] + n_seeds * c['neuroweave_steps'] + nw_cells = 2 * 64 * c['neuroweave_steps'] + n_seeds * len(c['fi_levels']) * c['neuroweave_steps'] + return {'patch_rk4_steps': int(patch), 'convergence_steps_both_methods': int(convergence), + 'cable_rk4_steps': int(cable), + 'cable_compartment_updates': int(cable * len(c['cable_diameters_um']) * c['cable_compartments']), + 'neuroweave_sequential_steps': int(nw_sequential), 'neuroweave_cell_updates': int(nw_cells)} + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Known-answer validation of the HH cable, then a descriptive f-I comparison with one NEUROWEAVE cell. + + Checks (``kind='validation'``, ``verdict`` in ``('pass', 'fail')``): resting potential within 0.5 mV of the + documented -65 mV and stationary without input; a sub-threshold step stays silent and a supra-threshold one + fires with a peak above 0 mV; conduction velocity positive, increasing with diameter, with a log-log slope + within ``scaling_tolerance`` of the 1/2 of HH eqn 34 (``theta = sqrt(K a / (2 R2 CM))``) and within + ``reference_tolerance`` of HH's computed 18.8 m/s for their axon (18.5 C, d = 476 um, Ra = 35.4 ohm cm), + measured between 1/3 and 2/3 of a 40 mm cable; spike timing converging when dt is halved (patch, RK4) and + the velocity changing little at dt/2 (and exponential Euler converging at first order); paired-pulse + refractoriness (second pulse fails at the shortest interval, succeeds at the longest). + The HH model is deterministic: ``seeds`` only seed the NEUROWEAVE ``CellPopulation`` constructors (whose random + state does not enter ``membrane_dynamics``), so per-seed NEUROWEAVE curves are reported and expected equal.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seeds(seeds) + cfg = dict(_DEFAULTS) + if quick: + cfg.update(_QUICK) + unknown = sorted(set(overrides) - set(cfg)) + if unknown: + raise ValueError(f'unknown run_experiment overrides: {unknown}') + cfg.update(overrides) + c = _validate_config(cfg) + from . import harness + t0 = time.perf_counter() + wall: dict[str, float] = {} + + # ---------------------------------------------------------------- patch (single compartment) + t = time.perf_counter() + patch = HHCable(dt_ms=c['patch_dt_ms'], temperature_c=c['patch_temperature_c']) + rest = patch.resting_potential() + thr = patch.threshold_current(c['fi_window_ms'], window_ms=c['threshold_window_ms'], + bracket=c['threshold_bracket'], rounds=c['threshold_rounds'], + batch=c['search_batch']) + if not thr['resolved']: + raise RuntimeError(f'HH long-step threshold not bracketed by {c["threshold_bracket"]}: {thr["reason"]}') + i_th = float(thr['threshold']) + levels = np.array(c['fi_levels']) + fi = patch.fi_curve(levels * i_th, window_ms=c['fi_window_ms'], transient_ms=c['fi_transient_ms']) + wall['patch_threshold_and_fi'] = time.perf_counter() - t + t = time.perf_counter() + refr = patch.refractory_period(pulse_ms=c['pulse_ms'], test_multiple=c['refractory_test_multiple'], + max_interval_ms=c['refractory_max_interval_ms'], + threshold_bracket=c['pulse_bracket'], threshold_rounds=c['threshold_rounds'], + rounds=c['refractory_rounds'], batch=c['search_batch'], + tail_ms=c['refractory_tail_ms']) + wall['patch_refractory'] = time.perf_counter() - t + t = time.perf_counter() + conv = _convergence(c) + wall['patch_convergence'] = time.perf_counter() - t + + zero_row = int(np.flatnonzero(levels == 0.0)[0]) if np.any(levels == 0.0) else None + sub = [i for i, x in enumerate(levels) if 0.0 < x <= 0.5] + supra = [i for i, x in enumerate(levels) if x >= 1.1] + peak_patch = max(fi['peak_mv'][i] for i in supra) + + # ---------------------------------------------------------------- cable (HH 1952 reference axon family) + t = time.perf_counter() + cable = HHCable(compartments=c['cable_compartments'], length_um=c['cable_length_um'], + diameter_um=HH1952_REFERENCE_AXON['diameter_um'], Ra=c['cable_Ra'], dt_ms=c['cable_dt_ms'], + temperature_c=c['cable_temperature_c']) + vel = cable.conduction_velocity(amplitude=c['cable_amplitude'], duration_ms=c['cable_pulse_ms'], + t_stop_ms=c['cable_t_stop_ms'], diameters_um=c['cable_diameters_um']) + vel_half = cable.replace(dt_ms=c['cable_dt_ms'] / 2).conduction_velocity( + amplitude=c['cable_amplitude'], duration_ms=c['cable_pulse_ms'], t_stop_ms=c['cable_t_stop_ms'], + diameters_um=c['cable_diameters_um']) + wall['cable'] = time.perf_counter() - t + v = [r['velocity_m_s'] for r in vel['rows']] + v_half = [r['velocity_m_s'] for r in vel_half['rows']] + v_ok = all(x is not None and x > 0 for x in v) + slope = None + if v_ok: + slope = float(np.polyfit(np.log(c['cable_diameters_um']), np.log(v), 1)[0]) + ref_idx = (c['cable_diameters_um'].index(HH1952_REFERENCE_AXON['diameter_um']) + if HH1952_REFERENCE_AXON['diameter_um'] in c['cable_diameters_um'] else None) + ref_v = v[ref_idx] if ref_idx is not None else None + reference_applies = (ref_idx is not None and c['cable_temperature_c'] == HH1952_REFERENCE_AXON['temperature_c'] + and c['cable_Ra'] == HH1952_REFERENCE_AXON['Ra_ohm_cm']) + ref_rel = (abs(ref_v - HH1952_REFERENCE_AXON['computed_velocity_m_s']) / HH1952_REFERENCE_AXON['computed_velocity_m_s'] + if ref_v is not None else None) + dt_rel = [abs(a - b) / b if a is not None and b else None for a, b in zip(v, v_half)] + + # ---------------------------------------------------------------- NEUROWEAVE cell (descriptive) + t = time.perf_counter() + nth = neuroweave_threshold(steps=c['neuroweave_steps'], seed=seed_list[0], rounds=2) + if not nth['resolved']: + raise RuntimeError('NEUROWEAVE cell threshold not bracketed') + nw_runs = [] + for s in seed_list: # same drive levels for every seed: the curves must agree if the seed is irrelevant + nfi = neuroweave_fi_curve(levels * nth['threshold'], steps=c['neuroweave_steps'], + transient=c['neuroweave_transient'], seed=s) + nw_runs.append({'seed': s, 'fi': nfi}) + wall['neuroweave'] = time.perf_counter() - t + nw = nw_runs[0] + cmp = compare_fi_curves(levels, fi['rates_hz'], nw['fi']['rates_per_step']) + a_level = c['adaptation_level'] + a_idx = int(np.argmin(np.abs(levels - a_level))) + adaptation = {'level': float(levels[a_idx]), + 'hh': adaptation_index(fi['isis_ms'][a_idx]), + 'neuroweave': adaptation_index(nw['fi']['isis_steps'][a_idx])} + + checks = { + 'resting_within_0.5mV_of_documented_-65mV': bool(abs(rest - HH_REST_MV) <= 0.5), + 'rest_stationary_without_input': bool(zero_row is not None and fi['spike_counts'][zero_row] == 0 + and abs(fi['final_v_mv'][zero_row] - rest) < 1e-6), + 'subthreshold_steps_silent': bool(sub) and all(fi['spike_counts'][i] == 0 for i in sub), + 'suprathreshold_steps_fire': all(fi['spike_counts'][i] >= 1 for i in supra), + 'spike_peak_above_0mV': bool(peak_patch > 0.0) and all(r['mid_peak_mv'] > 0.0 for r in vel['rows']), + 'velocity_positive': v_ok, + 'velocity_increases_with_diameter': v_ok and all(b > a for a, b in zip(v, v[1:])), + 'velocity_scaling_exponent_within_tolerance_of_0.5': (slope is not None + and abs(slope - 0.5) <= c['scaling_tolerance']), + # RK4 at these steps is already at the interpolation/rounding floor, so "converges" means: the change at + # dt/2 at least halves, or both changes are below ``convergence_floor_ms`` + 'spike_time_converges_under_dt_halving': bool( + conv['rk4']['error_fine'] is not None and conv['rk4']['error_fine'] < 1e-3 + and conv['rk4']['error_fine'] <= max(0.5 * conv['rk4']['error_coarse'], c['convergence_floor_ms'])), + 'exp_euler_first_order_convergence': bool( + conv['exp_euler']['observed_order'] is not None and 0.7 <= conv['exp_euler']['observed_order'] <= 1.5), + 'velocity_changes_below_1pct_at_dt_half': all(x is not None and x < 0.01 for x in dt_rel), + 'refractory_second_pulse_fails_then_recovers': bool(refr['fails_at_min_interval'] + and refr['succeeds_at_max_interval'] + and refr['refractory_ms'] is not None), + } + if reference_applies: + checks['reference_velocity_within_tolerance_of_hh1952_computed'] = bool( + ref_rel is not None and ref_rel <= c['reference_tolerance']) + + receipt = harness.base_receipt(MODULE_ID, 'validation', {**c, 'quick': quick, 'seeds': list(seed_list), + 'spike_threshold_mv': SPIKE_THRESHOLD_MV, + 'rearm_mv': REARM_MV}) + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['patch'] = { + 'config': patch.config(), 'resting_potential_mv': rest, 'documented_rest_mv': HH_REST_MV, + 'threshold_long_step': {**thr, 'step_ms': c['fi_window_ms']}, + 'spike_peak_mv': peak_patch, + 'fi_curve': {**{k: fi[k] for k in ('amplitudes', 'rates_hz', 'spike_counts', 'peak_mv')}, + 'levels': list(c['fi_levels']), 'window_ms': fi['window_ms'], 'transient_ms': fi['transient_ms']}, + 'refractory': refr, 'convergence': conv} + receipt['cable'] = { + 'config': cable.config(), 'distance_um': vel['distance_um'], 'sites': vel['sites'], + 'rows': vel['rows'], 'velocities_dt_half_m_s': v_half, 'dt_half_relative_change': dt_rel, + 'log_log_slope': slope, 'expected_slope': 0.5, + 'reference': {**HH1952_REFERENCE_AXON, 'model_velocity_m_s': ref_v, 'relative_difference': ref_rel, + 'applies': reference_applies}} + receipt['neuroweave_reference'] = { + 'cell': 'synapse.neuroweave.cells.CellPopulation, flags {membrane_dynamics}, constant external drive, ' + 'no recurrent input, neutral controls; time unit = one engine step', + 'threshold_drive': nth['threshold'], 'threshold_bracket': nth['bracket'], + 'threshold_seed': seed_list[0], + 'per_seed': [{'seed': r['seed'], 'rates_per_step': r['fi']['rates_per_step'], + 'spike_counts': r['fi']['spike_counts']} for r in nw_runs], + 'seed_invariant': all(r['fi']['rates_per_step'] == nw['fi']['rates_per_step'] + and r['fi']['spike_counts'] == nw['fi']['spike_counts'] for r in nw_runs), + 'comparison': cmp, 'adaptation_index': adaptation, + 'note': 'descriptive only: the abstract cell is compared in shape (threshold- and max-normalised), ' + 'never validated against the HH reference'} + receipt['checks'] = checks + receipt['verdict'] = 'pass' if all(checks.values()) else 'fail' + receipt['verdict_basis'] = ('all_known_answer_checks' if receipt['verdict'] == 'pass' + else 'failed_checks: ' + ', '.join(k for k, ok in checks.items() if not ok)) + receipt['estimated_cost'] = _estimated_cost(c, len(seed_list), refr) + receipt['measured_wallclock_s'] = {**wall, 'total': time.perf_counter() - t0} + receipt['notes'] = ( + 'Hodgkin-Huxley (1952) membrane on a uniform sealed-end cable, central differences with g_ax = a/(2 Ra dx^2), ' + 'RK4 unless stated; checks use cases with known answers (documented rest, all-or-none response, ' + 'sqrt(diameter) velocity scaling of a uniform cable, HH\'s own computed velocity of 18.8 m/s for their ' + 'axon, time-step convergence, refractoriness). The NEUROWEAVE comparison is descriptive: an abstract ' + 'discrete-time unit is compared in normalised shape only. Not a validated neuron simulator; no claim of ' + 'biological fidelity for the NEUROWEAVE cell.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/joint_failure.py b/synapse/frontier/joint_failure.py new file mode 100644 index 0000000000000000000000000000000000000000..17399627725f02742c31af6cb56bab97003a475f --- /dev/null +++ b/synapse/frontier/joint_failure.py @@ -0,0 +1,927 @@ +"""Joint-failure ensemble selection (frontier module ``joint_failure``). + +Inspired by FAULTLINE (kai9987kai, https://github.com/kai9987kai/FAULTLINE), a CPU-local laboratory for +correlated and higher-order failures in small voting ensembles. This module is a synthetic computational +abstraction: it re-implements the four FAULTLINE selection rules for NumPy failure arrays and adds its own +seeded generator, exact population errors and a NEUROWEAVE application; it reproduces none of FAULTLINE's +recorded numbers. Full description and limits: ``docs/frontier/modules/joint_failure.md``. + +Data. ``failures[i, c, t]`` is true when component ``i`` is wrong on trial ``t`` of condition ``c``; every +condition has the same number of trials ``T``. A panel ``P`` of odd size ``k`` votes by majority. With binary +labels every wrong member votes for the one wrong label, so the vote is wrong exactly when at least +``s = (k + 1) / 2`` members are wrong (with more labels this is an upper bound on plurality-vote error):: + + 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] + +``Err`` depends only on the joint failure pattern (signature) of each trial, so it is computed exactly from +signature counts alone by ``majority_error_from_signatures``. + +Selectors (calibration trials only; scores are integer counts, so ties are exact; a tie goes to the next +key and finally to the lexicographically first panel): + +* ``accuracy`` min sum_{i in P} e_i (pooled individual error) +* ``pairwise`` min max_c B(P | c), then sum_c B(P | c), then accuracy, where + ``B(P | c) = sum_{i= Err(P | c)`` is the second + factorial-moment bound (``1[W >= s] <= C(W, 2) / C(s, 2)``); for ``k = 1`` the individual error +* ``pooled`` min pooled majority error, then worst-condition majority error, then accuracy +* ``joint`` min worst-condition majority error ``max_c Err(P | c)``, then pooled, then accuracy + +All randomness comes from ``numpy.random.default_rng(seed + offset)``. +""" +from __future__ import annotations + +import hashlib +import itertools +import math +import time +from typing import Any, Mapping, Sequence + +import numpy as np + +from . import harness + +__all__ = ['MODULE_ID', 'NEUROWEAVE_ID', 'SOURCE', 'EXPERIMENTS', 'POLICIES', 'SCENARIOS', 'validate_failures', + 'majority_threshold', 'majority_error', 'pairwise_bound', 'failure_signatures', + 'majority_error_from_signatures', 'panel_scores', 'select_panels', 'select_panel', 'evaluate_panel', + 'run_selection', 'make_failure_data', 'expected_condition_errors', 'constructed_cases', + 'check_constructed_cases', 'run_experiment', 'run_neuroweave_application'] + +MODULE_ID = 'joint_failure' +NEUROWEAVE_ID = MODULE_ID + '_neuroweave' +SOURCE = ('FAULTLINE: Joint-Failure Ensemble Selection Laboratory (kai9987kai), ' + 'https://github.com/kai9987kai/FAULTLINE (design dated 24 October 2026)') +POLICIES = ('accuracy', 'pairwise', 'pooled', 'joint') +SCENARIOS = ('shared', 'independent', 'shift') + +MAX_COMPONENTS = 24 +MAX_CONDITIONS = 64 +MAX_TRIALS = 100_000 +MAX_CELLS = 5_000_000 # components x conditions x trials per failure array +MAX_PANELS = 100_000 # candidate panels enumerated per selection +_CHUNK_CELLS = 2_000_000 # panels x conditions x trials evaluated per chunk (bounded memory) + +_STRUCT_OFFSET = 89_101 +_CAL_OFFSET = 89_113 +_TEST_OFFSET = 89_127 +_HIDDEN_OFFSET = 89_137 + + +# ====================================================================== validation helpers +def _int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _num(name: str, value: Any, low: float, high: float) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + if not math.isfinite(v) or v < low or v > high: + raise ValueError(f'{name} must be a finite number in [{low}, {high}]') + return v + + +def _range(name: str, value: Any, low: float, high: float) -> tuple[float, float]: + if isinstance(value, (str, bytes, Mapping)): + raise ValueError(f'{name} must be a pair (lo, hi)') + try: + pair = tuple(value) + except TypeError as exc: + raise ValueError(f'{name} must be a pair (lo, hi)') from exc + if len(pair) != 2: + raise ValueError(f'{name} must be a pair (lo, hi)') + lo, hi = _num(name, pair[0], low, high), _num(name, pair[1], low, high) + if lo > hi: + raise ValueError(f'{name} must satisfy lo <= hi') + return lo, hi + + +def _seeds(seeds: Any) -> tuple[int, ...]: + if isinstance(seeds, (str, bytes, Mapping)): + raise ValueError('seeds must be an iterable of ints') + try: + out = tuple(_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +def validate_failures(failures: Any, *, name: str = 'failures') -> np.ndarray: + """Return a boolean copy of a ``(components, conditions, trials)`` failure array (0/1 or bool entries).""" + if isinstance(failures, (str, bytes, Mapping)): + raise ValueError(f'{name} must be a 3-D array of booleans or 0/1 values') + try: + a = np.asarray(failures) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be a 3-D array of booleans or 0/1 values') from exc + if a.ndim != 3 or a.dtype.kind not in 'biuf': + raise ValueError(f'{name} must be a 3-D array (components x conditions x trials) of booleans or 0/1 values') + m, k, t = a.shape + if not (1 <= m <= MAX_COMPONENTS and 1 <= k <= MAX_CONDITIONS and 1 <= t <= MAX_TRIALS) or a.size > MAX_CELLS: + raise ValueError(f'{name} shape must be at most ({MAX_COMPONENTS}, {MAX_CONDITIONS}, {MAX_TRIALS}) with ' + f'every axis non-empty and at most {MAX_CELLS} cells') + if a.dtype.kind == 'b': + return a.astype(bool, copy=True) + if a.dtype.kind == 'f' and not np.all(np.isfinite(a)): + raise ValueError(f'{name} must contain only 0/1 values') + if not np.all((a == 0) | (a == 1)): + raise ValueError(f'{name} must contain only 0/1 values') + return a == 1 + + +def majority_threshold(panel_size: Any) -> int: + """``s = (k + 1) / 2`` for an odd panel size ``k``.""" + k = _int('panel_size', panel_size, 1, MAX_COMPONENTS) + if k % 2 == 0: + raise ValueError('panel_size must be odd') + return (k + 1) // 2 + + +def _panel(panel: Any, m: int) -> tuple[int, ...]: + if isinstance(panel, (str, bytes, Mapping)): + raise ValueError('panel must be a sequence of component indices') + try: + p = tuple(_int('panel member', v, 0, m - 1) for v in panel) + except TypeError as exc: + raise ValueError('panel must be a sequence of component indices') from exc + if not p or len(p) % 2 == 0: + raise ValueError('panel must have an odd number of members') + if len(set(p)) != len(p): + raise ValueError('panel members must be distinct') + return tuple(sorted(p)) + + +# ====================================================================== exact panel statistics +def majority_error(failures: Any, panel: Any) -> np.ndarray: + """Per-condition majority-vote error ``Err(P | c)`` of ``panel`` (exact, from the joint failures).""" + f = validate_failures(failures) + p = _panel(panel, f.shape[0]) + wrong = f[list(p)].sum(axis=0, dtype=np.int64) + return (wrong >= (len(p) + 1) // 2).mean(axis=1) + + +def pairwise_bound(failures: Any, panel: Any) -> np.ndarray: + """Per-condition second factorial-moment bound ``B(P | c) >= Err(P | c)`` (individual error for ``k = 1``).""" + f = validate_failures(failures) + p = _panel(panel, f.shape[0]) + if len(p) == 1: + return f[p[0]].mean(axis=1) + sub = f[list(p)].astype(np.float64) + co = np.einsum('ict,jct->ijc', sub, sub) + iu = np.triu_indices(len(p), 1) + s = (len(p) + 1) // 2 + return co[iu].sum(axis=0) / (math.comb(s, 2) * f.shape[2]) + + +def failure_signatures(failures: Any) -> list[dict[str, Any]]: + """Empirical failure hyperedges: for each condition the distinct sets of failing components and their counts. + + The empty set (no component failed) is included, so the counts of each condition sum to ``T``.""" + f = validate_failures(failures) + m, k, t = f.shape + weights = np.left_shift(np.int64(1), np.arange(m, dtype=np.int64)) + out = [] + for c in range(k): + codes = weights @ f[:, c, :].astype(np.int64) + uniq, counts = np.unique(codes, return_counts=True) + sigs = [{'members': [i for i in range(m) if (code >> i) & 1], 'count': int(n)} + for code, n in zip(uniq.tolist(), counts.tolist())] + out.append({'condition': c, 'components': int(m), 'trials': int(t), 'signatures': sigs}) + return out + + +def majority_error_from_signatures(signatures: Any, panel: Any) -> np.ndarray: + """``Err(P | c)`` computed from signature counts only (``failure_signatures`` output). + + When the entries carry ``components`` (as ``failure_signatures`` output does), every signature member and + every panel member must be a valid component index; otherwise indices up to ``MAX_COMPONENTS - 1`` are + accepted and a component that never appears in a signature never failed.""" + if isinstance(signatures, (str, bytes, Mapping)) or not isinstance(signatures, Sequence) or not signatures: + raise ValueError('signatures must be a non-empty list of per-condition mappings') + rows = [] + n_comp = MAX_COMPONENTS + declared = [_int('components', entry['components'], 1, MAX_COMPONENTS) for entry in signatures + if isinstance(entry, Mapping) and entry.get('components') is not None] + if declared: + if len(declared) != len(signatures) or len(set(declared)) != 1: + raise ValueError('every condition entry must declare the same number of components') + n_comp = declared[0] + for entry in signatures: + if not isinstance(entry, Mapping) or 'trials' not in entry or 'signatures' not in entry: + raise ValueError('each condition entry needs trials and signatures') + trials = _int('trials', entry['trials'], 1, MAX_TRIALS) + sigs = entry['signatures'] + if isinstance(sigs, (str, bytes, Mapping)) or not isinstance(sigs, Sequence): + raise ValueError('signatures must be a list of {members, count}') + parsed, total = [], 0 + for sig in sigs: + if not isinstance(sig, Mapping) or 'members' not in sig or 'count' not in sig: + raise ValueError('each signature needs members and count') + members = sig['members'] + if isinstance(members, (str, bytes, Mapping)) or not isinstance(members, Sequence): + raise ValueError('signature members must be a list of component indices') + mem = {_int('signature member', v, 0, n_comp - 1) for v in members} + if len(mem) != len(members): + raise ValueError('signature members must be distinct') + count = _int('count', sig['count'], 0, MAX_TRIALS) + parsed.append((mem, count)) + total += count + if total != trials: + raise ValueError('signature counts of a condition must sum to its trials') + rows.append((trials, parsed)) + p = set(_panel(panel, n_comp)) + s = (len(p) + 1) // 2 + return np.array([sum(n for mem, n in parsed if len(mem & p) >= s) / trials for trials, parsed in rows]) + + +def evaluate_panel(failures: Any, panel: Any) -> dict[str, Any]: + """Majority-vote error by condition, worst condition, pooled error and unanimous-failure rate.""" + f = validate_failures(failures) + p = _panel(panel, f.shape[0]) + wrong = f[list(p)].sum(axis=0, dtype=np.int64) + err = (wrong >= (len(p) + 1) // 2).mean(axis=1) + return {'panel': list(p), 'condition_error': err.tolist(), 'worst_condition_error': float(err.max()), + 'worst_condition': int(np.argmax(err)), 'pooled_error': float(err.mean()), + 'unanimous_failure_rate': float((wrong == len(p)).mean()), + 'pairwise_bound_worst': float(pairwise_bound(f, p).max()) if len(p) > 1 else float(err.max())} + + +# ====================================================================== selection +def _panel_table(f: np.ndarray, k: int) -> dict[str, np.ndarray]: + m, kc, t = f.shape + if k > m: + raise ValueError('panel_size must not exceed the number of components') + n_p = math.comb(m, k) + if n_p > MAX_PANELS: + raise ValueError(f'C(components, panel_size) must be at most {MAX_PANELS}') + panels = np.array(list(itertools.combinations(range(m), k)), dtype=np.int64).reshape(n_p, k) + s = (k + 1) // 2 + ind = f.sum(axis=(1, 2), dtype=np.int64) + ind_c = f.sum(axis=2, dtype=np.int64) # (m, K) + flat = f.reshape(m, kc * t).astype(np.float32) # exact for counts <= 2**24 + maj = np.empty((n_p, kc), dtype=np.int64) + chunk = max(1, _CHUNK_CELLS // max(1, kc * t)) + for start in range(0, n_p, chunk): + sel = panels[start:start + chunk] + inc = np.zeros((sel.shape[0], m), dtype=np.float32) + np.put_along_axis(inc, sel, 1.0, axis=1) + wrong = (inc @ flat).reshape(sel.shape[0], kc, t) + maj[start:start + chunk] = (wrong >= s - 0.5).sum(axis=2) + if k >= 2: + fc = f.astype(np.float64) + co = np.einsum('ict,jct->ijc', fc, fc).round().astype(np.int64) # (m, m, K) co-failure counts + pair = np.zeros((n_p, kc), dtype=np.int64) + for a, b in itertools.combinations(range(k), 2): + pair += co[panels[:, a], panels[:, b], :] + else: + pair = ind_c[panels[:, 0], :] + return {'panels': panels, 'individual_sum': ind[panels].sum(axis=1), 'pair_by_condition': pair, + 'majority_by_condition': maj, 'trials': np.int64(t)} + + +def _keys(table: Mapping[str, np.ndarray], policy: str) -> list[np.ndarray]: + ind = table['individual_sum'] + maj, pair = table['majority_by_condition'], table['pair_by_condition'] + if policy == 'accuracy': + return [ind] + if policy == 'pairwise': + return [pair.max(axis=1), pair.sum(axis=1), ind] + if policy == 'pooled': + return [maj.sum(axis=1), maj.max(axis=1), ind] + if policy == 'joint': + return [maj.max(axis=1), maj.sum(axis=1), ind] + raise ValueError(f'policy must be one of {POLICIES}') + + +def _argbest(keys: Sequence[np.ndarray]) -> int: + n = keys[0].shape[0] + return int(np.lexsort((np.arange(n),) + tuple(reversed(list(keys))))[0]) + + +def panel_scores(failures: Any, panel_size: Any) -> dict[str, Any]: + """Every candidate panel (lexicographic order) with the integer scores the selectors rank by.""" + f = validate_failures(failures) + k = majority_threshold(panel_size) * 2 - 1 + table = _panel_table(f, k) + return {'panels': table['panels'].tolist(), 'trials_per_condition': int(table['trials']), + 'individual_failures': table['individual_sum'].tolist(), + 'pair_cofailures_by_condition': table['pair_by_condition'].tolist(), + 'majority_failures_by_condition': table['majority_by_condition'].tolist(), + 'pair_bound_denominator': math.comb((k + 1) // 2, 2) if k >= 3 else 1} + + +def select_panels(failures: Any, panel_size: Any, policies: Sequence[str] = POLICIES) -> dict[str, tuple[int, ...]]: + """Panel chosen by each policy from the (calibration) failures.""" + f = validate_failures(failures) + k = majority_threshold(panel_size) * 2 - 1 + if isinstance(policies, str) or any(p not in POLICIES for p in policies): + raise ValueError(f'policies must be a sequence drawn from {POLICIES}') + table = _panel_table(f, k) + return {p: tuple(int(v) for v in table['panels'][_argbest(_keys(table, p))]) for p in policies} + + +def select_panel(failures: Any, panel_size: Any, policy: str) -> tuple[int, ...]: + if policy not in POLICIES: + raise ValueError(f'policy must be one of {POLICIES}') + return select_panels(failures, panel_size, (policy,))[policy] + + +def run_selection(calibration: Any, test: Any, panel_size: Any) -> dict[str, Any]: + """Select with every policy on ``calibration``, evaluate the frozen panels on held-out ``test`` trials. + + ``oracle`` is the panel with the lowest *test* worst-condition error (chosen on the test data: a reference + for how much any calibration-only rule could achieve, never a selector).""" + cal = validate_failures(calibration, name='calibration') + tst = validate_failures(test, name='test') + if cal.shape[:2] != tst.shape[:2]: + raise ValueError('calibration and test must have the same components and conditions') + k = majority_threshold(panel_size) * 2 - 1 + table = _panel_table(cal, k) + out: dict[str, Any] = {'panel_size': k, 'candidate_panels': int(table['panels'].shape[0]), + 'calibration_trials': int(cal.shape[2]), 'test_trials': int(tst.shape[2]), 'policies': {}} + for policy in POLICIES: + panel = tuple(int(v) for v in table['panels'][_argbest(_keys(table, policy))]) + out['policies'][policy] = {'panel': list(panel), 'calibration': evaluate_panel(cal, panel), + 'test': evaluate_panel(tst, panel)} + test_table = _panel_table(tst, k) + best = _argbest(_keys(test_table, 'joint')) + out['oracle'] = {'panel': test_table['panels'][best].tolist(), + 'test': evaluate_panel(tst, test_table['panels'][best])} + return out + + +# ====================================================================== synthetic generator +_GEN_DEFAULTS: dict[str, Any] = { + 'families': 3, 'family_size': 3, 'calibration_trials': 64, 'test_trials': 512, + 'accurate_error': (0.01, 0.03), 'other_error': (0.03, 0.07), 'stress_activation': (0.25, 0.40), + 'stress_hit': 0.85, 'independent_error': (0.04, 0.16), 'independent_multiplier': (1.0, 1.6), + 'shift_activation': 0.6, 'shift_hit': 0.9, 'shift_target': 'hardened'} + + +def _gen_config(params: Mapping[str, Any]) -> dict[str, Any]: + unknown = sorted(set(params) - set(_GEN_DEFAULTS)) + if unknown: + raise ValueError(f'unknown generator parameters: {unknown}') + cfg = {**_GEN_DEFAULTS, **params} + cfg['families'] = _int('families', cfg['families'], 1, MAX_CONDITIONS - 1) + cfg['family_size'] = _int('family_size', cfg['family_size'], 1, MAX_COMPONENTS) + if cfg['families'] * cfg['family_size'] > MAX_COMPONENTS: + raise ValueError(f'families * family_size must be at most {MAX_COMPONENTS}') + cfg['calibration_trials'] = _int('calibration_trials', cfg['calibration_trials'], 1, MAX_TRIALS) + cfg['test_trials'] = _int('test_trials', cfg['test_trials'], 1, MAX_TRIALS) + for key in ('accurate_error', 'other_error', 'stress_activation', 'independent_error'): + cfg[key] = _range(key, cfg[key], 0.0, 1.0) + cfg['independent_multiplier'] = _range('independent_multiplier', cfg['independent_multiplier'], 0.0, 10.0) + if cfg['independent_error'][1] * cfg['independent_multiplier'][1] > 1.0: + raise ValueError('independent_error hi * independent_multiplier hi must be at most 1') + for key in ('stress_hit', 'shift_activation', 'shift_hit'): + cfg[key] = _num(key, cfg[key], 0.0, 1.0) + if cfg['shift_target'] not in ('hardened', 'random'): + raise ValueError("shift_target must be 'hardened' or 'random'") + m, k = cfg['families'] * cfg['family_size'], cfg['families'] + 1 + if m * k * max(cfg['calibration_trials'], cfg['test_trials']) > MAX_CELLS: + raise ValueError(f'components * conditions * trials must be at most {MAX_CELLS}') + return cfg + + +def make_failure_data(seed: int, *, scenario: str = 'shared', **params: Any) -> dict[str, Any]: + """Seeded synthetic failure observations (calibration and held-out test) with a documented hidden structure. + + Components come in ``families`` of ``family_size`` (shuffled per seed so tie-breaking cannot favour a + family); conditions are ``nominal`` plus one ``stress_f`` per family. + + * ``shared``: each component fails independently at its base rate (family 0, the "accurate" family: + ``accurate_error``; others: ``other_error``); in condition ``stress_f`` a shared stressor of family ``f`` + is active with probability ``stress_activation`` and then hits each family member with ``stress_hit``. + * ``independent`` (negative control): no shared stressor; component ``i`` fails independently with + ``independent_error_i * multiplier_c`` (one multiplier per condition, so every condition ranks the + components identically and the individually best panel is optimal everywhere). + * ``shift`` (unobserved common-cause stress test): calibration identical to ``shared``; on test trials of + the ``nominal`` condition a common cause never seen in calibration is active with probability + ``shift_activation`` and hits each member of one cross-family set with ``shift_hit``. ``shift_target`` + ``'hardened'`` puts the lowest-base-error member of every family in that set (adversarial to diversity-based + selection by construction); ``'random'`` draws one member per family.""" + if scenario not in SCENARIOS: + raise ValueError(f'scenario must be one of {SCENARIOS}') + seed = _int('seed', seed, 0, 2**31 - 1) + cfg = _gen_config(params) + nf, fs = cfg['families'], cfg['family_size'] + m, k = nf * fs, nf + 1 + rng = np.random.default_rng(seed + _STRUCT_OFFSET) + family_raw = np.repeat(np.arange(nf), fs) + acc = rng.uniform(*cfg['accurate_error'], m) + oth = rng.uniform(*cfg['other_error'], m) + base_raw = np.where(family_raw == 0, acc, oth) + activation = rng.uniform(*cfg['stress_activation'], nf) + ind_raw = rng.uniform(*cfg['independent_error'], m) + mult = np.concatenate([[1.0], rng.uniform(*cfg['independent_multiplier'], nf)]) + random_pick = rng.integers(0, fs, nf) + perm = rng.permutation(m) # output component j is raw component perm[j] + if cfg['shift_target'] == 'hardened': + hidden_raw = np.array([f * fs + int(np.argmin(base_raw[f * fs:(f + 1) * fs])) for f in range(nf)]) + else: + hidden_raw = np.array([f * fs + int(random_pick[f]) for f in range(nf)]) + + def split(offset: int, trials: int, hidden: bool) -> np.ndarray: + r = np.random.default_rng(seed + offset) + if scenario == 'independent': + fails = r.random((m, k, trials)) < (ind_raw[:, None] * mult[None, :])[:, :, None] + else: + fails = r.random((m, k, trials)) < base_raw[:, None, None] + active = r.random((nf, trials)) < activation[:, None] + hit = r.random((m, trials)) < cfg['stress_hit'] + for f in range(nf): + mem = family_raw == f + fails[mem, f + 1, :] |= active[f][None, :] & hit[mem] + if hidden: + h = np.random.default_rng(seed + _HIDDEN_OFFSET) + active = h.random(trials) < cfg['shift_activation'] + hit = h.random((hidden_raw.size, trials)) < cfg['shift_hit'] + fails[hidden_raw, 0, :] |= active[None, :] & hit + return fails[perm] + + cal = split(_CAL_OFFSET, cfg['calibration_trials'], False) + test = split(_TEST_OFFSET, cfg['test_trials'], scenario == 'shift') + inv = np.argsort(perm) + structure = {'scenario': scenario, 'family': family_raw[perm].tolist(), 'base_error': base_raw[perm].tolist(), + 'stress_activation': activation.tolist(), 'stress_hit': cfg['stress_hit'], + 'independent_error': ind_raw[perm].tolist(), 'independent_multiplier': mult.tolist(), + 'hidden_common_cause': {'members': sorted(int(inv[i]) for i in hidden_raw), 'condition': 0, + 'activation': cfg['shift_activation'], 'hit': cfg['shift_hit'], + 'target': cfg['shift_target'], 'active_in': 'test split of the shift scenario'}} + h = hashlib.sha256() + h.update(f'{scenario}|{seed}|{cal.shape}|{test.shape}'.encode('utf-8')) + h.update(np.packbits(cal).tobytes()) + h.update(np.packbits(test).tobytes()) + return {'seed': seed, 'scenario': scenario, 'config': cfg, + 'conditions': ['nominal'] + [f'stress_{f}' for f in range(nf)], + 'calibration': cal, 'test': test, 'structure': structure, 'digest': h.hexdigest()} + + +def _tail(p: np.ndarray, s: int) -> float: + """``Pr(sum of independent Bernoulli(p_i) >= s)`` (Poisson-binomial tail, exact by recursion).""" + dist = np.zeros(p.size + 1) + dist[0] = 1.0 + for q in p: + dist[1:] = dist[1:] * (1.0 - q) + dist[:-1] * q + dist[0] *= 1.0 - q + return float(dist[s:].sum()) + + +def expected_condition_errors(structure: Mapping[str, Any], panel: Any, *, split: str = 'test') -> np.ndarray: + """Population (infinite-trial) ``Err(P | c)`` of a panel under a ``make_failure_data`` structure. + + Given the state of the (at most one) channel acting in a condition, components fail independently, so the + majority error is a mixture of Poisson-binomial tails.""" + if split not in ('calibration', 'test'): + raise ValueError("split must be 'calibration' or 'test'") + st = _parse_structure(structure) + p = list(_panel(panel, st['family'].size)) + s = (len(p) + 1) // 2 + mult = st['independent_multiplier'] + out = np.zeros(mult.size) + if st['scenario'] == 'independent': + ind = st['independent_error'][p] + return np.array([_tail(np.clip(ind * mu, 0.0, 1.0), s) for mu in mult]) + base = st['base_error'][p] + fam = st['family'][p] + act, hit = st['stress_activation'], st['stress_hit'] + for c in range(mult.size): + if c == 0: + if st['scenario'] == 'shift' and split == 'test': + members = np.isin(p, st['hidden_members']) + hit_p = np.where(members, 1.0 - (1.0 - base) * (1.0 - st['hidden_hit']), base) + a = st['hidden_activation'] + out[c] = a * _tail(hit_p, s) + (1.0 - a) * _tail(base, s) + else: + out[c] = _tail(base, s) + else: + hit_p = np.where(fam == c - 1, 1.0 - (1.0 - base) * (1.0 - hit), base) + out[c] = act[c - 1] * _tail(hit_p, s) + (1.0 - act[c - 1]) * _tail(base, s) + return out + + +def _parse_structure(structure: Any) -> dict[str, Any]: + """Validated arrays from a ``make_failure_data`` structure (``ValueError`` on anything malformed).""" + if not isinstance(structure, Mapping) or structure.get('scenario') not in SCENARIOS: + raise ValueError('structure must come from make_failure_data') + + def probs(key: str, value: Any, size: int | None) -> np.ndarray: + a = np.asarray(value, dtype=np.float64) + if a.ndim != 1 or (size is not None and a.size != size) or not np.all((a >= 0.0) & (a <= 1.0)): + raise ValueError(f'structure {key} must be a list of probabilities of the right length') + return a + + try: + family = np.asarray(structure['family']) + if family.ndim != 1 or not 1 <= family.size <= MAX_COMPONENTS or family.dtype.kind not in 'iu': + raise ValueError('structure family must be a list of component family indices') + family = family.astype(np.int64) + m, nf = family.size, int(family.max()) + 1 + if family.min() < 0 or nf > MAX_CONDITIONS - 1: + raise ValueError('structure family indices are out of range') + mult = np.asarray(structure['independent_multiplier'], dtype=np.float64) + if mult.shape != (nf + 1,) or not np.all(np.isfinite(mult) & (mult >= 0.0)): + raise ValueError('structure independent_multiplier must have one finite value per condition') + hidden = structure['hidden_common_cause'] + members = np.asarray(hidden['members']) + if members.ndim != 1 or (members.size and (members.dtype.kind not in 'iu' or members.min() < 0 + or members.max() >= m)): + raise ValueError('structure hidden_common_cause members must be component indices') + return {'scenario': structure['scenario'], 'family': family, 'independent_multiplier': mult, + 'independent_error': probs('independent_error', structure['independent_error'], m), + 'base_error': probs('base_error', structure['base_error'], m), + 'stress_activation': probs('stress_activation', structure['stress_activation'], nf), + 'stress_hit': float(probs('stress_hit', [structure['stress_hit']], 1)[0]), + 'hidden_members': members.astype(np.int64), + 'hidden_hit': float(probs('hidden hit', [hidden['hit']], 1)[0]), + 'hidden_activation': float(probs('hidden activation', [hidden['activation']], 1)[0])} + except (KeyError, TypeError, IndexError) as exc: + raise ValueError('structure must come from make_failure_data') from exc + + +# ====================================================================== constructed known-answer cases +def _rows(spec: Sequence[tuple[Sequence[int], int]], m: int, trials: int) -> np.ndarray: + """One condition: ``spec`` lists (failing components, number of trials); remaining trials have no failure.""" + out = np.zeros((m, trials), dtype=bool) + t = 0 + for members, count in spec: + out[list(members), t:t + count] = True + t += count + if t > trials: + raise AssertionError('constructed case overflows its trials') + return out + + +def constructed_cases() -> dict[str, dict[str, Any]]: + """Hand-built failure arrays with known answers (used by tests and recorded in receipts). + + * ``parity``: 3 components; ``even`` holds the four even-weight failure patterns, ``odd`` the four odd-weight + ones. Marginal (1/2) and pairwise (1/4) failure rates are identical, majority error is 3/4 vs 1/4. + * ``accuracy_trap``: components 0-2 are individually best (error 0.10) but fail together on 20 % of + ``stress`` trials; 3-5 (error 0.15) never fail together. Accuracy picks 0-2 (worst error 0.20), the + joint rule finds a panel with worst error 0. + * ``pairwise_trap``: one condition; panel (2, 3, 4) fails only unanimously (10 %), so its pairwise bound is + 30 %, while (0, 1, 2) fails in pairs (18 %, bound 18 %); cross pairs make every mixed panel worse. + Pairwise picks (0, 1, 2), the joint rule (2, 3, 4). + * ``pooled_trap``: components 0-2 fail together on 30 % of ``b`` trials only (pooled 15 %, worst 30 %); + 3-5 fail together on 20 % of trials in both conditions (pooled and worst 20 %). Pooled picks a panel + with worst error 0.30, the joint rule one with 0.20.""" + parity = np.zeros((3, 2, 4), dtype=bool) + for t, pat in enumerate(((), (0, 1), (0, 2), (1, 2))): + parity[list(pat), 0, t] = True + for t, pat in enumerate(((0,), (1,), (2,), (0, 1, 2))): + parity[list(pat), 1, t] = True + acc = np.stack([_rows([((0, 1, 2), 12), ((3,), 9), ((4,), 9), ((5,), 9)], 6, 60), + _rows([((3,), 9), ((4,), 9), ((5,), 9)], 6, 60)], axis=1) + pair = _rows([((2, 3, 4), 5), ((0, 1), 3), ((0, 2), 3), ((1, 2), 3), + ((0, 3), 4), ((0, 4), 4), ((1, 3), 4), ((1, 4), 4)], 5, 50)[:, None, :] + pooled = np.stack([_rows([((3, 4, 5), 10)], 6, 50), _rows([((0, 1, 2), 15), ((3, 4, 5), 10)], 6, 50)], axis=1) + return { + 'parity': {'failures': parity, 'conditions': ['even', 'odd'], 'panel_size': 3, + 'expected_majority_error': [0.75, 0.25]}, + 'accuracy_trap': {'failures': acc, 'conditions': ['nominal', 'stress'], 'panel_size': 3, + 'expected_accuracy_panel': [0, 1, 2], 'expected_accuracy_worst': 0.2, + 'expected_joint_worst': 0.0}, + 'pairwise_trap': {'failures': pair, 'conditions': ['storm'], 'panel_size': 3, + 'expected_pairwise_panel': [0, 1, 2], 'expected_joint_panel': [2, 3, 4], + 'expected_pairwise_worst': 0.18, 'expected_joint_worst': 0.10}, + 'pooled_trap': {'failures': pooled, 'conditions': ['a', 'b'], 'panel_size': 3, + 'expected_pooled_worst': 0.30, 'expected_pooled_pooled': 0.15, + 'expected_joint_worst': 0.20, 'expected_joint_pooled': 0.20}, + } + + +def check_constructed_cases() -> dict[str, bool]: + """Named booleans: exactness on the parity case and the expected direction on each trap.""" + cases = constructed_cases() + checks: dict[str, bool] = {} + par = cases['parity']['failures'] + err = majority_error(par, (0, 1, 2)) + checks['parity_majority_error_exact'] = bool(np.array_equal(err, [0.75, 0.25])) + checks['parity_signature_path_exact'] = bool(np.array_equal( + majority_error_from_signatures(failure_signatures(par), (0, 1, 2)), [0.75, 0.25])) + marg = par.mean(axis=2) + co = np.array([[par[i, c] & par[j, c] for c in range(2)] for i, j in ((0, 1), (0, 2), (1, 2))]).mean(axis=2) + checks['parity_marginals_and_pairs_identical'] = bool(np.all(marg == 0.5) and np.all(co == 0.25)) + for name, policy, other in (('accuracy_trap', 'joint', 'accuracy'), ('pairwise_trap', 'joint', 'pairwise'), + ('pooled_trap', 'joint', 'pooled')): + case = cases[name] + f = case['failures'] + chosen = select_panels(f, case['panel_size']) + worst = {p: float(majority_error(f, chosen[p]).max()) for p in chosen} + checks[f'{name}_joint_lower_worst_condition_error_than_{other}'] = bool(worst[policy] < worst[other]) + acc = cases['accuracy_trap'] + pick = select_panels(acc['failures'], 3) + checks['accuracy_trap_values'] = bool(list(pick['accuracy']) == acc['expected_accuracy_panel'] and math.isclose( + majority_error(acc['failures'], pick['accuracy']).max(), acc['expected_accuracy_worst']) and + majority_error(acc['failures'], pick['joint']).max() == acc['expected_joint_worst']) + pt = cases['pairwise_trap'] + pick = select_panels(pt['failures'], 3) + checks['pairwise_trap_values'] = bool( + list(pick['pairwise']) == pt['expected_pairwise_panel'] and list(pick['joint']) == pt['expected_joint_panel'] + and math.isclose(majority_error(pt['failures'], pick['pairwise'])[0], pt['expected_pairwise_worst']) + and math.isclose(majority_error(pt['failures'], pick['joint'])[0], pt['expected_joint_worst'])) + po = cases['pooled_trap'] + pick = select_panels(po['failures'], 3) + e_pool, e_joint = majority_error(po['failures'], pick['pooled']), majority_error(po['failures'], pick['joint']) + checks['pooled_trap_values'] = bool( + math.isclose(e_pool.max(), po['expected_pooled_worst']) and math.isclose(e_pool.mean(), po['expected_pooled_pooled']) + and math.isclose(e_joint.max(), po['expected_joint_worst']) + and math.isclose(e_joint.mean(), po['expected_joint_pooled'])) + return checks + + +# ====================================================================== synthetic benchmark +_EXP_DEFAULTS: dict[str, Any] = {'panel_size': 3, **_GEN_DEFAULTS} +_EXP_QUICK: dict[str, Any] = {'calibration_trials': 48, 'test_trials': 256} + + +def _policy_record(sel: Mapping[str, Any], structure: Mapping[str, Any], policy: str) -> dict[str, Any]: + rec = sel['policies'][policy] + expected = expected_condition_errors(structure, rec['panel'], split='test') + return {'panel': rec['panel'], 'calibration_worst_condition_error': rec['calibration']['worst_condition_error'], + 'test_worst_condition_error': rec['test']['worst_condition_error'], + 'test_pooled_error': rec['test']['pooled_error'], 'test_condition_error': rec['test']['condition_error'], + 'expected_worst_condition_error': float(expected.max()), 'expected_pooled_error': float(expected.mean())} + + +def _scenario_summary(per_seed: list[dict[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for policy in POLICIES + ('oracle',): + rows = [r['policies'][policy] for r in per_seed] + out[policy] = {key: float(np.mean([r[key] for r in rows])) for key in + ('test_worst_condition_error', 'test_pooled_error', 'expected_worst_condition_error')} + return out + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Synthetic joint-failure selection benchmark (FAULTLINE-style), held-out worst-condition error. + + For every seed and scenario (``shared``, ``independent``, ``shift``) all four selectors see the same + calibration trials and candidate panels; frozen panels are scored on fresh test trials. The verdict is + ``harness.compare`` of joint vs accuracy test worst-condition error in the ``shared`` scenario (lower is + better). Other comparisons, exact population errors of every chosen panel and the constructed + known-answer checks are reported alongside.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seeds(seeds) + unknown = sorted(set(overrides) - set(_EXP_DEFAULTS)) + if unknown: + raise ValueError(f'unknown run_experiment parameters: {unknown}') + cfg = {**_EXP_DEFAULTS, **(_EXP_QUICK if quick else {}), **overrides} + k = majority_threshold(cfg.pop('panel_size')) * 2 - 1 + gen = _gen_config(cfg) + m = gen['families'] * gen['family_size'] + if k > m: + raise ValueError('panel_size must not exceed families * family_size') + if math.comb(m, k) > MAX_PANELS: + raise ValueError(f'C(components, panel_size) must be at most {MAX_PANELS}') + t0 = time.perf_counter() + per: dict[str, list[dict[str, Any]]] = {s: [] for s in SCENARIOS} + for seed in seed_list: + for scenario in SCENARIOS: + data = make_failure_data(seed, scenario=scenario, **gen) + sel = run_selection(data['calibration'], data['test'], k) + rec = {'seed': seed, 'data_digest': data['digest'], + 'policies': {p: _policy_record(sel, data['structure'], p) for p in POLICIES}} + orc = sel['oracle'] + expected = expected_condition_errors(data['structure'], orc['panel'], split='test') + rec['policies']['oracle'] = {'panel': orc['panel'], + 'test_worst_condition_error': orc['test']['worst_condition_error'], + 'test_pooled_error': orc['test']['pooled_error'], + 'expected_worst_condition_error': float(expected.max())} + per[scenario].append(rec) + checks = check_constructed_cases() + wall = time.perf_counter() - t0 + + def vals(scenario: str, policy: str) -> list[float]: + return [r['policies'][policy]['test_worst_condition_error'] for r in per[scenario]] + + comparisons = { + 'shared_joint_vs_accuracy': harness.compare(vals('shared', 'joint'), vals('shared', 'accuracy'), + higher_is_better=False), + 'shared_joint_vs_pairwise': harness.compare(vals('shared', 'joint'), vals('shared', 'pairwise'), + higher_is_better=False), + 'shared_joint_vs_pooled': harness.compare(vals('shared', 'joint'), vals('shared', 'pooled'), + higher_is_better=False), + 'independent_joint_vs_accuracy': harness.compare(vals('independent', 'joint'), vals('independent', 'accuracy'), + higher_is_better=False), + 'shift_joint_vs_accuracy': harness.compare(vals('shift', 'joint'), vals('shift', 'accuracy'), + higher_is_better=False), + } + n_p = math.comb(m, k) + kc = gen['families'] + 1 + receipt = harness.base_receipt(MODULE_ID, 'selection_benchmark', { + **gen, 'panel_size': k, 'seeds': list(seed_list), 'quick': quick, 'components': m, 'conditions': kc, + 'scenarios': list(SCENARIOS), 'policies': list(POLICIES), + 'metric': 'held-out (test) worst-condition majority-vote error, lower is better', + 'selection': 'calibration trials only; exhaustive over all C(components, panel_size) panels; integer-count ' + 'keys, ties to the next key then the lexicographically first panel', + 'oracle': 'panel with the lowest test worst-condition error (chosen on test data; reference only)', + 'expected': 'exact population error of the chosen panel under the generator (Poisson-binomial mixture)'}) + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['per_seed'] = per + receipt['summary'] = {s: _scenario_summary(per[s]) for s in SCENARIOS} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['shared_joint_vs_accuracy']['verdict'] + receipt['verdict_basis'] = 'joint_vs_accuracy_heldout_worst_condition_error_shared_scenario' + receipt['constructed_checks'] = checks + receipt['constructed_checks_pass'] = bool(all(checks.values())) + receipt['budget'] = {'candidate_panels': n_p, 'calibration_component_calls': m * kc * gen['calibration_trials'], + 'deployment_component_calls_per_case': k, 'trainable_parameters': 0, + 'note': 'every selector sees the same calibration trials and candidate panels'} + receipt['estimated_cost'] = {'panel_trial_evaluations_per_selection': n_p * kc * gen['calibration_trials'], + 'pair_cofailure_updates_per_selection': m * m * kc * gen['calibration_trials']} + receipt['measured_wallclock_s'] = wall + receipt['notes'] = ('Synthetic benchmark with a documented generator: correlated stressors shared within a ' + 'family (shared), a same-ranking independent-error control (independent), and a common ' + 'cause that is absent from calibration and active on held-out nominal trials (shift; with ' + "shift_target='hardened' it hits the lowest-error member of every family, which is " + 'adversarial to diversity-based selection by construction). Joint-failure selection can ' + 'only protect against failure modes that calibration exercised. Paired 95 % t intervals over ' + 'seeds summarise seed-to-seed variability; they are not anytime-valid. Inspired by FAULTLINE; ' + 'none of its recorded numbers are reproduced.') + return harness.seal(receipt) + + +# ====================================================================== NEUROWEAVE application +# The unmodified engine plus the six single mechanisms that changed the most training-phase head decisions +# relative to it in a diversity probe on seed 99 (never an evaluation seed here), 16 and 24 neurons, 120 and +# 160 steps (2026-11-20). The probe looked at decision changes only, never at accuracy or at any selector. +_NW_MECHANISM_SETS: tuple[tuple[str, ...], ...] = ( + (), ('sparse_code',), ('homeostatic_governor',), ('astrocyte_regulation',), ('multi_soma',), + ('reward_plasticity',), ('dendritic_compartments',)) +_NW_DEFAULTS: dict[str, Any] = { + 'mechanism_sets': _NW_MECHANISM_SETS, 'tasks': harness.TASKS, 'panel_size': 3, 'neurons': 24, + 'topology': 'clustered', 'train_steps': 160, 'calibration_steps': 96, 'test_steps': 96, + 'calibration_seed_offset': 50_000, 'test_seed_offset': 60_000} +_NW_QUICK: dict[str, Any] = {'mechanism_sets': _NW_MECHANISM_SETS[:5], 'neurons': 16, 'train_steps': 120, + 'calibration_steps': 32, 'test_steps': 32} + + +def _nw_config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + from ..neuroweave.spec import MECHANISM_IDS, TOPOLOGIES + from ..neuroweave.tasks import TASKS as NW_TASKS + unknown = sorted(set(overrides) - set(_NW_DEFAULTS)) + if unknown: + raise ValueError(f'unknown run_neuroweave_application parameters: {unknown}') + cfg = {**_NW_DEFAULTS, **(_NW_QUICK if quick else {}), **overrides} + sets = cfg['mechanism_sets'] + if isinstance(sets, (str, bytes, Mapping)): + raise ValueError('mechanism_sets must be a sequence of mechanism-id sequences') + try: + sets = tuple(tuple(s) if not isinstance(s, str) else (s,) for s in sets) + except TypeError as exc: + raise ValueError('mechanism_sets must be a sequence of mechanism-id sequences') from exc + if not 1 <= len(sets) <= 12: + raise ValueError('mechanism_sets must hold 1..12 sets') + for s in sets: + bad = [x for x in s if x not in MECHANISM_IDS] + if bad: + raise ValueError(f'unknown NEUROWEAVE mechanisms: {bad}') + if len({tuple(sorted(s)) for s in sets}) != len(sets): + raise ValueError('mechanism_sets must be distinct') + cfg['mechanism_sets'] = sets + tasks = cfg['tasks'] + if isinstance(tasks, (str, bytes, Mapping)): + raise ValueError('tasks must be a sequence of task ids') + tasks = tuple(tasks) + if not tasks or len(set(tasks)) != len(tasks) or any(t not in NW_TASKS for t in tasks): + raise ValueError(f'tasks must be distinct ids from {NW_TASKS}') + cfg['tasks'] = tasks + k = majority_threshold(cfg['panel_size']) * 2 - 1 + if k > len(sets): + raise ValueError('panel_size must not exceed the number of mechanism sets') + cfg['panel_size'] = k + cfg['neurons'] = _int('neurons', cfg['neurons'], 8, 512) + if cfg['topology'] not in TOPOLOGIES: + raise ValueError(f'topology must be one of {TOPOLOGIES}') + for key in ('train_steps', 'calibration_steps', 'test_steps'): + cfg[key] = _int(key, cfg[key], 4, 20_000) + for key in ('calibration_seed_offset', 'test_seed_offset'): + cfg[key] = _int(key, cfg[key], 1, 2**30) + if cfg['calibration_seed_offset'] == cfg['test_seed_offset']: + raise ValueError('calibration_seed_offset and test_seed_offset must differ') + return cfg + + +def _nw_component(mechs: tuple[str, ...], seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]: + from ..neuroweave.engine import NeuroWeaveEngine + from ..neuroweave.experiments import ReadoutHead, clone_engine, make_spec, run_task_phase + from ..neuroweave.tasks import make_stream + tasks = cfg['tasks'] + spec = make_spec(mechs, seed=seed, neurons=cfg['neurons'], topology=cfg['topology'], steps=cfg['train_steps']) + engine = NeuroWeaveEngine(spec) + heads = {t: ReadoutHead(engine.n, seed) for t in tasks} + train_stream = make_stream(seed, cfg['train_steps']) + train = run_task_phase(engine, heads, train_stream, learn=True) + out: dict[str, Any] = {'mechanisms': list(mechs), 'train_stream_digest': train_stream.digest, + 'train_accuracy': {t: train['tasks'][t]['accuracy'] for t in tasks}, + 'head_parameters': int(sum(h.parameter_count for h in heads.values()))} + for split, offset, steps in (('calibration', cfg['calibration_seed_offset'], cfg['calibration_steps']), + ('test', cfg['test_seed_offset'], cfg['test_steps'])): + stream = make_stream(seed + offset, steps) + res = run_task_phase(clone_engine(engine), {t: h.copy() for t, h in heads.items()}, stream, learn=False) + out[f'{split}_failures'] = np.array([[c < 0.5 for c in res['tasks'][t]['correct']] for t in tasks], dtype=bool) + out[f'{split}_accuracy'] = {t: res['tasks'][t]['accuracy'] for t in tasks} + out[f'{split}_stream_digest'] = stream.digest + return out + + +def run_neuroweave_application(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), + **overrides: Any) -> dict[str, Any]: + """Joint-failure panel selection over NEUROWEAVE readouts. + + Components are NEUROWEAVE engines that differ only in their mechanism set, each trained (``learn=True``, + the lab's ``run_task_phase``) with one logistic ``ReadoutHead`` per task; conditions are the temporal + tasks. Failures are recorded frozen on a calibration stream and on a disjoint test stream (stream seeds + ``seed + calibration_seed_offset`` / ``seed + test_seed_offset``). The verdict is ``harness.compare`` of + joint vs accuracy held-out worst-task error over seeds (lower is better).""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seeds(seeds) + cfg = _nw_config(quick, overrides) + train_seeds = set(seed_list) + cal_seeds = {s + cfg['calibration_seed_offset'] for s in seed_list} + test_seeds = {s + cfg['test_seed_offset'] for s in seed_list} + if train_seeds & cal_seeds or train_seeds & test_seeds or cal_seeds & test_seeds: + raise ValueError('training, calibration and test stream seeds must be pairwise disjoint') + k = cfg['panel_size'] + t0 = time.perf_counter() + per_seed = [] + for seed in seed_list: + comps = [_nw_component(m, seed, cfg) for m in cfg['mechanism_sets']] + cal = np.stack([c['calibration_failures'] for c in comps]) + test = np.stack([c['test_failures'] for c in comps]) + sel = run_selection(cal, test, k) + flat = cal.reshape(cal.shape[0], -1) + agreement = (flat[:, None, :] == flat[None, :, :]).mean(axis=2) + iu = np.triu_indices(cal.shape[0], 1) + per_seed.append({ + 'seed': seed, + 'components': [{key: c[key] for key in ('mechanisms', 'train_stream_digest', 'train_accuracy', + 'calibration_accuracy', 'test_accuracy', 'head_parameters', + 'calibration_stream_digest', 'test_stream_digest')} + for c in comps], + 'policies': {p: {'panel': sel['policies'][p]['panel'], + 'calibration_worst_condition_error': sel['policies'][p]['calibration']['worst_condition_error'], + 'test_worst_condition_error': sel['policies'][p]['test']['worst_condition_error'], + 'test_pooled_error': sel['policies'][p]['test']['pooled_error'], + 'test_condition_error': sel['policies'][p]['test']['condition_error']} + for p in POLICIES}, + 'oracle': {'panel': sel['oracle']['panel'], + 'test_worst_condition_error': sel['oracle']['test']['worst_condition_error']}, + 'best_single_component_test_worst_error': float(test.mean(axis=2).max(axis=1).min()), + 'calibration_failure_agreement': {'mean_offdiagonal': float(agreement[iu].mean()), + 'min_offdiagonal': float(agreement[iu].min()), + 'identical_pairs': int(np.sum(agreement[iu] == 1.0))}, + }) + wall = time.perf_counter() - t0 + + def vals(policy: str) -> list[float]: + return [r['policies'][policy]['test_worst_condition_error'] for r in per_seed] + + comparisons = {'joint_vs_accuracy': harness.compare(vals('joint'), vals('accuracy'), higher_is_better=False), + 'joint_vs_pairwise': harness.compare(vals('joint'), vals('pairwise'), higher_is_better=False), + 'joint_vs_pooled': harness.compare(vals('joint'), vals('pooled'), higher_is_better=False)} + n_c, n_t = len(cfg['mechanism_sets']), len(cfg['tasks']) + steps_per_component = cfg['train_steps'] + cfg['calibration_steps'] + cfg['test_steps'] + receipt = harness.base_receipt(NEUROWEAVE_ID, 'selection_application', { + **cfg, 'mechanism_sets': [list(s) for s in cfg['mechanism_sets']], 'tasks': list(cfg['tasks']), + 'seeds': list(seed_list), 'quick': quick, + 'protocol': 'per seed and mechanism set: one engine trained learn=True with one ReadoutHead per task ' + '(run_task_phase; the first task supplies the reward), then frozen calibration and test streams', + 'metric': 'held-out (test) worst-task majority-vote error, lower is better'}) + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['per_seed'] = per_seed + receipt['summary'] = {p: {'test_worst_condition_error': float(np.mean(vals(p)))} for p in POLICIES} + receipt['summary']['oracle'] = {'test_worst_condition_error': float(np.mean( + [r['oracle']['test_worst_condition_error'] for r in per_seed]))} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['joint_vs_accuracy']['verdict'] + receipt['verdict_basis'] = 'joint_vs_accuracy_heldout_worst_task_error' + receipt['budget'] = {'components': n_c, 'candidate_panels': math.comb(n_c, k), + 'calibration_component_calls': n_c * n_t * cfg['calibration_steps'], + 'deployment_component_calls_per_case': k, + 'head_parameters_per_component': per_seed[0]['components'][0]['head_parameters']} + receipt['estimated_cost'] = {'engine_steps': len(seed_list) * n_c * steps_per_component} + receipt['measured_wallclock_s'] = wall + receipt['notes'] = ('Synthetic NEUROWEAVE temporal tasks with binary targets, so majority-of-failures equals ' + 'majority-vote error exactly. Components differ only in their mechanism set (same seed, ' + 'topology, training stream and head initialisation), so their failures are strongly ' + 'correlated; calibration_failure_agreement reports how often two components fail on the same ' + 'trials. The default mechanism sets were chosen by a decision-diversity probe on seed 99, ' + 'not by accuracy or by any selector outcome; many other single mechanisms leave the head ' + 'decisions unchanged at these sizes. The heads are close to chance on most tasks, so this ' + 'demonstrates the selection pipeline on real engine outputs; it is not evidence that any ' + 'mechanism or selector helps NEUROWEAVE.') + return harness.seal(receipt) + + +EXPERIMENTS = {MODULE_ID: run_experiment, NEUROWEAVE_ID: run_neuroweave_application} diff --git a/synapse/frontier/kuramoto.py b/synapse/frontier/kuramoto.py new file mode 100644 index 0000000000000000000000000000000000000000..a0331a943f844caf1abcbc9a538d74461be68eac --- /dev/null +++ b/synapse/frontier/kuramoto.py @@ -0,0 +1,1063 @@ +"""Oscillatory binding units (frontier module ``kuramoto_binding``). + +Inspired by *Artificial Kuramoto Oscillatory Neurons* (AKOrN) -- Takeru Miyato, Sindy Löwe, Andreas +Geiger and Max Welling, ICLR 2025 (oral), April 2025; arXiv:2410.13821, https://arxiv.org/abs/2410.13821. +This module is a synthetic computational abstraction. It implements the paper's discrete oscillator +update and uses it in three small settings; it does not reproduce the paper's networks (no learned +convolutional or attention couplings, no readout blocks, no training) or any of its results. +Full, verified references: ``docs/frontier/modules/kuramoto_binding.md``. + +Update (paper Sec. 3 Eq. 2 and Sec. 4 Eqs. 4-5, here with scalar couplings ``J_ij * I_N``):: + + dx_i = Omega_i x_i + Proj_{x_i}(c_i + sum_j J_ij x_j), Proj_x(y) = y - x + x_i <- Pi(x_i + gamma * dx_i), Pi(v) = v / ||v|| + +Each ``x_i`` is a unit vector in ``R^N`` (``N`` even), ``Omega_i`` is an antisymmetric natural-frequency +matrix (block rotations), ``c_i`` the conditional stimulus, and ``K`` iterations run per call. The global +order parameter is ``R = ||mean_i x_i||`` (Kuramoto's ``||`` when ``N = 2``). + +Settings +-------- +* :class:`KuramotoExtension` -- NEUROWEAVE engine extension: one oscillator per region (or per sampled + unit), couplings aggregated from the engine's synapse table at ``bind``, stimuli from the group's mean + output. It only adds readout features; it never changes the drive. +* :class:`KuramotoObserver` -- read-only live observer: oscillators driven by subsampled rates with fixed + sparse coupling plus a slow, bounded Hebbian co-activity estimate; reports order-parameter statistics, + phase-cluster counts and the metastability and chimera indices of Shanahan (Chaos 20, 013108, 2010). +* :func:`run_binding_benchmark` -- a synthetic binding task scored with the adjusted Rand index (Hubert & + Arabie, 1985), against a shuffled-coupling and a zero-coupling control (plus a non-oscillatory reference). + +All randomness comes from ``numpy.random.default_rng(seed + offset)``. +""" +from __future__ import annotations + +import hashlib +import json +import math +import time +from typing import Any, Mapping, Sequence + +import numpy as np + +from ..neuroweave.spec import REGIONS +from . import harness +from .extension import EngineExtension +from .spec import EVIDENCE_TIER, FrontierSpecV1 + +__all__ = ['MODULE_ID', 'BENCHMARK_ID', 'SOURCE', 'EXPERIMENTS', 'OBSERVER_STATE_SCHEMA', 'KuramotoExtension', + 'KuramotoObserver', + 'project_tangent', 'natural_frequency_matrices', 'akorn_step', 'akorn_run', 'kuramoto_energy', + 'order_parameter', 'group_coherence', 'phases', 'phase_locking_value', 'count_phase_clusters', + 'shanahan_indices', 'adjusted_rand_index', 'kmeans_labels', 'make_binding_task', 'correlation_coupling', + 'shuffle_coupling', 'run_experiment', 'run_binding_benchmark'] + +MODULE_ID = 'kuramoto_binding' +BENCHMARK_ID = MODULE_ID + '_benchmark' +SOURCE = ('Miyato, Löwe, Geiger & Welling, "Artificial Kuramoto Oscillatory Neurons", ICLR 2025 (oral), ' + 'April 2025, arXiv:2410.13821, https://arxiv.org/abs/2410.13821') +OBSERVER_STATE_SCHEMA = 'KuramotoObserverStateV1' + +_EXT_OFFSET = 61_001 +_UNIT_OFFSET = 61_007 +_OBS_OFFSET = 61_013 +_TASK_OFFSET = 61_027 +_INIT_OFFSET = 61_031 +_KMEANS_OFFSET = 61_043 +_SHUFFLE_OFFSET = 61_051 +_EPS = 1e-12 +_MAX_COUPLING = 1e6 +_STATS_RATE = 0.05 # observer: EWMA rate of the running mean / variance used to standardise rates +_Z_CLIP = 3.0 # observer: standardised co-activity is clipped to +/-3 sd, then scaled to [-1, 1] +# FrontierSpecV1 observer parameters meant for other observers; accepted and ignored here. +_SPEC_OBSERVER_PARAMS = frozenset({'sync_pairs', 'sae_features', 'sae_k', 'fc_window', 'max_observed_units', + 'observe_every'}) + + +# ====================================================================== validation helpers +def _int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _num(name: str, value: Any, low: float, high: float, *, open_low: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + if not math.isfinite(v) or v < low or v > high or (open_low and v <= low): + raise ValueError(f'{name} must be a finite number in {"(" if open_low else "["}{low}, {high}]') + return v + + +def _even_dim(value: Any) -> int: + d = _int('dim', value, 2, 64) + if d % 2: + raise ValueError('dim must be even (oscillators rotate in 2-d planes)') + return d + + +def _normalize(v: np.ndarray) -> np.ndarray: + """Rows scaled to unit norm (a zero row, which the update cannot produce, maps to e_0).""" + norm = np.linalg.norm(v, axis=-1, keepdims=True) + out = v / np.where(norm > _EPS, norm, 1.0) + zero = norm[..., 0] <= _EPS + if np.any(zero): + out[zero] = 0.0 + out[zero, 0] = 1.0 + return out + + +def _unit_rows(rng: np.random.Generator, count: int, dim: int) -> np.ndarray: + return _normalize(rng.standard_normal((count, dim))) + + +def _as_states(x: Any) -> np.ndarray: + a = np.asarray(x, dtype=np.float64) + if a.ndim != 2 or a.shape[0] < 1 or a.shape[1] < 2 or a.shape[1] % 2 or not np.all(np.isfinite(a)): + raise ValueError('oscillator states must be a finite (C, N) array with N even and >= 2') + return a + + +def _check_coupling(coupling: Any, c: int, n: int) -> np.ndarray | None: + if coupling is None: + return None + j = np.asarray(coupling, dtype=np.float64) + if j.shape not in ((c, c), (c * n, c * n)) or not np.all(np.isfinite(j)) or np.any(np.abs(j) > _MAX_COUPLING): + raise ValueError(f'coupling must be a finite ({c}, {c}) or ({c * n}, {c * n}) array with |J| <= 1e6') + return j + + +def _check_stimulus(stimulus: Any, c: int, n: int) -> np.ndarray | None: + if stimulus is None: + return None + s = np.asarray(stimulus, dtype=np.float64) + if s.shape != (c, n) or not np.all(np.isfinite(s)) or np.any(np.abs(s) > _MAX_COUPLING): + raise ValueError(f'stimulus must be a finite ({c}, {n}) array with |c| <= 1e6') + return s + + +def _check_omega(omega: Any, c: int, n: int) -> np.ndarray | None: + if omega is None: + return None + om = np.asarray(omega, dtype=np.float64) + if om.shape == (n, n): + om = np.broadcast_to(om, (c, n, n)) + if om.shape != (c, n, n) or not np.all(np.isfinite(om)) or np.any(np.abs(om) > _MAX_COUPLING): + raise ValueError(f'omega must be a finite ({c}, {n}, {n}) or ({n}, {n}) array') + if np.max(np.abs(om + np.swapaxes(om, 1, 2))) > 1e-9 * max(1.0, float(np.max(np.abs(om)))): + raise ValueError('omega must be antisymmetric (Omega^T = -Omega)') + return om + + +# ====================================================================== AKOrN core +def project_tangent(x: Any, y: Any) -> np.ndarray: + """``Proj_x(y) = y - x`` row-wise (the tangent-space projection for unit ``x``).""" + xa = np.asarray(x, dtype=np.float64) + ya = np.asarray(y, dtype=np.float64) + if xa.shape != ya.shape or xa.ndim < 1 or not (np.all(np.isfinite(xa)) and np.all(np.isfinite(ya))): + raise ValueError('x and y must be finite arrays of the same shape') + return ya - np.sum(ya * xa, axis=-1, keepdims=True) * xa + + +def natural_frequency_matrices(frequencies: Any, dim: int) -> np.ndarray: + """Antisymmetric ``Omega_i`` built from per-plane angular frequencies. + + ``frequencies`` is ``(C,)`` (same frequency in every plane) or ``(C, dim // 2)``. Plane ``p`` uses the + block ``[[0, -w], [w, 0]]`` on coordinates ``(2p, 2p + 1)``, so ``dtheta/dt = w`` (counter-clockwise).""" + d = _even_dim(dim) + half = d // 2 + f = np.asarray(frequencies, dtype=np.float64) + if f.ndim == 1: + f = np.repeat(f[:, None], half, axis=1) + if f.ndim != 2 or f.shape[0] < 1 or f.shape[1] != half or not np.all(np.isfinite(f)) or np.any(np.abs(f) > 1e6): + raise ValueError(f'frequencies must be finite with shape (C,) or (C, {half})') + om = np.zeros((f.shape[0], d, d)) + for p in range(half): + om[:, 2 * p, 2 * p + 1] = -f[:, p] + om[:, 2 * p + 1, 2 * p] = f[:, p] + return om + + +def _step(x: np.ndarray, coupling: np.ndarray | None, stimulus: np.ndarray | None, omega: np.ndarray | None, + gamma: float) -> np.ndarray: + """One unchecked AKOrN update of unit-norm ``x`` (shapes already validated).""" + c, n = x.shape + y = np.zeros_like(x) if stimulus is None else stimulus.copy() + if coupling is not None: + y += coupling @ x if coupling.shape == (c, c) else (coupling @ x.reshape(-1)).reshape(c, n) + dx = y - np.sum(y * x, axis=1, keepdims=True) * x + if omega is not None: + dx += np.einsum('cij,cj->ci', omega, x) + return _normalize(x + gamma * dx) + + +def akorn_step(x: Any, coupling: Any = None, stimulus: Any = None, omega: Any = None, *, + gamma: float = 0.1) -> np.ndarray: + """One discrete AKOrN update ``x <- Pi(x + gamma (Omega x + Proj_x(c + J x)))``. + + ``x`` is ``(C, N)`` and is first put on the sphere; ``coupling`` is ``(C, C)`` scalar couplings or a + ``(C*N, C*N)`` block matrix; ``stimulus`` is ``(C, N)``; ``omega`` is ``(C, N, N)`` or ``(N, N)`` + antisymmetric. ``None`` means zero.""" + xa = _as_states(x) + c, n = xa.shape + return _step(_normalize(xa), _check_coupling(coupling, c, n), _check_stimulus(stimulus, c, n), + _check_omega(omega, c, n), _num('gamma', gamma, 0.0, 10.0, open_low=True)) + + +def akorn_run(x: Any, coupling: Any = None, stimulus: Any = None, omega: Any = None, *, gamma: float = 0.1, + iterations: int = 16) -> np.ndarray: + """``iterations`` AKOrN updates with a constant stimulus (validated once).""" + xa = _as_states(x) + c, n = xa.shape + j, s, om = _check_coupling(coupling, c, n), _check_stimulus(stimulus, c, n), _check_omega(omega, c, n) + g = _num('gamma', gamma, 0.0, 10.0, open_low=True) + k = _int('iterations', iterations, 0, 100_000) + out = _normalize(xa) + for _ in range(k): + out = _step(out, j, s, om, g) + return out + + +def kuramoto_energy(x: Any, coupling: Any = None, stimulus: Any = None) -> float: + """``E = -1/2 sum_ij x_i^T J_ij x_j - sum_i c_i^T x_i`` (paper Eq. 3). It is a Lyapunov function of the + continuous flow only for symmetric scalar couplings, shared ``Omega`` and ``Omega c_i = 0``.""" + xa = _as_states(x) + c, n = xa.shape + j, s = _check_coupling(coupling, c, n), _check_stimulus(stimulus, c, n) + e = 0.0 + if j is not None: + e -= 0.5 * float(np.sum(j * (xa @ xa.T))) if j.shape == (c, c) else 0.5 * float(xa.reshape(-1) @ j @ xa.reshape(-1)) + if s is not None: + e -= float(np.sum(s * xa)) + return e + + +def order_parameter(x: Any) -> float: + """``R = ||mean_i x_i||`` in ``[0, 1]`` for unit-norm rows (clipped at 1 against round-off).""" + return min(1.0, float(np.linalg.norm(_as_states(x).mean(axis=0)))) + + +def group_coherence(x: Any, labels: Any, n_groups: int | None = None) -> np.ndarray: + """Per-group order parameter ``||mean_{i in g} x_i||`` (0 for an empty group; clipped at 1).""" + xa = _as_states(x) + lab = np.asarray(labels) + if lab.shape != (xa.shape[0],) or not np.issubdtype(lab.dtype, np.integer) or np.any(lab < 0): + raise ValueError('labels must be non-negative ints, one per oscillator') + g = int(lab.max()) + 1 if n_groups is None else _int('n_groups', n_groups, int(lab.max()) + 1, 1_000_000) + sums = np.zeros((g, xa.shape[1])) + np.add.at(sums, lab, xa) + cnt = np.bincount(lab, minlength=g) + return np.minimum(1.0, np.linalg.norm(sums, axis=1) / np.maximum(cnt, 1)) + + +def phases(x: Any) -> np.ndarray: + """Phase of each oscillator in its first rotation plane, ``atan2(x_1, x_0)`` (exact for ``N = 2``).""" + xa = _as_states(x) + return np.arctan2(xa[:, 1], xa[:, 0]) + + +def phase_locking_value(phase_a: Any, phase_b: Any) -> float: + """``|mean_t exp(i (phi_a(t) - phi_b(t)))|`` (Lachaux et al., 1999), in ``[0, 1]``.""" + a = np.asarray(phase_a, dtype=np.float64) + b = np.asarray(phase_b, dtype=np.float64) + if a.ndim != 1 or a.shape != b.shape or a.size == 0 or not (np.all(np.isfinite(a)) and np.all(np.isfinite(b))): + raise ValueError('phase series must be finite, 1-D, non-empty and of equal length') + return float(np.abs(np.mean(np.exp(1j * (a - b))))) + + +def count_phase_clusters(phase: Any, *, bins: int = 36, min_fraction: float = 0.1) -> int: + """Number of phase clusters from an angle histogram. + + A bin is *dense* when it holds at least ``max(1, ceil(min_fraction * M))`` of the ``M`` oscillators; + a cluster is a circular run of dense bins bounded by sparse bins. A spread-out (incoherent) population + gives 0, and so does a histogram with no sparse bin at all (nothing separates one cluster from + another). A cluster smaller than about ``2 * min_fraction`` of the population can be missed when it + straddles a bin edge.""" + p = np.asarray(phase, dtype=np.float64) + if p.ndim != 1 or not np.all(np.isfinite(p)): + raise ValueError('phase must be a finite 1-D array') + b = _int('bins', bins, 2, 100_000) + frac = _num('min_fraction', min_fraction, 0.0, 1.0, open_low=True) + if p.size == 0: + return 0 + idx = np.minimum(b - 1, np.floor(np.mod(p, 2.0 * np.pi) / (2.0 * np.pi / b)).astype(np.int64)) + dense = np.bincount(idx, minlength=b) >= max(1, math.ceil(frac * p.size - 1e-9)) + if dense.all(): + return 0 + return int(np.sum(dense & ~np.roll(dense, 1))) + + +def shanahan_indices(community_order: Any) -> dict[str, float]: + """Metastability and chimera indices of Shanahan (2010) from community synchrony ``phi`` of shape ``(T, M)``. + + As defined in the paper: ``metastability_index`` (lambda) is the mean over the ``M`` communities of the + variance over time ``sigma_met(c) = 1/(T-1) sum_t (phi_c(t) - _T)^2``; ``chimera_index`` (chi) + is the mean over the ``T`` samples of the variance across communities + ``sigma_chi(t) = 1/(M-1) sum_c (phi_c(t) - _C)^2``. A variance over a single sample (``T = 1`` + or ``M = 1``) is reported as 0.""" + phi = np.asarray(community_order, dtype=np.float64) + if phi.ndim != 2 or phi.shape[0] < 1 or phi.shape[1] < 1 or not np.all(np.isfinite(phi)): + raise ValueError('community_order must be a finite (T, M) array') + t, m = phi.shape + met = float(np.mean(np.var(phi, axis=0, ddof=1))) if t > 1 else 0.0 + chi = float(np.mean(np.var(phi, axis=1, ddof=1))) if m > 1 else 0.0 + return {'metastability_index': met, 'chimera_index': chi} + + +# ====================================================================== clustering scores +def adjusted_rand_index(labels_true: Any, labels_pred: Any) -> float: + """Adjusted Rand index (Hubert & Arabie, 1985): ``(index - expected) / (max_index - expected)``. + + 1 for identical partitions (up to relabelling), about 0 for chance agreement, negative below chance. + When the denominator vanishes (both partitions are one cluster, or both all singletons) the + partitions are identical and the score is 1.""" + a = np.asarray(labels_true) + b = np.asarray(labels_pred) + if a.ndim != 1 or a.shape != b.shape: + raise ValueError('label arrays must be 1-D and of equal length') + n = a.size + if n < 2: + return 1.0 + _, ai = np.unique(a, return_inverse=True) + _, bi = np.unique(b, return_inverse=True) + table = np.zeros((int(ai.max()) + 1, int(bi.max()) + 1), dtype=np.int64) + np.add.at(table, (ai.ravel(), bi.ravel()), 1) + + def pairs(v: np.ndarray) -> int: + v = v.astype(np.int64) + return int(np.sum(v * (v - 1) // 2)) + + index, sum_a, sum_b = pairs(table), pairs(table.sum(axis=1)), pairs(table.sum(axis=0)) + total = n * (n - 1) // 2 + expected = sum_a * sum_b / total + denom = 0.5 * (sum_a + sum_b) - expected + if denom == 0.0: + return 1.0 + return float((index - expected) / denom) + + +def kmeans_labels(points: Any, k: int, *, seed: int = 0, restarts: int = 8, max_iter: int = 100) -> np.ndarray: + """Seeded Lloyd k-means with k-means++ seeding (Arthur & Vassilvitskii, SODA 2007); the restart with the + lowest inertia wins. An empty cluster is re-seeded at the worst-fitting point. + + On unit vectors Euclidean k-means is equivalent to clustering by cosine similarity.""" + x = np.asarray(points, dtype=np.float64) + if x.ndim != 2 or x.shape[0] < 1 or not np.all(np.isfinite(x)): + raise ValueError('points must be a finite (M, D) array') + m = x.shape[0] + k = _int('k', k, 1, m) + rng = np.random.default_rng(_int('seed', seed, 0, 2**62)) + restarts = _int('restarts', restarts, 1, 1000) + max_iter = _int('max_iter', max_iter, 1, 100_000) + best: tuple[float, np.ndarray] | None = None + rows = np.arange(m) + for _ in range(restarts): + centers = [x[int(rng.integers(m))]] + d2 = np.sum((x - centers[0]) ** 2, axis=1) + for _ in range(1, k): + total = float(d2.sum()) + idx = int(rng.integers(m)) if total <= 0.0 else int(rng.choice(m, p=d2 / total)) + centers.append(x[idx]) + d2 = np.minimum(d2, np.sum((x - x[idx]) ** 2, axis=1)) + cen = np.array(centers) + for _ in range(max_iter): + dist = np.sum((x[:, None, :] - cen[None, :, :]) ** 2, axis=2) + lab = dist.argmin(axis=1) + new = cen.copy() + for j in range(k): + members = lab == j + if members.any(): + new[j] = x[members].mean(axis=0) + else: # empty cluster: re-seed at the worst-fit point + new[j] = x[int(dist[rows, lab].argmax())] + done = np.allclose(new, cen, rtol=0.0, atol=1e-12) + cen = new + if done: + break + dist = np.sum((x[:, None, :] - cen[None, :, :]) ** 2, axis=2) + lab = dist.argmin(axis=1) + inertia = float(dist[rows, lab].sum()) + if best is None or inertia < best[0] - 1e-12: + best = (inertia, lab) + assert best is not None + return best[1].astype(np.int64) + + +# ====================================================================== engine extension +class KuramotoExtension(EngineExtension): + """AKOrN oscillators attached to a NEUROWEAVE engine (features only; the drive is never changed). + + ``mode='region'``: one oscillator per NEUROWEAVE region (10). ``mode='units'``: one oscillator per + sampled unit (``units`` of them, sampled at ``bind`` with the extension seed). + + * Coupling ``J`` (copied at ``bind``; the engine is not kept): synapse weights summed over + ``src -> dst`` pairs into ``J[group(dst), group(src)]``, divided by the target group's size (mean + input per target unit), diagonal zeroed (self-coupling vanishes under the projection), then scaled + so the largest absolute row sum equals ``|coupling_scale|`` (a negative scale flips every sign). + Inhibitory synapses give negative (anti-phase) couplings. Later plasticity is not tracked: ``J`` is + a snapshot. + * Stimulus ``c_g = stimulus_scale * m_g * u_g``: the group's current mean output ``m_g`` times a fixed + seeded unit vector ``u_g``. + * ``iterations`` AKOrN updates per engine step with natural frequencies + ``omega_mean + omega_spread * N(0, 1)`` per oscillator and plane. + + Features (``feature_dim = C + 1 + top_pairs``; 15 in region mode with the defaults): + ``C`` cosines of each oscillator with the global mean-field direction (0 when ``R`` is ~0), the global + order parameter ``R``, and the ``top_pairs`` largest pairwise phase-locking values (first rotation + plane), sorted in descending order. PLVs are exponentially weighted over steps (rate ``plv_rate``) and + bias-corrected. All features lie in ``[-1, 1]``. The extension has no trainable parameters, so it is + trivially frozen when ``ctx['learn']`` is false.""" + + id = MODULE_ID + + def __init__(self, seed: int = 0, *, mode: str = 'region', units: int = 16, dim: int = 2, iterations: int = 4, + gamma: float = 0.1, coupling_scale: float = 1.0, stimulus_scale: float = 1.0, omega_mean: float = 1.0, + omega_spread: float = 0.5, top_pairs: int = 4, plv_rate: float = 0.1) -> None: + self.seed = _int('seed', seed, 0, 2**31 - 1) + if mode not in ('region', 'units'): + raise ValueError("mode must be 'region' or 'units'") + self.mode = mode + self.units = _int('units', units, 2, 4096) + self.dim = _even_dim(dim) + self.iterations = _int('iterations', iterations, 1, 256) + self.gamma = _num('gamma', gamma, 0.0, 10.0, open_low=True) + self.coupling_scale = _num('coupling_scale', coupling_scale, -100.0, 100.0) + self.stimulus_scale = _num('stimulus_scale', stimulus_scale, -100.0, 100.0) + self.omega_mean = _num('omega_mean', omega_mean, -100.0, 100.0) + self.omega_spread = _num('omega_spread', omega_spread, 0.0, 100.0) + self.plv_rate = _num('plv_rate', plv_rate, 0.0, 1.0, open_low=True) + self.oscillators = len(REGIONS) if mode == 'region' else self.units + c = self.oscillators + self.top_pairs = _int('top_pairs', top_pairs, 0, c * (c - 1) // 2) + self.feature_dim = c + 1 + self.top_pairs + rng = np.random.default_rng(self.seed + _EXT_OFFSET) + self._x0 = _unit_rows(rng, c, self.dim) + self._freq = self.omega_mean + self.omega_spread * rng.standard_normal((c, self.dim // 2)) + self._omega = natural_frequency_matrices(self._freq, self.dim) + self._stim_dir = _unit_rows(rng, c, self.dim) + self._iu = np.triu_indices(c, 1) + # filled by bind() + self._n = 0 + self._group = np.zeros(0, dtype=np.int64) # oscillator index per unit, -1 = not represented + self._count = np.zeros(c) + self._coupling = np.zeros((c, c)) + self.reset() + + # ------------------------------------------------------------------ lifecycle + def config(self) -> dict[str, Any]: + return {'seed': self.seed, 'mode': self.mode, 'units': self.units, 'dim': self.dim, + 'iterations': self.iterations, 'gamma': self.gamma, 'coupling_scale': self.coupling_scale, + 'stimulus_scale': self.stimulus_scale, 'omega_mean': self.omega_mean, + 'omega_spread': self.omega_spread, 'top_pairs': self.top_pairs, 'plv_rate': self.plv_rate, + 'oscillators': self.oscillators, 'feature_dim': self.feature_dim} + + def bind(self, engine: Any) -> None: + try: + n = int(engine.n) + brain = engine.brain + region = np.asarray(brain.cells.region, dtype=np.int64)[:n].copy() + n_regions = len(brain.regions) + syn = brain.synapses + src = np.asarray(syn.src, dtype=np.int64).copy() + dst = np.asarray(syn.dst, dtype=np.int64).copy() + w = np.asarray(syn.w, dtype=np.float64).copy() + except AttributeError as exc: # pragma: no cover - only non-NEUROWEAVE engines + raise ValueError('kuramoto_binding needs a NEUROWEAVE engine (brain.cells.region, brain.synapses)') from exc + c = self.oscillators + if region.size != n or src.shape != dst.shape or src.shape != w.shape or not np.all(np.isfinite(w)): + raise ValueError('engine synapse table is inconsistent') + if self.mode == 'region': + if n_regions != c: + raise ValueError(f'region mode expects {c} regions, engine has {n_regions}') + group = region + else: + if n < c: + raise ValueError(f'units ({c}) must not exceed engine.n ({n})') + chosen = np.sort(np.random.default_rng(self.seed + _UNIT_OFFSET).choice(n, size=c, replace=False)) + group = np.full(n, -1, dtype=np.int64) + group[chosen] = np.arange(c) + count = np.bincount(group[group >= 0], minlength=c).astype(np.float64) + ok = (src >= 0) & (src < n) & (dst >= 0) & (dst < n) + s, d, ww = src[ok], dst[ok], w[ok] + keep = (group[s] >= 0) & (group[d] >= 0) + j = np.zeros((c, c)) + np.add.at(j, (group[d[keep]], group[s[keep]]), ww[keep]) + j /= np.maximum(count, 1.0)[:, None] + np.fill_diagonal(j, 0.0) + row = float(np.max(np.abs(j).sum(axis=1))) if c else 0.0 + self._coupling = self.coupling_scale * j / row if row > _EPS else np.zeros((c, c)) + self._n, self._group, self._count = n, group, count + self.reset() + + def reset(self) -> None: + self._x = self._x0.copy() + self._plv = np.zeros(self._iu[0].size, dtype=np.complex128) + self._steps = 0 + self._last_mean = np.zeros(self.oscillators) + + # ------------------------------------------------------------------ hooks + def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None: + if self._n == 0: + raise ValueError('kuramoto_binding is not bound to an engine') + out = np.asarray(output, dtype=np.float64).ravel() + if not np.all(np.isfinite(out)): + raise ValueError('output must be finite') + o = np.zeros(self._n) + m = min(self._n, out.size) # neurons born after bind are ignored (fixed shape) + o[:m] = np.clip(out[:m], -10.0, 10.0) + rep = self._group >= 0 + mean = np.bincount(self._group[rep], weights=o[rep], minlength=self.oscillators) / np.maximum(self._count, 1.0) + stim = self.stimulus_scale * mean[:, None] * self._stim_dir + x = self._x + for _ in range(self.iterations): + x = _step(x, self._coupling, stim, self._omega, self.gamma) + self._x = x + if self._plv.size: + th = np.arctan2(x[:, 1], x[:, 0]) + a = self.plv_rate + self._plv = (1.0 - a) * self._plv + a * np.exp(1j * (th[self._iu[0]] - th[self._iu[1]])) + self._steps += 1 + self._last_mean = mean + + def coupling_matrix(self) -> np.ndarray: + """The oscillator coupling ``J`` copied from the engine at ``bind`` (``J[target, source]``); a copy.""" + return self._coupling.copy() + + def states(self) -> np.ndarray: + """Current oscillator states ``(C, N)``, unit rows; a copy.""" + return self._x.copy() + + def _plv_values(self) -> np.ndarray: + if self._steps == 0 or not self._plv.size: + return np.zeros(self._plv.size) + weight = 1.0 - (1.0 - self.plv_rate) ** self._steps # bias correction of the EWMA + return np.clip(np.abs(self._plv) / max(weight, _EPS), 0.0, 1.0) + + def features(self) -> np.ndarray: + x = self._x + mf = x.mean(axis=0) + r = float(np.linalg.norm(mf)) + coh = x @ (mf / r) if r > 1e-9 else np.zeros(self.oscillators) + top = np.zeros(self.top_pairs) + if self.top_pairs: + plv = np.sort(self._plv_values())[::-1] + top[:min(self.top_pairs, plv.size)] = plv[:self.top_pairs] + return np.clip(np.concatenate([coh, [r], top]), -1.0, 1.0) # every block is a cosine or a modulus + + # ------------------------------------------------------------------ accounting / persistence + def parameter_count(self) -> int: + return 0 + + def state_numbers(self) -> int: + return int(self._coupling.size + self._omega.size + self._stim_dir.size + self._x.size + self._x0.size + + 2 * self._plv.size + self._group.size + self._count.size + self._last_mean.size + 1) + + def telemetry(self) -> dict[str, Any]: + plv = self._plv_values() + off = self._coupling[~np.eye(self.oscillators, dtype=bool)] + nonzero = off[off != 0.0] + return {'id': self.id, 'mode': self.mode, 'oscillators': self.oscillators, 'dim': self.dim, + 'steps': int(self._steps), 'order_parameter': order_parameter(self._x), + 'mean_plv': float(plv.mean()) if plv.size else 0.0, 'max_plv': float(plv.max()) if plv.size else 0.0, + 'coupling_max_abs_row_sum': float(np.max(np.abs(self._coupling).sum(axis=1))), + 'coupling_nonzero': int(nonzero.size), + 'coupling_negative_fraction': float(np.mean(nonzero < 0.0)) if nonzero.size else 0.0} + + def export_state(self) -> dict[str, Any]: + return {'id': self.id, 'config': self.config(), 'n': int(self._n), 'steps': int(self._steps), + 'x': self._x.tolist(), 'plv_re': self._plv.real.tolist(), 'plv_im': self._plv.imag.tolist(), + 'last_mean': self._last_mean.tolist(), 'coupling': self._coupling.tolist()} + + def import_state(self, state: Mapping[str, Any]) -> None: + super().import_state(state) + c, p = self.oscillators, self._iu[0].size + try: + cfg = dict(state['config']) + n, steps = state['n'], state['steps'] + x = np.asarray(state['x'], dtype=np.float64) + plv = np.asarray(state['plv_re'], dtype=np.float64) + 1j * np.asarray(state['plv_im'], dtype=np.float64) + last = np.asarray(state['last_mean'], dtype=np.float64) + coupling = np.asarray(state['coupling'], dtype=np.float64) + except (KeyError, TypeError, ValueError) as exc: + raise ValueError('kuramoto_binding state is incomplete or malformed') from exc + if cfg != self.config() or n != self._n or type(steps) is not int or steps < 0: + raise ValueError('kuramoto_binding state does not match this extension (config, n or steps)') + if (x.shape != (c, self.dim) or plv.shape != (p,) or last.shape != (c,) or coupling.shape != (c, c) + or not all(np.all(np.isfinite(a)) for a in (x, plv, last, coupling))): + raise ValueError('kuramoto_binding state arrays have the wrong shape or non-finite values') + if np.max(np.abs(np.linalg.norm(x, axis=1) - 1.0)) > 1e-6 or np.any(np.abs(plv) > 1.0 + 1e-9): + raise ValueError('kuramoto_binding state is out of bounds (unit norm, |plv| <= 1)') + if np.any(np.abs(coupling) > _MAX_COUPLING) or np.any(np.diag(coupling) != 0.0): + raise ValueError('kuramoto_binding coupling is out of bounds') + # stored as given (unit norm checked above): renormalising would perturb the last bits and break the + # bit-exact continuation of an exported run + self._x, self._plv, self._last_mean = x.copy(), plv, last + self._coupling, self._steps = coupling, int(steps) + + +# ====================================================================== live observer +class KuramotoObserver: + """Read-only AKOrN observer of live unit activity. + + ``M = min(oscillators, n_units)`` oscillators, each driven by one subsampled unit (seeded, sorted + indices): stimulus ``c_i = stimulus_scale * tanh(rate_i) * u_i`` with a fixed seeded unit vector ``u_i``. + Coupling ``J = J0 + hebbian_scale * H / sqrt(M - 1)``: + + * ``J0`` -- fixed seeded sparse coupling, ``fan_in`` random partners per oscillator with weight + ``coupling / fan_in``; + * ``H`` -- slow Hebbian co-activity estimate: rates are standardised with running EWMA mean/variance + (rate 0.05) and clipped to +/-3 sd (``z``); ``S <- (1 - eta) S + eta z z^T`` starts at the identity + (a shrinkage prior), and ``H_ij = S_ij / sqrt(S_ii S_jj)`` off the diagonal, so ``|H| <= 1`` and early + estimates stay near 0. ``eta = hebbian_rate``. + + ``iterations`` AKOrN updates run per observation. Communities (for Shanahan's indices) are contiguous + blocks of the sampled unit order (NEUROWEAVE regions are contiguous unit blocks) or the given ``groups`` + labels (one per unit). The observer copies what it reads and never writes to its input. Unknown keyword + parameters raise ``ValueError``; FrontierSpecV1 parameters meant for other observers (``sync_pairs``, + ``sae_features``, ``sae_k``, ``fc_window``, ``max_observed_units``, ``observe_every``) are ignored.""" + + module_id = MODULE_ID + schema = OBSERVER_STATE_SCHEMA + + def __init__(self, n_units: int, *, seed: int = 7, history: int = 256, oscillators: int = 64, dim: int = 2, + iterations: int = 2, gamma: float = 0.1, omega_mean: float = 1.0, omega_spread: float = 0.3, + fan_in: int = 4, coupling: float = 0.5, hebbian_rate: float = 0.01, hebbian_scale: float = 2.0, + stimulus_scale: float = 0.5, communities: int = 8, groups: Sequence[int] | None = None, + bins: int = 36, min_cluster_fraction: float = 0.1, **params: Any) -> None: + unknown = sorted(set(params) - _SPEC_OBSERVER_PARAMS) + if unknown: + raise ValueError(f'unknown KuramotoObserver parameters: {unknown}') + self.n_units = _int('n_units', n_units, 1, 1_000_000) + self.seed = _int('seed', seed, 0, 2**31 - 1) + self.history = _int('history', history, 2, 8192) + self.oscillators = _int('oscillators', oscillators, 1, 4096) + self.dim = _even_dim(dim) + self.iterations = _int('iterations', iterations, 1, 64) + self.gamma = _num('gamma', gamma, 0.0, 10.0, open_low=True) + self.omega_mean = _num('omega_mean', omega_mean, -100.0, 100.0) + self.omega_spread = _num('omega_spread', omega_spread, 0.0, 100.0) + self.fan_in = _int('fan_in', fan_in, 0, 4096) + self.coupling = _num('coupling', coupling, -100.0, 100.0) + self.hebbian_rate = _num('hebbian_rate', hebbian_rate, 0.0, 1.0) + self.hebbian_scale = _num('hebbian_scale', hebbian_scale, -100.0, 100.0) + self.stimulus_scale = _num('stimulus_scale', stimulus_scale, -100.0, 100.0) + self.communities = _int('communities', communities, 1, 4096) + self.bins = _int('bins', bins, 2, 3600) + self.min_cluster_fraction = _num('min_cluster_fraction', min_cluster_fraction, 0.0, 1.0, open_low=True) + m = self.m = min(self.oscillators, self.n_units) + rng = np.random.default_rng(self.seed + _OBS_OFFSET) + self._units = (np.arange(self.n_units) if m == self.n_units + else np.sort(rng.choice(self.n_units, size=m, replace=False))) + if groups is None: + self.groups = None + self.n_communities = min(self.communities, m) + self._community = (np.arange(m) * self.n_communities) // m + else: + g = np.asarray(groups) + if g.shape != (self.n_units,) or not np.issubdtype(g.dtype, np.integer) or np.any(g < 0): + raise ValueError('groups must be one non-negative int label per unit') + self.groups = [int(v) for v in g] + _, inverse = np.unique(g[self._units], return_inverse=True) + self._community = inverse.astype(np.int64).ravel() + self.n_communities = int(self._community.max()) + 1 + self._x0 = _unit_rows(rng, m, self.dim) + self._omega = natural_frequency_matrices( + self.omega_mean + self.omega_spread * rng.standard_normal((m, self.dim // 2)), self.dim) + self._stim_dir = _unit_rows(rng, m, self.dim) + k = min(self.fan_in, m - 1) + self._j0 = np.zeros((m, m)) + if k: + for i in range(m): + others = rng.choice(m - 1, size=k, replace=False) + self._j0[i, others + (others >= i)] = self.coupling / k + self.reset() + + @classmethod + def from_spec(cls, n_units: int, spec: Any, **params: Any) -> 'KuramotoObserver': + """Observer sized from a :class:`~synapse.frontier.spec.FrontierSpecV1` (``seed``, ``history``); + ``params`` are the observer's own keyword parameters (``oscillators``, ``dim``, ...).""" + if not isinstance(spec, FrontierSpecV1): + raise ValueError('spec must be a FrontierSpecV1') + return cls(n_units, seed=spec.seed, history=spec.history, **params) + + @property + def observed_steps(self) -> int: + return int(self._steps) + + # ------------------------------------------------------------------ state + def config(self) -> dict[str, Any]: + return {'n_units': self.n_units, 'seed': self.seed, 'history': self.history, 'oscillators': self.oscillators, + 'dim': self.dim, 'iterations': self.iterations, 'gamma': self.gamma, 'omega_mean': self.omega_mean, + 'omega_spread': self.omega_spread, 'fan_in': self.fan_in, 'coupling': self.coupling, + 'hebbian_rate': self.hebbian_rate, 'hebbian_scale': self.hebbian_scale, + 'stimulus_scale': self.stimulus_scale, 'communities': self.communities, 'groups': self.groups, + 'bins': self.bins, 'min_cluster_fraction': self.min_cluster_fraction} + + def reset(self) -> None: + m = self.m + self._x = self._x0.copy() + self._coact = np.eye(m) + self._mu = np.zeros(m) + self._var = np.ones(m) + self._r_hist = np.zeros(self.history) + self._comm_hist = np.zeros((self.history, self.n_communities)) + self._cluster_hist = np.zeros(self.history, dtype=np.int64) + self._pos = 0 + self._filled = 0 + self._steps = 0 + + def hebbian(self) -> np.ndarray: + """Hebbian co-activity estimate ``H`` (running correlation, zero diagonal, ``|H| <= 1``); a copy.""" + d = np.sqrt(np.clip(np.diag(self._coact), 0.0, None)) + denom = np.outer(d, d) + h = np.where(denom > _EPS, self._coact / np.where(denom > _EPS, denom, 1.0), 0.0) + np.fill_diagonal(h, 0.0) + return np.clip(h, -1.0, 1.0) + + def coupling_matrix(self) -> np.ndarray: + """Current effective coupling ``J0 + hebbian_scale * H / sqrt(M - 1)``; a copy.""" + return self._j0 + self.hebbian_scale * self.hebbian() / math.sqrt(max(1, self.m - 1)) + + # ------------------------------------------------------------------ observe + def observe(self, x: np.ndarray) -> None: + v = np.asarray(x, dtype=np.float64) + if v.ndim != 1 or v.size != self.n_units or not np.all(np.isfinite(v)): + raise ValueError(f'observe expects a finite 1-D array of length {self.n_units}') + rate = np.clip(v[self._units], -10.0, 10.0) # fancy indexing copies; the input is never written + if self._steps == 0: + self._mu = rate.copy() + z = np.zeros(self.m) + else: + d = rate - self._mu + self._mu = self._mu + _STATS_RATE * d + self._var = (1.0 - _STATS_RATE) * (self._var + _STATS_RATE * d * d) + z = np.clip(d / np.sqrt(self._var + 1e-6), -_Z_CLIP, _Z_CLIP) + if self.hebbian_rate > 0.0: + self._coact = (1.0 - self.hebbian_rate) * self._coact + self.hebbian_rate * np.outer(z, z) + coupling = self.coupling_matrix() + stim = self.stimulus_scale * np.tanh(rate)[:, None] * self._stim_dir + xs = self._x + for _ in range(self.iterations): + xs = _step(xs, coupling, stim, self._omega, self.gamma) + self._x = xs + p = self._pos + self._r_hist[p] = min(1.0, float(np.linalg.norm(xs.mean(axis=0)))) + self._comm_hist[p] = np.minimum(1.0, group_coherence(xs, self._community, self.n_communities)) + self._cluster_hist[p] = count_phase_clusters(np.arctan2(xs[:, 1], xs[:, 0]), bins=self.bins, + min_fraction=self.min_cluster_fraction) + self._pos = (p + 1) % self.history + self._filled = min(self.history, self._filled + 1) + self._steps += 1 + + def summary(self) -> dict[str, Any]: + """JSON-safe statistics over the bounded history (``None`` before the first observation). + + ``R_std`` is the metastability of the global order parameter (its std over the history); + ``metastability_index`` and ``chimera_index`` follow Shanahan (2010) over the communities; + ``phase_clusters`` counts dense runs of the phase histogram (first rotation plane).""" + h = self._filled + base: dict[str, Any] = {'module': MODULE_ID, 'evidence_tier': EVIDENCE_TIER, 'observed_steps': int(self._steps), + 'history_len': int(h), 'history': self.history, 'oscillators': self.m, + 'dim': self.dim, 'communities': self.n_communities} + hebb = np.abs(self.hebbian()) + base['hebbian_mean_abs'] = float(hebb.sum() / max(1, self.m * (self.m - 1))) + base['hebbian_max_abs'] = float(hebb.max()) if hebb.size else 0.0 + if h == 0: + base.update({k: None for k in ('R_last', 'R_mean', 'R_std', 'metastability_index', 'chimera_index', + 'community_R_mean', 'phase_clusters', 'phase_clusters_mean')}) + return base + last = (self._pos - 1) % self.history + r, comm, cl = self._r_hist[:h], self._comm_hist[:h], self._cluster_hist[:h] # order is irrelevant here + idx = shanahan_indices(comm) + base.update({'R_last': float(self._r_hist[last]), 'R_mean': float(r.mean()), 'R_std': float(r.std()), + 'metastability_index': idx['metastability_index'], 'chimera_index': idx['chimera_index'], + 'community_R_mean': float(comm.mean()), 'phase_clusters': int(self._cluster_hist[last]), + 'phase_clusters_mean': float(cl.mean())}) + return base + + def export_state(self) -> dict[str, Any]: + return {'module': MODULE_ID, 'schema': self.schema, 'config': self.config(), 'x': self._x.tolist(), + 'coactivity': self._coact.tolist(), 'mean': self._mu.tolist(), 'var': self._var.tolist(), + 'r_history': self._r_hist.tolist(), 'community_history': self._comm_hist.tolist(), + 'cluster_history': self._cluster_hist.tolist(), 'pos': int(self._pos), 'filled': int(self._filled), + 'steps': int(self._steps)} + + def import_state(self, state: Mapping[str, Any]) -> None: + if not isinstance(state, Mapping) or state.get('module') != MODULE_ID or state.get('schema') != self.schema: + raise ValueError('state does not belong to a KuramotoObserver') + m, hlen = self.m, self.history + try: + cfg = dict(state['config']) + x = np.asarray(state['x'], dtype=np.float64) + coact = np.asarray(state['coactivity'], dtype=np.float64) + mu = np.asarray(state['mean'], dtype=np.float64) + var = np.asarray(state['var'], dtype=np.float64) + r_hist = np.asarray(state['r_history'], dtype=np.float64) + comm = np.asarray(state['community_history'], dtype=np.float64) + cl_raw = np.asarray(state['cluster_history']) + pos, filled, steps = state['pos'], state['filled'], state['steps'] + except (KeyError, TypeError, ValueError) as exc: + raise ValueError('KuramotoObserver state is incomplete or malformed') from exc + if cfg != self.config(): + raise ValueError('KuramotoObserver state was made with a different configuration') + shapes = ((x, (m, self.dim)), (coact, (m, m)), (mu, (m,)), (var, (m,)), (r_hist, (hlen,)), + (comm, (hlen, self.n_communities))) + if any(a.shape != s or not np.all(np.isfinite(a)) for a, s in shapes): + raise ValueError('KuramotoObserver state arrays have the wrong shape or non-finite values') + if cl_raw.shape != (hlen,) or not np.issubdtype(cl_raw.dtype, np.integer) or np.any(cl_raw < 0): + raise ValueError('cluster_history must hold non-negative ints') + if not all(type(v) is int for v in (pos, filled, steps)) or not (0 <= pos < hlen and 0 <= filled <= hlen + and steps >= filled): + raise ValueError('KuramotoObserver counters are inconsistent') + if filled < hlen and pos != filled: + raise ValueError('KuramotoObserver ring-buffer position is inconsistent') + bound = _Z_CLIP ** 2 + 1.0 + if (np.max(np.abs(np.linalg.norm(x, axis=1) - 1.0)) > 1e-6 or not np.allclose(coact, coact.T, atol=1e-12) + or np.any(np.abs(coact) > bound) or np.any(np.diag(coact) < 0.0) or np.any(var < 0.0) + or np.any(np.abs(mu) > 10.0 + 1e-9) or np.any((r_hist < 0.0) | (r_hist > 1.0)) + or np.any((comm < 0.0) | (comm > 1.0))): + raise ValueError('KuramotoObserver state is out of bounds') + self._x, self._coact, self._mu, self._var = x.copy(), coact.copy(), mu.copy(), var.copy() # bit-exact resume + self._r_hist, self._comm_hist, self._cluster_hist = r_hist.copy(), comm.copy(), cl_raw.astype(np.int64) + self._pos, self._filled, self._steps = pos, filled, steps + + +# ====================================================================== synthetic binding benchmark +def make_binding_task(seed: int, *, groups: int = 4, per_group: int = 8, samples: int = 64, + noise: float = 1.0) -> dict[str, Any]: + """``groups`` latent signals ``s_g(t) ~ N(0, 1)``; feature ``i`` of group ``g`` is + ``a_i s_g(t) + noise * eps_i(t)`` with loading ``a_i ~ U(0.5, 1.5)``. Returns ``features`` (C, T), + ground-truth ``labels`` (C,) and a digest of the features.""" + seed = _int('seed', seed, 0, 2**31 - 1) + g = _int('groups', groups, 2, 64) + f = _int('per_group', per_group, 2, 256) + t = _int('samples', samples, 4, 100_000) + sigma = _num('noise', noise, 0.0, 100.0) + rng = np.random.default_rng(seed + _TASK_OFFSET) + latent = rng.standard_normal((g, t)) + labels = np.repeat(np.arange(g), f) + loading = rng.uniform(0.5, 1.5, labels.size) + feats = loading[:, None] * latent[labels] + sigma * rng.standard_normal((labels.size, t)) + digest = hashlib.sha256(json.dumps(np.round(feats, 12).tolist()).encode('utf-8')).hexdigest() + return {'features': feats, 'labels': labels, 'digest': digest} + + +def correlation_coupling(features: Any, *, scale: float = 2.0, center: bool = True) -> np.ndarray: + """Symmetric couplings from input correlations: Pearson correlation of the feature rows, minus the mean + off-diagonal correlation when ``center`` (a uniform global inhibition, so weakly related features repel), + zero diagonal, scaled so the largest absolute row sum equals ``scale``.""" + x = np.asarray(features, dtype=np.float64) + if x.ndim != 2 or x.shape[0] < 2 or x.shape[1] < 2 or not np.all(np.isfinite(x)): + raise ValueError('features must be a finite (C, T) array with C, T >= 2') + s = _num('scale', scale, -100.0, 100.0) + xc = x - x.mean(axis=1, keepdims=True) + sd = np.sqrt(np.sum(xc * xc, axis=1)) + unit = xc / np.where(sd > _EPS, sd, 1.0)[:, None] + corr = unit @ unit.T # a constant feature has zero correlation with all + np.fill_diagonal(corr, 0.0) + if center: + c = corr.shape[0] + corr = corr - corr.sum() / (c * (c - 1)) + np.fill_diagonal(corr, 0.0) + row = float(np.max(np.abs(corr).sum(axis=1))) + return s * corr / row if row > _EPS else np.zeros_like(corr) + + +def shuffle_coupling(coupling: Any, seed: int) -> np.ndarray: + """Control coupling: the upper-triangle values of a symmetric coupling matrix permuted (seeded) and + mirrored, so the multiset of coupling values is kept and its alignment with the inputs is destroyed.""" + j = np.asarray(coupling, dtype=np.float64) + if j.ndim != 2 or j.shape[0] != j.shape[1] or not np.all(np.isfinite(j)) or not np.allclose(j, j.T): + raise ValueError('coupling must be a finite symmetric square matrix') + iu = np.triu_indices(j.shape[0], 1) + vals = j[iu][np.random.default_rng(_int('seed', seed, 0, 2**62)).permutation(iu[0].size)] + out = np.zeros_like(j) + out[iu] = vals + return out + out.T + + +def _seeds(seeds: Any) -> tuple[int, ...]: + try: + out = tuple(_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +_BENCH_DEFAULTS: dict[str, Any] = {'groups': 4, 'per_group': 8, 'samples': 256, 'noise': 1.0, 'dim': 2, + 'iterations': 120, 'gamma': 0.1, 'coupling_scale': 2.0, 'omega_mean': 1.0, + 'omega_spread': 0.05, 'kmeans_restarts': 8} +_BENCH_QUICK: dict[str, Any] = {'groups': 3, 'per_group': 6, 'samples': 128} + + +def _max_group_cosine(x: np.ndarray, labels: np.ndarray, groups: int) -> float: + """Largest cosine between the mean-field directions of two different ground-truth groups. + + Near 1 means two groups ended up (nearly) in phase, which no clustering of the final states can undo.""" + sums = np.zeros((groups, x.shape[1])) + np.add.at(sums, labels, x) + norm = np.linalg.norm(sums, axis=1) + unit = sums / np.where(norm > _EPS, norm, 1.0)[:, None] + cos = unit @ unit.T + return float(np.clip(cos[np.triu_indices(groups, 1)].max(), -1.0, 1.0)) + + +def _binding_arm(seed: int, x0: np.ndarray, coupling: np.ndarray | None, omega: np.ndarray, labels: np.ndarray, + cfg: Mapping[str, Any], checkpoints: Sequence[int]) -> dict[str, Any]: + x = x0.copy() + g = int(cfg['groups']) + curve = [] + for t in range(int(cfg['iterations']) + 1): + if t in checkpoints: + pred = kmeans_labels(x, g, seed=seed + _KMEANS_OFFSET, restarts=int(cfg['kmeans_restarts'])) + curve.append(adjusted_rand_index(labels, pred)) + if t < cfg['iterations']: + x = _step(x, coupling, None, omega, float(cfg['gamma'])) + return {'seed': int(seed), 'ari': curve[-1], 'ari_by_iteration': curve, + 'within_group_R': float(group_coherence(x, labels, g).mean()), 'global_R': order_parameter(x), + 'max_group_cosine': _max_group_cosine(x, labels, g)} + + +def _arm_summary(per_seed: list[dict[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {'ari_mean': float(np.mean([a['ari'] for a in per_seed])), + 'ari_min': float(np.min([a['ari'] for a in per_seed]))} + for key in ('within_group_R', 'global_R', 'max_group_cosine'): + if key in per_seed[0]: + out[f'{key}_mean'] = float(np.mean([a[key] for a in per_seed])) + if 'ari_by_iteration' in per_seed[0]: + out['ari_by_iteration_mean'] = np.mean([a['ari_by_iteration'] for a in per_seed], axis=0).tolist() + return out + + +def run_binding_benchmark(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Synthetic binding: do oscillators coupled by input correlations synchronise by latent group? + + Arms share each seed's task, initial states and natural frequencies: ``candidate`` (correlation + coupling), ``shuffled_control`` (same coupling values, shuffled), ``zero_control`` (no coupling) and a + non-oscillatory ``reference_correlation_kmeans`` (k-means on correlation rows). Final oscillator states + are clustered with seeded k-means (``k = groups``) and scored by the adjusted Rand index. The verdict + is ``harness.compare`` of candidate vs shuffled-control ARI over seeds.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seeds(seeds) + unknown = sorted(set(overrides) - set(_BENCH_DEFAULTS)) + if unknown: + raise ValueError(f'unknown benchmark parameters: {unknown}') + cfg = {**_BENCH_DEFAULTS, **(_BENCH_QUICK if quick else {}), **overrides} + groups, per_group = _int('groups', cfg['groups'], 2, 64), _int('per_group', cfg['per_group'], 2, 256) + _int('samples', cfg['samples'], 4, 100_000) + _num('noise', cfg['noise'], 0.0, 100.0) + dim = _even_dim(cfg['dim']) + iterations = _int('iterations', cfg['iterations'], 1, 100_000) + _num('gamma', cfg['gamma'], 0.0, 10.0, open_low=True) + _num('coupling_scale', cfg['coupling_scale'], -100.0, 100.0) + _num('omega_mean', cfg['omega_mean'], -100.0, 100.0) + _num('omega_spread', cfg['omega_spread'], 0.0, 100.0) + _int('kmeans_restarts', cfg['kmeans_restarts'], 1, 1000) + c = groups * per_group + checkpoints = sorted({0, iterations // 8, iterations // 4, iterations // 2, iterations}) + arms: dict[str, list[dict[str, Any]]] = {'candidate': [], 'shuffled_control': [], 'zero_control': [], + 'reference_correlation_kmeans': []} + digests = [] + t0 = time.perf_counter() + for s in seed_list: + task = make_binding_task(s, groups=groups, per_group=per_group, samples=cfg['samples'], noise=cfg['noise']) + labels = task['labels'] + digests.append(task['digest']) + coupling = correlation_coupling(task['features'], scale=cfg['coupling_scale']) + rng = np.random.default_rng(s + _INIT_OFFSET) + x0 = _unit_rows(rng, c, dim) + omega = natural_frequency_matrices( + cfg['omega_mean'] + cfg['omega_spread'] * rng.standard_normal((c, dim // 2)), dim) + for name, j in (('candidate', coupling), ('shuffled_control', shuffle_coupling(coupling, s + _SHUFFLE_OFFSET)), + ('zero_control', None)): + arms[name].append(_binding_arm(s, x0, j, omega, labels, cfg, checkpoints)) + corr_rows = correlation_coupling(task['features'], scale=1.0, center=False) + ref = kmeans_labels(corr_rows, groups, seed=s + _KMEANS_OFFSET, restarts=int(cfg['kmeans_restarts'])) + arms['reference_correlation_kmeans'].append({'seed': int(s), 'ari': adjusted_rand_index(labels, ref)}) + wall = time.perf_counter() - t0 + ari = {name: [a['ari'] for a in per_seed] for name, per_seed in arms.items()} + comparisons = { + 'candidate_vs_shuffled_control': harness.compare(ari['candidate'], ari['shuffled_control']), + 'candidate_vs_zero_control': harness.compare(ari['candidate'], ari['zero_control']), + 'candidate_vs_reference_correlation_kmeans': harness.compare(ari['candidate'], + ari['reference_correlation_kmeans']), + } + flops_iter = 2 * c * c + 12 * c * dim + 4 * c * dim * dim + receipt = harness.base_receipt(BENCHMARK_ID, 'binding_benchmark', { + **cfg, 'seeds': list(seed_list), 'quick': quick, 'oscillators': c, 'checkpoints': checkpoints, + 'stimulus': 'none (c_i = 0; binding comes from the coupling alone)', + 'coupling': 'pearson correlation minus mean off-diagonal correlation, zero diagonal, max |row sum| = coupling_scale', + 'clustering': 'seeded k-means++ (k = groups) on final unit vectors; adjusted Rand index vs ground truth', + 'diagnostics': 'within_group_R = mean ground-truth group order parameter; max_group_cosine = largest cosine ' + 'between two group mean-field directions (near 1: two groups in phase)'}) + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['task_digests'] = digests + receipt['arms'] = {name: {'per_seed': per_seed, 'summary': _arm_summary(per_seed)} for name, per_seed in arms.items()} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['candidate_vs_shuffled_control']['verdict'] + receipt['verdict_basis'] = 'candidate_vs_shuffled_coupling_control' + receipt['budget'] = {'oscillators': c, 'dim': dim, 'state_numbers_per_arm': c * dim + c * dim * dim + c * c, + 'trainable_parameters': 0, + 'capacity_note': 'candidate and shuffled control use the same multiset of coupling values'} + receipt['estimated_cost'] = {'flops_per_iteration': flops_iter, + 'oscillator_flops_total': flops_iter * iterations * 3 * len(seed_list)} + receipt['measured_wallclock_s'] = wall + receipt['notes'] = ('Synthetic binding task with a known partition. Oscillator updates follow the AKOrN rule ' + 'with fixed (not learned) correlation couplings and no stimulus; nothing here reproduces ' + 'AKOrN results. The task is easy for a direct clustering of the correlation matrix too (see ' + 'the reference arm), so this tests that the oscillator dynamics implement binding, not that ' + 'they beat conventional clustering. Limitation: with symmetric scalar couplings the ' + 'between-group repulsion only constrains the resultant of the group mean fields, so for four ' + 'or more groups (and for three groups whose latents correlate by chance in a finite sample) ' + 'two groups can settle nearly in phase; max_group_cosine near 1 flags this, and within_group_R ' + 'shows whether each group synchronised internally.') + return harness.seal(receipt) + + +# ====================================================================== NEUROWEAVE extension experiment +_EXT_PARAM_KEYS = ('mode', 'units', 'dim', 'iterations', 'gamma', 'coupling_scale', 'stimulus_scale', 'omega_mean', + 'omega_spread', 'top_pairs', 'plv_rate') +_RUN_KEYS = ('task', 'heldout_seeds', 'steps', 'heldout_steps', 'neurons', 'topology', 'mechanisms', 'metric') + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Baseline vs ``KuramotoExtension`` vs random-trace control on NEUROWEAVE ``context_switch``. + + ``quick=True`` uses the harness quick sizes (24 neurons, 24 train steps, one 12-step held-out stream); + ``seeds`` are always used as given. Extension parameters and harness run parameters can be overridden.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seeds(seeds) + unknown = sorted(set(overrides) - set(_EXT_PARAM_KEYS) - set(_RUN_KEYS)) + if unknown: + raise ValueError(f'unknown run_experiment parameters: {unknown}') + ext_params = {k: overrides[k] for k in _EXT_PARAM_KEYS if k in overrides} + probe = KuramotoExtension(0, **ext_params) # validates the extension parameters up front + run: dict[str, Any] = {'task': 'context_switch', 'heldout_seeds': (100, 101), 'steps': 300, 'heldout_steps': None, + 'neurons': 48, 'topology': 'clustered', 'mechanisms': ()} + if quick: + run.update({k: v for k, v in harness.QUICK_ARGS.items() if k != 'seeds'}) + run.update({k: overrides[k] for k in _RUN_KEYS if k in overrides}) + notes = (f'Candidate: AKOrN-style oscillators ({probe.mode} mode, {probe.oscillators} oscillators, N={probe.dim}) ' + 'coupled by region-aggregated synapse weights copied at bind and driven by group mean outputs; they add ' + f'{probe.feature_dim} readout features and never change the drive. Control: random leaky traces with the ' + 'same feature count. Synthetic temporal task; not a reproduction of AKOrN results.') + t0 = time.perf_counter() + receipt = dict(harness.run_extension_experiment(MODULE_ID, lambda s: KuramotoExtension(int(s), **ext_params), + seeds=seed_list, control='random_trace', notes=notes, **run)) + wall = time.perf_counter() - t0 + receipt.pop('digest', None) + cfg = probe.config() + cfg.pop('seed') + receipt['config'] = {**receipt['config'], 'quick': quick, 'extension': cfg} + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['measured_wallclock_s_total'] = wall + return harness.seal(receipt) + + +EXPERIMENTS = {MODULE_ID: run_experiment, BENCHMARK_ID: run_binding_benchmark} diff --git a/synapse/frontier/morphogenesis.py b/synapse/frontier/morphogenesis.py new file mode 100644 index 0000000000000000000000000000000000000000..265adcf2ddd54cfa154ae7417fe74e67ce0f7b5b --- /dev/null +++ b/synapse/frontier/morphogenesis.py @@ -0,0 +1,575 @@ +"""Developmental growth and regeneration of a connectome (frontier module ``morphogenesis``). + +Inspired by the user's morpheus, prometheus-alpha, GenesisEngine and MOLT projects +(kai9987kai), by Growing Neural Cellular Automata (Mordvintsev, Randazzo, +Niklasson & Levin, Distill, 2020) and by the bioelectric "pattern memory" view of +regeneration (Pezzulo & Levin, Integrative Biology, 2015). It is a synthetic +abstraction: no claim of biological fidelity and no reproduction of either paper. + +Model +----- +* A 2-D grid of sites. A body grows from one seed cell (the *organizer*). Every + step, an empty site next to living tissue becomes alive, and a living cell + dies, according to a *growth logit* evaluated under a seeded stochastic update + mask (as in neural cellular automata, only a random subset of sites updates):: + + logit = theta . [1, n/8, dx^2, dy^2, dx^4] + + where ``n`` is the number of living 8-neighbours and ``(dx, dy)`` is the + position relative to the organizer in units of a quarter of the grid side. + The developmental program is the five numbers ``theta``. A site is born when + ``logit > 0``; a living cell dies when ``logit < -death_margin``. +* Cell types come from positional information around the organizer + (French-flag style): ``sensory`` at one pole, ``action`` at the other, + ``memory`` in the core and ``association`` elsewhere. +* :func:`body_to_topology` turns a body into a valid + :class:`synapse.neuroweave.topology.Topology` (cells -> neurons, types -> + regions, proximity and type-rank rules -> edges, distance -> delays), so the + NEUROWEAVE graph metrics apply. +* :func:`evolve_program` fits ``theta`` to a target shape with a seeded + (1 + lambda) evolution strategy. +* Regeneration: a lesion removes a block of tissue (possibly the organizer). + Regrowth runs the same developmental rule with (a) a stored **pattern memory** + (a coarse setpoint map of the intact body and the organizer position, held by + every surviving cell), (b) no memory (the organizer, if lost, is re-derived + from the centroid of the surviving tissue), or (c) a capacity-matched control + memory with the same size but shuffled content. +""" +from __future__ import annotations + +import math +import time +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass +from typing import Any + +import numpy as np + +from ..neuroweave.spec import REGIONS +from ..neuroweave.topology import KIND_RANK, WEIGHT_MIN, WEIGHT_SPAN, Topology, topology_metrics +from . import harness + +__all__ = ['MODULE_ID', 'CELL_TYPES', 'TARGETS', 'DevelopmentalProgram', 'PatternMemory', 'Body', 'target_mask', + 'grow', 'lesion', 'regrow', 'make_memory', 'shuffled_memory', 'body_to_topology', 'iou', + 'edge_jaccard', 'evolve_program', 'run_experiment', 'EXPERIMENTS', 'DEFAULTS'] + +MODULE_ID = 'morphogenesis' +CELL_TYPES = ('sensory', 'association', 'memory', 'action') +TYPE_REGION = (0, 3, 5, 8) # visual_sensory, association_a, working_memory, premotor (REGIONS indices) +TARGETS = ('two_lobes', 'ellipse', 'cross') +N_PARAMS = 5 +MIN_GRID, MAX_GRID = 8, 48 +MAX_STEPS = 400 +_GROW_OFFSET = 31_337 +_ES_OFFSET = 271_828 +_LESION_OFFSET = 161_803 +_SHUFFLE_OFFSET = 141_421 +EMPTY = -1 + +for _t, _r in zip(CELL_TYPES, TYPE_REGION, strict=True): + assert REGIONS[_r][1] == _t, (REGIONS[_r], _t) + + +def _check_grid(size: Any) -> int: + if type(size) is not int or not MIN_GRID <= size <= MAX_GRID: + raise ValueError(f'grid size must be an int in [{MIN_GRID}, {MAX_GRID}]') + return size + + +def _check_seed(seed: Any) -> int: + if type(seed) is not int or not 0 <= seed <= 2**31 - 1: + raise ValueError('seed must be a non-negative int') + return seed + + +@dataclass(frozen=True) +class DevelopmentalProgram: + """Five-number growth rule plus fixed update settings.""" + + theta: tuple[float, ...] = (2.0, 1.0, -1.2, -1.2, 0.0) + p_update: float = 0.5 + death_margin: float = 2.0 + + def __post_init__(self) -> None: + th = tuple(float(v) for v in self.theta) + if len(th) != N_PARAMS or not all(math.isfinite(v) and abs(v) <= 50.0 for v in th): + raise ValueError(f'theta must hold {N_PARAMS} finite numbers with |value| <= 50') + if not isinstance(self.p_update, (int, float)) or not 0.05 <= float(self.p_update) <= 1.0: + raise ValueError('p_update must lie in [0.05, 1]') + if not isinstance(self.death_margin, (int, float)) or not 0.0 <= float(self.death_margin) <= 50.0: + raise ValueError('death_margin must lie in [0, 50]') + object.__setattr__(self, 'theta', th) + object.__setattr__(self, 'p_update', float(self.p_update)) + object.__setattr__(self, 'death_margin', float(self.death_margin)) + + def to_dict(self) -> dict[str, Any]: + return {'theta': list(self.theta), 'p_update': self.p_update, 'death_margin': self.death_margin} + + +@dataclass(frozen=True) +class PatternMemory: + """Coarse setpoint map (block-averaged body mask) plus the organizer position, held by every cell.""" + + setpoint: np.ndarray # (size // block, size // block) in [0, 1] + block: int + organizer: tuple[int, int] + strength: float = 3.0 + + def field(self, size: int) -> np.ndarray: + """Up-sampled setpoint in [0, 1] at grid resolution.""" + up = np.kron(self.setpoint, np.ones((self.block, self.block))) + out = np.zeros((size, size)) + n = min(size, up.shape[0]) + out[:n, :n] = up[:n, :n] + return out + + @property + def numbers(self) -> int: + return int(self.setpoint.size + 2) + + +@dataclass +class Body: + alive: np.ndarray # (size, size) bool + cell_type: np.ndarray # (size, size) int8, EMPTY where dead + organizer: tuple[int, int] + + @property + def size(self) -> int: + return int(self.alive.shape[0]) + + @property + def cells(self) -> int: + return int(self.alive.sum()) + + def copy(self) -> Body: + return Body(self.alive.copy(), self.cell_type.copy(), tuple(self.organizer)) + + +# ---------------------------------------------------------------------- geometry + +def target_mask(name: str, size: int) -> np.ndarray: + """Boolean target morphology centred on the grid.""" + size = _check_grid(size) + c = (size - 1) / 2.0 + yy, xx = np.mgrid[0:size, 0:size].astype(np.float64) + dx, dy = (xx - c) / size, (yy - c) / size + if name == 'two_lobes': + r = 0.2 + mask = ((dx - 0.17) ** 2 + dy ** 2 <= r * r) | ((dx + 0.17) ** 2 + dy ** 2 <= r * r) + elif name == 'ellipse': + mask = (dx / 0.4) ** 2 + (dy / 0.25) ** 2 <= 1.0 + elif name == 'cross': + mask = ((np.abs(dx) <= 0.12) & (np.abs(dy) <= 0.38)) | ((np.abs(dy) <= 0.12) & (np.abs(dx) <= 0.38)) + else: + raise ValueError(f'target must be one of {TARGETS}') + return mask + + +def _features(size: int, organizer: tuple[int, int]) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + yy, xx = np.mgrid[0:size, 0:size].astype(np.float64) + scale = size / 4.0 + dx = (xx - organizer[1]) / scale + dy = (yy - organizer[0]) / scale + return dx, dy, np.stack([dx * dx, dy * dy, dx ** 4]) + + +def _neighbours(alive: np.ndarray) -> np.ndarray: + a = np.pad(alive.astype(np.int16), 1) + s = alive.shape[0] + total = np.zeros(alive.shape, dtype=np.int16) + for di in (-1, 0, 1): + for dj in (-1, 0, 1): + if di or dj: + total += a[1 + di:1 + di + s, 1 + dj:1 + dj + s] + return total + + +def _assign_types(size: int, organizer: tuple[int, int]) -> np.ndarray: + dx, dy, _ = _features(size, organizer) + types = np.full((size, size), 1, dtype=np.int8) # association + types[dx * dx + dy * dy <= 0.36] = 2 # memory core + types[dx < -1.0] = 0 # sensory pole + types[dx > 1.0] = 3 # action pole + return types + + +def _logit(program: DevelopmentalProgram, alive: np.ndarray, organizer: tuple[int, int], + memory: PatternMemory | None) -> np.ndarray: + size = alive.shape[0] + _, _, quad = _features(size, organizer) + th = program.theta + out = th[0] + th[1] * _neighbours(alive) / 8.0 + th[2] * quad[0] + th[3] * quad[1] + th[4] * quad[2] + if memory is not None: + out = out + memory.strength * (2.0 * memory.field(size) - 1.0) + return out + + +def _develop(program: DevelopmentalProgram, body: Body, steps: int, rng: np.random.Generator, + memory: PatternMemory | None) -> Body: + alive = body.alive.copy() + organizer = body.organizer + for _ in range(steps): + logit = _logit(program, alive, organizer, memory) + mask = rng.random(alive.shape) < program.p_update + has_nb = _neighbours(alive) > 0 + born = (~alive) & has_nb & (logit > 0.0) & mask + die = alive & (logit < -program.death_margin) & mask + die[organizer] = False # the organizer persists while alive + alive = (alive | born) & ~die + if not alive.any(): + break + types = _assign_types(alive.shape[0], organizer) + cell_type = np.where(alive, types, EMPTY).astype(np.int8) + return Body(alive, cell_type, organizer) + + +def grow(program: DevelopmentalProgram, size: int, *, seed: int = 0, steps: int | None = None) -> Body: + """Grow a body from a single organizer cell at the grid centre (deterministic for a given seed).""" + if not isinstance(program, DevelopmentalProgram): + raise ValueError('program must be a DevelopmentalProgram') + size = _check_grid(size) + seed = _check_seed(seed) + steps = 2 * size if steps is None else steps + if type(steps) is not int or not 1 <= steps <= MAX_STEPS: + raise ValueError(f'steps must be an int in [1, {MAX_STEPS}]') + c = size // 2 + alive = np.zeros((size, size), dtype=bool) + alive[c, c] = True + start = Body(alive, np.where(alive, 2, EMPTY).astype(np.int8), (c, c)) + return _develop(program, start, steps, np.random.default_rng(seed + _GROW_OFFSET), None) + + +def lesion(body: Body, box: tuple[int, int, int, int]) -> Body: + """Remove all tissue inside the half-open box ``(row0, row1, col0, col1)``.""" + if not isinstance(body, Body): + raise ValueError('body must be a Body') + r0, r1, c0, c1 = (int(v) for v in box) + s = body.size + if not (0 <= r0 < r1 <= s and 0 <= c0 < c1 <= s): + raise ValueError('lesion box must lie inside the grid and be non-empty') + out = body.copy() + out.alive[r0:r1, c0:c1] = False + out.cell_type[r0:r1, c0:c1] = EMPTY + return out + + +def make_memory(body: Body, *, block: int = 2, strength: float = 3.0) -> PatternMemory: + """Coarse pattern memory of an intact body: block-averaged occupancy plus the organizer position.""" + if not isinstance(body, Body): + raise ValueError('body must be a Body') + if type(block) is not int or not 1 <= block <= body.size // 2: + raise ValueError('block must be an int in [1, size // 2]') + if not isinstance(strength, (int, float)) or not 0.0 <= float(strength) <= 50.0: + raise ValueError('strength must lie in [0, 50]') + n = body.size // block + occ = body.alive[:n * block, :n * block].reshape(n, block, n, block).mean(axis=(1, 3)) + setpoint = occ.astype(np.float64) # fractional occupancy: 0.5 is neutral, so block edges stay rule-driven + setpoint.setflags(write=False) + return PatternMemory(setpoint, block, tuple(body.organizer), float(strength)) + + +def shuffled_memory(memory: PatternMemory, *, seed: int = 0) -> PatternMemory: + """Capacity-matched control: same number of setpoint cells and numbers, shuffled content and organizer.""" + if not isinstance(memory, PatternMemory): + raise ValueError('memory must be a PatternMemory') + rng = np.random.default_rng(_check_seed(seed) + _SHUFFLE_OFFSET) + flat = memory.setpoint.ravel().copy() + rng.shuffle(flat) + n = memory.setpoint.shape[0] + side = n * memory.block + organizer = (int(rng.integers(side)), int(rng.integers(side))) + setpoint = flat.reshape(memory.setpoint.shape) + setpoint.setflags(write=False) + return PatternMemory(setpoint, memory.block, organizer, memory.strength) + + +def regrow(program: DevelopmentalProgram, damaged: Body, *, memory: PatternMemory | None = None, seed: int = 0, + steps: int | None = None) -> Body: + """Regrow a lesioned body with the same developmental rule. + + With a pattern memory the organizer position comes from the memory and the setpoint biases growth and + death. Without one, a lost organizer is re-derived from the centroid of the surviving tissue (nearest + living cell).""" + if not isinstance(program, DevelopmentalProgram): + raise ValueError('program must be a DevelopmentalProgram') + if not isinstance(damaged, Body): + raise ValueError('damaged must be a Body') + if memory is not None and not isinstance(memory, PatternMemory): + raise ValueError('memory must be a PatternMemory or None') + seed = _check_seed(seed) + size = damaged.size + steps = 2 * size if steps is None else steps + if type(steps) is not int or not 1 <= steps <= MAX_STEPS: + raise ValueError(f'steps must be an int in [1, {MAX_STEPS}]') + if not damaged.alive.any(): + return damaged.copy() # nothing left to regrow from + body = damaged.copy() + oy, ox = body.organizer + if memory is not None: + my, mx = (min(size - 1, max(0, int(v))) for v in memory.organizer) + body.organizer = (my, mx) # re-established by growth if it was lost + elif not body.alive[oy, ox]: + ys, xs = np.nonzero(body.alive) + cy, cx = ys.mean(), xs.mean() + k = int(np.argmin((ys - cy) ** 2 + (xs - cx) ** 2)) + body.organizer = (int(ys[k]), int(xs[k])) + return _develop(program, body, steps, np.random.default_rng(seed + _GROW_OFFSET + 1), memory) + + +# ---------------------------------------------------------------------- connectome + +def body_to_topology(body: Body, *, radius: float = 1.5, name: str = 'morphogenesis', seed: int = 0) -> Topology: + """Cells -> neurons (row-major order), types -> regions, proximity + type-rank rules -> edges. + + * same type within ``radius``: reciprocal (local recurrent) edges; + * different types within ``radius``: feedforward edge from lower to higher processing rank, plus a feedback + edge when the cells are direct (4-)neighbours; + * delay 1 / 2 / 3 by distance; weight magnitude decays with distance; sign fixed by site position + (~20 % inhibitory, spread across the grid) so the same site keeps its sign after regrowth.""" + if not isinstance(body, Body): + raise ValueError('body must be a Body') + if not isinstance(radius, (int, float)) or not 1.0 <= float(radius) <= 4.0: + raise ValueError('radius must lie in [1, 4]') + ys, xs = np.nonzero(body.alive) + n = int(ys.size) + types = body.cell_type[ys, xs].astype(np.int64) + rank = np.array([KIND_RANK[CELL_TYPES[t]] for t in types], dtype=np.int64) + region = np.array([TYPE_REGION[t] for t in types], dtype=np.int64) + sign = np.where((ys * 7 + xs * 13) % 5 == 0, -1, 1).astype(np.int8) + if n >= 2: + dy = ys[:, None] - ys[None, :] + dx = xs[:, None] - xs[None, :] + dist = np.sqrt(dy * dy + dx * dx) + near = (dist <= radius + 1e-9) & ~np.eye(n, dtype=bool) + same = types[:, None] == types[None, :] + ff = rank[:, None] < rank[None, :] + fb = (rank[:, None] > rank[None, :]) & (dist <= 1.0 + 1e-9) + adj = near & (same | ff | fb) + src, dst = np.nonzero(adj) + d = dist[src, dst] + else: + src = dst = np.zeros(0, dtype=np.int64) + d = np.zeros(0) + delay = (1 + (d > 1.5 + 1e-9) + (d > 2.5 + 1e-9)).astype(np.int64) + mag = WEIGHT_MIN + WEIGHT_SPAN * np.clip(1.0 - (d - 1.0) / max(float(radius), 1.0), 0.0, 1.0) + weight = sign[src].astype(np.float64) * mag + topo = Topology(n=n, src=src.astype(np.int64), dst=dst.astype(np.int64), weight=weight, delay=delay, + sign=sign, region=region, name=str(name), seed=int(seed), regions=REGIONS) + topo.validate() + return topo + + +def _edge_keys(body: Body, topo: Topology) -> set[tuple[int, int]]: + ys, xs = np.nonzero(body.alive) + pos = ys * body.size + xs + return set(zip(pos[topo.src].tolist(), pos[topo.dst].tolist(), strict=True)) + + +def iou(a: np.ndarray, b: np.ndarray) -> float: + a, b = np.asarray(a, dtype=bool), np.asarray(b, dtype=bool) + if a.shape != b.shape: + raise ValueError('masks must share a shape') + union = int((a | b).sum()) + return float((a & b).sum() / union) if union else 1.0 + + +def edge_jaccard(body_a: Body, body_b: Body, *, radius: float = 1.5) -> float: + """Jaccard similarity of position-keyed directed edge sets of the two grown connectomes.""" + ea = _edge_keys(body_a, body_to_topology(body_a, radius=radius)) + eb = _edge_keys(body_b, body_to_topology(body_b, radius=radius)) + union = len(ea | eb) + return float(len(ea & eb) / union) if union else 1.0 + + +def _type_agreement(ref: Body, other: Body) -> float: + both = ref.alive & other.alive + return float(np.mean(ref.cell_type[both] == other.cell_type[both])) if both.any() else 0.0 + + +def _metric_similarity(a: Body, b: Body) -> float: + keys = ('density', 'clustering_mean', 'modularity', 'global_efficiency') + if a.cells < 2 or b.cells < 2: + return 0.0 + ma, mb = topology_metrics(body_to_topology(a)), topology_metrics(body_to_topology(b)) + diffs = [abs(ma[k] - mb[k]) / max(abs(ma[k]), abs(mb[k]), 1e-9) for k in keys] + return float(1.0 - np.mean(diffs)) + + +# ---------------------------------------------------------------------- evolution + +def evolve_program(target: np.ndarray, *, seed: int = 0, generations: int = 30, offspring: int = 8, + sigma: float = 0.4, growth_seed: int = 0, steps: int | None = None) -> dict[str, Any]: + """Seeded (1 + lambda)-ES on ``theta`` maximising IoU between the grown body and ``target``. + + Ties keep the parent (no drift on plateaus). Returns the best program and the fitness trace.""" + tgt = np.asarray(target, dtype=bool) + if tgt.ndim != 2 or tgt.shape[0] != tgt.shape[1]: + raise ValueError('target must be a square boolean mask') + size = _check_grid(int(tgt.shape[0])) + seed = _check_seed(seed) + for nm, v, lo, hi in (('generations', generations, 0, 500), ('offspring', offspring, 1, 64)): + if type(v) is not int or not lo <= v <= hi: + raise ValueError(f'{nm} must be an int in [{lo}, {hi}]') + if not isinstance(sigma, (int, float)) or not 0.0 < float(sigma) <= 5.0: + raise ValueError('sigma must lie in (0, 5]') + rng = np.random.default_rng(seed + _ES_OFFSET) + parent = DevelopmentalProgram() + + def fitness(p: DevelopmentalProgram) -> float: + return iou(grow(p, size, seed=growth_seed, steps=steps).alive, tgt) + + best = fitness(parent) + initial = best + trace = [best] + evaluations = 1 + for _ in range(generations): + base = np.asarray(parent.theta) + children = [DevelopmentalProgram(tuple(np.clip(base + float(sigma) * rng.standard_normal(N_PARAMS), + -50.0, 50.0))) + for _ in range(offspring)] + scores = [fitness(c) for c in children] + evaluations += offspring + k = int(np.argmax(scores)) + if scores[k] > best: + parent, best = children[k], scores[k] + trace.append(best) + return {'program': parent, 'fitness': best, 'initial_fitness': initial, 'trace': trace, + 'evaluations': evaluations} + + +# ---------------------------------------------------------------------- experiment + +DEFAULTS: dict[str, Any] = {'size': 20, 'target': 'two_lobes', 'generations': 30, 'offspring': 8, 'sigma': 0.4, + 'lesions_per_seed': 4, 'lesion_fraction': 0.4, 'memory_block': 2, + 'memory_strength': 3.0, 'radius': 1.5} +_QUICK: dict[str, Any] = {'size': 14, 'generations': 10, 'offspring': 6, 'lesions_per_seed': 3} + + +def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + unknown = set(overrides) - set(DEFAULTS) + if unknown: + raise ValueError(f'unknown overrides: {sorted(unknown)}') + cfg = {**DEFAULTS, **(_QUICK if quick else {}), **overrides} + _check_grid(cfg['size']) + if cfg['target'] not in TARGETS: + raise ValueError(f'target must be one of {TARGETS}') + if type(cfg['lesions_per_seed']) is not int or not 1 <= cfg['lesions_per_seed'] <= 64: + raise ValueError('lesions_per_seed must be an int in [1, 64]') + if not isinstance(cfg['lesion_fraction'], (int, float)) or not 0.1 <= cfg['lesion_fraction'] <= 0.7: + raise ValueError('lesion_fraction must lie in [0.1, 0.7]') + if type(cfg['memory_block']) is not int or not 1 <= cfg['memory_block'] <= cfg['size'] // 2: + raise ValueError('memory_block must be an int in [1, size // 2]') + return cfg + + +def _lesion_box(body: Body, rng: np.random.Generator, fraction: float) -> tuple[int, int, int, int]: + """A square box centred on a random living cell, sized to cover ``fraction`` of the body's bounding box.""" + ys, xs = np.nonzero(body.alive) + h = int(ys.max() - ys.min() + 1) + w = int(xs.max() - xs.min() + 1) + side = max(2, int(round(math.sqrt(fraction * h * w)))) + k = int(rng.integers(ys.size)) + cy, cx = int(ys[k]), int(xs[k]) + s = body.size + r0 = min(max(0, cy - side // 2), s - side) + c0 = min(max(0, cx - side // 2), s - side) + return r0, r0 + side, c0, c0 + side + + +def _run_seed(seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]: + size = int(cfg['size']) + tgt = target_mask(cfg['target'], size) + evo = evolve_program(tgt, seed=seed, generations=cfg['generations'], offspring=cfg['offspring'], + sigma=cfg['sigma'], growth_seed=seed) + program: DevelopmentalProgram = evo['program'] + body = grow(program, size, seed=seed) + memory = make_memory(body, block=cfg['memory_block'], strength=cfg['memory_strength']) + rng = np.random.default_rng(seed + _LESION_OFFSET) + arms: dict[str, dict[str, list[float]]] = {a: {'iou': [], 'edge_jaccard': [], 'type_agreement': [], + 'metric_similarity': []} + for a in ('pattern_memory', 'no_memory', 'shuffled_memory')} + lesions = [] + for j in range(int(cfg['lesions_per_seed'])): + box = _lesion_box(body, rng, float(cfg['lesion_fraction'])) + damaged = lesion(body, box) + oy, ox = body.organizer + lesions.append({'box': list(box), 'removed_cells': int(body.cells - damaged.cells), + 'organizer_lost': bool(not damaged.alive[oy, ox])}) + mems = {'pattern_memory': memory, 'no_memory': None, + 'shuffled_memory': shuffled_memory(memory, seed=seed * 1_000 + j)} + for a, mem in mems.items(): + healed = regrow(program, damaged, memory=mem, seed=seed * 1_000 + j) + rec = arms[a] + rec['iou'].append(iou(healed.alive, body.alive)) + rec['edge_jaccard'].append(edge_jaccard(body, healed, radius=cfg['radius'])) + rec['type_agreement'].append(_type_agreement(body, healed)) + rec['metric_similarity'].append(_metric_similarity(body, healed)) + topo = body_to_topology(body, radius=cfg['radius']) + metrics = topology_metrics(topo) + return { + 'seed': int(seed), + 'development': {'target_iou': float(evo['fitness']), 'initial_program_iou': float(evo['initial_fitness']), + 'es_trace': [float(v) for v in evo['trace']], 'evaluations': int(evo['evaluations']), + 'theta': list(program.theta), 'cells': body.cells, + 'type_counts': {t: int(np.sum(body.cell_type == i)) for i, t in enumerate(CELL_TYPES)}}, + 'connectome': {k: metrics[k] for k in ('n', 'edges', 'density', 'clustering_mean', 'modularity', + 'global_efficiency', 'reachable_pair_fraction')}, + 'lesions': lesions, + 'arms': {a: {k: float(np.mean(v)) for k, v in rec.items()} for a, rec in arms.items()}, + } + + +def run_experiment(*, quick: bool = False, seeds: Iterable[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Regeneration with a stored pattern memory vs without one vs a shuffled (capacity-matched) memory. + + Per seed: evolve a developmental program towards the target shape, grow a body, apply several random lesions + and regrow under each arm. Metric: IoU between the regrown and the pre-lesion body (higher is better).""" + seeds = tuple(seeds) + 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): + raise ValueError('seeds must be unique non-negative ints') + cfg = _config(quick, overrides) + t0 = time.perf_counter() + runs = [_run_seed(s, cfg) for s in seeds] + arm_names = ('pattern_memory', 'no_memory', 'shuffled_memory') + vals = {a: [r['arms'][a]['iou'] for r in runs] for a in arm_names} + vs_none = harness.compare(vals['pattern_memory'], vals['no_memory']) + vs_shuffled = harness.compare(vals['pattern_memory'], vals['shuffled_memory']) + head = harness.headline_verdict(vs_none, vs_shuffled) + edge = {a: [r['arms'][a]['edge_jaccard'] for r in runs] for a in arm_names} + receipt = harness.base_receipt(MODULE_ID, 'regeneration_comparison', { + **cfg, 'quick': quick, 'seeds': list(seeds), 'metric': 'recovery_iou_vs_pre_lesion_body', + 'program_parameters': N_PARAMS, 'cell_types': list(CELL_TYPES), + 'type_regions': [REGIONS[r][0] for r in TYPE_REGION]}) + receipt['per_seed'] = runs + receipt['arms'] = {a: {'summary': {k: float(np.mean([r['arms'][a][k] for r in runs])) + for k in ('iou', 'edge_jaccard', 'type_agreement', 'metric_similarity')}} + for a in arm_names} + receipt['development_summary'] = { + 'target_iou': float(np.mean([r['development']['target_iou'] for r in runs])), + 'initial_program_iou': float(np.mean([r['development']['initial_program_iou'] for r in runs]))} + receipt['comparisons'] = {'pattern_memory_vs_no_memory': vs_none, + 'pattern_memory_vs_shuffled_memory': vs_shuffled, + 'edge_jaccard_pattern_memory_vs_no_memory': harness.compare(edge['pattern_memory'], + edge['no_memory'])} + receipt['verdict'] = head['verdict'] + receipt['verdict_basis'] = head['basis'] + ' (paired 95% t interval over seeds on recovery IoU)' + mem_numbers = (cfg['size'] // cfg['memory_block']) ** 2 + 2 + receipt['parameter_budget'] = {'program_parameters': N_PARAMS, 'pattern_memory_numbers': int(mem_numbers), + 'shuffled_memory_numbers': int(mem_numbers), 'no_memory_numbers': 0} + receipt['estimated_cost'] = { + 'estimated_site_updates_per_growth': int(2 * cfg['size'] * cfg['size'] ** 2), + 'estimated_growths_per_seed': int(1 + cfg['generations'] * cfg['offspring'] + 1 + 3 * cfg['lesions_per_seed'])} + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0} + receipt['notes'] = ( + 'Synthetic developmental abstraction inspired by growing neural cellular automata (Mordvintsev et al., Distill ' + '2020) and bioelectric pattern memory (Pezzulo & Levin, Integr. Biol. 2015). The rule is a hand-designed ' + 'five-parameter growth logit, not a trained neural CA. The pattern memory is a coarse copy of the intact body, ' + 'so it helps by construction when lesions remove the organizer; the shuffled-memory arm checks that the gain ' + 'comes from the content of the memory rather than its presence or size.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/muon.py b/synapse/frontier/muon.py new file mode 100644 index 0000000000000000000000000000000000000000..06da8554fcfc83f596a8d571be3eeab0d93902e1 --- /dev/null +++ b/synapse/frontier/muon.py @@ -0,0 +1,815 @@ +"""Orthogonalised-momentum optimiser (Muon-style) with an internal AdamW, plus a neural-graft benchmark. + +Inspired by (citations verified 2026-11-17 and re-checked 2026-11-20, see +``docs/frontier/modules/muon_optimizer.md``): + +* K. Jordan, Y. Jin, V. Boza, J. You, F. Cesista, L. Newhouse, J. Bernstein, "Muon: An optimizer for hidden + layers in neural networks", blog post, 8 December 2024, https://kellerjordan.github.io/posts/muon/ +* J. Liu, J. Su, X. Yao, Z. Jiang, G. Lai, Y. Du, ... Z. Yang (Moonshot AI), "Muon is Scalable for LLM + Training", technical report, arXiv:2502.16982, 24 February 2025, https://arxiv.org/abs/2502.16982 + +For a matrix parameter ``W`` of shape ``A x B`` with gradient ``G``, momentum ``mu``, learning rate ``lr`` and +decoupled weight decay ``wd`` one step is:: + + M_t = mu * M_{t-1} + (1 - mu) * G_t momentum (EMA form of Jordan's reference code) + U_t = (1 - mu) * G_t + mu * M_t Nesterov input (or U_t = M_t without Nesterov) + O_t = NS5(U_t) quintic Newton-Schulz, 5 steps, Frobenius-normalised input + W_t = W_{t-1} - lr * (0.2 * sqrt(max(A, B)) * O_t + wd * W_{t-1}) (Liu et al., Eq. 4) + +``NS5`` iterates ``X <- a X + b (X X^T) X + c (X X^T)^2 X`` with ``(a, b, c) = (3.4445, -4.7750, 2.0315)`` on the +wide orientation of the matrix (transposed when rows > cols). It does not return the exact polar factor +``U V^T``: it maps each singular value ``s`` of the Frobenius-normalised input through ``p^5`` with +``p(x) = a x + b x^3 + c x^5``. Iterating that scalar map (measured 2026-11-17 on a dense grid) gives outputs in +[0.6818, 1.1344] for every start ``s >= 0.01`` and in (0, 1.2024] for every ``s`` in (0, 1] (see the tests). The +EMA momentum differs from Liu et al.'s ``M_t = mu M_{t-1} + G_t`` only by the factor ``1 - mu``, which the +Frobenius normalisation removes. Everything that is not a 2-D weight matrix (biases, norm gains, embeddings, +other shapes) is updated by an internal AdamW whose arithmetic follows ``torch.optim.AdamW``. The +0.2 * sqrt(max(A, B)) scale lets Muon and the AdamW part share one learning rate. + +The module is a synthetic computational abstraction: an optimiser and a small, honest benchmark on the +Sonapse neural-graft architecture. It does not reproduce any published training result. +""" +from __future__ import annotations + +import copy +import math +import time +from contextlib import contextmanager +from typing import Any, Callable, Iterable, Iterator, Mapping, Sequence + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from . import harness +from .spec import GRAFT_OPTIMIZERS + +__all__ = ['MODULE_ID', 'NS_COEFFICIENTS', 'zeropower_via_newtonschulz5', 'MuonWithAuxAdam', 'muon_param_groups', + 'graft_output_layers', 'graft_input_layers', 'make_graft_optimizer', 'run_experiment', 'EXPERIMENTS', + 'ARMS', 'DEFAULT_CONFIG', 'QUICK_CONFIG'] + +MODULE_ID = 'muon_optimizer' +NS_COEFFICIENTS = (3.4445, -4.7750, 2.0315) +_NS_EPS = 1e-7 +_HYPER_KEYS = ('lr', 'momentum', 'nesterov', 'ns_steps', 'weight_decay', 'betas', 'eps', 'update_scale') +_GROUP_KEYS = frozenset(('params', 'use_muon') + _HYPER_KEYS) +_MUON_STATE_KEYS = frozenset(('momentum_buffer',)) +_ADAM_STATE_KEYS = frozenset(('step', 'exp_avg', 'exp_avg_sq')) + + +# ====================================================================== Newton-Schulz orthogonalisation +def _newton_schulz(matrix: torch.Tensor, steps: int, eps: float) -> torch.Tensor: + """Unvalidated core of :func:`zeropower_via_newtonschulz5` (callers check shape, dtype and finiteness).""" + a, b, c = NS_COEFFICIENTS + x = matrix if matrix.dtype in (torch.float32, torch.float64) else matrix.float() + transpose = x.size(0) > x.size(1) + if transpose: + x = x.mT + norm = torch.linalg.matrix_norm(x) + if not bool(torch.isfinite(norm)): # the squares overflowed (huge finite entries): rescale first + x = x / x.abs().amax() + norm = torch.linalg.matrix_norm(x) + x = x / (norm + eps) + for _ in range(steps): + gram = x @ x.mT + poly = torch.addmm(gram, gram, gram, beta=b, alpha=c) # b * A + c * A @ A + x = torch.addmm(x, poly, x, beta=a) # a * X + B @ X + if transpose: + x = x.mT + return x.to(matrix.dtype) + + +def zeropower_via_newtonschulz5(matrix: torch.Tensor, steps: int = 5, eps: float = _NS_EPS) -> torch.Tensor: + """Approximate the orthogonal polar factor ``U V^T`` of a 2-D matrix ``U S V^T`` (quintic Newton-Schulz). + + The input is Frobenius-normalised (so every singular value starts in ``(0, 1]``), the iteration runs on the + wide orientation (transposed when rows > cols) and the result keeps the input's singular vectors with + singular values pushed into a band around 1. The input is not modified. Computation is float32 (or float64 + for float64 inputs); the reference code uses bfloat16 on GPUs, which this CPU build does not. Entries so + large that the Frobenius norm overflows are rescaled by the largest magnitude first (the reference code + would return zeros there). + """ + if not isinstance(matrix, torch.Tensor) or matrix.ndim != 2 or matrix.numel() == 0: + raise ValueError('matrix must be a non-empty 2-D tensor') + if not matrix.is_floating_point(): + raise ValueError('matrix must have a floating-point dtype') + if type(steps) is not int or not 0 <= steps <= 64: + raise ValueError('steps must be an int in [0, 64]') + if not (isinstance(eps, float) and math.isfinite(eps) and eps > 0.0): + raise ValueError('eps must be a positive finite float') + if not bool(torch.isfinite(matrix).all()): + raise ValueError('matrix must be finite') + return _newton_schulz(matrix, steps, eps) + + +# ====================================================================== validation helpers +def _real(name: str, value: Any, *, low: float, high: float, low_open: bool = False, high_open: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a real number') + v = float(value) + if (not math.isfinite(v) or v < low or v > high or (low_open and v == low) or (high_open and v == high)): + lb, hb = '(' if low_open else '[', ')' if high_open else ']' + raise ValueError(f'{name} must be finite and in {lb}{low}, {high}{hb}') + return v + + +def _check_hyper(h: Mapping[str, Any]) -> dict[str, Any]: + out = {'lr': _real('lr', h['lr'], low=0.0, high=10.0), + 'momentum': _real('momentum', h['momentum'], low=0.0, high=1.0, high_open=True), + 'weight_decay': _real('weight_decay', h['weight_decay'], low=0.0, high=10.0), + 'eps': _real('eps', h['eps'], low=0.0, high=1.0, low_open=True), + 'update_scale': _real('update_scale', h['update_scale'], low=0.0, high=100.0, low_open=True)} + if type(h['nesterov']) is not bool: + raise ValueError('nesterov must be a bool') + if type(h['ns_steps']) is not int or not 0 <= h['ns_steps'] <= 64: + raise ValueError('ns_steps must be an int in [0, 64]') + betas = h['betas'] + if not isinstance(betas, (tuple, list)) or len(betas) != 2: + raise ValueError('betas must be a pair') + out['betas'] = tuple(_real(f'betas[{i}]', bv, low=0.0, high=1.0, high_open=True) for i, bv in enumerate(betas)) + out['nesterov'] = h['nesterov'] + out['ns_steps'] = h['ns_steps'] + return out + + +def _as_param_list(params: Any) -> list[torch.Tensor]: + if isinstance(params, torch.Tensor): + return [params] + if isinstance(params, (set, frozenset)): + raise ValueError('parameters must be given in a deterministic order (not a set)') + try: + out = list(params) + except TypeError as exc: + raise ValueError('parameters must be a tensor or an iterable of tensors') from exc + if not all(isinstance(p, torch.Tensor) for p in out): + raise ValueError('parameter groups must contain only tensors') + return out + + +# ====================================================================== parameter routing +def muon_param_groups(module: nn.Module, *, aux_modules: Iterable[nn.Module] = (), **hyper: Any) -> list[dict[str, Any]]: + """Split ``module.parameters()`` (in order) into a Muon group and an AdamW group. + + Muon gets every 2-D parameter that is not an ``nn.Embedding``/``nn.EmbeddingBag`` weight and not owned by one + of ``aux_modules``; everything else (biases, norm gains, embeddings, non-2-D tensors, ``aux_modules``) goes to + the AdamW group. Extra keyword arguments are copied into both groups. Empty groups are omitted.""" + if not isinstance(module, nn.Module): + raise ValueError('module must be a torch.nn.Module') + unknown = set(hyper) - set(_HYPER_KEYS) + if unknown: + raise ValueError(f'unknown optimiser options: {sorted(unknown)}') + aux_list = list(aux_modules) + if not all(isinstance(m, nn.Module) for m in aux_list): + raise ValueError('aux_modules must be torch.nn.Module instances') + embed = {id(p) for m in module.modules() if isinstance(m, (nn.Embedding, nn.EmbeddingBag)) + for p in m.parameters(recurse=False)} + aux = {id(p) for m in aux_list for p in m.parameters()} + muon, adam = [], [] + for p in module.parameters(): + (muon if p.ndim == 2 and id(p) not in embed and id(p) not in aux else adam).append(p) + groups = [] + if muon: + groups.append({'params': muon, 'use_muon': True, **hyper}) + if adam: + groups.append({'params': adam, 'use_muon': False, **hyper}) + return groups + + +def _normalise_groups(params: Any) -> list[dict[str, Any]]: + if isinstance(params, nn.Module): + groups = muon_param_groups(params) + if not groups: + raise ValueError('optimizer got an empty parameter list') + return groups + if isinstance(params, torch.Tensor): + raise ValueError('params must be an iterable of tensors or dicts, or an nn.Module (got a single tensor)') + if isinstance(params, (set, frozenset)): + raise ValueError('parameters must be given in a deterministic order (not a set)') + try: + items = list(params) + except TypeError as exc: + raise ValueError('params must be an nn.Module, an iterable of tensors or an iterable of dicts') from exc + if not items: + raise ValueError('optimizer got an empty parameter list') + if all(isinstance(i, Mapping) for i in items): + groups: list[dict[str, Any]] = [] + for item in items: + g = dict(item) + if 'params' not in g: + raise ValueError('every parameter group needs a "params" entry') + unknown = set(g) - _GROUP_KEYS + if unknown: + raise ValueError(f'unknown parameter-group keys: {sorted(unknown)}') + ps = _as_param_list(g.pop('params')) + if 'use_muon' in g: + groups.append({'params': ps, **g}) # checked by add_param_group + else: + muon = [p for p in ps if p.ndim == 2] + adam = [p for p in ps if p.ndim != 2] + if muon: + groups.append({'params': muon, 'use_muon': True, **g}) + if adam or not muon: + groups.append({'params': adam, 'use_muon': False, **g}) + return groups + if all(isinstance(i, torch.Tensor) for i in items): + muon = [p for p in items if p.ndim == 2] + adam = [p for p in items if p.ndim != 2] + return ([{'params': muon, 'use_muon': True}] if muon else []) + \ + ([{'params': adam, 'use_muon': False}] if adam else []) + raise ValueError('params must be an nn.Module, an iterable of tensors or an iterable of dicts') + + +def _all_finite(tensors: list[torch.Tensor]) -> bool: + """True when every entry of every tensor is finite. + + Fast path: one fused 2-norm call (a finite 2-norm proves every entry finite). Only when a 2-norm is not + finite, which also happens when the squares of large finite values overflow, the exact per-tensor check + decides. (The fused max-abs norm would avoid the overflow but measured 10-100x slower on this CPU build.)""" + if not tensors: + return True + try: + norms = torch._foreach_norm(tensors) + if bool(torch.isfinite(torch.stack([n.to(torch.float64) for n in norms])).all()): + return True + except (AttributeError, RuntimeError, NotImplementedError, TypeError): # pragma: no cover - old torch + pass + return all(bool(torch.isfinite(t).all()) for t in tensors) + + +# ====================================================================== optimiser +class MuonWithAuxAdam(torch.optim.Optimizer): + """Muon for 2-D weight matrices plus an internal AdamW for everything else, in one optimiser. + + ``params`` may be an ``nn.Module`` (routed by :func:`muon_param_groups`), an iterable of tensors (2-D tensors + go to Muon, the rest to AdamW) or an iterable of group dicts. A group dict may set ``use_muon`` explicitly + (``True`` needs ``ndim >= 2``; tensors with more than two dimensions are flattened to ``(shape[0], -1)``) + or leave it out to be split by ``ndim``. Groups may override any hyper-parameter. Groups added later with + :meth:`add_param_group` must set ``use_muon`` or hold only 2-D (Muon) or only non-2-D (AdamW) tensors. + + Defaults follow Liu et al. (2025): one learning rate for both parts, momentum 0.95 with Nesterov, five + Newton-Schulz steps, update scale ``0.2 * sqrt(max(A, B))`` and decoupled weight decay. The AdamW part uses + ``torch.optim.AdamW``'s defaults (betas 0.9/0.999, eps 1e-8). Each step is computed in full before it is + applied: a non-finite gradient, or an update that would make a parameter or state value non-finite + (numeric overflow), raises ``ValueError`` and leaves every parameter and all state unchanged. + """ + + def __init__(self, params: Any, lr: float = 1e-3, *, momentum: float = 0.95, nesterov: bool = True, + ns_steps: int = 5, weight_decay: float = 0.0, betas: Sequence[float] = (0.9, 0.999), + eps: float = 1e-8, update_scale: float = 0.2) -> None: + defaults = _check_hyper({'lr': lr, 'momentum': momentum, 'nesterov': nesterov, 'ns_steps': ns_steps, + 'weight_decay': weight_decay, 'betas': betas, 'eps': eps, + 'update_scale': update_scale}) + groups = _normalise_groups(params) + super().__init__(groups, defaults) # every group passes through add_param_group (validated) + + def add_param_group(self, param_group: Mapping[str, Any]) -> None: + """Validate a group (keys, routing, hyper-parameters) before registering it.""" + if not isinstance(param_group, Mapping) or 'params' not in param_group: + raise ValueError('a parameter group must be a mapping with a "params" entry') + g = dict(param_group) + unknown = set(g) - _GROUP_KEYS + if unknown: + raise ValueError(f'unknown parameter-group keys: {sorted(unknown)}') + ps = _as_param_list(g['params']) + if 'use_muon' not in g: + kinds = {p.ndim == 2 for p in ps} + if len(kinds) > 1: + raise ValueError('a group without use_muon must hold only 2-D or only non-2-D tensors') + g['use_muon'] = kinds == {True} + if type(g['use_muon']) is not bool: + raise ValueError('use_muon must be a bool') + if g['use_muon'] and any(p.ndim < 2 for p in ps): + raise ValueError('use_muon=True needs parameters with at least 2 dimensions') + _check_hyper({**self.defaults, **{k: v for k, v in g.items() if k in _HYPER_KEYS}}) + g['params'] = ps + super().add_param_group(g) + self.param_groups[-1].update(_check_hyper(self.param_groups[-1])) + + # ------------------------------------------------------------------ introspection + def muon_parameters(self) -> list[torch.Tensor]: + return [p for g in self.param_groups if g['use_muon'] for p in g['params']] + + def adam_parameters(self) -> list[torch.Tensor]: + return [p for g in self.param_groups if not g['use_muon'] for p in g['params']] + + def state_numbers(self) -> int: + """Stored optimiser numbers (momentum / moment buffers; step counters excluded), for budget reports.""" + return _moment_numbers(self) + + # ------------------------------------------------------------------ step + @torch.no_grad() + def step(self, closure: Callable[[], Any] | None = None) -> Any: + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + grads = [] + for g in self.param_groups: + for p in g['params']: + if p.grad is not None: + if p.grad.is_sparse: + raise ValueError('MuonWithAuxAdam does not support sparse gradients') + grads.append(p.grad) + if not _all_finite(grads): + raise ValueError('non-finite gradient: optimiser step refused (parameters and state unchanged)') + plan: list[tuple[torch.Tensor, torch.Tensor, dict[str, Any]]] = [] + for group in self.param_groups: + (self._plan_muon if group['use_muon'] else self._plan_adam)(group, plan) + produced = [t for _, new_p, new_state in plan + for t in (new_p, *(v for v in new_state.values() if isinstance(v, torch.Tensor)))] + if not _all_finite(produced): + raise ValueError('non-finite update (numeric overflow): optimiser step refused ' + '(parameters and state unchanged)') + for p, new_p, new_state in plan: # commit + self.state[p].update(new_state) + p.copy_(new_p) + return loss + + def _plan_muon(self, group: Mapping[str, Any], plan: list) -> None: + lr, mu, wd = group['lr'], group['momentum'], group['weight_decay'] + for p in group['params']: + grad = p.grad + if grad is None: + continue + buf = self.state.get(p, {}).get('momentum_buffer') + if buf is None: + buf = torch.zeros_like(p, memory_format=torch.preserve_format) + new_buf = torch.lerp(buf, grad, 1.0 - mu) + update = torch.lerp(grad, new_buf, mu) if group['nesterov'] else new_buf + mat = update if update.ndim == 2 else update.reshape(update.shape[0], -1) + ortho = _newton_schulz(mat, group['ns_steps'], _NS_EPS) + scale = group['update_scale'] * math.sqrt(max(mat.shape[0], mat.shape[1])) + new_p = p.mul(1.0 - lr * wd) if wd != 0.0 else p.clone() + new_p.add_(ortho.reshape(p.shape), alpha=-lr * scale) + plan.append((p, new_p, {'momentum_buffer': new_buf})) + + def _plan_adam(self, group: Mapping[str, Any], plan: list) -> None: + # Same arithmetic, in the same order, as torch.optim.AdamW's single-tensor path (out of place). + lr, wd, eps = group['lr'], group['weight_decay'], group['eps'] + beta1, beta2 = group['betas'] + for p in group['params']: + grad = p.grad + if grad is None: + continue + state = self.state.get(p, {}) + step = int(state.get('step', 0)) + 1 + exp_avg = state.get('exp_avg') + exp_avg_sq = state.get('exp_avg_sq') + if exp_avg is None: + exp_avg = torch.zeros_like(p, memory_format=torch.preserve_format) + if exp_avg_sq is None: + exp_avg_sq = torch.zeros_like(p, memory_format=torch.preserve_format) + new_p = p.mul(1.0 - lr * wd) if wd != 0.0 else p.clone() + new_m = torch.lerp(exp_avg, grad, 1.0 - beta1) + new_v = exp_avg_sq.mul(beta2).addcmul_(grad, grad, value=1.0 - beta2) + bias_correction1 = 1.0 - beta1 ** step + bias_correction2 = 1.0 - beta2 ** step + step_size = lr / bias_correction1 + denom = (new_v.sqrt() / bias_correction2 ** 0.5).add_(eps) + new_p.addcdiv_(new_m, denom, value=-step_size) + plan.append((p, new_p, {'step': step, 'exp_avg': new_m, 'exp_avg_sq': new_v})) + + # ------------------------------------------------------------------ persistence + def load_state_dict(self, state_dict: Mapping[str, Any]) -> None: + """Validate fully (group layout, routing, hyper-parameters, state shapes and finiteness), then load a + private deep copy, so the result never aliases tensors of the given dict.""" + if not isinstance(state_dict, Mapping) or 'state' not in state_dict or 'param_groups' not in state_dict: + raise ValueError('optimizer state must be a mapping with "state" and "param_groups"') + saved_groups = state_dict['param_groups'] + if not isinstance(saved_groups, (list, tuple)) or len(saved_groups) != len(self.param_groups): + raise ValueError('optimizer state has a different number of parameter groups') + index_to_param: dict[int, tuple[torch.Tensor, bool]] = {} + for mine, saved in zip(self.param_groups, saved_groups): + if not isinstance(saved, Mapping) or set(saved) - _GROUP_KEYS or 'params' not in saved: + raise ValueError('optimizer state has malformed parameter groups') + if saved.get('use_muon') is not mine['use_muon']: + raise ValueError('optimizer state routes parameters differently (use_muon mismatch)') + if not isinstance(saved['params'], (list, tuple)) or len(saved['params']) != len(mine['params']): + raise ValueError('optimizer state group sizes do not match') + _check_hyper({**self.defaults, **{k: v for k, v in saved.items() if k in _HYPER_KEYS}}) + for idx, p in zip(saved['params'], mine['params']): + if type(idx) is not int or idx in index_to_param: + raise ValueError('optimizer state has invalid parameter indices') + index_to_param[idx] = (p, mine['use_muon']) + state = state_dict['state'] + if not isinstance(state, Mapping): + raise ValueError('optimizer state must contain a mapping "state"') + for idx, entry in state.items(): + if idx not in index_to_param or not isinstance(entry, Mapping): + raise ValueError('optimizer state refers to unknown parameters') + p, use_muon = index_to_param[idx] + allowed = _MUON_STATE_KEYS if use_muon else _ADAM_STATE_KEYS + if set(entry) - allowed or (not use_muon and entry and set(entry) != _ADAM_STATE_KEYS): + raise ValueError('optimizer state entries do not match the parameter routing') + for key, value in entry.items(): + if key == 'step': + step = int(value.item()) if isinstance(value, torch.Tensor) and value.numel() == 1 else value + if type(step) is not int or not 0 <= step < 2**62: + raise ValueError('optimizer step count must be a non-negative int') + continue + if (not isinstance(value, torch.Tensor) or value.shape != p.shape or not value.is_floating_point() + or not bool(torch.isfinite(value).all())): + raise ValueError(f'optimizer state {key!r} must be a finite tensor shaped like its parameter') + if key == 'exp_avg_sq' and bool((value < 0).any()): + raise ValueError('exp_avg_sq must be non-negative') + private = copy.deepcopy({'state': dict(state), 'param_groups': [dict(g) for g in saved_groups]}) + for entry in private['state'].values(): + if 'step' in entry and isinstance(entry['step'], torch.Tensor): + entry['step'] = int(entry['step'].item()) + super().load_state_dict(private) + for g in self.param_groups: + g.update(_check_hyper(g)) + + +def _moment_numbers(optimizer: torch.optim.Optimizer) -> int: + """Numbers held in an optimiser's per-parameter state tensors, step counters excluded.""" + return int(sum(v.numel() for s in optimizer.state.values() for k, v in s.items() + if k != 'step' and isinstance(v, torch.Tensor))) + + +# ====================================================================== graft helper +def _graft_paths(network: nn.Module) -> list[list[nn.Linear]] | None: + paths = [] + for name in ('actor_encoder', 'value', 'dynamics'): + seq = getattr(network, name, None) + linears = [m for m in seq if isinstance(m, nn.Linear)] if isinstance(seq, nn.Sequential) else [] + if not linears: + return None + paths.append(linears) + return paths + + +def graft_output_layers(network: nn.Module) -> tuple[nn.Module, ...]: + """The output (head) layers of a neural-graft ``_ResidualNetwork``: the actor head and the last linear layer + of the value and dynamics paths. Returns ``()`` for modules without that structure.""" + paths = _graft_paths(network) + actor = getattr(network, 'actor_head', None) + if paths is None or not isinstance(actor, nn.Linear): + return () + return (actor, paths[1][-1], paths[2][-1]) + + +def graft_input_layers(network: nn.Module) -> tuple[nn.Module, ...]: + """The input layers of a neural-graft ``_ResidualNetwork``: the first linear layer of the actor encoder and of + the value and dynamics paths (the layers that read the graft's raw inputs). ``()`` without that structure.""" + paths = _graft_paths(network) + if paths is None or not isinstance(getattr(network, 'actor_head', None), nn.Linear): + return () + return tuple(p[0] for p in paths) + + +def make_graft_optimizer(params_or_module: Any, kind: str = 'adam', lr: float = 3e-4, *, + heads_on_adam: bool = True, inputs_on_adam: bool | None = None, + **muon_options: Any) -> torch.optim.Optimizer: + """Optimiser for the live neural-graft fit, selected by ``FrontierSpecV1.graft_optimizer``. + + ``'adam'`` returns exactly ``torch.optim.Adam(params, lr=lr)`` (the graft's current optimiser; no other + option is accepted). ``'muon'`` returns :class:`MuonWithAuxAdam`. For a module with the graft's structure the + three output layers stay on AdamW (``heads_on_adam``; both Jordan et al. and Liu et al. keep output heads on + AdamW) and so do the three input layers (``inputs_on_adam``; Jordan et al.: input and output layers belong on + AdamW even though they are 2-D), which leaves Muon the hidden-to-hidden matrices. ``inputs_on_adam=None`` (the + default) means ``True`` for a graft-structured module and ``False`` otherwise; ``inputs_on_adam=False`` puts + the input layers on Muon too (the benchmark's routing ablation). Other modules are routed by + :func:`muon_param_groups`, parameter iterables by ``ndim``; ``inputs_on_adam=True`` needs a graft module.""" + if kind not in GRAFT_OPTIMIZERS: + raise ValueError(f'kind must be one of {GRAFT_OPTIMIZERS}') + _real('lr', lr, low=0.0, high=10.0, low_open=True) + if type(heads_on_adam) is not bool or (inputs_on_adam is not None and type(inputs_on_adam) is not bool): + raise ValueError('heads_on_adam must be a bool and inputs_on_adam a bool or None') + if kind == 'adam': + if muon_options or not heads_on_adam or inputs_on_adam is True: + raise ValueError("options other than lr apply only to kind='muon'") + params = params_or_module.parameters() if isinstance(params_or_module, nn.Module) else params_or_module + return torch.optim.Adam(params, lr=lr) + unknown = set(muon_options) - (set(_HYPER_KEYS) - {'lr'}) + if unknown: + raise ValueError(f'unknown muon options: {sorted(unknown)}') + if isinstance(params_or_module, nn.Module): + inputs = graft_input_layers(params_or_module) + inputs_aux = bool(inputs) if inputs_on_adam is None else inputs_on_adam + if inputs_aux and not inputs: + raise ValueError('inputs_on_adam=True needs a module with the neural-graft structure') + aux = (graft_output_layers(params_or_module) if heads_on_adam else ()) + (inputs if inputs_aux else ()) + return MuonWithAuxAdam(muon_param_groups(params_or_module, aux_modules=aux), lr=lr, **muon_options) + if inputs_on_adam: + raise ValueError('inputs_on_adam=True needs a module with the neural-graft structure') + return MuonWithAuxAdam(params_or_module, lr=lr, **muon_options) + + +# ====================================================================== benchmark +ARMS = ('adam', 'muon', 'muon_with_inputs') +DEFAULT_CONFIG: dict[str, Any] = { + 'hidden': 64, 'steps': 300, 'batch_size': 128, 'n_train': 2048, 'n_val': 512, 'n_test': 1024, + 'lr_grid': (3e-4, 1e-3, 3e-3, 1e-2, 3e-2), 'clip_grad_norm': 1.0, 'teacher_gain': 2.0, 'momentum': 0.95, + 'nesterov': True, 'ns_steps': 5, 'weight_decay': 0.0, 'heads_on_adam': True, 'routing_ablation': True, +} +QUICK_CONFIG: dict[str, Any] = {'hidden': 32, 'steps': 40, 'batch_size': 128, 'n_train': 512, 'n_val': 256, + 'n_test': 256, 'lr_grid': (1e-3, 1e-2)} +_DATA_OFFSET, _TEACHER_OFFSET, _STUDENT_OFFSET, _BATCH_OFFSET = 52_001, 52_103, 52_207, 52_309 +_N_STATE, _N_OBS, _N_ACT = 256, 155, 5 +_HEADS = ('policy', 'value', 'dynamics') + + +@contextmanager +def _one_torch_thread() -> Iterator[None]: + """Run with one intra-op thread (stable float results, no oversubscription); restore the caller's count.""" + before = torch.get_num_threads() + try: + if before != 1: + torch.set_num_threads(1) + yield + finally: + if torch.get_num_threads() != before: + torch.set_num_threads(before) + + +def _seeds(seeds: Any) -> tuple[int, ...]: + out = tuple(seeds) + if (not out or any(type(s) is not int or not 0 <= s <= 2**31 - 1 for s in out) or len(set(out)) != len(out)): + raise ValueError('seeds must be a non-empty sequence of unique ints in [0, 2**31 - 1]') + return out + + +def _int(cfg: Mapping[str, Any], name: str, low: int, high: int) -> int: + v = cfg[name] + if type(v) is not int or not low <= v <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return v + + +def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + unknown = set(overrides) - set(DEFAULT_CONFIG) + if unknown: + raise ValueError(f'unknown muon_optimizer options: {sorted(unknown)}') + cfg = {**DEFAULT_CONFIG, **(QUICK_CONFIG if quick else {}), **dict(overrides)} + _int(cfg, 'hidden', 32, 1024) # NeuralResidualGraft's own hidden_dim range + _int(cfg, 'steps', 1, 100_000) + _int(cfg, 'batch_size', 1, 4096) + _int(cfg, 'n_train', 8, 1_000_000) + _int(cfg, 'n_val', 8, 1_000_000) + _int(cfg, 'n_test', 8, 1_000_000) + grid = cfg['lr_grid'] + if not isinstance(grid, (list, tuple)) or not grid or len(grid) > 32: + raise ValueError('lr_grid must be a non-empty sequence of at most 32 values') + cfg['lr_grid'] = tuple(_real('lr_grid entry', v, low=0.0, high=1.0, low_open=True) for v in grid) + if len(set(cfg['lr_grid'])) != len(cfg['lr_grid']): + raise ValueError('lr_grid entries must be unique') + cfg['clip_grad_norm'] = _real('clip_grad_norm', cfg['clip_grad_norm'], low=0.0, high=1e6) + cfg['teacher_gain'] = _real('teacher_gain', cfg['teacher_gain'], low=0.0, high=10.0, low_open=True) + cfg['weight_decay'] = _real('weight_decay', cfg['weight_decay'], low=0.0, high=10.0) + _check_hyper({'lr': 1e-3, 'momentum': cfg['momentum'], 'nesterov': cfg['nesterov'], 'ns_steps': cfg['ns_steps'], + 'weight_decay': cfg['weight_decay'], 'betas': (0.9, 0.999), 'eps': 1e-8, 'update_scale': 0.2}) + cfg['momentum'] = float(cfg['momentum']) + for name in ('heads_on_adam', 'routing_ablation'): + if type(cfg[name]) is not bool: + raise ValueError(f'{name} must be a bool') + return cfg + + +def _graft_network(hidden: int, generator: torch.Generator, *, teacher_gain: float | None = None) -> nn.Module: + """A ``_ResidualNetwork`` initialised from ``generator`` only (the global torch RNG is left untouched). + + Students get PyTorch's default ``nn.Linear`` distribution (uniform +-1/sqrt(fan_in)) and the architecture's + zero actor head; teachers get every linear layer, the actor head included, at ``teacher_gain`` times that.""" + from ..neural_graft import _ResidualNetwork + with torch.random.fork_rng(devices=[]): # construction draws from the global RNG: restore it after + net = _ResidualNetwork(hidden) + gain = 1.0 if teacher_gain is None else float(teacher_gain) + with torch.no_grad(): + for m in net.modules(): + if isinstance(m, nn.Linear): + bound = gain / math.sqrt(m.in_features) + m.weight.copy_((torch.rand(m.weight.shape, generator=generator) * 2.0 - 1.0) * bound) + m.bias.copy_((torch.rand(m.bias.shape, generator=generator) * 2.0 - 1.0) * bound) + elif isinstance(m, nn.LayerNorm): + m.weight.fill_(1.0) + m.bias.zero_() + if teacher_gain is None: + net.actor_head.weight.zero_() + net.actor_head.bias.zero_() + return net + + +def _sample_inputs(rng: np.random.Generator, n: int) -> dict[str, torch.Tensor]: + obs = rng.standard_normal((n, _N_OBS)) + features = rng.standard_normal((n, 64)) + baseline = rng.uniform(-1.0, 1.0, (n, _N_ACT)) + prior = rng.uniform(-1.0, 1.0, (n, 32)) + action = rng.uniform(-1.0, 1.0, (n, _N_ACT)) + state = np.clip(np.concatenate([obs, features, baseline, prior], axis=1), -5.0, 5.0) + return {'state': torch.from_numpy(state.astype(np.float32)), + 'obs': torch.from_numpy(state[:, :_N_OBS].astype(np.float32)), + 'dyn': torch.from_numpy(np.concatenate([state[:, :_N_OBS], action], axis=1).astype(np.float32))} + + +def _outputs(net: nn.Module, x: Mapping[str, torch.Tensor]) -> dict[str, torch.Tensor]: + return {'policy': net.policy(x['state']), 'value': net.value(x['obs']), 'dynamics': net.dynamics(x['dyn'])} + + +def _task(seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]: + """Inputs shaped like the graft's (state 256, observation 155, observation+action 160) and standardised + targets from a fixed, never-trained random teacher of the same architecture.""" + rng = np.random.default_rng(seed + _DATA_OFFSET) + splits = {name: _sample_inputs(rng, cfg[f'n_{name}']) for name in ('train', 'val', 'test')} + teacher = _graft_network(cfg['hidden'], torch.Generator().manual_seed(seed + _TEACHER_OFFSET), + teacher_gain=cfg['teacher_gain']) + with torch.no_grad(): + raw = {name: _outputs(teacher, x) for name, x in splits.items()} + mean = {h: raw['train'][h].mean(0, keepdim=True) for h in _HEADS} + std = {h: raw['train'][h].std(0, keepdim=True).clamp_min(1e-8) for h in _HEADS} + targets = {name: {h: (raw[name][h] - mean[h]) / std[h] for h in _HEADS} for name in splits} + batches = np.random.default_rng(seed + _BATCH_OFFSET).integers(0, cfg['n_train'], + size=(cfg['steps'], cfg['batch_size'])) + return {'inputs': splits, 'targets': targets, 'batches': torch.from_numpy(batches), + 'teacher_raw_std': {h: float(raw['train'][h].std()) for h in _HEADS}} + + +def _head_mse(net: nn.Module, x: Mapping[str, torch.Tensor], y: Mapping[str, torch.Tensor]) -> dict[str, float]: + with torch.no_grad(): + out = _outputs(net, x) + return {h: float(F.mse_loss(out[h], y[h])) for h in _HEADS} + + +def _optimizer(arm: str, net: nn.Module, lr: float, cfg: Mapping[str, Any]) -> torch.optim.Optimizer: + if arm == 'adam': + if cfg['weight_decay'] > 0.0: # the Muon arms decay their weights: give the baseline the same decay + return torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=cfg['weight_decay']) + return make_graft_optimizer(net, 'adam', lr) + hyper = dict(momentum=cfg['momentum'], nesterov=cfg['nesterov'], ns_steps=cfg['ns_steps'], + weight_decay=cfg['weight_decay']) + if arm == 'muon': # the live opt-in's routing (input layers on AdamW) + return make_graft_optimizer(net, 'muon', lr, heads_on_adam=cfg['heads_on_adam'], **hyper) + return make_graft_optimizer(net, 'muon', lr, heads_on_adam=cfg['heads_on_adam'], inputs_on_adam=False, **hyper) + + +def _train(arm: str, lr: float, seed: int, task: Mapping[str, Any], cfg: Mapping[str, Any]) -> dict[str, Any]: + net = _graft_network(cfg['hidden'], torch.Generator().manual_seed(seed + _STUDENT_OFFSET)) + opt = _optimizer(arm, net, lr, cfg) + x, y = task['inputs']['train'], task['targets']['train'] + params = list(net.parameters()) + clip = cfg['clip_grad_norm'] if cfg['clip_grad_norm'] > 0 else float('inf') + diverged, last = False, None + for t in range(cfg['steps']): + idx = task['batches'][t] + out = _outputs(net, {k: v[idx] for k, v in x.items()}) + loss = sum(F.mse_loss(out[h], y[h][idx]) for h in _HEADS) + if not bool(torch.isfinite(loss)): + diverged = True + break + opt.zero_grad(set_to_none=True) + loss.backward() + norm = nn.utils.clip_grad_norm_(params, clip) + if not bool(torch.isfinite(norm)): + diverged = True + break + try: + opt.step() + except ValueError: # MuonWithAuxAdam refuses non-finite updates + diverged = True + break + last = float(loss.detach()) + val = _head_mse(net, task['inputs']['val'], task['targets']['val']) + test = _head_mse(net, task['inputs']['test'], task['targets']['test']) + bad = diverged or not all(math.isfinite(v) for v in (*val.values(), *test.values())) + return {'seed': seed, 'lr': lr, 'diverged': bool(bad), 'final_train_loss': last, + 'val_mse': float('inf') if bad else float(np.mean(list(val.values()))), + 'test_mse': float('inf') if bad else float(np.mean(list(test.values()))), + 'test_mse_by_head': test, 'optimizer_state_numbers': _moment_numbers(opt)} + + +def _routing(arms: Sequence[str], cfg: Mapping[str, Any]) -> dict[str, Any]: + net = _graft_network(cfg['hidden'], torch.Generator().manual_seed(0)) + names = {id(p): n for n, p in net.named_parameters()} + out: dict[str, Any] = {} + for arm in arms: + if arm == 'adam': + continue + opt = _optimizer(arm, net, 1e-3, cfg) + muon, adam = opt.muon_parameters(), opt.adam_parameters() + out[arm] = {'muon': [names[id(p)] for p in muon], 'adamw': [names[id(p)] for p in adam], + 'muon_numbers': int(sum(p.numel() for p in muon)), + 'adamw_numbers': int(sum(p.numel() for p in adam)), + 'muon_shapes': [list(p.shape) for p in muon]} + out['parameters'] = int(sum(p.numel() for p in net.parameters())) + out['linear_macs_per_sample'] = int(sum(m.in_features * m.out_features for m in net.modules() + if isinstance(m, nn.Linear))) + return out + + +def _ns_flops(shapes: Sequence[Sequence[int]], ns_steps: int) -> int: + """Dense-matmul FLOPs of the Newton-Schulz iterations per optimiser step (m <= n after orientation).""" + return int(ns_steps * sum(4 * min(s) ** 2 * max(s) + 2 * min(s) ** 3 for s in shapes)) + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Muon (candidate) vs Adam (baseline) on the neural-graft architecture, held-out MSE (lower is better). + + For every seed a fixed random teacher of the same architecture defines standardised regression targets for + the policy, value and dynamics heads. Every optimiser trains the same student initialisation on the same + minibatch sequence for the same number of steps (graft-style loss sum and gradient clipping). Each arm's + learning rate is chosen from ``lr_grid`` by mean validation MSE over seeds; the verdict is the paired 95 % t + interval of Muon minus Adam test MSE at the selected learning rates. The ``muon`` arm uses the live opt-in's + routing (input and output layers on AdamW, as Jordan et al. recommend; Muon on the hidden-to-hidden + matrices). With ``routing_ablation`` a third arm, ``muon_with_inputs`` (the input layers on Muon too), is + reported against Adam as a secondary comparison that does not set the verdict.""" + seeds = _seeds(seeds) + if type(quick) is not bool: + raise ValueError('quick must be a bool') + cfg = _config(quick, overrides) + arms_run = ARMS if cfg['routing_ablation'] else ARMS[:2] + t0 = time.perf_counter() + walls: dict[str, float] = {arm: 0.0 for arm in arms_run} + runs: dict[str, dict[float, list[dict[str, Any]]]] = {arm: {} for arm in arms_run} + with _one_torch_thread(): + routing = _routing(arms_run, cfg) + teacher_std = {} + for seed in seeds: + task = _task(seed, cfg) + teacher_std[str(seed)] = task['teacher_raw_std'] + for arm in arms_run: + for lr in cfg['lr_grid']: + t1 = time.perf_counter() + runs[arm].setdefault(lr, []).append(_train(arm, lr, seed, task, cfg)) + walls[arm] += time.perf_counter() - t1 + arms: dict[str, Any] = {} + for arm in arms_run: + grid = [] + for lr in cfg['lr_grid']: + vals = [r['val_mse'] for r in runs[arm][lr]] + grid.append({'lr': lr, 'mean_val_mse': float(np.mean(vals)) if all(map(math.isfinite, vals)) else None, + 'diverged_seeds': [r['seed'] for r in runs[arm][lr] if r['diverged']]}) + finite = [g for g in grid if g['mean_val_mse'] is not None] + best = min(finite, key=lambda g: g['mean_val_mse'])['lr'] if finite else cfg['lr_grid'][0] + per_seed = runs[arm][best] + edge = len(cfg['lr_grid']) > 1 and best in (min(cfg['lr_grid']), max(cfg['lr_grid'])) + arms[arm] = {'selected_lr': best, 'selected_at_grid_edge': bool(edge), 'lr_grid': grid, 'per_seed': per_seed, + 'diverged_seeds_at_selected_lr': [r['seed'] for r in per_seed if r['diverged']], + 'summary': {'test_mse': harness._mean(r['test_mse'] for r in per_seed), + 'val_mse': harness._mean(r['val_mse'] for r in per_seed), + 'test_mse_by_head': {h: harness._mean(r['test_mse_by_head'][h] for r in per_seed) + for h in _HEADS}}, + 'all_runs': {str(lr): [{k: r[k] for k in ('seed', 'val_mse', 'test_mse', 'diverged')} + for r in runs[arm][lr]] for lr in cfg['lr_grid']}} + + def test_mse(arm: str) -> list[float]: + return [r['test_mse'] for r in arms[arm]['per_seed']] + comparisons: dict[str, Any] = {'muon_vs_adam': {'role': 'verdict', **harness.compare( + test_mse('muon'), test_mse('adam'), higher_is_better=False)}} + if 'muon_with_inputs' in arms: + comparisons['muon_with_inputs_vs_adam'] = {'role': 'routing_ablation (does not set the verdict)', + **harness.compare(test_mse('muon_with_inputs'), test_mse('adam'), + higher_is_better=False)} + vs = comparisons['muon_vs_adam'] + verdict, basis = vs['verdict'], 'muon_vs_adam_paired_t95_on_heldout_test_mse_at_validation_selected_lr' + bad = {arm: arms[arm]['diverged_seeds_at_selected_lr'] for arm in ('adam', 'muon')} + if bad['muon'] or bad['adam']: # paired stats drop non-finite pairs: never let that hide a failure + verdict = 'worse' if bad['muon'] and not bad['adam'] else 'no_detectable_difference' + basis = 'training_diverged_at_selected_lr' + receipt = harness.base_receipt(MODULE_ID, 'optimizer_comparison', { + 'quick': quick, 'seeds': list(seeds), **{k: (list(v) if isinstance(v, tuple) else v) for k, v in cfg.items()}, + 'arms': list(arms_run), + 'metric': 'heldout_test_mse_mean_over_heads (standardised targets; lower is better)', + 'selection': 'per arm: lr in lr_grid with the lowest mean validation MSE over seeds', + 'baseline': ('adam: torch.optim.Adam(params, lr) == make_graft_optimizer(kind="adam")' + if cfg['weight_decay'] == 0.0 else + 'adam: torch.optim.AdamW(params, lr, weight_decay) (same decoupled weight decay as the Muon arms)'), + 'candidate': ('muon: MuonWithAuxAdam via make_graft_optimizer(kind="muon", heads_on_adam=heads_on_adam) ' + '(input layers on AdamW, the live opt-in routing)'), + 'ablation': ('muon_with_inputs: make_graft_optimizer(kind="muon", heads_on_adam=heads_on_adam, ' + 'inputs_on_adam=False) (input layers on Muon too)' if cfg['routing_ablation'] else None), + 'architecture': 'synapse.neural_graft._ResidualNetwork (policy, value and dynamics heads)'}) + receipt['parameter_routing'] = routing + receipt['arms'] = arms + receipt['comparisons'] = comparisons + receipt['verdict'] = verdict + receipt['verdict_basis'] = basis + receipt['budget'] = { + 'parameters': routing['parameters'], 'training_steps_per_run': cfg['steps'], + 'runs_per_arm': len(seeds) * len(cfg['lr_grid']), + 'per_arm': {arm: {'muon_parameters': routing[arm]['muon_numbers'] if arm in routing else 0, + 'adamw_or_adam_parameters': (routing[arm]['adamw_numbers'] if arm in routing + else routing['parameters']), + 'optimizer_state_numbers': arms[arm]['per_seed'][0]['optimizer_state_numbers']} + for arm in arms_run}} + receipt['estimated_cost'] = { + 'forward_backward_flops_per_step': int(6 * routing['linear_macs_per_sample'] * cfg['batch_size']), + 'newton_schulz_flops_per_step': {arm: _ns_flops(routing[arm]['muon_shapes'], cfg['ns_steps']) + for arm in arms_run if arm in routing}, + 'note': 'analytic estimates (dense matmul FLOPs), not measurements'} + receipt['task'] = {'teacher_raw_output_std': teacher_std, + 'targets': 'per-output standardised with training-split mean and std'} + receipt['notes'] = ('Synthetic teacher-student regression on the graft architecture; inspired by Muon (Jordan ' + 'et al., 2024) with the update scale and weight decay of Liu et al. (2025); not a ' + 'reproduction. Equal steps, shared initialisation and minibatches; the candidate keeps the ' + f'output heads on AdamW (heads_on_adam={cfg["heads_on_adam"]}) and the input layers on ' + 'AdamW (Jordan et al.), Muon on the hidden-to-hidden matrices; the muon_with_inputs ablation ' + '(when present) puts the input layers on Muon too and is reported, not used for the ' + 'verdict. Quick mode is a pipeline check with very few steps; its verdict is not evidence. Three seeds give a wide t interval. Results may not transfer ' + 'to the live graft, whose targets come from executed transitions.') + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0, + **{f'{arm}_runs': walls[arm] for arm in arms_run}} + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/nir_export.py b/synapse/frontier/nir_export.py new file mode 100644 index 0000000000000000000000000000000000000000..4881352ec160e8aac0c8e8cca5c0b110224feb76 --- /dev/null +++ b/synapse/frontier/nir_export.py @@ -0,0 +1,1119 @@ +"""Neuromorphic interchange export (frontier module ``nir_export``). + +Exports a NEUROWEAVE brain as a graph in the style of the Neuromorphic Intermediate Representation (NIR) of +J. E. Pedersen et al., "Neuromorphic intermediate representation: A unified instruction set for interoperable +brain-inspired computing", Nature Communications 15, 8122 (16 September 2024), doi:10.1038/s41467-024-52259-9, +using the node types and parameter names of the NIR Python package (github.com/neuromorphs/NIR; checked on +2026-11-20 against the main branch, PyPI release 1.0.8). Full, verified references: +``docs/frontier/modules/nir_export.md``. + +Graph format (JSON-safe; lists, not arrays):: + + {'nodes': {name: {'type': , 'params': {field: value}}}, + 'edges': [[src, dst], ...], # incoming edges of a node are summed element-wise (NIR) + 'metadata': {...}} # optional; ignored by graph equality + +The export is a *lossy approximation* of the abstract NEUROWEAVE cell, and every NEUROWEAVE feature that cannot +be represented is listed (``lossy_features``). Exact parts: the linear input projection, the recurrent synapse +table split into one ``Delay`` + ``Linear`` pair per delay class (a frozen snapshot, with quantisation, region +routing, myelin gain and structural source weights folded in when those mechanisms are on), and, for isolated +cells, the synaptic current and (up to the documented adaptation current) the membrane of the ``CubaLIF`` cell, +whose parameters come from the zero-order-hold mapping ``tau = -dt / ln(decay per step)`` of the cell constants +in ``synapse/neuroweave/cells.py``. Approximated or dropped: graded ``tanh`` transmission (NIR edges carry spikes), +the direct recurrent feed-through, multiplicative reset, refractoriness, adaptive threshold, calcium feedback, +learning rules and the nonlinear mechanisms listed by :func:`unrepresentable_features`. + +``write_nir`` writes a real NIR (HDF5) file with ``nir.write`` and reads it back with ``nir.read`` when the +optional ``nir`` package imports; otherwise it writes JSON tagged ``'format': 'nir-json-fallback'``. Either way it +reports whether the read-back graph equals the written one. ``simulate_graph`` is a small NumPy discrete-time +simulator for the node types used here (zero-order-hold updates; Delay nodes break recurrent loops). Nothing here +touches global random or thread state, and the exported brain is never mutated (the exporter works on a copy). +""" +from __future__ import annotations + +from collections import Counter +import json +import math +from pathlib import Path +import tempfile +import time +from typing import Any, Callable, Mapping, Sequence + +import numpy as np + +__all__ = ['MODULE_ID', 'SOURCE', 'EXPERIMENTS', 'FALLBACK_FORMAT', 'NIR_FORMAT', 'NODE_PARAMS', 'NIR_NODE_TYPES', + 'NEURON_TYPES', 'SPIKING_TYPES', 'CELL_CONSTANTS', 'cell_parameters', 'nir_status', 'brain_to_nir', + 'unrepresentable_features', 'validate_graph', 'node_io_shapes', 'canonical_graph', 'graphs_equal', + 'write_nir', 'read_nir', 'simulate_graph', 'run_experiment'] + +MODULE_ID = 'nir_export' +SOURCE = ('Pedersen, J. E., Abreu, S., Jobst, M., Lenz, G., Fra, V., Bauer, F. C., Muir, D. R., Zhou, P., ' + 'Vogginger, B., Heckel, K., Urgese, G., Shankar, S., Stewart, T. C., Sheik, S. & Eshraghian, J. K., ' + '"Neuromorphic intermediate representation: A unified instruction set for interoperable brain-inspired ' + 'computing", Nature Communications 15, 8122, September 2024, doi:10.1038/s41467-024-52259-9') +FALLBACK_FORMAT = 'nir-json-fallback' +FALLBACK_VERSION = 1 +NIR_FORMAT = 'nir-hdf5' +GRAPH_FORMAT = 'nir-style-graph' +_HDF5_MAGIC = b'\x89HDF\r\n\x1a\n' + +# Parameter fields of the NIR primitives handled here (names as in the nir package's dataclasses). +NODE_PARAMS: dict[str, tuple[str, ...]] = { + 'Input': ('shape',), + 'Output': ('shape',), + 'Affine': ('weight', 'bias'), + 'Linear': ('weight',), + 'Scale': ('scale',), + 'Delay': ('delay',), + 'I': ('r',), + 'IF': ('r', 'v_threshold', 'v_reset'), + 'LI': ('tau', 'r', 'v_leak'), + 'LIF': ('tau', 'r', 'v_leak', 'v_threshold', 'v_reset'), + 'CubaLI': ('tau_syn', 'tau_mem', 'r', 'v_leak', 'w_in'), + 'CubaLIF': ('tau_syn', 'tau_mem', 'r', 'v_leak', 'v_threshold', 'v_reset', 'w_in'), +} +NIR_NODE_TYPES: tuple[str, ...] = tuple(NODE_PARAMS) +NEURON_TYPES: tuple[str, ...] = ('I', 'IF', 'LI', 'LIF', 'CubaLI', 'CubaLIF') +SPIKING_TYPES: tuple[str, ...] = ('IF', 'LIF', 'CubaLIF') +_POSITIVE = frozenset({'tau', 'tau_syn', 'tau_mem'}) + +# Constants of the NEUROWEAVE cell update (synapse/neuroweave/cells.py, CellPopulation.step); the parity checks in +# run_experiment and the tests confirm the exported dynamics against the cell code itself. +CELL_CONSTANTS: dict[str, float] = { + 'fast_decay': 0.58, # fast = 0.58 fast + u + 0.52 eff + 'external_gain': 1.0, + 'recurrent_gain': 0.52, + 'pre_fast': 0.84, # pre = 0.84 fast + 0.16 eff (no multi_soma) + 'pre_direct': 0.16, + 'membrane_decay': 0.78, # membrane = 0.78 membrane + 0.22 pre - 0.06 adaptation + 'membrane_input': 0.22, + 'adaptation_current': 0.06, + 'reset_factor': 0.26, # membrane <- 0.26 membrane at a spike + 'refractory_steps': 2.0, +} + +_MAX_NODES = 4096 +_MAX_EDGES = 65536 +_MAX_ERRORS = 64 +_MAX_ELEMENTS = 4_000_000 +_MAX_SIM_STEPS = 100_000 +_MAX_DELAY_STEPS = 10_000 +_INPUT_OFFSET = 7_919 +_SIM_OFFSET = 7_927 +_PARITY_OFFSET = 7_933 + + +# ====================================================================== small helpers +def _int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _num(name: str, value: Any, low: float, high: float, *, open_low: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + if not math.isfinite(v) or v < low or v > high or (open_low and v <= low): + raise ValueError(f'{name} must be a finite number in {"(" if open_low else "["}{low}, {high}]') + return v + + +def _floats(x: Any) -> Any: + """Nested lists of Python floats (exactly representable in JSON via repr).""" + return np.asarray(x, dtype=np.float64).tolist() + + +def _tau(decay: float, dt: float) -> float: + """Zero-order-hold time constant of a per-step decay: ``exp(-dt / tau) = decay``.""" + return -dt / math.log(decay) + + +# ====================================================================== optional nir package +def _import_nir() -> tuple[Any, str | None]: + try: + import nir # type: ignore[import-not-found] + except ImportError as exc: + return None, f'ImportError: {exc}' + except Exception as exc: # a broken optional install must not break the module + return None, f'{type(exc).__name__}: {exc}' + return nir, None + + +def nir_status() -> dict[str, Any]: + """Whether the optional ``nir`` package imports (and its version).""" + nir, err = _import_nir() + return {'available': nir is not None, 'version': None if nir is None else str(getattr(nir, '__version__', '?')), + 'error': err} + + +# ====================================================================== NEUROWEAVE -> graph +def cell_parameters(model: str, *, dt: float = 1.0) -> dict[str, float]: + """Scalar NIR parameters that approximate one NEUROWEAVE cell. + + ``'CubaLIF'`` (cells with ``membrane_dynamics``): synaptic current = the fast channel, membrane = the membrane + state; ``w_in = 1 / (1 - fast_decay)`` makes an external input of 1 add exactly 1 to the current per step. + ``'LIF'`` (cells without it): the membrane is the fast channel and the threshold is the fast-channel level at + which ``tanh(0.84 fast)`` crosses the base threshold; the source never resets the fast channel, so + ``v_reset = v_threshold`` (closest constant reset).""" + from ..neuroweave.cells import BASE_THRESHOLD + dt = _num('dt', dt, 0.0, 1e6, open_low=True) + k = CELL_CONSTANTS + if model == 'CubaLIF': + return {'tau_syn': _tau(k['fast_decay'], dt), 'tau_mem': _tau(k['membrane_decay'], dt), + 'r': k['pre_fast'] * k['membrane_input'] / (1.0 - k['membrane_decay']), 'v_leak': 0.0, + 'v_threshold': float(BASE_THRESHOLD), 'v_reset': k['reset_factor'] * float(BASE_THRESHOLD), + 'w_in': k['external_gain'] / (1.0 - k['fast_decay'])} + if model == 'LIF': + theta = math.atanh(float(BASE_THRESHOLD)) / k['pre_fast'] + return {'tau': _tau(k['fast_decay'], dt), 'r': k['external_gain'] / (1.0 - k['fast_decay']), 'v_leak': 0.0, + 'v_threshold': theta, 'v_reset': theta} + raise ValueError("model must be 'CubaLIF' or 'LIF'") + + +def _brain_copy(source: Any) -> Any: + """A private, validated NeuroWeaveBrain built from a brain, an engine or their exported states.""" + from ..neuroweave.brain import BRAIN_SCHEMA, NeuroWeaveBrain + from ..neuroweave.engine import NeuroWeaveEngine + from ..neuroweave.spec import NeuroWeaveSpecV1 + if isinstance(source, NeuroWeaveEngine): + return source.brain.clone() + if isinstance(source, NeuroWeaveBrain): + return source.clone() + if isinstance(source, Mapping): + state = source + if state.get('schema') != BRAIN_SCHEMA and isinstance(state.get('brain'), Mapping): + state = state['brain'] # an engine export carries the brain export + if state.get('schema') != BRAIN_SCHEMA: + raise ValueError(f'expected a NEUROWEAVE brain export (schema {BRAIN_SCHEMA!r}) or an engine export') + try: + spec = NeuroWeaveSpecV1.from_dict(state['spec']) + except (KeyError, TypeError) as exc: + raise ValueError(f'malformed brain export: {exc}') from exc + brain = NeuroWeaveBrain(spec) + brain.import_state(state) # validates fully before assigning + return brain + raise ValueError('source must be a NeuroWeaveBrain, a NeuroWeaveEngine or one of their exports') + + +def _lossy(feature: str, kind: str, treatment: str, reason: str) -> dict[str, str]: + return {'feature': feature, 'kind': kind, 'treatment': treatment, 'reason': reason} + + +_NEURON_FLAG_REASONS = { + 'multi_soma': 'coupled fast/slow/context/integrator soma channels feed the spike input', + 'extended_somas': 'primary/secondary/burst soma roles and a multiplicative gating soma', + 'dendritic_compartments': 'per-compartment dendritic filters with a tanh apical gate', + 'predictive_coding': 'per-unit prediction, clipped residual and surprise trace', + 'hierarchical_temporal_memory': 'fast/medium/slow activity traces feed a temporal contrast', + 'axonal_branches': 'branch and terminal traces with myelin-scaled release feed the output', + 'homeostatic_governor': 'activity-dependent multiplicative output gain', + 'astrocyte_regulation': 'slow glial reservoir scales the output gain', + 'q88_state': 'Q8.8 fixed-point rounding of the output and several states', + 'sparse_code': 'global k-winners-take-all mask on the output', +} +_BRAIN_FLAG_REASONS = { + 'context_attention': 'softmax attention over the strongest incoming neighbours adds to the apical drive', + 'flyhash_projection': 'nonlinear top-k FlyHash code added to the input (only its linear part is exported)', + 'adaptive_routing': 'per-step gain from the destination cell state (gating, apical) scales transmission', + 'uncertainty_gating': 'runtime uncertainty input scales transmission (exported at gate 1.0, uncertainty 0)', + 'multi_region_routing': 'stored region-pair gains are folded in; runtime gains passed by the engine are not', +} +_PLASTIC_FLAGS = ('reward_plasticity', 'stdp', 'meta_plasticity', 'structural_plasticity', 'neurogenesis', + 'sleep_consolidation', 'adaptive_conduction') + + +def unrepresentable_features(source: Any) -> list[dict[str, str]]: + """Every NEUROWEAVE feature of ``source`` that the NIR-style graph cannot represent exactly. + + ``treatment`` is ``'approximated'`` (mapped to the closest NIR construct), ``'dropped'`` (absent from the + graph) or ``'frozen_snapshot'`` (current values exported; the learning or adaptation rule is not).""" + brain = _brain_copy(source) + return _unrepresentable(brain) + + +def _unrepresentable(brain: Any) -> list[dict[str, str]]: + from ..neuroweave.brain import CONSUMED_FLAGS + flags = brain.flags + out = [ + _lossy('graded_output_transmission', 'cell_model', 'approximated', + 'NEUROWEAVE synapses transmit the graded output tanh(gain * pre - shift) (+ hillock boost on spikes); ' + 'NIR edges from a spiking node carry 0/1 spikes'), + _lossy('direct_recurrent_feedthrough', 'cell_model', 'dropped', + 'pre = 0.84 fast + 0.16 recurrent drive: the 0.16 path bypasses the synaptic filter'), + _lossy('readout_head', 'brain', 'dropped', + 'the logistic readout uses nonlinear population features (|a|, std, tanh of channels)'), + _lossy('input_clipping', 'brain', 'dropped', 'external input is clipped to [-10, 10] before projection'), + _lossy('control_inputs', 'cell_model', 'dropped', + 'runtime controls (gain, threshold shift, attention, plasticity scale) are exported at neutral values'), + ] + if 'membrane_dynamics' in flags: + out += [ + _lossy('multiplicative_reset', 'cell_model', 'approximated', + 'membrane <- 0.26 * membrane at a spike; NIR resets to a constant (0.26 * base threshold)'), + _lossy('refractory_period', 'cell_model', 'dropped', + 'two-step refractory hold (and 0.7x scaling of the output drive while held)'), + _lossy('adaptive_threshold', 'cell_model', 'dropped', + 'threshold = clip(0.53 + 0.18 * adaptation, 0.42, 0.78) and a -0.06 * adaptation current'), + _lossy('calcium_feedback', 'cell_model', 'dropped', 'calcium trace feeds back into the output drive'), + ] + else: + out += [ + _lossy('threshold_on_graded_output', 'cell_model', 'approximated', + 'spikes are tanh(pre) > threshold; exported as a membrane threshold atanh(0.53) / 0.84 on the fast ' + 'channel (exact only without recurrent input)'), + _lossy('no_reset_in_source', 'cell_model', 'approximated', + 'the fast channel is never reset; NIR LIF resets (v_reset = v_threshold)'), + ] + for flag in sorted(flags): + if flag in _NEURON_FLAG_REASONS: + out.append(_lossy(flag, 'mechanism', 'dropped', _NEURON_FLAG_REASONS[flag])) + elif flag in _BRAIN_FLAG_REASONS: + treatment = 'approximated' if flag in ('multi_region_routing', 'uncertainty_gating', + 'flyhash_projection') else 'dropped' + out.append(_lossy(flag, 'mechanism', treatment, _BRAIN_FLAG_REASONS[flag])) + elif flag in _PLASTIC_FLAGS: + out.append(_lossy(flag, 'mechanism', 'frozen_snapshot', + 'learning/adaptation rule; NIR has no plasticity, so the current weights, delays and ' + 'myelin gains are exported as a frozen snapshot')) + for flag in sorted(set(brain.spec.mechanisms) - set(CONSUMED_FLAGS)): + out.append(_lossy(flag, 'engine_mechanism', 'dropped', + 'engine-level mechanism outside the brain graph (memory, modulation, prediction or sensing)')) + return out + + +def _folded(flags: frozenset[str]) -> list[str]: + out = ['synapse_table_snapshot'] + for flag in ('synaptic_delays', 'quantised_synapses', 'multi_region_routing', 'adaptive_conduction', + 'structural_encoder', 'tiled_execution'): + if flag in flags: + out.append(flag) + return out + + +def _input_projection(brain: Any, d: int) -> np.ndarray: + """Exact linear input map (n, d) of ``brain.project_input`` without the nonlinear FlyHash term.""" + lin = brain.clone() + lin.flags = frozenset(brain.flags - {'flyhash_projection'}) + eye = np.eye(d) + return np.stack([lin.project_input(eye[j]) for j in range(d)], axis=1) + + +def _folded_weights(brain: Any) -> tuple[np.ndarray, np.ndarray]: + """Per-edge transmission weights and delays of the current synapse table with the static gains folded in.""" + from ..neuroweave.connectome import dequantise_int8, quantise_int8 + syn, flags = brain.synapses, brain.flags + w = syn.w.astype(np.float64).copy() + if 'quantised_synapses' in flags: + q, scale = quantise_int8(w) + w = dequantise_int8(q, scale) + if 'multi_region_routing' in flags: + w = w * syn.route_gain[syn.region[syn.src], syn.region[syn.dst]] + if 'adaptive_conduction' in flags: + w = w * (0.85 + 0.25 * syn.myelin) + if 'structural_encoder' in flags: + w = w * brain._structural_weight()[syn.src] + return w, syn.effective_delay(flags).astype(np.int64) + + +def brain_to_nir(source: Any, *, input_dim: int | None = None, step_ms: float = 1.0) -> dict[str, Any]: + """NIR-style graph of a NEUROWEAVE brain (a brain, an engine, or their ``export_state()`` dicts). + + Layout: ``input`` (Input, ``input_dim``) -> ``input_projection`` (Linear) -> ``cells`` (CubaLIF with + ``membrane_dynamics``, else LIF) -> ``output`` (Output); for every synaptic delay class ``k`` (steps) + ``cells -> delay_k`` (Delay ``k * step_ms``) ``-> recurrent_k`` (Linear, 0.52 x folded weights) ``-> cells``. + Time constants and delays are in ms with one engine step = ``step_ms`` ms (``metadata.dt``).""" + from ..neuroweave.brain import BRAIN_SCHEMA + from ..neuroweave.spec import TASK_INPUT_DIM + d = TASK_INPUT_DIM if input_dim is None else _int('input_dim', input_dim, 1, 256) + dt = _num('step_ms', step_ms, 0.0, 1e6, open_low=True) + brain = _brain_copy(source) + flags = brain.flags + n = int(brain.n) + model = 'CubaLIF' if 'membrane_dynamics' in flags else 'LIF' + scalar = cell_parameters(model, dt=dt) + P = _input_projection(brain, d) + w, delay = _folded_weights(brain) + syn = brain.synapses + g = CELL_CONSTANTS['recurrent_gain'] + nodes: dict[str, Any] = { + 'input': {'type': 'Input', 'params': {'shape': [d]}}, + 'input_projection': {'type': 'Linear', 'params': {'weight': _floats(P)}}, + 'cells': {'type': model, 'params': {k: [float(v)] * n for k, v in scalar.items()}}, + 'output': {'type': 'Output', 'params': {'shape': [n]}}, + } + edges: list[list[str]] = [['input', 'input_projection'], ['input_projection', 'cells'], ['cells', 'output']] + classes = sorted(int(k) for k in np.unique(delay)) if syn.size else [] + expected_nonzero = 0 + for k in classes: + sel = delay == k + W = np.zeros((n, n)) + np.add.at(W, (syn.dst[sel], syn.src[sel]), g * w[sel]) + expected_nonzero += int(np.count_nonzero(W)) + nodes[f'delay_{k}'] = {'type': 'Delay', 'params': {'delay': [float(k * dt)] * n}} + nodes[f'recurrent_{k}'] = {'type': 'Linear', 'params': {'weight': _floats(W)}} + edges += [['cells', f'delay_{k}'], [f'delay_{k}', f'recurrent_{k}'], [f'recurrent_{k}', 'cells']] + triples = len(set(zip(syn.src.tolist(), syn.dst.tolist(), delay.tolist()))) + metadata = { + 'producer': 'synapse.frontier.nir_export', 'format': GRAPH_FORMAT, 'format_version': 1, + 'time_unit': 'ms', 'dt': dt, 'reference': SOURCE, + 'source': {'schema': BRAIN_SCHEMA, 'seed': int(brain.spec.seed), 'step': int(brain.step_count), + 'neurons': n, 'synapses': int(syn.size), 'unique_src_dst_delay': int(triples), + 'input_dim': d, 'mechanisms': list(brain.spec.mechanisms)}, + 'neuron_model': model, 'cell_parameters': scalar, 'cell_constants': dict(CELL_CONSTANTS), + 'delay_classes_steps': classes, 'represented_synapses': int(expected_nonzero), + 'mapping': ('tau = -dt / ln(decay per step) (zero-order hold); recurrent Linear = 0.52 x folded weights ' + '(W[dst, src], summed over duplicate edges); input Linear = exact linear part of project_input'), + 'folded_features': _folded(flags), 'lossy_features': _unrepresentable(brain), + } + return {'nodes': nodes, 'edges': edges, 'metadata': metadata} + + +# ====================================================================== validation +def _array(name: str, value: Any, errors: list[str]) -> np.ndarray | None: + try: + arr = np.asarray(value, dtype=np.float64) + except (TypeError, ValueError): + errors.append(f'{name}: not numeric') + return None + if arr.size > _MAX_ELEMENTS: + errors.append(f'{name}: more than {_MAX_ELEMENTS} elements') + return None + if not np.all(np.isfinite(arr)): + errors.append(f'{name}: non-finite values') + return None + return arr + + +def _shape(name: str, value: Any, errors: list[str]) -> tuple[int, ...] | None: + if not isinstance(value, (list, tuple)) or not value or len(value) > 8: + errors.append(f'{name}: shape must be a non-empty list of positive ints') + return None + out = [] + for x in value: + if isinstance(x, bool) or not isinstance(x, (int, np.integer)) or int(x) < 1: + errors.append(f'{name}: shape must be a non-empty list of positive ints') + return None + out.append(int(x)) + return tuple(out) + + +def node_io_shapes(name: str, node: Mapping[str, Any], errors: list[str] | None = None + ) -> tuple[tuple[int, ...] | None, tuple[int, ...] | None]: + """``(input_shape, output_shape)`` of a node (``None`` for no input / no output); appends problems to + ``errors`` (or raises ``ValueError`` when ``errors`` is None).""" + own: list[str] = [] if errors is None else errors + start = len(own) + t = node.get('type') if isinstance(node, Mapping) else None + params = node.get('params') if isinstance(node, Mapping) else None + shapes: tuple[Any, Any] = (None, None) + if not isinstance(t, str) or t not in NODE_PARAMS: + own.append(f'{name}: unknown node type {t!r} (known: {", ".join(NIR_NODE_TYPES)})') + elif not isinstance(params, Mapping): + own.append(f'{name}: params must be a mapping') + elif set(params) != set(NODE_PARAMS[t]): + missing = sorted(set(NODE_PARAMS[t]) - set(params)) + extra = sorted(set(params) - set(NODE_PARAMS[t])) + own.append(f'{name}: {t} params mismatch (missing {missing}, unexpected {extra})') + elif t in ('Input', 'Output'): + s = _shape(f'{name}.shape', params['shape'], own) + if s is not None: + shapes = (None, s) if t == 'Input' else (s, None) + elif t in ('Affine', 'Linear'): + W = _array(f'{name}.weight', params['weight'], own) + if W is not None and (W.ndim != 2 or 0 in W.shape): + own.append(f'{name}.weight: must be a non-empty 2-D (out, in) matrix') + elif W is not None: + shapes = ((W.shape[1],), (W.shape[0],)) + if t == 'Affine': + b = _array(f'{name}.bias', params['bias'], own) + if b is not None and b.shape != (W.shape[0],): + own.append(f'{name}.bias: shape {b.shape} does not match weight rows {W.shape[0]}') + else: + arrays = {k: _array(f'{name}.{k}', params[k], own) for k in NODE_PARAMS[t]} + if all(a is not None for a in arrays.values()): + ref = arrays[NODE_PARAMS[t][0]].shape + if len(ref) != 1 or ref[0] < 1: + own.append(f'{name}: parameters must be non-empty 1-D vectors') + elif any(a.shape != ref for a in arrays.values()): + own.append(f'{name}: parameter shapes differ ({ {k: a.shape for k, a in arrays.items()} })') + else: + if any(k in _POSITIVE and np.any(a <= 0.0) for k, a in arrays.items()): + own.append(f'{name}: time constants must be positive') + elif t == 'Delay' and np.any(arrays['delay'] < 0.0): + own.append(f'{name}: delays must be non-negative') + else: + shapes = (ref, ref) + if errors is None and len(own) > start: + raise ValueError('; '.join(own[start:])) + return shapes + + +def validate_graph(graph: Any) -> dict[str, Any]: + """Structural validation: known node types with the right parameter fields, finite parameters with + consistent shapes, edge endpoints that exist, no edges into an Input or out of an Output, matching shapes + along every edge, no duplicate edges, at least one Input and one Output. Returns a report; ``valid`` is + False when ``errors`` is non-empty (``warnings`` flag nodes without incoming/outgoing edges).""" + errors: list[str] = [] + warnings: list[str] = [] + if not isinstance(graph, Mapping): + return {'valid': False, 'errors': ['graph must be a mapping with nodes and edges'], 'warnings': [], + 'node_count': 0, 'edge_count': 0, 'node_types': {}} + nodes, edges = graph.get('nodes'), graph.get('edges') + if not isinstance(nodes, Mapping) or not 1 <= len(nodes) <= _MAX_NODES: + errors.append(f'nodes must be a mapping of 1..{_MAX_NODES} named nodes') + nodes = {} + if not isinstance(edges, (list, tuple)) or len(edges) > _MAX_EDGES: + errors.append(f'edges must be a list of at most {_MAX_EDGES} [src, dst] pairs') + edges = [] + io: dict[str, tuple[Any, Any]] = {} + for name, node in nodes.items(): + if not isinstance(name, str) or not name: + errors.append(f'node names must be non-empty strings (got {name!r})') + continue + io[name] = node_io_shapes(name, node, errors) + types = {name: node.get('type') for name, node in nodes.items() if isinstance(node, Mapping)} + seen: set[tuple[str, str]] = set() + indeg: Counter = Counter() + outdeg: Counter = Counter() + for e in edges: + if not isinstance(e, (list, tuple)) or len(e) != 2 or not all(isinstance(x, str) for x in e): + errors.append(f'edge {e!r} must be a [src, dst] pair of node names') + continue + src, dst = e + if src not in nodes or dst not in nodes: + errors.append(f'edge {src!r} -> {dst!r}: endpoint does not exist') + continue + if (src, dst) in seen: + errors.append(f'edge {src!r} -> {dst!r}: duplicate') + continue + seen.add((src, dst)) + indeg[dst] += 1 + outdeg[src] += 1 + if types.get(src) == 'Output': + errors.append(f'edge {src!r} -> {dst!r}: an Output node cannot have outgoing edges') + if types.get(dst) == 'Input': + errors.append(f'edge {src!r} -> {dst!r}: an Input node cannot have incoming edges') + out_shape = io.get(src, (None, None))[1] + in_shape = io.get(dst, (None, None))[0] + if out_shape is not None and in_shape is not None and out_shape != in_shape: + errors.append(f'edge {src!r} -> {dst!r}: shape {list(out_shape)} does not match input {list(in_shape)}') + if nodes and not any(t == 'Input' for t in types.values()): + errors.append('graph has no Input node') + if nodes and not any(t == 'Output' for t in types.values()): + errors.append('graph has no Output node') + for name, t in types.items(): + if t != 'Input' and indeg[name] == 0: + warnings.append(f'{name}: no incoming edges') + if t != 'Output' and outdeg[name] == 0: + warnings.append(f'{name}: no outgoing edges') + if len(errors) > _MAX_ERRORS: + errors = errors[:_MAX_ERRORS] + [f'... {len(errors) - _MAX_ERRORS} more errors'] + return {'valid': not errors, 'errors': errors, 'warnings': warnings[:_MAX_ERRORS], 'node_count': len(nodes), + 'edge_count': len(edges), 'node_types': dict(sorted(Counter(t for t in types.values() + if isinstance(t, str)).items()))} + + +def _require_valid(graph: Any) -> None: + report = validate_graph(graph) + if not report['valid']: + raise ValueError('invalid NIR-style graph: ' + '; '.join(report['errors'])) + + +# ====================================================================== equality and serialisation +def canonical_graph(graph: Mapping[str, Any], *, include_metadata: bool = True) -> dict[str, Any]: + """Validated, JSON-safe copy: params as nested float lists, shapes as int lists, edges as [src, dst] lists.""" + _require_valid(graph) + nodes = {} + for name in sorted(graph['nodes']): + node = graph['nodes'][name] + t = node['type'] + if t in ('Input', 'Output'): + params = {'shape': [int(x) for x in node['params']['shape']]} + else: + params = {k: _floats(node['params'][k]) for k in NODE_PARAMS[t]} + nodes[name] = {'type': t, 'params': params} + out = {'nodes': nodes, 'edges': [[str(s), str(d)] for s, d in graph['edges']]} + if include_metadata and isinstance(graph.get('metadata'), Mapping): + out['metadata'] = json.loads(json.dumps(graph['metadata'], sort_keys=True, allow_nan=False)) + return out + + +def graphs_equal(a: Mapping[str, Any], b: Mapping[str, Any]) -> bool: + """Same node names, types, parameter values (exact, shape included) and edge set; metadata is ignored.""" + try: + ca, cb = canonical_graph(a, include_metadata=False), canonical_graph(b, include_metadata=False) + except ValueError: + return False + if set(ca['nodes']) != set(cb['nodes']): + return False + for name, na in ca['nodes'].items(): + nb = cb['nodes'][name] + if na['type'] != nb['type']: + return False + for k, va in na['params'].items(): + x, y = np.asarray(va), np.asarray(nb['params'][k]) + if x.shape != y.shape or not np.array_equal(x, y): + return False + return sorted(map(tuple, ca['edges'])) == sorted(map(tuple, cb['edges'])) + + +def _to_nir(graph: Mapping[str, Any], nir: Any) -> Any: + nodes = {} + for name, node in graph['nodes'].items(): + t, p = node['type'], node['params'] + if t == 'Input': + nodes[name] = nir.Input(input_type=np.asarray(p['shape'], dtype=np.int64)) + elif t == 'Output': + nodes[name] = nir.Output(output_type=np.asarray(p['shape'], dtype=np.int64)) + else: + nodes[name] = getattr(nir, t)(**{k: np.asarray(p[k], dtype=np.float64) for k in NODE_PARAMS[t]}) + return nir.NIRGraph(nodes=nodes, edges=[(str(s), str(d)) for s, d in graph['edges']]) + + +def _shape_of(types: Any, key: str) -> list[int]: + value = types[key] if isinstance(types, Mapping) else types + return [int(x) for x in np.asarray(value).ravel()] + + +def _from_nir(g: Any) -> dict[str, Any]: + nodes = {} + for name, node in g.nodes.items(): + t = type(node).__name__ + if t == 'Input': + nodes[str(name)] = {'type': t, 'params': {'shape': _shape_of(node.input_type, 'input')}} + elif t == 'Output': + nodes[str(name)] = {'type': t, 'params': {'shape': _shape_of(node.output_type, 'output')}} + elif t in NODE_PARAMS: + nodes[str(name)] = {'type': t, 'params': {k: _floats(getattr(node, k)) for k in NODE_PARAMS[t]}} + else: + raise ValueError(f'NIR node {name!r} has a type this module does not handle: {t}') + edges = [[a.decode('utf8') if isinstance(a, bytes) else str(a), b.decode('utf8') if isinstance(b, bytes) else str(b)] + for a, b in g.edges] + return {'nodes': nodes, 'edges': edges} + + +def write_nir(graph: Mapping[str, Any], path: str | Path, *, backend: str = 'auto') -> dict[str, Any]: + """Write ``graph`` to ``path`` and read it back. + + ``backend='auto'`` writes a real NIR (HDF5) file with ``nir.write`` / ``nir.read`` when the optional ``nir`` + package imports and JSON tagged ``'format': 'nir-json-fallback'`` otherwise; ``'json'`` forces the fallback and + ``'nir'`` requires the package. Returns ``format``, ``round_trip_equal`` (nodes, parameters and edges compared + exactly), node/edge counts before and after, and the nir package status. NIR files carry no metadata here (the + metadata stays in the JSON form and in the in-memory graph).""" + if backend not in ('auto', 'json', 'nir'): + raise ValueError("backend must be 'auto', 'json' or 'nir'") + canon = canonical_graph(graph) # validates before anything is written + p = Path(path) + status = nir_status() + nir = None + if backend in ('auto', 'nir'): + nir, _ = _import_nir() + if nir is None and backend == 'nir': + raise ValueError(f'the optional nir package is not importable ({status["error"]})') + if nir is not None: + nir.write(str(p), _to_nir(canon, nir)) + back = read_nir(p) + fmt = NIR_FORMAT + else: + doc = {'format': FALLBACK_FORMAT, 'format_version': FALLBACK_VERSION, 'reference': SOURCE, 'graph': canon} + p.write_text(json.dumps(doc, sort_keys=True, allow_nan=False, separators=(',', ':')), encoding='utf-8') + back = read_nir(p) + fmt = FALLBACK_FORMAT + return {'format': fmt, 'round_trip_equal': graphs_equal(canon, back), + 'node_count': len(canon['nodes']), 'edge_count': len(canon['edges']), + 'read_node_count': len(back['nodes']), 'read_edge_count': len(back['edges']), + 'nir': status} + + +def read_nir(path: str | Path) -> dict[str, Any]: + """Read a JSON fallback file, or a real NIR file when the optional ``nir`` package imports; returns a + validated graph dict (JSON fallback files keep their metadata).""" + p = Path(path) + with p.open('rb') as fh: + head = fh.read(8) + if head == _HDF5_MAGIC: + nir, err = _import_nir() + if nir is None: + raise ValueError(f'{p.name} is an HDF5 (NIR) file but the optional nir package is not importable ({err})') + graph = _from_nir(nir.read(str(p))) + else: + try: + doc = json.loads(p.read_text(encoding='utf-8')) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f'{p.name} is neither an HDF5 NIR file nor JSON') from exc + if not isinstance(doc, Mapping) or doc.get('format') != FALLBACK_FORMAT: + raise ValueError(f"JSON file is not tagged 'format': {FALLBACK_FORMAT!r}") + if doc.get('format_version') != FALLBACK_VERSION or not isinstance(doc.get('graph'), Mapping): + raise ValueError('unsupported nir-json-fallback version or missing graph') + graph = dict(doc['graph']) + _require_valid(graph) + return graph + + +# ====================================================================== discrete-time simulation +def simulate_graph(graph: Mapping[str, Any], inputs: Any, *, dt: float | None = None, record_states: bool = False, + max_steps: int = _MAX_SIM_STEPS) -> dict[str, Any]: + """Simulate a validated graph in discrete time with step ``dt`` (default ``metadata.dt`` or 1). + + Zero-order-hold updates: ``a = exp(-dt / tau)``; LI ``v <- a v + (1 - a)(v_leak + r x)``; CubaLI/CubaLIF + ``i <- a_s i + (1 - a_s) w_in x`` then ``v <- a_m v + (1 - a_m)(v_leak + r i)``; I/IF ``v <- v + dt r x``; + spiking types emit ``v > v_threshold`` and reset to ``v_reset``. Initial ``v = v_leak`` (0 for I/IF), ``i = 0``. + Incoming edges are summed; Delay ``d`` outputs its input from ``round(d / dt)`` steps earlier (zeros before + that; ``d`` must be a multiple of ``dt``), so Delay nodes with ``d >= dt`` break recurrent loops; any loop + without one raises ``ValueError``. ``inputs`` is an array (T, k) for a single Input node or a mapping + {input name: array (T, k)}. Returns per-Output arrays (T, k), spike counts per spiking node, ``finite`` and, + with ``record_states``, neuron states ``v`` (and ``i``) of shape (T, k).""" + _require_valid(graph) + max_steps = _int('max_steps', max_steps, 1, _MAX_SIM_STEPS) + meta = graph.get('metadata') if isinstance(graph.get('metadata'), Mapping) else {} + step = _num('dt', meta.get('dt', 1.0) if dt is None else dt, 0.0, 1e6, open_low=True) + nodes = {name: {'type': nd['type'], 'p': {k: np.asarray(v, dtype=np.float64) for k, v in nd['params'].items()}} + for name, nd in graph['nodes'].items()} + in_names = [n for n, nd in nodes.items() if nd['type'] == 'Input'] + if isinstance(inputs, Mapping): + if set(inputs) != set(in_names): + raise ValueError(f'inputs must provide exactly the Input nodes {sorted(in_names)}') + X = dict(inputs) + else: + if len(in_names) != 1: + raise ValueError('a bare input array needs exactly one Input node; pass a mapping instead') + X = {in_names[0]: inputs} + T = None + for name in in_names: + try: + arr = np.asarray(X[name], dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'inputs[{name!r}] must be numeric') from exc + shape = tuple(int(x) for x in nodes[name]['p']['shape']) + if len(shape) != 1 or arr.ndim != 2 or arr.shape[1] != shape[0]: + raise ValueError(f'inputs[{name!r}] must have shape (T, {shape[0] if len(shape) == 1 else shape})') + if not np.all(np.isfinite(arr)): + raise ValueError(f'inputs[{name!r}] must be finite') + if T is not None and arr.shape[0] != T: + raise ValueError('all inputs must have the same number of steps') + T = int(arr.shape[0]) + X[name] = arr + if T is None or not 1 <= T <= max_steps: + raise ValueError(f'inputs must have 1..{max_steps} steps') + for name, nd in nodes.items(): + if nd['type'] in ('Input', 'Output') and len(nd['p']['shape']) != 1: + raise ValueError(f'{name}: the simulator handles 1-D shapes only') + + preds: dict[str, list[str]] = {name: [] for name in nodes} + for s, d in graph['edges']: + preds[d].append(s) + lag: dict[str, np.ndarray] = {} + for name, nd in nodes.items(): + if nd['type'] == 'Delay': + q = nd['p']['delay'] / step + k = np.rint(q) + if np.any(np.abs(q - k) > 1e-9 * np.maximum(1.0, np.abs(q))) or np.any(k > _MAX_DELAY_STEPS): + raise ValueError(f'{name}: delays must be multiples of dt up to {_MAX_DELAY_STEPS} steps') + lag[name] = k.astype(np.int64) + breaking = {name for name, k in lag.items() if k.min() >= 1} + deps = {name: [s for s in preds[name]] for name in nodes if name not in breaking} + order: list[str] = [] + state_mark: dict[str, int] = {} + + def visit(name: str, stack: list[str]) -> None: + mark = state_mark.get(name, 0) + if mark == 2: + return + if mark == 1: + raise ValueError('algebraic loop without a delay: ' + ' -> '.join(stack + [name])) + state_mark[name] = 1 + for s in deps.get(name, []): + if s not in breaking: + visit(s, stack + [name]) + state_mark[name] = 2 + order.append(name) + + for name in sorted(nodes): + if name not in breaking: + visit(name, []) + + out_dim = {name: (int(nd['p']['weight'].shape[0]) if nd['type'] in ('Affine', 'Linear') + else int(nd['p']['shape'][0]) if nd['type'] in ('Input', 'Output') + else int(next(iter(nd['p'].values())).shape[0])) for name, nd in nodes.items()} + v: dict[str, np.ndarray] = {} + cur: dict[str, np.ndarray] = {} + decay: dict[str, dict[str, np.ndarray]] = {} + for name, nd in nodes.items(): + t, p = nd['type'], nd['p'] + if t in ('LI', 'LIF'): + v[name] = p['v_leak'].copy() + decay[name] = {'m': np.exp(-step / p['tau'])} + elif t in ('CubaLI', 'CubaLIF'): + v[name] = p['v_leak'].copy() + cur[name] = np.zeros_like(p['v_leak']) + decay[name] = {'s': np.exp(-step / p['tau_syn']), 'm': np.exp(-step / p['tau_mem'])} + elif t in ('I', 'IF'): + v[name] = np.zeros_like(p['r']) + hist = {name: np.zeros((int(k.max()) + 1, out_dim[name])) for name, k in lag.items()} + outputs = {name: np.zeros((T, out_dim[name])) for name, nd in nodes.items() if nd['type'] == 'Output'} + spikes = {name: 0 for name, nd in nodes.items() if nd['type'] in SPIKING_TYPES} + states: dict[str, dict[str, np.ndarray]] = {} + if record_states: + for name, nd in nodes.items(): + if nd['type'] in NEURON_TYPES: + states[name] = {'v': np.zeros((T, out_dim[name]))} + if name in cur: + states[name]['i'] = np.zeros((T, out_dim[name])) + finite = True + chan = {name: np.arange(out_dim[name]) for name in lag} + for t in range(T): + val: dict[str, np.ndarray] = {} + + def delayed(name: str) -> np.ndarray: + k = lag[name] + idx = (t - k) % hist[name].shape[0] + got = hist[name][idx, chan[name]] + return np.where(t - k >= 0, got, 0.0) + + for name in breaking: + val[name] = delayed(name) + for name in order: + nd = nodes[name] + t_, p = nd['type'], nd['p'] + if t_ == 'Input': + val[name] = X[name][t] + continue + x = np.zeros(out_dim[name] if t_ not in ('Affine', 'Linear') else p['weight'].shape[1]) + for s in preds[name]: + x = x + val[s] + if t_ == 'Output': + outputs[name][t] = x + val[name] = x + elif t_ == 'Linear': + val[name] = p['weight'] @ x + elif t_ == 'Affine': + val[name] = p['weight'] @ x + p['bias'] + elif t_ == 'Scale': + val[name] = p['scale'] * x + elif t_ == 'Delay': # some channel has zero delay: pass those through + k = lag[name] + idx = (t - k) % hist[name].shape[0] + old = np.where(t - k >= 0, hist[name][idx, chan[name]], 0.0) + val[name] = np.where(k == 0, x, old) + else: + if t_ in ('LI', 'LIF'): + a = decay[name]['m'] + v[name] = a * v[name] + (1.0 - a) * (p['v_leak'] + p['r'] * x) + elif t_ in ('CubaLI', 'CubaLIF'): + a_s, a_m = decay[name]['s'], decay[name]['m'] + cur[name] = a_s * cur[name] + (1.0 - a_s) * p['w_in'] * x + v[name] = a_m * v[name] + (1.0 - a_m) * (p['v_leak'] + p['r'] * cur[name]) + else: # I, IF + v[name] = v[name] + step * p['r'] * x + if record_states: + states[name]['v'][t] = v[name] + if name in cur: + states[name]['i'][t] = cur[name] + if t_ in SPIKING_TYPES: + # Thresholding can turn even an infinite potential into a + # finite spike and reset. Check before discarding the state. + if finite and not np.all(np.isfinite(v[name])): + finite = False + z = v[name] > p['v_threshold'] + v[name] = np.where(z, p['v_reset'], v[name]) + spikes[name] += int(z.sum()) + val[name] = z.astype(np.float64) + else: + val[name] = v[name].copy() + for name in lag: + x = np.zeros(out_dim[name]) + for s in preds[name]: + x = x + val[s] + hist[name][t % hist[name].shape[0]] = x + if finite and not all(np.all(np.isfinite(a)) for a in val.values()): + finite = False + result: dict[str, Any] = {'steps': T, 'dt': step, 'outputs': outputs, 'spike_counts': spikes, 'finite': finite, + 'order': order, 'delay_breaks': sorted(breaking)} + if record_states: + result['states'] = states + return result + + +# ====================================================================== validation experiment +_DEFAULTS: dict[str, Any] = { + 'neurons': 48, 'topology': 'clustered', + 'mechanisms': ('membrane_dynamics', 'synaptic_delays', 'quantised_synapses', 'stdp'), + 'warmup_steps': 100, 'simulate_steps': 200, 'input_dim': 8, 'input_scale': 1.0, 'step_ms': 1.0, + 'parity_cells': 16, 'parity_steps': 200, 'parity_drive_max': 0.6, 'parity_tolerance': 1e-9, 'backend': 'auto', +} +_QUICK: dict[str, Any] = {'neurons': 24, 'warmup_steps': 30, 'simulate_steps': 80, 'parity_cells': 8, + 'parity_steps': 80} +_LOSSY_CONNECTOME = frozenset({'adaptive_routing', 'uncertainty_gating', 'context_attention'}) + + +def _seeds(seeds: Any) -> tuple[int, ...]: + try: + out = tuple(_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +def _validate_config(cfg: Mapping[str, Any]) -> dict[str, Any]: + from ..neuroweave.spec import MECHANISMS, TOPOLOGIES + c = dict(cfg) + c['neurons'] = _int('neurons', c['neurons'], 4, 512) + if c['topology'] not in TOPOLOGIES: + raise ValueError(f'topology must be one of {TOPOLOGIES}') + if isinstance(c['mechanisms'], str): + raise ValueError('mechanisms must be a sequence of mechanism ids') + mechs = tuple(c['mechanisms']) + known = {m.id for m in MECHANISMS} + if any(m not in known for m in mechs) or len(set(mechs)) != len(mechs): + raise ValueError('mechanisms must be unique NEUROWEAVE mechanism ids') + c['mechanisms'] = mechs + c['warmup_steps'] = _int('warmup_steps', c['warmup_steps'], 0, 100_000) + c['simulate_steps'] = _int('simulate_steps', c['simulate_steps'], 4, 100_000) + c['input_dim'] = _int('input_dim', c['input_dim'], 1, 256) + c['input_scale'] = _num('input_scale', c['input_scale'], 0.0, 10.0) + c['step_ms'] = _num('step_ms', c['step_ms'], 0.0, 1e6, open_low=True) + c['parity_cells'] = _int('parity_cells', c['parity_cells'], 1, 4096) + c['parity_steps'] = _int('parity_steps', c['parity_steps'], 4, 100_000) + c['parity_drive_max'] = _num('parity_drive_max', c['parity_drive_max'], 0.0, 10.0, open_low=True) + c['parity_tolerance'] = _num('parity_tolerance', c['parity_tolerance'], 0.0, 1e-3, open_low=True) + if c['backend'] not in ('auto', 'json', 'nir'): + raise ValueError("backend must be 'auto', 'json' or 'nir'") + return c + + +def _recurrent_parity(brain: Any, graph: Mapping[str, Any]) -> dict[str, Any]: + """Recurrent drive of the exported Delay/Linear pairs on NEUROWEAVE's own output history vs the synapse + table's transmission (same history, run on a copy). Exact unless state-dependent gains are on.""" + lossy = sorted(_LOSSY_CONNECTOME & brain.flags) + if lossy: + return {'applicable': False, 'reason': f'state-dependent gains: {lossy}', 'max_abs_difference': None} + ref = brain.clone() + syn = ref.synapses + out = ref.cells.output.copy() + drive = syn.transmit(out, ref.flags, tile_size=ref.spec.tile_size if 'tiled_execution' in ref.flags else None, + uncertainty_gate=1.0, cells=ref.cells, + src_weight=ref._structural_weight() if 'structural_encoder' in ref.flags else None) + expect = drive.total + got = np.zeros(ref.n) + g = CELL_CONSTANTS['recurrent_gain'] + delayed_ok = 'synaptic_delays' in ref.flags + for name, node in graph['nodes'].items(): + if node['type'] == 'Delay': + k = int(round(float(node['params']['delay'][0]) / float(graph['metadata']['dt']))) + src = out if k == 1 or not delayed_ok else (syn.hist[k - 1] if syn.hist_count >= k else out) + W = np.asarray(graph['nodes'][f'recurrent_{k}']['params']['weight']) + got = got + (W / g) @ src + return {'applicable': True, 'reason': None, 'max_abs_difference': float(np.max(np.abs(got - expect))) + if ref.n else 0.0, 'history_steps': int(syn.hist_count)} + + +def _cell_parity(graph: Mapping[str, Any], c: Mapping[str, Any], seed: int) -> dict[str, Any]: + """Isolated cells (no recurrent input): NEUROWEAVE ``CellPopulation`` vs the exported neuron node driven + through an identity Linear. The synaptic current must equal the fast channel; before a cell's first spike + the membrane must equal NEUROWEAVE's membrane minus its (known, dropped) adaptation current.""" + from ..neuroweave.cells import CellPopulation, CompartmentDrive + cells_node = graph['nodes']['cells'] + model = cells_node['type'] + k, T = c['parity_cells'], c['parity_steps'] + params = {name: [float(vals[0])] * k for name, vals in cells_node['params'].items()} + tiny = {'nodes': {'x': {'type': 'Input', 'params': {'shape': [k]}}, + 'eye': {'type': 'Linear', 'params': {'weight': np.eye(k).tolist()}}, + 'cells': {'type': model, 'params': params}, + 'y': {'type': 'Output', 'params': {'shape': [k]}}}, + 'edges': [['x', 'eye'], ['eye', 'cells'], ['cells', 'y']], 'metadata': {'dt': graph['metadata']['dt']}} + rng = np.random.default_rng(int(seed) + _PARITY_OFFSET) + u = rng.uniform(0.0, c['parity_drive_max'], size=(T, k)) + sim = simulate_graph(tiny, u, record_states=True) + flags = frozenset({'membrane_dynamics'}) if model == 'CubaLIF' else frozenset() + pop = CellPopulation(k, seed=int(seed), regions=np.zeros(k, dtype=np.int64), signs=np.ones(k, dtype=np.int64)) + zero = np.zeros(k) + fast = np.zeros((T, k)) + memb = np.zeros((T, k)) + adapt = np.zeros((T, k)) + nw_spike = np.zeros((T, k), dtype=bool) + for t in range(T): + pop.step(CompartmentDrive(zero.copy(), zero.copy(), zero.copy(), zero.copy(), u[t].copy()), flags) + fast[t], memb[t], adapt[t], nw_spike[t] = pop.fast, pop.membrane, pop.adaptation, pop.spike > 0 + nir_spike = sim['outputs']['y'] > 0 + i_dev = None + if model == 'CubaLIF': + i_dev = float(np.max(np.abs(sim['states']['cells']['i'] - fast))) + corr = np.zeros(k) # accumulated -0.06 * adaptation current + ref_v = np.zeros((T, k)) + for t in range(T): + corr = CELL_CONSTANTS['membrane_decay'] * corr - CELL_CONSTANTS['adaptation_current'] * adapt[t] + ref_v[t] = memb[t] - corr + v_nir = sim['states']['cells']['v'] + else: + ref_v, v_nir = fast, sim['states']['cells']['v'] + + def first(s: np.ndarray) -> list[int | None]: + return [int(np.flatnonzero(s[:, j])[0]) if s[:, j].any() else None for j in range(k)] + + f_nw, f_nir = first(nw_spike), first(nir_spike) + v_dev = 0.0 + for j in range(k): # compare up to (and including) the first spike step + stops = [s for s in (f_nw[j], f_nir[j]) if s is not None] + end = min(stops) + 1 if stops else T + if model == 'CubaLIF': + seg = slice(0, end) + # the spike step itself is compared before the reset: NEUROWEAVE stores the reset membrane + pre_reset = np.abs(v_nir[seg, j] - ref_v[seg, j]) + if stops and nw_spike[end - 1, j]: + pre_reset = pre_reset[:-1] + v_dev = max(v_dev, float(pre_reset.max()) if pre_reset.size else 0.0) + else: + seg = slice(0, end - 1 if stops else T) # LIF state is recorded before the NIR reset + if seg.stop: + v_dev = max(v_dev, float(np.max(np.abs(v_nir[seg, j] - ref_v[seg, j])))) + both = [(a, b) for a, b in zip(f_nw, f_nir) if a is not None and b is not None] + return {'model': model, 'cells': k, 'steps': T, 'drive_max': c['parity_drive_max'], + 'synaptic_current_max_abs_difference': i_dev, 'membrane_max_abs_difference_before_first_spike': v_dev, + 'first_spike_step_neuroweave': f_nw, 'first_spike_step_nir': f_nir, + 'first_spike_agreement': (sum(1 for a, b in both if a == b) / len(both)) if both else None, + 'spike_rate_neuroweave': float(nw_spike.mean()), 'spike_rate_nir': float(nir_spike.mean())} + + +def _seed_run(seed: int, c: Mapping[str, Any], out_dir: Path) -> dict[str, Any]: + from ..neuroweave.brain import NeuroWeaveBrain + from ..neuroweave.experiments import make_spec + spec = make_spec(c['mechanisms'], seed=seed, neurons=c['neurons'], topology=c['topology'], + steps=max(4, c['warmup_steps'])) + brain = NeuroWeaveBrain(spec) + rng = np.random.default_rng(int(seed) + _INPUT_OFFSET) + for _ in range(c['warmup_steps']): + brain.step(rng.uniform(-1.0, 1.0, c['input_dim']) * c['input_scale']) + export = brain.export_state() + graph = brain_to_nir(export, input_dim=c['input_dim'], step_ms=c['step_ms']) + report = validate_graph(graph) + rt = write_nir(graph, out_dir / f'brain_seed{seed}.nir', backend=c['backend']) + back = read_nir(out_dir / f'brain_seed{seed}.nir') + srng = np.random.default_rng(int(seed) + _SIM_OFFSET) + X = srng.uniform(-1.0, 1.0, (c['simulate_steps'], c['input_dim'])) * c['input_scale'] + sim = simulate_graph(graph, X) + ref = brain.clone() # NEUROWEAVE on the same inputs, frozen (descriptive) + nw_spikes = 0 + for t in range(c['simulate_steps']): + ref.frozen_step(X[t]) + nw_spikes += int(np.count_nonzero(ref.cells.spike)) + recurrent_nodes = [nd for name, nd in graph['nodes'].items() if name.startswith('recurrent_')] + nnz = int(sum(np.count_nonzero(np.asarray(nd['params']['weight'])) for nd in recurrent_nodes)) + meta = graph['metadata'] + n = meta['source']['neurons'] + spikes = int(sum(sim['spike_counts'].values())) + return { + 'seed': int(seed), 'neurons': n, 'synapses': meta['source']['synapses'], + 'unique_src_dst_delay': meta['source']['unique_src_dst_delay'], + 'represented_synapses': meta['represented_synapses'], 'recurrent_nonzero_weights': nnz, + 'delay_classes_steps': meta['delay_classes_steps'], 'node_types': report['node_types'], + 'node_count': report['node_count'], 'edge_count': report['edge_count'], + 'validation': {'valid': report['valid'], 'errors': report['errors'], 'warnings': report['warnings']}, + 'round_trip': {k: rt[k] for k in ('format', 'round_trip_equal', 'node_count', 'edge_count', + 'read_node_count', 'read_edge_count')}, + 'reread_equal': graphs_equal(graph, back), + 'simulation': {'steps': sim['steps'], 'finite': sim['finite'], 'spikes': spikes, + 'spike_rate': spikes / float(sim['steps'] * n), + 'output_abs_sum': float(np.abs(sim['outputs']['output']).sum()), + 'neuroweave_spike_rate_same_input': nw_spikes / float(c['simulate_steps'] * n)}, + 'recurrent_parity': _recurrent_parity(brain, graph), + 'cell_parity': _cell_parity(graph, c, seed), + 'lossy_features': meta['lossy_features'], 'folded_features': meta['folded_features'], + 'cell_parameters': meta['cell_parameters'], + } + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Export small NEUROWEAVE brains, validate, round-trip through a file, simulate the exported graph. + + Checks (``kind='validation'``, ``verdict`` in ``('pass', 'fail')``) per seed: graph valid with known node + types; file round trip equal (real NIR file when the optional ``nir`` package imports, else the JSON fallback) + with node and edge counts preserved; the exported recurrent weights reproduce every synapse (non-zero entries + = unique src/dst/delay triples) and NEUROWEAVE's own recurrent drive on its output history; the exported cell + reproduces the fast channel exactly and the membrane up to the dropped adaptation current (isolated cells); + simulating the exported graph stays finite and spikes; lossy features are listed.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seeds(seeds) + cfg = dict(_DEFAULTS) + if quick: + cfg.update(_QUICK) + unknown = sorted(set(overrides) - set(cfg)) + if unknown: + raise ValueError(f'unknown run_experiment overrides: {unknown}') + cfg.update(overrides) + c = _validate_config(cfg) + from . import harness + t0 = time.perf_counter() + with tempfile.TemporaryDirectory(prefix='nir_export_') as tmp: + rows = [_seed_run(s, c, Path(tmp)) for s in seed_list] + tol = c['parity_tolerance'] + first = rows[0] + applicable = [r['recurrent_parity'] for r in rows if r['recurrent_parity']['applicable']] + checks = { + 'graph_valid': all(r['validation']['valid'] for r in rows), + 'node_types_known': all(set(r['node_types']) <= set(NIR_NODE_TYPES) for r in rows), + 'round_trip_equal': all(r['round_trip']['round_trip_equal'] and r['reread_equal'] for r in rows), + 'edge_and_node_counts_preserved': all(r['round_trip']['edge_count'] == r['round_trip']['read_edge_count'] + and r['round_trip']['node_count'] == r['round_trip']['read_node_count'] + for r in rows), + 'synapse_count_matches': all(r['recurrent_nonzero_weights'] == r['represented_synapses'] + and r['represented_synapses'] <= r['unique_src_dst_delay'] <= r['synapses'] + for r in rows), + 'recurrent_drive_parity': all(p['max_abs_difference'] <= tol for p in applicable), + 'synaptic_current_parity': all(r['cell_parity']['synaptic_current_max_abs_difference'] is None + or r['cell_parity']['synaptic_current_max_abs_difference'] <= tol + for r in rows), + 'membrane_parity_before_first_spike': all(r['cell_parity']['membrane_max_abs_difference_before_first_spike'] + <= tol for r in rows), + 'simulation_finite': all(r['simulation']['finite'] for r in rows), + 'simulation_active': all(r['simulation']['spikes'] > 0 for r in rows), + 'lossy_features_listed': all(any(f['feature'] == 'graded_output_transmission' for f in r['lossy_features']) + for r in rows), + } + receipt = harness.base_receipt(MODULE_ID, 'validation', {**c, 'quick': quick, 'seeds': list(seed_list)}) + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['nir_package'] = {k: v for k, v in nir_status().items() if k != 'error'} + receipt['file_format'] = first['round_trip']['format'] + receipt['per_seed'] = rows + receipt['lossy_features'] = first['lossy_features'] + receipt['folded_features'] = first['folded_features'] + receipt['summary'] = { + 'node_types': first['node_types'], 'neuron_model': next(iter(t for t in first['node_types'] + if t in NEURON_TYPES), None), + 'lossy_feature_count': len(first['lossy_features']), + 'max_recurrent_drive_difference': max((p['max_abs_difference'] for p in applicable), default=None), + 'recurrent_parity_applicable_seeds': len(applicable), + 'nir_spike_rate': [r['simulation']['spike_rate'] for r in rows], + 'neuroweave_spike_rate_same_input': [r['simulation']['neuroweave_spike_rate_same_input'] for r in rows], + 'first_spike_agreement': [r['cell_parity']['first_spike_agreement'] for r in rows], + } + if not applicable: + checks['recurrent_drive_parity'] = True # vacuous; recorded in the summary and per-seed rows + receipt['summary']['recurrent_parity_note'] = 'not applicable: state-dependent transmission gains enabled' + receipt['checks'] = checks + receipt['verdict'] = 'pass' if all(checks.values()) else 'fail' + receipt['verdict_basis'] = ('all_known_answer_checks' if receipt['verdict'] == 'pass' + else 'failed_checks: ' + ', '.join(k for k, ok in checks.items() if not ok)) + receipt['estimated_cost'] = { + 'neuroweave_brain_steps': int(len(seed_list) * (c['warmup_steps'] + c['simulate_steps'])), + 'graph_simulation_steps': int(len(seed_list) * c['simulate_steps']), + 'parity_cell_updates': int(len(seed_list) * c['parity_cells'] * c['parity_steps']), + 'files_written': len(seed_list)} + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0} + receipt['notes'] = ( + 'NIR-style export of a frozen NEUROWEAVE brain snapshot. Exact: linear input projection, recurrent synapse ' + 'table as Delay+Linear pairs per delay class (with static gains folded in), fast-channel synaptic current; ' + 'membrane exact up to the dropped adaptation current. Approximated or dropped: graded tanh transmission ' + '(edges carry spikes), direct feed-through, multiplicative reset, refractoriness, adaptive threshold, ' + 'calcium, plasticity rules and the listed mechanisms; the simulated spike rates of the exported graph and of ' + 'NEUROWEAVE are reported side by side and are not expected to agree. Real NIR files are written only when ' + 'the optional nir package imports (file_format says which). Not a claim of hardware deployment or of ' + 'equivalence with any NIR backend.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/quality_diversity.py b/synapse/frontier/quality_diversity.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd87238a9439590eba7d3b9bbd521c10d7d8da9 --- /dev/null +++ b/synapse/frontier/quality_diversity.py @@ -0,0 +1,1346 @@ +"""Quality-diversity architecture search over NEUROWEAVE configurations (frontier module ``quality_diversity``). + +Inspired by MAP-Elites -- Jean-Baptiste Mouret and Jeff Clune, "Illuminating search spaces by mapping elites", +arXiv:1504.04909, April 2015 -- by the parent selection of the Darwin Gödel Machine (DGM) -- Jenny Zhang, +Shengran Hu, Cong Lu, Robert Lange and Jeff Clune, arXiv:2505.22954, May 2025 (ICLR 2026 poster) -- and by the +sibling ``kai9987kai`` projects SONAPSE-ORIGIN (a 2-D MAP-Elites archive with mutation and crossover, an NSGA-II +Pareto front) and sonapse-evo (named structural operators with preconditions, a failure archive with reasons, +verify-before-commit transactions). This is a synthetic computational abstraction: it searches a small declared +space of NEUROWEAVE switches on tiny temporal tasks and reproduces none of those papers' systems or results. +Full, verified references: ``docs/frontier/modules/quality_diversity.md``. + +Search loop (MAP-Elites, paper Fig. 2, with a DGM-style parent distribution):: + + for t = 1 .. budget: + if t <= G or the archive is empty: x' <- random genome + else: a, b ~ Categorical(p) (two draws, with replacement); x' <- mutate(crossover(a, b) or a) + receipt <- evaluate(x') # NEUROWEAVE train run + frozen held-out runs, SHA-256 sealed + reasons <- verify(x', receipt) # + re-evaluation digest check on every k-th candidate + if reasons: log the rejection # the archive is unchanged + else: b' <- (bin of log2 estimated ops/step, bin of activity sparseness); q' <- (accuracy, -log loss) + if cell b' is empty or q' > q(elite[b']): elite[b'] <- x' + + s_i = 1 / (1 + exp(-lambda (f_i - f_0))) h_i = 1 / (1 + n_i) p_i = s_i h_i / sum_j s_j h_j + +``f_i`` is an elite's held-out accuracy and ``n_i`` its number of children that passed verification (DGM counts +children that kept codebase-editing functionality); as in DGM (arXiv v3, App. C.2) only elites with ``f_i < 1`` are +eligible, and -- our addition, which DGM does not define -- all elites are when every one is perfect. ``lambda = 10`` +and ``f_0 = 0.5`` are the DGM values. DGM samples ``k`` parents with replacement and each produces its own child; +here each iteration draws two parents with replacement and makes one child (the second parent is only a crossover +partner). Activity sparseness is Hoyer's (2004) measure ``(sqrt(n) - ||x||_1/||x||_2) / (sqrt(n) - 1)`` of each +held-out output vector, averaged over steps. QD-score (Pugh, Soros, Szerlip & Stanley, GECCO 2015; Pugh, Soros & +Stanley, 2016) is the total fitness over filled cells; reliability, precision and coverage follow Mouret & Clune +(2015, Sec. 5 and 9.4). The summary also lists the elites on the Pareto front of (fitness, estimated cost), the +sibling projects' multi-objective view of the same archive. + +All randomness comes from ``numpy.random.default_rng(seed + offset)``; the NEUROWEAVE runs are seeded by the +engine itself. Nothing here touches global NumPy/PyTorch random or thread state. +""" +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass, replace +import hashlib +import json +import math +import time +from typing import Any, Callable, Iterable, Mapping, Sequence + +import numpy as np + +from ..neuroweave.engine import NeuroWeaveEngine +from ..neuroweave.experiments import (ReadoutHead, _estimated_cost, _jsonable, _mean, _strip_wallclock, clone_engine, + make_spec, run_task_phase) +from ..neuroweave.spec import MECHANISM_IDS, TOPOLOGIES, NeuroWeaveSpecV1 +from ..neuroweave.tasks import TASKS as NEUROWEAVE_TASKS, make_stream +from . import harness +from .extension import EngineExtension +from .spec import EVIDENCE_TIER, LAB_SCHEMA + +__all__ = ['MODULE_ID', 'SOURCE', 'EXPERIMENTS', 'CANDIDATE_RECEIPT_ID', 'ARCHIVE_SCHEMA', 'SEARCH_MECHANISMS', + 'NEURON_CHOICES', 'SPARSITY_CHOICES', 'MUTATION_OPERATORS', 'REJECTION_REASONS', 'Genome', 'GenomeSpace', + 'ActivityRecorder', 'NeuroWeaveEvaluator', 'LandscapeEvaluator', 'EliteArchive', 'QualityDiversitySearch', + 'hoyer_sparseness', 'mutate', 'crossover', 'applicable_operators', 'dgm_parent_probabilities', + 'candidate_metrics', 'verify_candidate', 'illumination_metrics', 'pareto_front', 'run_experiment'] + +MODULE_ID = 'quality_diversity' +CANDIDATE_RECEIPT_ID = MODULE_ID + '_candidate' # experiment id inside per-candidate receipts (not registered) +ARCHIVE_SCHEMA = 'QualityDiversityArchiveV1' +SOURCE = ('SONAPSE-ORIGIN and sonapse-evo (kai9987kai); Mouret & Clune, "Illuminating search spaces by mapping ' + 'elites", arXiv:1504.04909, April 2015, https://arxiv.org/abs/1504.04909; Zhang, Hu, Lu, Lange & Clune, ' + '"Darwin Godel Machine: Open-Ended Evolution of Self-Improving Agents", arXiv:2505.22954, May 2025 ' + '(ICLR 2026), https://arxiv.org/abs/2505.22954') + +# A declared search set of ten NEUROWEAVE switches (canonical MECHANISM_IDS order). Five of them also change the +# engine's estimated operation count, so the compute-cost descriptor is not only a function of size and topology. +SEARCH_MECHANISMS: tuple[str, ...] = tuple(m for m in MECHANISM_IDS if m in { + 'structural_encoder', 'sparse_code', 'reward_plasticity', 'synaptic_delays', 'homeostatic_governor', + 'context_attention', 'flyhash_projection', 'adaptive_routing', 'hierarchical_temporal_memory', + 'membrane_dynamics'}) +NEURON_CHOICES: tuple[int, ...] = (16, 24, 32) +SPARSITY_CHOICES: tuple[float, ...] = (0.05, 0.15, 0.3, 0.5) # k-winners fraction; expressed with 'sparse_code' +MUTATION_OPERATORS = ('toggle_mechanism', 'swap_mechanism', 'change_topology', 'step_neurons', 'step_sparsity') +REJECTION_REASONS = ('evaluation_error', 'receipt_not_a_mapping', 'receipt_digest_mismatch', 'receipt_schema_mismatch', + 'genome_outside_space', 'genome_mismatch', 'protocol_mismatch', 'invalid_spec', 'spec_mismatch', + 'invalid_metrics', 'inconsistent_metrics', 'spot_check_error', 'spot_check_digest_mismatch') +ORIGINS = ('random', 'mutation', 'crossover') +STATUSES = ('elite', 'not_elite', 'rejected') +SELECTIONS = ('dgm', 'uniform') +METHODS = ('qd', 'random') +DESCRIPTOR_KEYS = ('log2_ops_per_step', 'activity_sparseness') +MAX_BUDGET = 10_000 +MAX_ARCHIVE_CHARS = 64 * 1024 * 1024 +_MAX_OPERATORS = 8 +_MAX_TEXT = 200 + +_INIT_OFFSET = 67_001 # random-genome stream (shared by both arms of a seed: common random numbers) +_VAR_OFFSET = 67_013 # parent selection / variation stream (QD arm only) + +_NODE_KEYS = frozenset({'id', 'genome', 'origin', 'parents', 'operators', 'status', 'reasons', 'error', 'cell', + 'fitness', 'log_loss', 'descriptors', 'digest', 'spot_checked', 'displaced_by'}) +_ELITE_KEYS = frozenset({'cell', 'id', 'genome', 'fitness', 'log_loss', 'descriptors', 'digest', 'receipt'}) +_REJECTION_KEYS = frozenset({'id', 'genome', 'reasons', 'error', 'digest'}) + + +# ====================================================================== validation helpers +def _int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _num(name: str, value: Any, low: float, high: float) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + if not math.isfinite(v) or not low <= v <= high: + raise ValueError(f'{name} must be a finite number in [{low}, {high}]') + return v + + +def _seq(name: str, value: Any) -> tuple: + if isinstance(value, (str, bytes)) or not isinstance(value, (list, tuple)): + raise ValueError(f'{name} must be a list or tuple') + return tuple(value) + + +def _seed_tuple(name: str, value: Any) -> tuple[int, ...]: + out = tuple(_int(name, s, 0, 2**31 - 1) for s in _seq(name, value)) + if not out or len(set(out)) != len(out): + raise ValueError(f'{name} must be non-empty and unique') + return out + + +def _rng(rng: Any) -> np.random.Generator: + if not isinstance(rng, np.random.Generator): + raise ValueError('rng must be a numpy.random.Generator') + return rng + + +def _canonical(obj: Any) -> str: + return json.dumps(obj, sort_keys=True, separators=(',', ':')) + + +def _sha256(obj: Any) -> str: + return hashlib.sha256(_canonical(obj).encode('utf-8')).hexdigest() + + +def _is_hex64(value: Any) -> bool: + return isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value) + + +# ====================================================================== genome and search space +@dataclass(frozen=True) +class Genome: + """One NEUROWEAVE configuration: a mechanism subset, a topology, a population size and a k-WTA fraction.""" + + mechanisms: tuple[str, ...] + topology: str + neurons: int + sparsity: float + + def __post_init__(self) -> None: + mechs = _seq('mechanisms', self.mechanisms) + if any(not isinstance(m, str) or m not in MECHANISM_IDS for m in mechs) or len(set(mechs)) != len(mechs): + raise ValueError('mechanisms must be unique NEUROWEAVE mechanism ids') + object.__setattr__(self, 'mechanisms', tuple(m for m in MECHANISM_IDS if m in set(mechs))) + if not isinstance(self.topology, str) or self.topology not in TOPOLOGIES: + raise ValueError(f'topology must be one of {TOPOLOGIES}') + object.__setattr__(self, 'neurons', _int('neurons', self.neurons, 8, 4096)) + object.__setattr__(self, 'sparsity', _num('sparsity', self.sparsity, 0.01, 1.0)) + + def to_dict(self) -> dict[str, Any]: + return {'mechanisms': list(self.mechanisms), 'topology': self.topology, 'neurons': self.neurons, + 'sparsity': self.sparsity} + + @classmethod + def from_dict(cls, data: Any) -> 'Genome': + if not isinstance(data, Mapping) or set(data) != {'mechanisms', 'topology', 'neurons', 'sparsity'}: + raise ValueError('genome must be a mapping with mechanisms, topology, neurons and sparsity') + return cls(tuple(_seq('mechanisms', data['mechanisms'])), data['topology'], data['neurons'], data['sparsity']) + + @property + def key(self) -> str: + """Canonical JSON identity (used for duplicate detection and lineage).""" + return _canonical(self.to_dict()) + + def to_spec(self, *, seed: int, steps: int) -> NeuroWeaveSpecV1: + """The lab spec (``experiments.make_spec``) with this genome's k-WTA fraction.""" + spec = make_spec(self.mechanisms, seed=int(seed), neurons=self.neurons, topology=self.topology, steps=int(steps)) + return replace(spec, sparsity=self.sparsity) + + +@dataclass(frozen=True) +class GenomeSpace: + """The declared search space. Choice lists are canonicalised (NEUROWEAVE order, ascending numbers).""" + + mechanisms: tuple[str, ...] = SEARCH_MECHANISMS + topologies: tuple[str, ...] = TOPOLOGIES + neurons: tuple[int, ...] = NEURON_CHOICES + sparsity: tuple[float, ...] = SPARSITY_CHOICES + + def __post_init__(self) -> None: + mechs = _seq('mechanisms', self.mechanisms) + if any(not isinstance(m, str) or m not in MECHANISM_IDS for m in mechs) or len(set(mechs)) != len(mechs): + raise ValueError('mechanisms must be unique NEUROWEAVE mechanism ids') + topos = _seq('topologies', self.topologies) + if not topos or any(not isinstance(t, str) or t not in TOPOLOGIES for t in topos) or len(set(topos)) != len(topos): + raise ValueError(f'topologies must be a non-empty unique subset of {TOPOLOGIES}') + neurons = tuple(_int('neurons', n, 8, 4096) for n in _seq('neurons', self.neurons)) + sparsity = tuple(_num('sparsity', s, 0.01, 1.0) for s in _seq('sparsity', self.sparsity)) + for name, vals in (('neurons', neurons), ('sparsity', sparsity)): + if not 1 <= len(vals) <= 64 or len(set(vals)) != len(vals): + raise ValueError(f'{name} must hold 1 to 64 unique values') + object.__setattr__(self, 'mechanisms', tuple(m for m in MECHANISM_IDS if m in set(mechs))) + object.__setattr__(self, 'topologies', tuple(t for t in TOPOLOGIES if t in set(topos))) + object.__setattr__(self, 'neurons', tuple(sorted(neurons))) + object.__setattr__(self, 'sparsity', tuple(sorted(sparsity))) + if self.size < 2: + raise ValueError('the search space must contain at least two genomes') + + @property + def size(self) -> int: + return 2 ** len(self.mechanisms) * len(self.topologies) * len(self.neurons) * len(self.sparsity) + + def contains(self, genome: Any) -> bool: + return (isinstance(genome, Genome) and set(genome.mechanisms) <= set(self.mechanisms) + and genome.topology in self.topologies and genome.neurons in self.neurons + and genome.sparsity in self.sparsity) + + def random_genome(self, rng: np.random.Generator) -> Genome: + """Uniform over the space: each mechanism on with probability 1/2, every other gene uniform.""" + rng = _rng(rng) + on = rng.random(len(self.mechanisms)) < 0.5 + return Genome(tuple(m for m, b in zip(self.mechanisms, on) if b), + self.topologies[int(rng.integers(len(self.topologies)))], + self.neurons[int(rng.integers(len(self.neurons)))], + self.sparsity[int(rng.integers(len(self.sparsity)))]) + + def to_dict(self) -> dict[str, Any]: + return {'mechanisms': list(self.mechanisms), 'topologies': list(self.topologies), + 'neurons': list(self.neurons), 'sparsity': list(self.sparsity)} + + @classmethod + def from_dict(cls, data: Any) -> 'GenomeSpace': + if not isinstance(data, Mapping) or set(data) != {'mechanisms', 'topologies', 'neurons', 'sparsity'}: + raise ValueError('genome space must be a mapping with mechanisms, topologies, neurons and sparsity') + return cls(*(tuple(_seq(k, data[k])) for k in ('mechanisms', 'topologies', 'neurons', 'sparsity'))) + + +# ====================================================================== variation operators (sonapse-evo style) +def _check_in_space(genome: Any, space: Any) -> None: + if not isinstance(space, GenomeSpace): + raise ValueError('space must be a GenomeSpace') + if not space.contains(genome): + raise ValueError('genome must be a Genome inside the search space') + + +def applicable_operators(genome: Genome, space: GenomeSpace) -> tuple[str, ...]: + """Operators whose preconditions hold; every listed operator always changes the genome.""" + _check_in_space(genome, space) + on = len(genome.mechanisms) + ok = {'toggle_mechanism': len(space.mechanisms) >= 1, + 'swap_mechanism': 1 <= on < len(space.mechanisms), + 'change_topology': len(space.topologies) >= 2, + 'step_neurons': len(space.neurons) >= 2, + 'step_sparsity': len(space.sparsity) >= 2} + return tuple(op for op in MUTATION_OPERATORS if ok[op]) + + +def _step(values: tuple, current: Any, rng: np.random.Generator) -> Any: + i = values.index(current) + moves = [j for j in (i - 1, i + 1) if 0 <= j < len(values)] + return values[moves[int(rng.integers(len(moves)))]] + + +def _apply(op: str, g: Genome, space: GenomeSpace, rng: np.random.Generator) -> tuple[Genome, str]: + if op == 'toggle_mechanism': + m = space.mechanisms[int(rng.integers(len(space.mechanisms)))] + if m in g.mechanisms: + return replace(g, mechanisms=tuple(x for x in g.mechanisms if x != m)), f'toggle_mechanism:-{m}' + return replace(g, mechanisms=g.mechanisms + (m,)), f'toggle_mechanism:+{m}' + if op == 'swap_mechanism': + off = tuple(m for m in space.mechanisms if m not in g.mechanisms) + out_m = g.mechanisms[int(rng.integers(len(g.mechanisms)))] + in_m = off[int(rng.integers(len(off)))] + return (replace(g, mechanisms=tuple(x for x in g.mechanisms if x != out_m) + (in_m,)), + f'swap_mechanism:-{out_m}+{in_m}') + if op == 'change_topology': + others = tuple(t for t in space.topologies if t != g.topology) + t = others[int(rng.integers(len(others)))] + return replace(g, topology=t), f'change_topology:{g.topology}->{t}' + if op == 'step_neurons': + n = _step(space.neurons, g.neurons, rng) + return replace(g, neurons=n), f'step_neurons:{g.neurons}->{n}' + s = _step(space.sparsity, g.sparsity, rng) + return replace(g, sparsity=s), f'step_sparsity:{g.sparsity}->{s}' + + +def mutate(genome: Genome, space: GenomeSpace, rng: np.random.Generator, *, extra_prob: float = 0.25, + max_operators: int = 3) -> tuple[Genome, tuple[str, ...]]: + """Apply one uniformly chosen applicable operator, then each further one with probability ``extra_prob`` + (at most ``max_operators``). The child always differs from ``genome``; the audit trail is returned.""" + _check_in_space(genome, space) + rng = _rng(rng) + extra_prob = _num('extra_prob', extra_prob, 0.0, 0.95) + max_operators = _int('max_operators', max_operators, 1, _MAX_OPERATORS - 2) + count = 1 + while count < max_operators and rng.random() < extra_prob: + count += 1 + g, trail = genome, [] + for _ in range(count): + ops = applicable_operators(g, space) + g, detail = _apply(ops[int(rng.integers(len(ops)))], g, space, rng) + trail.append(detail) + if g == genome: # e.g. the same mechanism toggled twice: one more change + ops = applicable_operators(g, space) + g, detail = _apply(ops[int(rng.integers(len(ops)))], g, space, rng) + trail.append(detail) + return g, tuple(trail) + + +def crossover(a: Genome, b: Genome, space: GenomeSpace, rng: np.random.Generator) -> Genome: + """Uniform crossover: each mechanism's membership and each other gene comes from either parent (p = 1/2).""" + _check_in_space(a, space) + _check_in_space(b, space) + rng = _rng(rng) + pick = rng.random(len(space.mechanisms) + 3) < 0.5 + mechs = tuple(m for i, m in enumerate(space.mechanisms) if m in (a.mechanisms if pick[i] else b.mechanisms)) + k = len(space.mechanisms) + return Genome(mechs, a.topology if pick[k] else b.topology, a.neurons if pick[k + 1] else b.neurons, + a.sparsity if pick[k + 2] else b.sparsity) + + +def dgm_parent_probabilities(fitness: Sequence[float], children: Sequence[int], *, sharpness: float = 10.0, + midpoint: float = 0.5) -> np.ndarray: + """DGM parent distribution (Zhang et al., 2025, arXiv v3 App. C.2): ``p_i ∝ sigmoid(sharpness (f_i - midpoint)) + / (1 + n_i)`` over elites with ``f_i < 1`` (our fallback: all elites when every one has ``f_i = 1``).""" + f = np.asarray(fitness, dtype=np.float64) + n = np.asarray(children) + if f.ndim != 1 or f.size == 0 or n.shape != f.shape: + raise ValueError('fitness and children must be equal-length non-empty 1-D sequences') + if not np.all(np.isfinite(f)) or np.any(f < 0.0) or np.any(f > 1.0): + raise ValueError('fitness values must be finite and in [0, 1]') + if n.dtype.kind not in 'iu' or np.any(n < 0): + raise ValueError('children must be non-negative integers') + sharpness = _num('sharpness', sharpness, 0.0, 100.0) + midpoint = _num('midpoint', midpoint, 0.0, 1.0) + s = 1.0 / (1.0 + np.exp(-sharpness * (f - midpoint))) # |exponent| <= 100: no overflow, s > 0 + w = s / (1.0 + n.astype(np.float64)) + eligible = f < 1.0 + if not eligible.any(): + eligible[:] = True + w = np.where(eligible, w, 0.0) + return w / w.sum() + + +# ====================================================================== activity sparseness +def hoyer_sparseness(x: Any) -> float | None: + """Hoyer (2004) sparseness of a vector, in [0, 1]: 1 for one non-zero entry, 0 when all magnitudes are equal. + Returns ``None`` for the all-zero vector, where the measure is undefined.""" + a = np.abs(np.asarray(x, dtype=np.float64)).ravel() + if a.size < 2 or not np.all(np.isfinite(a)): + raise ValueError('x must hold at least two finite values') + peak = float(a.max()) + if peak == 0.0: + return None + b = a / peak # scale first: no underflow in the squares + n = a.size + v = (math.sqrt(n) - float(b.sum()) / math.sqrt(float(b @ b))) / (math.sqrt(n) - 1.0) + return float(min(1.0, max(0.0, v))) + + +class ActivityRecorder(EngineExtension): + """Read-only engine extension: running mean of the Hoyer sparseness of the engine output. + + It adds no readout features and leaves the drive untouched (the neutral base hooks), so an engine's + trajectory is identical with and without it (tested). All-zero (silent) steps are counted separately. + It keeps counting during frozen (``learn=False``) runs, where it is used: these are measurements that never + feed back into the engine or the readout, so frozen evaluation is unaffected. ``reset()`` keeps the counts.""" + + id = 'qd_activity_recorder' + feature_dim = 0 + + def __init__(self) -> None: + self._sum = 0.0 + self._scored = 0 + self._silent = 0 + + def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None: + h = hoyer_sparseness(output) + if h is None: + self._silent += 1 + else: + self._sum += h + self._scored += 1 + + def state_numbers(self) -> int: + return 3 + + def stats(self) -> dict[str, Any]: + return {'hoyer_sum': self._sum, 'scored_steps': self._scored, 'silent_steps': self._silent} + + @staticmethod + def combine(recorders: Iterable['ActivityRecorder']) -> dict[str, Any]: + """Pooled mean over every scored step; a run whose steps were all silent counts as fully sparse (1.0).""" + total, scored, silent = 0.0, 0, 0 + for r in recorders: + total += r._sum + scored += r._scored + silent += r._silent + return {'hoyer_sparseness': float(total / scored) if scored else 1.0, 'scored_steps': scored, + 'silent_steps': silent} + + def telemetry(self) -> dict[str, Any]: + return {'id': self.id, **self.stats()} + + def export_state(self) -> dict[str, Any]: + return {'id': self.id, **self.stats()} + + def import_state(self, state: Mapping[str, Any]) -> None: + super().import_state(state) + if set(state) != {'id', 'hoyer_sum', 'scored_steps', 'silent_steps'}: + raise ValueError('activity recorder state has unexpected keys') + scored = _int('scored_steps', state['scored_steps'], 0, 2**62) + silent = _int('silent_steps', state['silent_steps'], 0, 2**62) + total = _num('hoyer_sum', state['hoyer_sum'], 0.0, float(scored)) + self._sum, self._scored, self._silent = total, scored, silent + + +# ====================================================================== candidate receipts and verification +def _candidate_receipt(genome: Genome, spec: NeuroWeaveSpecV1, *, seed: int, protocol: Mapping[str, Any], + train: Mapping[str, Any], heldout: Mapping[str, Any], estimated_cost: Mapping[str, Any], + activity: Mapping[str, Any], budget: Mapping[str, Any] | None, + wallclock: Mapping[str, float]) -> dict[str, Any]: + steps = int(protocol['steps']) + ops = float(estimated_cost['total_ops']) + if not ops > 0.0: + raise ValueError('estimated total_ops must be positive') + receipt = harness.base_receipt(CANDIDATE_RECEIPT_ID, 'candidate_evaluation', { + 'genome': genome.to_dict(), 'seed': int(seed), 'spec': spec.to_dict(), 'protocol': dict(protocol)}) + receipt['module'] = MODULE_ID + receipt['train'] = dict(train) + receipt['heldout'] = dict(heldout) + receipt['activity'] = dict(activity) + receipt['estimated_cost'] = dict(estimated_cost) + receipt['budget'] = None if budget is None else dict(budget) + receipt['fitness'] = heldout['accuracy'] + receipt['descriptors'] = {'log2_ops_per_step': math.log2(ops / steps), + 'activity_sparseness': activity['hoyer_sparseness']} + receipt['measured_wallclock_s'] = dict(wallclock) + return harness.seal(receipt) + + +def candidate_metrics(receipt: Mapping[str, Any]) -> dict[str, float]: + """Fitness, tie-break and descriptors recomputed from a candidate receipt's raw fields (``ValueError`` if + a field is missing or out of range). Fitness is held-out accuracy; lower held-out log loss breaks ties.""" + try: + steps = receipt['config']['protocol']['steps'] + acc = receipt['heldout']['accuracy'] + loss = receipt['heldout']['log_loss'] + ops = receipt['estimated_cost']['total_ops'] + sparse = receipt['activity']['hoyer_sparseness'] + except (KeyError, TypeError) as exc: + raise ValueError('candidate receipt is missing metric fields') from exc + steps = _int('protocol steps', steps, 1, 10_000_000) + acc = _num('heldout accuracy', acc, 0.0, 1.0) + loss = _num('heldout log_loss', loss, 0.0, 1e6) + ops = _num('estimated total_ops', ops, 0.0, 1e18) + sparse = _num('activity sparseness', sparse, 0.0, 1.0) + if not ops > 0.0: + raise ValueError('estimated total_ops must be positive') + return {'fitness': acc, 'log_loss': loss, 'log2_ops_per_step': math.log2(ops / steps), 'activity_sparseness': sparse} + + +def verify_candidate(genome: Genome, receipt: Any, *, seed: int, protocol: Mapping[str, Any], + space: GenomeSpace) -> list[str]: + """Static admission checks; returns the failed reason codes (empty = verified). It never raises for a bad + receipt: the seal, schema, genome, protocol, spec (valid *and* equal to the spec the genome implies) and + metric consistency are all checked against what the search asked for, not against the receipt itself. + Bad *arguments* (``seed``, ``protocol`` without an int ``steps``, ``space``) raise ``ValueError``.""" + seed = _int('seed', seed, 0, 2**31 - 1) + if not isinstance(protocol, Mapping) or type(protocol.get('steps')) is not int: + raise ValueError('protocol must be a mapping with an int steps') + if not isinstance(space, GenomeSpace): + raise ValueError('space must be a GenomeSpace') + if not isinstance(receipt, Mapping): + return ['receipt_not_a_mapping'] + reasons: list[str] = [] + if not harness.verify_receipt(receipt): + reasons.append('receipt_digest_mismatch') + if (receipt.get('schema') != LAB_SCHEMA or receipt.get('experiment_id') != CANDIDATE_RECEIPT_ID + or receipt.get('kind') != 'candidate_evaluation' or receipt.get('evidence_tier') != EVIDENCE_TIER + or receipt.get('module') != MODULE_ID): + reasons.append('receipt_schema_mismatch') + if not space.contains(genome): + reasons.append('genome_outside_space') + cfg = receipt.get('config') + cfg = cfg if isinstance(cfg, Mapping) else {} + if not isinstance(genome, Genome) or cfg.get('genome') != genome.to_dict(): + reasons.append('genome_mismatch') + if cfg.get('protocol') != _jsonable(dict(protocol)) or cfg.get('seed') != seed: + reasons.append('protocol_mismatch') + try: + spec = NeuroWeaveSpecV1.from_dict(cfg.get('spec')) + except (ValueError, TypeError): + reasons.append('invalid_spec') + else: + if not isinstance(genome, Genome) or spec != genome.to_spec(seed=seed, steps=int(protocol['steps'])): + reasons.append('spec_mismatch') + try: + m = candidate_metrics(receipt) + except ValueError: + reasons.append('invalid_metrics') + else: + if (receipt.get('fitness') != m['fitness'] or receipt.get('descriptors') != + {'log2_ops_per_step': m['log2_ops_per_step'], 'activity_sparseness': m['activity_sparseness']}): + reasons.append('inconsistent_metrics') + return reasons + + +# ====================================================================== evaluators +def _engine_budget(engine: NeuroWeaveEngine, head: ReadoutHead) -> dict[str, int]: + """``experiments._budget`` without its ``state_numbers`` count (a full state export per candidate).""" + f = engine.flags + syn = engine.brain.synapses + micro = int(engine.micro.parameter_count) if 'micro_collective' in f else 0 + graft = int(sum(w.size for w in engine.graft._weights())) if engine.graft is not None else 0 + return {'neurons': int(engine.n), 'synapses': int(syn.size), + 'trainable_parameters': int(syn.size) + int(head.parameter_count) + micro + graft, + 'micro_parameters': micro, 'graft_parameters': graft} + + +class NeuroWeaveEvaluator: + """Fitness of a genome on a NEUROWEAVE temporal task, following ``experiments._task_arm``'s protocol. + + Train: a fresh engine from ``genome.to_spec(seed, steps)`` and a fresh ``ReadoutHead`` run prequentially on + ``make_stream(seed, steps)``. Held out: for each held-out seed, the trained engine (a validated clone for all + but the last stream) and a copy of the head run frozen (``learn=False``) on ``make_stream(h, heldout_steps)``, + with an :class:`ActivityRecorder` attached. Fitness = mean held-out accuracy. With ``sparsity = 0.15`` (the + spec default) the metrics and estimated cost equal ``_task_arm``'s exactly (tested); the recorder does not + change the trajectory (tested). The k-WTA ``sparsity`` gene only acts when ``sparse_code`` is on.""" + + def __init__(self, *, task: str = 'delayed_recall', steps: int = 48, heldout_seeds: Sequence[int] = (100, 101), + heldout_steps: int = 24) -> None: + if task not in NEUROWEAVE_TASKS: + raise ValueError(f'task must be one of {NEUROWEAVE_TASKS}') + self.task = task + self.steps = _int('steps', steps, 4, 100_000) + self.heldout_seeds = _seed_tuple('heldout_seeds', heldout_seeds) + self.heldout_steps = _int('heldout_steps', heldout_steps, 1, 100_000) + + def protocol(self, heldout_seeds: Sequence[int] | None = None) -> dict[str, Any]: + held = self.heldout_seeds if heldout_seeds is None else heldout_seeds + return {'kind': 'neuroweave_temporal_task', 'task': self.task, 'steps': self.steps, + 'heldout_seeds': list(held), 'heldout_steps': self.heldout_steps, + 'readout': 'experiments.ReadoutHead (logistic, lr 0.05), frozen held-out evaluation on clones', + 'activity': 'Hoyer sparseness of held-out outputs (ActivityRecorder)'} + + def __call__(self, genome: Genome, seed: int) -> dict[str, Any]: + return self.evaluate(genome, seed) + + def evaluate(self, genome: Genome, seed: int, *, heldout_seeds: Sequence[int] | None = None) -> dict[str, Any]: + if not isinstance(genome, Genome): + raise ValueError('genome must be a Genome') + seed = _int('seed', seed, 0, 2**31 - 1) + held = self.heldout_seeds if heldout_seeds is None else _seed_tuple('heldout_seeds', heldout_seeds) + if seed in held: + raise ValueError('the training seed must not be a held-out seed') + spec = genome.to_spec(seed=seed, steps=self.steps) + engine = NeuroWeaveEngine(spec) + head = ReadoutHead(engine.n, seed) + stream = make_stream(seed, self.steps) + t0 = time.perf_counter() + train = run_task_phase(engine, {self.task: head}, stream, learn=True) + cost = _estimated_cost(engine, self.steps, head.dim) # training steps only (before any held-out step) + budget = _engine_budget(engine, head) + t1 = time.perf_counter() + runs, recorders = [], [] + for k, h in enumerate(held): + # Every held-out stream starts from the trained state: earlier streams run on validated clones, the + # last one on the trained engine itself (it is not used again; equal to a clone's run, tested). + target = engine if k == len(held) - 1 else clone_engine(engine) + recorder = ActivityRecorder() + target.attach_extension(recorder) + runs.append(run_task_phase(target, {self.task: head.copy()}, make_stream(h, self.heldout_steps), + learn=False)) + recorders.append(recorder) + t2 = time.perf_counter() + keys = ('accuracy', 'log_loss', 'brier', 'chance_accuracy') + tm = train['tasks'][self.task] + heldout = {k: _mean(r['tasks'][self.task][k] for r in runs) for k in keys} + return _candidate_receipt( + genome, spec, seed=seed, protocol=self.protocol(held), train={k: tm[k] for k in keys}, heldout=heldout, + estimated_cost=cost, activity=ActivityRecorder.combine(recorders), budget=budget, + wallclock={'train': t1 - t0, 'heldout': t2 - t1}) + + +class LandscapeEvaluator: + """Deterministic synthetic evaluator with a known answer (no NEUROWEAVE run), for tests and dry runs. + + Fitness is the fraction of genes equal to a hidden ``target`` genome (each search-set mechanism's membership, + topology, neurons, sparsity), so ``target`` is the unique optimum with fitness 1. Analytic descriptors: + ``ops/step = 16 * neurons * (4 + #mechanisms)``; activity sparseness ``1 - sparsity`` with ``sparse_code`` + and ``0.05`` without. Log loss ``0.75 - 0.5 * fitness + 0.01 * u(genome)`` (``u`` from the genome hash) gives + deterministic tie-breaks.""" + + def __init__(self, target: Genome, space: GenomeSpace, *, steps: int = 16) -> None: + if not isinstance(space, GenomeSpace) or not space.contains(target): + raise ValueError('target must be a Genome inside the GenomeSpace') + self.target, self.space = target, space + self.steps = _int('steps', steps, 4, 100_000) + + def protocol(self) -> dict[str, Any]: + return {'kind': 'synthetic_landscape', 'target': self.target.to_dict(), 'space': self.space.to_dict(), + 'steps': self.steps} + + def fitness(self, genome: Genome) -> float: + _check_in_space(genome, self.space) + t = self.target + matches = sum((m in genome.mechanisms) == (m in t.mechanisms) for m in self.space.mechanisms) + matches += (genome.topology == t.topology) + (genome.neurons == t.neurons) + (genome.sparsity == t.sparsity) + return matches / (len(self.space.mechanisms) + 3) + + def __call__(self, genome: Genome, seed: int) -> dict[str, Any]: + seed = _int('seed', seed, 0, 2**31 - 1) + f = self.fitness(genome) + u = int(hashlib.sha256(genome.key.encode('utf-8')).hexdigest()[:8], 16) / 2**32 + sparse = 1.0 - genome.sparsity if 'sparse_code' in genome.mechanisms else 0.05 + ops = 16 * genome.neurons * (4 + len(genome.mechanisms)) * self.steps + heldout = {'accuracy': f, 'log_loss': 0.75 - 0.5 * f + 0.01 * u, 'brier': None, 'chance_accuracy': 0.5} + return _candidate_receipt(genome, genome.to_spec(seed=seed, steps=self.steps), seed=seed, + protocol=self.protocol(), train=dict(heldout), heldout=heldout, + estimated_cost={'total_ops': ops}, + activity={'hoyer_sparseness': sparse, 'scored_steps': self.steps, 'silent_steps': 0}, + budget=None, wallclock={'total': 0.0}) + + +# ====================================================================== the archive (grid + lineage + failures) +def _quality(entry: Mapping[str, Any]) -> tuple[float, float]: + return (float(entry['fitness']), -float(entry['log_loss'])) + + +def _bin(value: float, lo: float, hi: float, bins: int) -> int: + return int(min(bins - 1, max(0, math.floor((value - lo) / (hi - lo) * bins)))) + + +def pareto_front(points: Any) -> list[int]: + """Indices of the non-dominated rows of ``points`` (every column maximised), in input order. + + Row ``a`` dominates row ``b`` when ``a >= b`` everywhere and ``a > b`` somewhere, so equal rows never + dominate each other and all stay on the front (the sonapse-evo / NSGA-II first front, without ranking).""" + p = np.asarray(points, dtype=np.float64) + if p.ndim != 2 or p.shape[0] == 0 or p.shape[1] == 0 or not np.all(np.isfinite(p)): + raise ValueError('points must be a non-empty finite 2-D array') + front = [] + for i in range(p.shape[0]): + dominated = np.any(np.all(p >= p[i], axis=1) & np.any(p > p[i], axis=1)) + if not dominated: + front.append(i) + return front + + +class EliteArchive: + """MAP-Elites grid over (log2 estimated ops per training step, activity sparseness), plus the lineage DAG of + every evaluated candidate and a log of rejected candidates with reasons. + + Invariant (checked again on import by replaying the lineage): each cell holds the verified candidate with the + highest ``(fitness, -log_loss)`` among all verified candidates that mapped to it; on an exact tie the earlier + one stays. Buffers are bounded by ``max_nodes`` (the evaluation budget).""" + + def __init__(self, *, cost_bins: int = 4, cost_range: Sequence[float] = (9.75, 11.75), activity_bins: int = 4, + activity_range: Sequence[float] = (0.0, 0.8), max_nodes: int = MAX_BUDGET) -> None: + self.cost_bins = _int('cost_bins', cost_bins, 1, 64) + self.activity_bins = _int('activity_bins', activity_bins, 1, 64) + self.cost_range = self._range('cost_range', cost_range, 0.0, 64.0) + self.activity_range = self._range('activity_range', activity_range, 0.0, 1.0) + self.max_nodes = _int('max_nodes', max_nodes, 1, MAX_BUDGET) + self._grid: dict[tuple[int, int], dict[str, Any]] = {} + self._lineage: list[dict[str, Any]] = [] + self._rejections: list[dict[str, Any]] = [] + self._children: dict[int, int] = {} + + @staticmethod + def _range(name: str, value: Any, low: float, high: float) -> tuple[float, float]: + v = _seq(name, value) + if len(v) != 2: + raise ValueError(f'{name} must be (lo, hi)') + lo, hi = _num(name, v[0], low, high), _num(name, v[1], low, high) + if not lo < hi: + raise ValueError(f'{name} must satisfy lo < hi') + return lo, hi + + # ------------------------------------------------------------------ geometry and metrics + def grid_config(self) -> dict[str, Any]: + return {'cost_bins': self.cost_bins, 'cost_range': list(self.cost_range), 'activity_bins': self.activity_bins, + 'activity_range': list(self.activity_range), 'max_nodes': self.max_nodes} + + @property + def total_cells(self) -> int: + return self.cost_bins * self.activity_bins + + def cell_of(self, descriptors: Mapping[str, Any]) -> tuple[int, int]: + """Grid cell of ``{'log2_ops_per_step', 'activity_sparseness'}`` (out-of-range values join the edge bins).""" + if not isinstance(descriptors, Mapping) or set(descriptors) != set(DESCRIPTOR_KEYS): + raise ValueError(f'descriptors must be a mapping with keys {DESCRIPTOR_KEYS}') + c = _num('log2_ops_per_step', descriptors['log2_ops_per_step'], -1e9, 1e9) + a = _num('activity_sparseness', descriptors['activity_sparseness'], 0.0, 1.0) + return (_bin(c, *self.cost_range, self.cost_bins), _bin(a, *self.activity_range, self.activity_bins)) + + @property + def evaluations(self) -> int: + return len(self._lineage) + + def __len__(self) -> int: + return len(self._grid) + + def coverage(self) -> float: + return len(self._grid) / self.total_cells + + def qd_score(self) -> float: + """Pugh, Soros & Stanley (2016): sum of elite fitness over filled cells (empty cells count 0).""" + return float(sum(e['fitness'] for e in self._grid.values())) + + def elites(self) -> list[dict[str, Any]]: + """Current elites sorted by cell (copies, without the stored receipts).""" + return [{k: _copy(v) for k, v in self._grid[c].items() if k != 'receipt'} for c in sorted(self._grid)] + + def elite_receipt(self, cell: Sequence[int]) -> dict[str, Any]: + key = tuple(int(x) for x in cell) + if key not in self._grid: + raise KeyError(key) + return _copy(self._grid[key]['receipt']) + + def best(self) -> dict[str, Any] | None: + """Highest ``(fitness, -log_loss)`` elite; ties go to the earliest candidate.""" + if not self._grid: + return None + e = max(self._grid.values(), key=lambda x: (_quality(x), -x['id'])) + return {k: _copy(v) for k, v in e.items() if k != 'receipt'} + + def pareto_front(self) -> list[dict[str, Any]]: + """Elites not dominated in (higher fitness, lower log2 estimated ops per step), cheapest first.""" + elites = self.elites() + if not elites: + return [] + idx = pareto_front([[e['fitness'], -e['descriptors']['log2_ops_per_step']] for e in elites]) + rows = [{'id': elites[i]['id'], 'cell': elites[i]['cell'], 'fitness': elites[i]['fitness'], + 'log2_ops_per_step': elites[i]['descriptors']['log2_ops_per_step']} for i in idx] + return sorted(rows, key=lambda r: (r['log2_ops_per_step'], r['id'])) + + def children_count(self, node_id: int) -> int: + return self._children.get(int(node_id), 0) + + def lineage(self) -> list[dict[str, Any]]: + return _copy(self._lineage) + + def rejections(self) -> list[dict[str, Any]]: + return _copy(self._rejections) + + # ------------------------------------------------------------------ admission transaction + def record(self, *, genome: Genome, origin: str, parents: Sequence[int], operators: Sequence[str], + receipt: Any, reasons: Sequence[str], spot_checked: bool, error: str | None = None) -> dict[str, Any]: + """Log one evaluated candidate and admit it when it passed verification and beats its cell's elite. + + Every argument is checked before anything changes; a candidate with ``reasons`` is logged as rejected + and leaves the grid untouched. Returns the new lineage node.""" + if len(self._lineage) >= self.max_nodes: + raise ValueError('the archive is full (max_nodes candidates recorded)') + if not isinstance(genome, Genome): + raise ValueError('genome must be a Genome') + if origin not in ORIGINS: + raise ValueError(f'origin must be one of {ORIGINS}') + parents = tuple(_int('parent', p, 0, MAX_BUDGET) for p in _seq('parents', parents)) + expected = {'random': 0, 'mutation': 1, 'crossover': 2}[origin] + if len(parents) != expected or len(set(parents)) != len(parents): + raise ValueError(f'{origin} candidates need {expected} distinct parents') + current = {e['id'] for e in self._grid.values()} + if any(p not in current for p in parents): + raise ValueError('parents must be current elites') + operators = tuple(_seq('operators', operators)) + if len(operators) > _MAX_OPERATORS or any(not isinstance(o, str) or not 0 < len(o) <= 96 for o in operators): + raise ValueError(f'operators must be at most {_MAX_OPERATORS} short strings') + reasons = list(dict.fromkeys(_seq('reasons', reasons))) + if any(r not in REJECTION_REASONS for r in reasons): + raise ValueError(f'reasons must come from {REJECTION_REASONS}') + if type(spot_checked) is not bool: + raise ValueError('spot_checked must be a boolean') + if error is not None and not isinstance(error, str): + raise ValueError('error must be a string or None') + node_id = len(self._lineage) + digest = receipt.get('digest') if isinstance(receipt, Mapping) else None + node: dict[str, Any] = { + 'id': node_id, 'genome': genome.to_dict(), 'origin': origin, 'parents': list(parents), + 'operators': list(operators), 'status': 'rejected', 'reasons': reasons, + 'error': None if error is None else error[:_MAX_TEXT], 'cell': None, 'fitness': None, 'log_loss': None, + 'descriptors': None, 'digest': digest if _is_hex64(digest) else None, 'spot_checked': spot_checked, + 'displaced_by': None} + if reasons: + self._lineage.append(node) + self._rejections.append({k: _copy(node[k]) for k in ('id', 'genome', 'reasons', 'error', 'digest')}) + return _copy(node) + if not harness.verify_receipt(receipt): + raise ValueError('a candidate without rejection reasons must carry a verifying receipt') + m = candidate_metrics(receipt) + descriptors = {k: m[k] for k in DESCRIPTOR_KEYS} + cell = self.cell_of(descriptors) + incumbent = self._grid.get(cell) + better = incumbent is None or _quality(m) > _quality(incumbent) + stored = _strip_wallclock(receipt) # wall-clock is outside the digest: keeps exports deterministic + stored['digest'] = receipt['digest'] + node.update({'status': 'elite' if better else 'not_elite', 'cell': list(cell), 'fitness': m['fitness'], + 'log_loss': m['log_loss'], 'descriptors': descriptors}) + # ---- commit (nothing above has changed the archive) + self._lineage.append(node) + for p in parents: + self._children[p] = self._children.get(p, 0) + 1 + if better: + if incumbent is not None: + self._lineage[incumbent['id']]['displaced_by'] = node_id + self._grid[cell] = {'cell': list(cell), 'id': node_id, 'genome': genome.to_dict(), 'fitness': m['fitness'], + 'log_loss': m['log_loss'], 'descriptors': dict(descriptors), 'digest': node['digest'], + 'receipt': stored} + return _copy(node) + + # ------------------------------------------------------------------ persistence + def _payload(self) -> dict[str, Any]: + return {'grid': self.grid_config(), + 'elites': [_copy(self._grid[c]) for c in sorted(self._grid)], + 'lineage': _copy(self._lineage), 'rejections': _copy(self._rejections)} + + @property + def sha256(self) -> str: + """SHA-256 of the canonical archive payload (the integrity hash written by :meth:`export_json`).""" + return _sha256(self._payload()) + + def export_json(self) -> str: + payload = self._payload() + return _canonical({'schema': ARCHIVE_SCHEMA, 'schema_version': 1, 'sha256': _sha256(payload), + 'payload': payload}) + + @classmethod + def from_json(cls, text: str) -> 'EliteArchive': + grid = _parse_archive(text)['grid'] + archive = cls(cost_bins=grid['cost_bins'], cost_range=grid['cost_range'], activity_bins=grid['activity_bins'], + activity_range=grid['activity_range'], max_nodes=grid['max_nodes']) + archive.import_json(text) + return archive + + def import_json(self, text: str) -> None: + """Replace this archive's contents with a validated export. Everything is checked first -- the SHA-256 + integrity hash, the schema, every elite receipt's seal and metrics, and a full replay of the lineage that + must reproduce each node's status, the grid and the rejection log -- and nothing changes on failure.""" + payload = _parse_archive(text) + if payload['grid'] != self.grid_config(): + raise ValueError('archive grid configuration does not match this archive') + lineage = payload['lineage'] + if not isinstance(lineage, list) or len(lineage) > self.max_nodes: + raise ValueError('lineage must be a list of at most max_nodes nodes') + grid: dict[tuple[int, int], dict[str, Any]] = {} # replayed: cell -> lineage node + children: dict[int, int] = {} + displaced: dict[int, int] = {} + for i, node in enumerate(lineage): + self._check_node(node, i, {e['id'] for e in grid.values()}) + for p in node['parents']: + if node['status'] != 'rejected': + children[p] = children.get(p, 0) + 1 + if node['status'] == 'rejected': + continue + cell = tuple(node['cell']) + incumbent = grid.get(cell) + better = incumbent is None or _quality(node) > _quality(incumbent) + if better != (node['status'] == 'elite'): + raise ValueError(f'lineage node {i} status contradicts the best-per-cell replay') + if better: + if incumbent is not None: + displaced[incumbent['id']] = i + grid[cell] = node + for i, node in enumerate(lineage): + if node['displaced_by'] != displaced.get(i): + raise ValueError(f'lineage node {i} displaced_by contradicts the replay') + elites = payload['elites'] + if not isinstance(elites, list) or len(elites) != len(grid): + raise ValueError('elites do not match the replayed grid') + new_grid: dict[tuple[int, int], dict[str, Any]] = {} + for e in elites: + if not isinstance(e, Mapping) or set(e) != _ELITE_KEYS: + raise ValueError('malformed elite entry') + raw_cell = e['cell'] + cell = (tuple(raw_cell) if isinstance(raw_cell, list) and all(type(x) is int for x in raw_cell) + else None) + node = grid.get(cell) + if node is None or cell in new_grid or e['id'] != node['id']: + raise ValueError('elite entry does not match the replayed grid') + for k in ('genome', 'fitness', 'log_loss', 'descriptors', 'digest'): + if e[k] != node[k]: + raise ValueError(f'elite {e["id"]} {k} differs from its lineage node') + receipt = e['receipt'] + if not harness.verify_receipt(receipt) or receipt.get('digest') != e['digest']: + raise ValueError(f'elite {e["id"]} receipt does not verify') + m = candidate_metrics(receipt) + if (m['fitness'] != e['fitness'] or m['log_loss'] != e['log_loss'] + or {k: m[k] for k in DESCRIPTOR_KEYS} != e['descriptors'] + or receipt.get('config', {}).get('genome') != e['genome']): + raise ValueError(f'elite {e["id"]} entry differs from its receipt') + new_grid[cell] = _copy(dict(e)) + expected_rejections = [{k: node[k] for k in ('id', 'genome', 'reasons', 'error', 'digest')} + for node in lineage if node['status'] == 'rejected'] + if payload['rejections'] != expected_rejections: + raise ValueError('rejection log does not match the lineage') + # ---- commit + self._grid = new_grid + self._lineage = _copy(lineage) + self._rejections = _copy(expected_rejections) + self._children = children + + def _check_node(self, node: Any, i: int, current_elites: set[int]) -> None: + if not isinstance(node, Mapping) or set(node) != _NODE_KEYS or type(node['id']) is not int or node['id'] != i: + raise ValueError(f'malformed lineage node {i}') + Genome.from_dict(node['genome']) + if node['origin'] not in ORIGINS or node['status'] not in STATUSES or type(node['spot_checked']) is not bool: + raise ValueError(f'lineage node {i} has an invalid origin, status or spot_checked flag') + parents = node['parents'] + expected = {'random': 0, 'mutation': 1, 'crossover': 2}[node['origin']] + if (not isinstance(parents, list) or len(parents) != expected or len(set(parents)) != len(parents) + or any(type(p) is not int or p not in current_elites for p in parents)): + raise ValueError(f'lineage node {i} parents must be elites at the time it was created') + ops = node['operators'] + if (not isinstance(ops, list) or len(ops) > _MAX_OPERATORS + or any(not isinstance(o, str) or not 0 < len(o) <= 96 for o in ops)): + raise ValueError(f'lineage node {i} has invalid operators') + if node['error'] is not None and (not isinstance(node['error'], str) or len(node['error']) > _MAX_TEXT): + raise ValueError(f'lineage node {i} has an invalid error message') + if node['displaced_by'] is not None and (type(node['displaced_by']) is not int or node['displaced_by'] <= i): + raise ValueError(f'lineage node {i} has an invalid displaced_by') + reasons = node['reasons'] + if not isinstance(reasons, list) or any(r not in REJECTION_REASONS for r in reasons) or len(set(reasons)) != len(reasons): + raise ValueError(f'lineage node {i} has invalid reasons') + if node['status'] == 'rejected': + if not reasons or any(node[k] is not None for k in ('cell', 'fitness', 'log_loss', 'descriptors')): + raise ValueError(f'rejected lineage node {i} must have reasons and no metrics') + if node['digest'] is not None and not _is_hex64(node['digest']): + raise ValueError(f'lineage node {i} has an invalid digest') + return + if reasons or not _is_hex64(node['digest']): + raise ValueError(f'verified lineage node {i} must have a digest and no reasons') + _num('fitness', node['fitness'], 0.0, 1.0) + _num('log_loss', node['log_loss'], 0.0, 1e6) + cell = node['cell'] + if (not isinstance(cell, list) or len(cell) != 2 or any(type(x) is not int for x in cell) + or tuple(cell) != self.cell_of(node['descriptors'])): + raise ValueError(f'lineage node {i} cell does not match its descriptors') + + +def _copy(obj: Any) -> Any: + """Deep copy of JSON-like data (dicts, lists, scalars).""" + if isinstance(obj, dict): + return {k: _copy(v) for k, v in obj.items()} + if isinstance(obj, list): + return [_copy(v) for v in obj] + return obj + + +def _parse_archive(text: Any) -> dict[str, Any]: + if not isinstance(text, str) or len(text) > MAX_ARCHIVE_CHARS: + raise ValueError(f'archive must be a JSON string of at most {MAX_ARCHIVE_CHARS} characters') + try: + doc = json.loads(text) + except ValueError as exc: + raise ValueError('archive is not valid JSON') from exc + if not isinstance(doc, dict) or set(doc) != {'schema', 'schema_version', 'sha256', 'payload'}: + raise ValueError('archive must have schema, schema_version, sha256 and payload') + if doc['schema'] != ARCHIVE_SCHEMA or doc['schema_version'] != 1: + raise ValueError('unsupported archive schema') + payload = doc['payload'] + if not isinstance(payload, dict) or doc['sha256'] != _sha256(payload): + raise ValueError('archive integrity hash mismatch') + if set(payload) != {'grid', 'elites', 'lineage', 'rejections'} or not isinstance(payload['grid'], dict): + raise ValueError('archive payload has unexpected keys') + if set(payload['grid']) != {'cost_bins', 'cost_range', 'activity_bins', 'activity_range', 'max_nodes'}: + raise ValueError('archive grid configuration has unexpected keys') + return payload + + +# ====================================================================== the search +class QualityDiversitySearch: + """Verifier-gated MAP-Elites (``method='qd'``) or random search (``method='random'``) at a fixed budget. + + Both methods insert into the same kind of archive through the same gate, so they differ only in how + candidates are proposed. The first ``initial_random`` genomes of both come from the same seeded stream. + ``spot_check_every = k`` re-evaluates candidates number k, 2k, 3k, ... (evaluation order) when they passed the + static checks and requires the same receipt digest (``0`` disables spot checks; ablation only). Evaluator + exceptions become rejections. + + ``cache`` (optional dict, shared between searches) memoises first evaluations by (protocol, seed, genome), + so two arms that propose the same candidate run it once; every candidate still costs one unit of budget. + Spot checks and :meth:`audit` always call the evaluator itself, never the cache.""" + + def __init__(self, evaluator: Callable[[Genome, int], Mapping[str, Any]], *, seed: int = 0, budget: int = 32, + method: str = 'qd', space: GenomeSpace | None = None, initial_random: int = 8, + selection: str = 'dgm', crossover_rate: float = 0.25, extra_mutation_prob: float = 0.25, + spot_check_every: int = 4, selection_sharpness: float = 10.0, selection_midpoint: float = 0.5, + max_resample: int = 16, cost_bins: int = 4, cost_range: Sequence[float] = (9.75, 11.75), + activity_bins: int = 4, activity_range: Sequence[float] = (0.0, 0.8), + cache: dict | None = None) -> None: + if not callable(evaluator) or not callable(getattr(evaluator, 'protocol', None)): + raise ValueError('evaluator must be callable as evaluator(genome, seed) and provide protocol()') + protocol = evaluator.protocol() + if not isinstance(protocol, Mapping) or type(protocol.get('steps')) is not int: + raise ValueError('evaluator.protocol() must be a mapping with an int steps') + if cache is not None and not isinstance(cache, dict): + raise ValueError('cache must be a dict or None') + self.evaluator = evaluator + self.protocol = _jsonable(dict(protocol)) + self._cache = cache + self._cache_prefix = _sha256(self.protocol) + self.cache_hits = 0 + self.evaluator_calls = 0 + self.space = GenomeSpace() if space is None else space + if not isinstance(self.space, GenomeSpace): + raise ValueError('space must be a GenomeSpace') + self.seed = _int('seed', seed, 0, 2**31 - 1) + self.budget = _int('budget', budget, 1, MAX_BUDGET) + if method not in METHODS: + raise ValueError(f'method must be one of {METHODS}') + if selection not in SELECTIONS: + raise ValueError(f'selection must be one of {SELECTIONS}') + self.method, self.selection = method, selection + self.initial_random = _int('initial_random', initial_random, 1, self.budget) + self.crossover_rate = _num('crossover_rate', crossover_rate, 0.0, 1.0) + self.extra_mutation_prob = _num('extra_mutation_prob', extra_mutation_prob, 0.0, 0.95) + self.spot_check_every = _int('spot_check_every', spot_check_every, 0, self.budget) + self.selection_sharpness = _num('selection_sharpness', selection_sharpness, 0.0, 100.0) + self.selection_midpoint = _num('selection_midpoint', selection_midpoint, 0.0, 1.0) + self.max_resample = _int('max_resample', max_resample, 1, 1000) + self.archive = EliteArchive(cost_bins=cost_bins, cost_range=cost_range, activity_bins=activity_bins, + activity_range=activity_range, max_nodes=self.budget) + self._init_rng = np.random.default_rng(self.seed + _INIT_OFFSET) + self._var_rng = np.random.default_rng(self.seed + _VAR_OFFSET) + self._seen: set[str] = set() + self.spot_checks = 0 + self.estimated_ops_verified = 0.0 + self.measured_wallclock_s = 0.0 + self._qd_trajectory: list[float] = [] + self._coverage_trajectory: list[float] = [] + + def config(self) -> dict[str, Any]: + return {'method': self.method, 'seed': self.seed, 'budget': self.budget, 'initial_random': self.initial_random, + 'selection': self.selection, 'crossover_rate': self.crossover_rate, + 'extra_mutation_prob': self.extra_mutation_prob, 'spot_check_every': self.spot_check_every, + 'selection_sharpness': self.selection_sharpness, 'selection_midpoint': self.selection_midpoint, + 'max_resample': self.max_resample, 'grid': self.archive.grid_config(), 'space': self.space.to_dict()} + + @property + def done(self) -> bool: + return self.archive.evaluations >= self.budget + + # ------------------------------------------------------------------ proposal + def _random_candidate(self) -> tuple[Genome, str, tuple[int, ...], tuple[str, ...]]: + g = self.space.random_genome(self._init_rng) + for _ in range(self.max_resample - 1): + if g.key not in self._seen: + break + g = self.space.random_genome(self._init_rng) + return g, 'random', (), () + + def parent_probabilities(self) -> tuple[list[dict[str, Any]], np.ndarray]: + """Current elites (by cell) and the parent distribution the next variation step would use.""" + elites = self.archive.elites() + if not elites: + raise ValueError('the archive is empty') + if self.selection == 'uniform': + return elites, np.full(len(elites), 1.0 / len(elites)) + return elites, dgm_parent_probabilities([e['fitness'] for e in elites], + [self.archive.children_count(e['id']) for e in elites], + sharpness=self.selection_sharpness, midpoint=self.selection_midpoint) + + def _varied_candidate(self) -> tuple[Genome, str, tuple[int, ...], tuple[str, ...]]: + elites, p = self.parent_probabilities() + rng = self._var_rng + for _ in range(self.max_resample): + i, j = (int(v) for v in rng.choice(len(elites), size=2, replace=True, p=p)) + a, b = elites[i], elites[j] + ga = Genome.from_dict(a['genome']) + if rng.random() < self.crossover_rate and a['id'] != b['id']: + child = crossover(ga, Genome.from_dict(b['genome']), self.space, rng) + child, ops = mutate(child, self.space, rng, extra_prob=self.extra_mutation_prob) + cand = (child, 'crossover', (a['id'], b['id']), ('crossover',) + ops) + else: + child, ops = mutate(ga, self.space, rng, extra_prob=self.extra_mutation_prob) + cand = (child, 'mutation', (a['id'],), ops) + if child.key not in self._seen: + break + return cand + + # ------------------------------------------------------------------ one gated evaluation + def _evaluate(self, genome: Genome) -> Any: + """First evaluation of a candidate, through the shared cache when one is given (copies in and out).""" + key = (self._cache_prefix, self.seed, genome.key) + if self._cache is not None and key in self._cache: + self.cache_hits += 1 + return _copy(self._cache[key]) + self.evaluator_calls += 1 + receipt = self.evaluator(genome, self.seed) + if self._cache is not None and isinstance(receipt, dict) and len(self._cache) < MAX_BUDGET: + self._cache[key] = _copy(receipt) + return receipt + + def step(self) -> dict[str, Any]: + """Propose, evaluate, verify (with a spot check when due) and record one candidate.""" + if self.done: + raise ValueError('the evaluation budget is exhausted') + index = self.archive.evaluations + if self.method == 'random' or index < self.initial_random or len(self.archive) == 0: + genome, origin, parents, ops = self._random_candidate() + else: + genome, origin, parents, ops = self._varied_candidate() + self._seen.add(genome.key) + t0 = time.perf_counter() + error = None + try: + receipt: Any = self._evaluate(genome) + except Exception as exc: # an evaluator failure is a rejection, never a crash + receipt, reasons, error = None, ['evaluation_error'], f'{type(exc).__name__}: {exc}' + else: + reasons = verify_candidate(genome, receipt, seed=self.seed, protocol=self.protocol, space=self.space) + spot = False + if not reasons and self.spot_check_every and (index + 1) % self.spot_check_every == 0: + spot = True + self.spot_checks += 1 + self.evaluator_calls += 1 + try: + again = self.evaluator(genome, self.seed) # never the cache: an independent re-run + except Exception as exc: + reasons, error = ['spot_check_error'], f'{type(exc).__name__}: {exc}' + else: + if (not isinstance(again, Mapping) or again.get('digest') != receipt.get('digest') + or not harness.verify_receipt(again)): + reasons = ['spot_check_digest_mismatch'] + self.measured_wallclock_s += time.perf_counter() - t0 + node = self.archive.record(genome=genome, origin=origin, parents=parents, operators=ops, receipt=receipt, + reasons=reasons, spot_checked=spot, error=error) + if node['status'] != 'rejected': + self.estimated_ops_verified += float(receipt['estimated_cost']['total_ops']) + self._qd_trajectory.append(self.archive.qd_score()) + self._coverage_trajectory.append(self.archive.coverage()) + return node + + def run(self) -> dict[str, Any]: + while not self.done: + self.step() + return self.summary() + + def audit(self) -> dict[str, Any]: + """Re-evaluate every current elite and check that its receipt digest reproduces (read-only).""" + rows = [] + for e in self.archive.elites(): + try: + again = self.evaluator(Genome.from_dict(e['genome']), self.seed) + ok = isinstance(again, Mapping) and again.get('digest') == e['digest'] and harness.verify_receipt(again) + except Exception: + ok = False + rows.append({'id': e['id'], 'cell': e['cell'], 'reproduced': bool(ok)}) + return {'checked': len(rows), 'reproduced': sum(r['reproduced'] for r in rows), + 'mismatched_ids': [r['id'] for r in rows if not r['reproduced']]} + + # ------------------------------------------------------------------ reporting + def summary(self) -> dict[str, Any]: + lineage = self.archive.lineage() + depth: list[int] = [] + for node in lineage: + depth.append(1 + max(depth[p] for p in node['parents']) if node['parents'] else 0) + reasons = Counter(r for node in lineage for r in node['reasons']) + status = Counter(node['status'] for node in lineage) + best = self.archive.best() + if best is not None: # 'receipt_digest', not 'digest': receipt seals skip keys named 'digest' + best['receipt_digest'] = best.pop('digest') + fits = [node['fitness'] for node in lineage if node['status'] != 'rejected'] + return { + 'method': self.method, 'seed': self.seed, 'evaluations': len(lineage), 'spot_checks': self.spot_checks, + 'evaluator_calls': self.evaluator_calls, 'cache_hits': self.cache_hits, + 'admitted_as_elite': status['elite'], 'verified_not_elite': status['not_elite'], + 'rejected': status['rejected'], 'displaced': sum(n['displaced_by'] is not None for n in lineage), + 'rejections_by_reason': dict(sorted(reasons.items())), + 'qd_score': self.archive.qd_score(), 'coverage': self.archive.coverage(), 'filled_cells': len(self.archive), + 'total_cells': self.archive.total_cells, 'best_fitness': None if best is None else best['fitness'], + 'verified_fitness': None if not fits else {'min': min(fits), 'max': max(fits), + 'mean': float(np.mean(fits)), 'distinct_values': len(set(fits))}, + 'best': best, 'elites': [{**{k: e[k] for k in ('cell', 'id', 'fitness', 'log_loss', 'genome')}, + 'receipt_digest': e['digest']} for e in self.archive.elites()], + 'pareto_front': self.archive.pareto_front(), + 'qd_score_trajectory': list(self._qd_trajectory), 'coverage_trajectory': list(self._coverage_trajectory), + 'lineage': {'nodes': len(lineage), 'max_depth': max(depth) if depth else 0, + 'origins': {o: sum(n['origin'] == o for n in lineage) for o in ORIGINS}}, + 'archive_sha256': self.archive.sha256, 'estimated_ops_verified_candidates': self.estimated_ops_verified, + 'measured_wallclock_s': self.measured_wallclock_s} + + +# ====================================================================== illumination metrics +def illumination_metrics(maps: Mapping[str, Mapping[Any, float]]) -> dict[str, dict[str, float | None]]: + """Mouret & Clune (2015, Sec. 9.4) metrics of several runs' maps (cell -> best fitness, fitness >= 0) over the + cells any of them filled: global reliability (mean over those cells of own / best, 0 where unfilled), + precision (the same mean over own filled cells) and coverage (own filled / union). Where the best value + is 0 an own value of 0 counts as ratio 1.""" + if not isinstance(maps, Mapping) or not maps: + raise ValueError('maps must be a non-empty mapping of run name -> {cell: fitness}') + clean: dict[str, dict[tuple, float]] = {} + for name, m in maps.items(): + if not isinstance(m, Mapping): + raise ValueError('each map must be a mapping of cell -> fitness') + clean[str(name)] = {tuple(c) if isinstance(c, (list, tuple)) else (c,): _num('fitness', v, 0.0, 1e12) + for c, v in m.items()} + union = set().union(*(m.keys() for m in clean.values())) + best = {c: max(m.get(c, 0.0) for m in clean.values()) for c in union} + out: dict[str, dict[str, float | None]] = {} + for name, m in clean.items(): + ratios = [m[c] / best[c] if best[c] > 0.0 else 1.0 for c in m] + out[name] = {'reliability': float(sum(ratios) / len(union)) if union else None, + 'precision': float(np.mean(ratios)) if ratios else None, + 'coverage_of_union': float(len(m) / len(union)) if union else None} + return out + + +# ====================================================================== lab experiment +# delayed_recall is the default task: in a 2026-11-20 scan of 10 random genomes of the default space (genomes from +# default_rng(0), seed 0, 48 training steps, held-out seeds 100 and 101 x 24 steps) it gave the most distinct held-out +# accuracies (6 values, sd 0.075; xor 4, parity 3, delayed_recall_6 2) while rhythm and context_switch gave every +# genome the same accuracy. Its best values were still close to the majority-class rate (0.604 vs 0.583). +_DEFAULTS: dict[str, Any] = { + 'task': 'delayed_recall', 'steps': 48, 'heldout_steps': 24, 'heldout_seeds': (100, 101), + 'test_seeds': (200, 201), 'budget': 16, 'initial_random': 6, 'selection': 'dgm', 'crossover_rate': 0.25, + 'extra_mutation_prob': 0.25, 'spot_check_every': 4, 'selection_sharpness': 10.0, 'selection_midpoint': 0.5, + 'max_resample': 16, 'mechanisms': SEARCH_MECHANISMS, 'topologies': TOPOLOGIES, 'neurons': NEURON_CHOICES, + 'sparsity': SPARSITY_CHOICES, 'cost_bins': 4, 'cost_range': (10.0, 12.0), 'activity_bins': 4, + 'activity_range': (0.0, 0.8)} +_QUICK: dict[str, Any] = {'steps': 16, 'heldout_steps': 8, 'heldout_seeds': (100,), 'test_seeds': (200,), + 'budget': 5, 'initial_random': 3, 'spot_check_every': 2, 'neurons': (16,), + 'cost_range': (10.1, 10.8)} +_SEARCH_KEYS = ('budget', 'initial_random', 'selection', 'crossover_rate', 'extra_mutation_prob', 'spot_check_every', + 'selection_sharpness', 'selection_midpoint', 'max_resample', 'cost_bins', 'cost_range', + 'activity_bins', 'activity_range') +_ARMS = (('quality_diversity', 'qd'), ('random_search', 'random')) +_METRICS = ('qd_score', 'coverage', 'best_fitness', 'best_test_accuracy', 'reliability', 'precision', + 'coverage_of_union') + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Verifier-gated MAP-Elites with DGM-style parent selection vs random search at an equal evaluation budget. + + Per seed both arms search the same space with the same evaluator (NEUROWEAVE ``task``, training stream + ``seed``, held-out streams ``heldout_seeds``), the same grid, the same admission gate and the same spot-check + schedule; their first ``initial_random`` candidates are identical (common random numbers, evaluated once via + a per-seed cache). Each arm's best elite is re-evaluated on fresh ``test_seeds`` streams. The verdict is + ``harness.compare`` of QD-score paired over seeds. ``quick=True`` shrinks the run (16 neurons, 16 + 8 steps, + 5 candidates per arm, every 2nd one spot-checked); ``seeds`` are always used as given.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seed_list = _seed_tuple('seeds', seeds) + unknown = sorted(set(overrides) - set(_DEFAULTS)) + if unknown: + raise ValueError(f'unknown run_experiment parameters: {unknown}') + cfg = {**_DEFAULTS, **(_QUICK if quick else {}), **overrides} + space = GenomeSpace(mechanisms=cfg['mechanisms'], topologies=cfg['topologies'], neurons=cfg['neurons'], + sparsity=cfg['sparsity']) + evaluator = NeuroWeaveEvaluator(task=cfg['task'], steps=cfg['steps'], heldout_seeds=cfg['heldout_seeds'], + heldout_steps=cfg['heldout_steps']) + test_seeds = _seed_tuple('test_seeds', cfg['test_seeds']) + held = evaluator.heldout_seeds + if set(seed_list) & set(held) or set(seed_list) & set(test_seeds) or set(held) & set(test_seeds): + raise ValueError('seeds, heldout_seeds and test_seeds must be pairwise disjoint') + search_kw = {k: cfg[k] for k in _SEARCH_KEYS} + QualityDiversitySearch(evaluator, seed=seed_list[0], space=space, **search_kw) # validate before running + arms: dict[str, list[dict[str, Any]]] = {name: [] for name, _ in _ARMS} + t0 = time.perf_counter() + for s in seed_list: + cache: dict = {} # per seed: identical candidates of the two arms are evaluated once + tests: dict[str, dict[str, Any]] = {} + maps = {} + for name, method in _ARMS: + search = QualityDiversitySearch(evaluator, seed=s, method=method, space=space, cache=cache, **search_kw) + row = search.run() + best = search.archive.best() + if best is None: + row['best_test'] = None + else: + key = _canonical(best['genome']) + if key not in tests: + test = evaluator.evaluate(Genome.from_dict(best['genome']), s, heldout_seeds=test_seeds) + tests[key] = {**{k: test['heldout'][k] for k in ('accuracy', 'log_loss', 'chance_accuracy')}, + 'receipt_digest': test['digest']} + row['best_test'] = dict(tests[key]) + row['best_test_accuracy'] = None if best is None else row['best_test']['accuracy'] + maps[name] = {tuple(e['cell']): e['fitness'] for e in search.archive.elites()} + arms[name].append(row) + illum = illumination_metrics(maps) + for name, _ in _ARMS: + arms[name][-1].update(illum[name]) + wall = time.perf_counter() - t0 + + vals = {name: {m: [row[m] for row in rows] for m in _METRICS} for name, rows in arms.items()} + comparisons = {m: harness.compare(vals['quality_diversity'][m], vals['random_search'][m]) for m in _METRICS} + receipt = harness.base_receipt(MODULE_ID, 'search_comparison', { + **{k: cfg[k] for k in ('task', 'steps', 'heldout_steps')}, 'seeds': list(seed_list), + 'heldout_seeds': list(held), 'test_seeds': list(test_seeds), 'quick': quick, **search_kw, + 'space': space.to_dict(), 'space_size': space.size, 'evaluator': evaluator.protocol(), + 'arms': {name: method for name, method in _ARMS}, + 'fitness': 'mean held-out accuracy (tie-break: lower held-out log loss)', + 'descriptors': 'log2(estimated total_ops / training steps), mean Hoyer sparseness of held-out outputs', + 'admission': 'receipt seal + schema + genome + protocol + spec validity/equality + metric consistency; ' + 'every spot_check_every-th verified candidate is re-evaluated and must reproduce its digest', + 'parent_selection': 'DGM: p_i ~ sigmoid(selection_sharpness (f_i - selection_midpoint)) / (1 + n_i) over ' + 'elites with f_i < 1; two draws with replacement (crossover when distinct)'}) + receipt['module'] = MODULE_ID + receipt['source'] = SOURCE + receipt['arms'] = {name: {'per_seed': rows, 'summary': {m: _mean(vals[name][m]) for m in _METRICS}} + for name, rows in arms.items()} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['qd_score']['verdict'] + receipt['verdict_basis'] = 'qd_score_quality_diversity_vs_random_search_equal_candidate_evaluation_budget' + receipt['budget'] = { + 'candidate_evaluations_per_arm_per_seed': int(cfg['budget']), + 'spot_check_evaluations': {name: [row['spot_checks'] for row in rows] for name, rows in arms.items()}, + 'evaluator_calls': {name: [row['evaluator_calls'] for row in rows] for name, rows in arms.items()}, + 'cache_hits': {name: [row['cache_hits'] for row in rows] for name, rows in arms.items()}, + 'test_evaluations_per_arm_per_seed': 1, 'search_space_size': space.size, + 'grid_cells': int(cfg['cost_bins']) * int(cfg['activity_bins']), 'trainable_parameters_searched': 0, + 'capacity_note': 'both arms evaluate the same number of candidates under the same gate and spot-check ' + 'schedule; the shared cache only avoids re-running identical candidates and does not ' + 'change any result; neither arm adds parameters to the evaluated engines'} + receipt['estimated_cost'] = {name: {'ops_verified_candidates': [row['estimated_ops_verified_candidates'] + for row in rows]} + for name, rows in arms.items()} + receipt['measured_wallclock_s'] = wall + receipt['notes'] = ( + 'Synthetic search over NEUROWEAVE switches at tiny sizes. Fitness is held-out accuracy on one short ' + 'temporal stream: it is coarse (1 / heldout_steps), often near chance and noisy, so the archive records ' + 'coverage plus selection on noise as much as real quality (see verified_fitness per arm). best_fitness ' + "is selected on the held-out stream and is optimistic, which is why each arm's best elite is re-scored on " + 'fresh test streams (best_test). Descriptor ranges are fixed in the config; values outside them join the ' + 'edge cells. Receipts and archive exports are SHA-256 sealed, which detects accidental or naive tampering ' + 'but is not a signature: only the periodic re-evaluation spot check tests that a result reproduces. ' + 'MAP-Elites and the DGM parent rule are reused as published ideas; nothing here reproduces either ' + "paper's systems or results.") + return harness.seal(receipt) + + +EXPERIMENTS = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/recursive_refiner.py b/synapse/frontier/recursive_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..044cf4ae634e9219f86bea5cb591aa4895f64871 --- /dev/null +++ b/synapse/frontier/recursive_refiner.py @@ -0,0 +1,873 @@ +"""Recursive latent refinement: a tiny recursive model with deep supervision and a halting head. + +Inspired by (not a reproduction of): + +* A. Jolicoeur-Martineau, "Less is More: Recursive Reasoning with Tiny Networks", + arXiv:2510.04871 (October 2025), https://arxiv.org/abs/2510.04871 -- the Tiny + Recursive Model (TRM). +* G. Wang, J. Li, Y. Sun, X. Chen, C. Liu, Y. Wu, M. Lu, S. Song, Y. Abbasi Yadkori, + "Hierarchical Reasoning Model", arXiv:2506.21734 (June 2025), + https://arxiv.org/abs/2506.21734 -- deep supervision with detached segments and a + Q-learning halting head (ACT). + +What is implemented +------------------- +One tiny network ``f`` refines a latent ``z`` and an answer state ``y`` for an embedded +question ``e = E x``. States are ``tokens`` vectors of size ``latent_dim`` (one per cell for +Sudoku; ``tokens=1`` gives a plain vector model). ``f`` is a residual block with a +parameter-free norm: a token-mixing MLP across positions (MLP-Mixer style, as TRM uses +for Sudoku instead of self-attention; skipped when ``tokens == 1``) followed by a +per-position channel MLP. + +* latent recursion: ``n`` times ``z <- f(z + y + e)``, then once ``y <- f(y + z)``. The + presence or absence of ``e`` in the sum is what tells the shared network which of the + two updates it is doing (as in TRM); +* one supervision step: ``T - 1`` latent recursions without gradient, then one with + gradient; the answer logits ``O y`` (per token) and a halting logit + ``q = w . mean_tokens(y) + b`` are read from ``y``; ``(y, z)`` are detached before the + next supervision step; +* deep supervision: every supervision step takes its own loss (cross-entropy on the + answer plus binary cross-entropy of ``sigmoid(q)`` against "the whole answer is + correct") and its own optimiser step; up to ``N_sup`` steps per example; +* halting (ACT, TRM variant without the Q-continue head): during training an example + leaves the batch when ``q > 0`` (after a random minimum number of steps with + probability ``halt_exploration``, as in HRM) or after ``N_sup`` steps and its slot is + refilled with a fresh example; evaluation runs all ``N_sup`` steps and also reports + the answer at the first step whose halting probability exceeds 0.5. + +Benchmark (``run_experiment``) +------------------------------ +4x4 Sudoku completion. All 288 valid 4x4 grids are enumerated, split by *grid* into +disjoint train / validation / held-out sets, and cells are blanked (keeping a unique +solution among all 288 grids) to make puzzles. Four arms at matched trainable +parameters (within ``param_tolerance``): + +* ``trm``: the recursive model trained with deep supervision and halting; +* ``unrolled``: the *same* network and initial weights run for the same inference depth, + trained with one loss at the end and full backpropagation through the unroll (no deep + supervision); +* ``shallow``: the same network and initial weights with a single latent recursion + (``n + 1`` applications of ``f``) and one loss (no recursion beyond one pass); +* ``mlp``: a single-pass flat MLP whose width matches the trainable parameters. + +All arms share the data, the minibatch stream and the number of optimiser updates. +Metrics: held-out exact-solve rate and cell accuracy on blank cells. The verdict compares +``trm`` with the baseline that has the best mean *validation* exact-solve +(``harness.compare``, paired 95 % t interval over seeds). + +Everything here is a synthetic computational benchmark; it does not reproduce the +papers' results (their Sudoku is 9x9 "Sudoku-Extreme" with 2-layer SwiGLU/RMSNorm mixer +blocks, EMA weights and heavy augmentation, none of which is used here). +""" +from __future__ import annotations + +import contextlib +import functools +import math +import time +from typing import Any, Callable, Iterable, Iterator, Mapping + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from . import harness + +__all__ = ['MODULE_ID', 'EXPERIMENTS', 'ARMS', 'GRID_COUNT', 'CELLS', 'DIGITS', 'INPUT_DIM', 'ANSWER_DIM', 'UNITS', + 'DEFAULTS', 'QUICK', 'enumerate_sudoku4', 'is_valid_sudoku4', 'is_consistent_puzzle', 'solution_count', + 'make_puzzles', 'encode_puzzles', 'TinyRecursiveModel', 'SinglePassMLP', 'matched_mlp_hidden', + 'train_recursive', 'train_unrolled', 'train_single_pass', 'evaluate_recursive', 'evaluate_single_pass', + 'run_experiment'] + +MODULE_ID = 'recursive_refiner' +ARMS = ('trm', 'unrolled', 'shallow', 'mlp') +SIDE = 4 +CELLS = 16 +DIGITS = 4 +GRID_COUNT = 288 # number of valid 4x4 Sudoku grids (verified by enumeration in the tests) +INPUT_DIM = CELLS * (DIGITS + 1) # one-hot per cell over {blank, 1, 2, 3, 4} +ANSWER_DIM = CELLS * DIGITS # logits per cell over {1, 2, 3, 4} + +_SPLIT_OFFSET = 31_001 +_PUZZLE_OFFSET = 31_103 +_INIT_OFFSET = 31_207 +_MLP_INIT_OFFSET = 31_259 +_STREAM_OFFSET = 31_301 +_HALT_OFFSET = 31_337 + + +def _units() -> tuple[tuple[int, ...], ...]: + rows = [tuple(r * SIDE + c for c in range(SIDE)) for r in range(SIDE)] + cols = [tuple(r * SIDE + c for r in range(SIDE)) for c in range(SIDE)] + boxes = [tuple((2 * br + i) * SIDE + 2 * bc + j for i in range(2) for j in range(2)) + for br in range(2) for bc in range(2)] + return tuple(rows + cols + boxes) + + +UNITS: tuple[tuple[int, ...], ...] = _units() # 4 rows, 4 columns, 4 boxes (cell indices, row-major) +_PEERS: tuple[tuple[int, ...], ...] = tuple( + tuple(sorted({p for u in UNITS if c in u for p in u} - {c})) for c in range(CELLS)) + + +# ====================================================================== Sudoku utilities +@functools.lru_cache(maxsize=1) +def _grid_table() -> np.ndarray: + grid = [0] * CELLS + out: list[tuple[int, ...]] = [] + + def fill(i: int) -> None: + if i == CELLS: + out.append(tuple(grid)) + return + used = {grid[p] for p in _PEERS[i] if p < i} + for d in range(1, DIGITS + 1): + if d not in used: + grid[i] = d + fill(i + 1) + grid[i] = 0 + + fill(0) + table = np.asarray(out, dtype=np.int8) + table.flags.writeable = False + return table + + +def enumerate_sudoku4() -> np.ndarray: + """All valid 4x4 Sudoku grids by backtracking, shape ``(288, 16)``, digits 1..4, lexicographic order.""" + return _grid_table().copy() + + +def _as_cells(grid: Any, name: str = 'grid') -> np.ndarray: + g = np.asarray(grid) + if g.size != CELLS: + raise ValueError(f'a 4x4 Sudoku {name} has 16 cells') + if g.dtype.kind not in 'iu': + raise ValueError(f'{name} must contain integers') + return g.reshape(CELLS).astype(np.int64) + + +def is_valid_sudoku4(grid: Any) -> bool: + """True when ``grid`` (16 ints, row-major, or 4x4) is a complete valid 4x4 Sudoku.""" + g = _as_cells(grid) + if g.min() < 1 or g.max() > DIGITS: + return False + return all(sorted(g[list(u)].tolist()) == [1, 2, 3, 4] for u in UNITS) + + +def is_consistent_puzzle(puzzle: Any) -> bool: + """True when a partial grid (0 = blank, digits 1..4) has no repeated digit in any row, column or box.""" + p = _as_cells(puzzle, 'puzzle') + if p.min() < 0 or p.max() > DIGITS: + return False + for u in UNITS: + vals = [int(v) for v in p[list(u)] if v] + if len(vals) != len(set(vals)): + return False + return True + + +@functools.lru_cache(maxsize=1) +def _bitsets() -> tuple[tuple[int, ...], ...]: + """``bits[c][d]``: bitset over the 288 grids of those with digit ``d`` in cell ``c`` (``d=0`` = all grids).""" + table = _grid_table() + full = (1 << len(table)) - 1 + bits = [[full] + [0] * DIGITS for _ in range(CELLS)] + for gi, g in enumerate(table): + for c in range(CELLS): + bits[c][int(g[c])] |= 1 << gi + return tuple(tuple(b) for b in bits) + + +def _count(p: np.ndarray) -> int: + bits = _bitsets() + mask = bits[0][0] + for c in range(CELLS): + d = int(p[c]) + if d: + mask &= bits[c][d] + return mask.bit_count() + + +def solution_count(puzzle: Any) -> int: + """Number of valid 4x4 grids that agree with the givens of ``puzzle`` (0 = blank).""" + p = _as_cells(puzzle, 'puzzle') + if p.min() < 0 or p.max() > DIGITS: + raise ValueError('puzzle cells must be in 0..4') + return _count(p) + + +def make_puzzles(grids: Any, count: int, *, rng: np.random.Generator, min_blanks: int, max_blanks: int, + max_attempts: int = 64) -> tuple[np.ndarray, np.ndarray]: + """Blank cells of randomly chosen ``grids`` while the solution stays unique among all 288 grids. + + Each puzzle draws a target number of blanks uniformly from ``[min_blanks, max_blanks]`` and removes + cells in random order, skipping removals that would admit a second solution. Returns + ``(puzzles, solutions)``, both ``(count, 16)`` int8 (puzzles use 0 for blank).""" + g = np.asarray(grids) + if g.ndim != 2 or g.shape[1] != CELLS or g.shape[0] < 1 or g.dtype.kind not in 'iu': + raise ValueError('grids must be an integer array of shape (n, 16)') + if not all(is_valid_sudoku4(row) for row in g): + raise ValueError('grids must be valid 4x4 Sudoku grids') + if type(count) is not int or count < 1: + raise ValueError('count must be a positive int') + if type(min_blanks) is not int or type(max_blanks) is not int or not 1 <= min_blanks <= max_blanks <= 12: + raise ValueError('need 1 <= min_blanks <= max_blanks <= 12 (a unique 4x4 puzzle keeps at least 4 givens)') + puzzles = np.zeros((count, CELLS), dtype=np.int8) + solutions = np.zeros((count, CELLS), dtype=np.int8) + for k in range(count): + for _ in range(max_attempts): + sol = g[int(rng.integers(len(g)))].astype(np.int64) + target = int(rng.integers(min_blanks, max_blanks + 1)) + p = sol.copy() + blanks = 0 + for c in rng.permutation(CELLS): + if blanks == target: + break + keep = p[c] + p[c] = 0 + if _count(p) == 1: + blanks += 1 + else: + p[c] = keep + if blanks >= min_blanks: + break + else: + raise RuntimeError('could not make a unique puzzle with the requested number of blanks') + puzzles[k] = p + solutions[k] = sol + return puzzles, solutions + + +def encode_puzzles(puzzles: Any) -> torch.Tensor: + """One-hot encoding over {blank, 1, 2, 3, 4} per cell: float32 tensor of shape ``(n, 80)`` (cell-major).""" + p = np.asarray(puzzles) + if p.ndim != 2 or p.shape[1] != CELLS or p.dtype.kind not in 'iu' or p.size == 0: + raise ValueError('puzzles must be a non-empty integer array of shape (n, 16)') + if p.min() < 0 or p.max() > DIGITS: + raise ValueError('puzzle cells must be in 0..4') + n = p.shape[0] + onehot = np.zeros((n, CELLS, DIGITS + 1), dtype=np.float32) + onehot[np.arange(n)[:, None], np.arange(CELLS)[None, :], p.astype(np.int64)] = 1.0 + return torch.from_numpy(onehot.reshape(n, INPUT_DIM)) + + +def _targets(solutions: np.ndarray) -> torch.Tensor: + return torch.from_numpy(np.asarray(solutions, dtype=np.int64) - 1) + + +# ====================================================================== models +def _check_int(name: str, value: Any, low: int, high: int) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return value + + +class _Linear(nn.Module): + """Affine map initialised like ``nn.Linear`` but from an explicit generator (never the global RNG).""" + + def __init__(self, in_features: int, out_features: int, generator: torch.Generator) -> None: + super().__init__() + bound = 1.0 / math.sqrt(in_features) + self.weight = nn.Parameter(torch.empty(out_features, in_features).uniform_(-bound, bound, generator=generator)) + self.bias = nn.Parameter(torch.empty(out_features).uniform_(-bound, bound, generator=generator)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return F.linear(x, self.weight, self.bias) + + +def _norm(h: torch.Tensor) -> torch.Tensor: + """Parameter-free post-norm (layer norm without affine terms) that keeps recursed states bounded.""" + return F.layer_norm(h, h.shape[-1:]) + + +def _truncated_normal(n: int, generator: torch.Generator, limit: float = 2.0) -> torch.Tensor: + out = torch.empty(n).normal_(generator=generator) + for _ in range(64): # rejection resampling of the (rare) out-of-range entries + bad = out.abs() > limit + if not bool(bad.any()): + break + out[bad] = torch.empty(int(bad.sum())).normal_(generator=generator) + return out.clamp_(-limit, limit) + + +class TinyRecursiveModel(nn.Module): + """One tiny network that recursively refines a latent ``z`` and an answer state ``y``. + + Inputs are ``(batch, tokens * input_dim)`` (token-major) and answers ``(batch, tokens * answer_dim)``; + internally ``x``, ``y`` and ``z`` are ``(batch, tokens, latent_dim)``. The network is + ``f(s) = norm(t + W2 relu(W1 t + b1) + b2)`` with ``t = norm(s + token_mlp(s))``, where the + token-mixing MLP (hidden width ``token_hidden``) acts across positions and is skipped when + ``tokens == 1``; ``norm`` is a layer norm without affine terms (TRM uses RMSNorm and SwiGLU, swapped + here for speed on CPU). A latent recursion is ``n_latent_steps`` updates ``z <- f(z + y + E x)`` + followed by ``y <- f(y + z)``; a supervision step is ``recursions - 1`` latent recursions without + gradient plus one with gradient, then the per-token answer head ``O y`` and the halting head + ``q = w . mean_tokens(y) + b`` (probability ``sigmoid(q)``). ``(y, z)`` are detached between + supervision steps. ``y_init`` / ``z_init`` are fixed (non-trainable) truncated-normal buffers shared by + all positions and the halting head starts at ``w = 0, b = -5`` (as in the HRM/TRM code), so early + training rarely halts. ``net_calls`` counts applications of ``f``.""" + + def __init__(self, input_dim: int, answer_dim: int, latent_dim: int, hidden: int, n_latent_steps: int, + supervision_steps: int, *, recursions: int = 2, tokens: int = 1, token_hidden: int | None = None, + seed: int = 0) -> None: + super().__init__() + self.input_dim = _check_int('input_dim', input_dim, 1, 1 << 16) + self.answer_dim = _check_int('answer_dim', answer_dim, 1, 1 << 16) + self.latent_dim = _check_int('latent_dim', latent_dim, 2, 4096) + self.hidden = _check_int('hidden', hidden, 1, 8192) + self.n_latent_steps = _check_int('n_latent_steps', n_latent_steps, 1, 64) + self.supervision_steps = _check_int('supervision_steps', supervision_steps, 1, 64) + self.recursions = _check_int('recursions', recursions, 1, 64) + self.tokens = _check_int('tokens', tokens, 1, 4096) + if tokens == 1: + if token_hidden not in (None, 0): + raise ValueError('token_hidden needs tokens > 1') + self.token_hidden = 0 + else: + self.token_hidden = _check_int('token_hidden', tokens if token_hidden is None else token_hidden, 1, 8192) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + g = torch.Generator().manual_seed(self.seed + _INIT_OFFSET) + self.input_embedding = _Linear(input_dim, latent_dim, g) + self.net_in = _Linear(latent_dim, hidden, g) + self.net_out = _Linear(hidden, latent_dim, g) + self.output_head = _Linear(latent_dim, answer_dim, g) + self.q_head = _Linear(latent_dim, 1, g) + self.token_in = _Linear(tokens, self.token_hidden, g) if tokens > 1 else None + self.token_out = _Linear(self.token_hidden, tokens, g) if tokens > 1 else None + with torch.no_grad(): + self.q_head.weight.zero_() + self.q_head.bias.fill_(-5.0) + self.register_buffer('y_init', _truncated_normal(latent_dim, g)) + self.register_buffer('z_init', _truncated_normal(latent_dim, g)) + self.net_calls = 0 + + # ------------------------------------------------------------------ building blocks + def net(self, s: torch.Tensor) -> torch.Tensor: + """The single shared tiny network ``f`` on states of shape ``(batch, tokens, latent_dim)``.""" + self.net_calls += 1 + if self.token_in is not None: + mixed = self.token_out(F.relu(self.token_in(s.transpose(1, 2)))).transpose(1, 2) + s = _norm(s + mixed) + return _norm(s + self.net_out(F.relu(self.net_in(s)))) + + def embed(self, x: torch.Tensor) -> torch.Tensor: + width = self.tokens * self.input_dim + if not isinstance(x, torch.Tensor) or x.ndim != 2 or x.shape[1] != width or not x.is_floating_point(): + raise ValueError(f'x must be a float tensor of shape (batch, {width})') + return self.input_embedding(x.reshape(x.shape[0], self.tokens, self.input_dim)) + + def initial_state(self, batch: int) -> tuple[torch.Tensor, torch.Tensor]: + shape = (batch, self.tokens, self.latent_dim) + return self.y_init.expand(shape).clone(), self.z_init.expand(shape).clone() + + def latent_recursion(self, e: torch.Tensor, y: torch.Tensor, z: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + for _ in range(self.n_latent_steps): + z = self.net(z + y + e) + y = self.net(y + z) + return y, z + + def read_out(self, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Answer logits ``(batch, tokens * answer_dim)`` and halting logits ``(batch,)`` from ``y``.""" + return self.output_head(y).reshape(y.shape[0], -1), self.q_head(y.mean(1)).squeeze(-1) + + def supervision_step(self, e: torch.Tensor, y: torch.Tensor, z: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """``recursions - 1`` gradient-free recursions, one with gradient; returns detached ``(y, z)``, + answer logits and the halting logit.""" + with torch.no_grad(): + for _ in range(self.recursions - 1): + y, z = self.latent_recursion(e, y, z) + y, z = self.latent_recursion(e, y, z) + logits, q = self.read_out(y) + return y.detach(), z.detach(), logits, q + + def halt_probability(self, y: torch.Tensor) -> torch.Tensor: + return torch.sigmoid(self.read_out(y)[1]) + + # ------------------------------------------------------------------ full passes + def forward(self, x: torch.Tensor, *, steps: int | None = None) -> dict[str, torch.Tensor]: + """Run ``steps`` (default ``supervision_steps``) supervision steps; returns the final logits, the + per-step logits ``(steps, batch, tokens * answer_dim)`` and halting probabilities ``(steps, batch)``.""" + steps = self.supervision_steps if steps is None else _check_int('steps', steps, 1, 1024) + e = self.embed(x) + y, z = self.initial_state(x.shape[0]) + logits, halts = [], [] + for _ in range(steps): + y, z, lg, q = self.supervision_step(e, y, z) + logits.append(lg) + halts.append(torch.sigmoid(q)) + return {'logits': logits[-1], 'step_logits': torch.stack(logits), 'halt_prob': torch.stack(halts)} + + def unrolled(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """The same computation as ``forward`` (``supervision_steps * recursions`` latent recursions) with + gradient through every recursion and no intermediate read-out; returns final logits and halting logit.""" + e = self.embed(x) + y, z = self.initial_state(x.shape[0]) + for _ in range(self.supervision_steps * self.recursions): + y, z = self.latent_recursion(e, y, z) + return self.read_out(y) + + # ------------------------------------------------------------------ accounting + def calls_per_supervision_step(self) -> int: + return self.recursions * (self.n_latent_steps + 1) + + def parameter_count(self) -> int: + return int(sum(p.numel() for p in self.parameters() if p.requires_grad)) + + def inference_macs(self) -> int: + """Estimated multiply-accumulates per example for a full ``forward`` (all supervision steps).""" + d, h, t = self.latent_dim, self.hidden, self.tokens + net = t * 2 * d * h + (2 * d * t * self.token_hidden if t > 1 else 0) + per_step = self.calls_per_supervision_step() * net + t * d * self.answer_dim + d + return int(t * self.input_dim * d + self.supervision_steps * per_step) + + +class SinglePassMLP(nn.Module): + """Single-pass baseline: ``depth`` ReLU hidden layers of width ``hidden``, then a linear answer head.""" + + def __init__(self, input_dim: int, answer_dim: int, hidden: int, *, depth: int = 2, seed: int = 0) -> None: + super().__init__() + self.input_dim = _check_int('input_dim', input_dim, 1, 1 << 16) + self.answer_dim = _check_int('answer_dim', answer_dim, 1, 1 << 16) + self.hidden = _check_int('hidden', hidden, 1, 8192) + self.depth = _check_int('depth', depth, 1, 16) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + g = torch.Generator().manual_seed(self.seed + _MLP_INIT_OFFSET) + dims = [input_dim] + [hidden] * depth + self.layers = nn.ModuleList(_Linear(a, b, g) for a, b in zip(dims[:-1], dims[1:])) + self.head = _Linear(hidden, answer_dim, g) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if not isinstance(x, torch.Tensor) or x.ndim != 2 or x.shape[1] != self.input_dim or not x.is_floating_point(): + raise ValueError(f'x must be a float tensor of shape (batch, {self.input_dim})') + h = x + for layer in self.layers: + h = F.relu(layer(h)) + return self.head(h) + + def parameter_count(self) -> int: + return int(sum(p.numel() for p in self.parameters() if p.requires_grad)) + + def inference_macs(self) -> int: + return int(self.input_dim * self.hidden + (self.depth - 1) * self.hidden ** 2 + self.hidden * self.answer_dim) + + +def _mlp_params(hidden: int, input_dim: int, answer_dim: int, depth: int) -> int: + return input_dim * hidden + hidden + (depth - 1) * (hidden * hidden + hidden) + hidden * answer_dim + answer_dim + + +def matched_mlp_hidden(target_params: int, input_dim: int, answer_dim: int, depth: int = 2) -> int: + """Hidden width whose ``SinglePassMLP`` parameter count is closest to ``target_params``.""" + _check_int('target_params', target_params, 1, 1 << 40) + _check_int('input_dim', input_dim, 1, 1 << 16) + _check_int('answer_dim', answer_dim, 1, 1 << 16) + _check_int('depth', depth, 1, 16) + best, gap = 1, None + for h in range(1, 8193): + n = _mlp_params(h, input_dim, answer_dim, depth) + if gap is None or abs(n - target_params) < gap: + best, gap = h, abs(n - target_params) + if n > target_params: + break + return best + + +# ====================================================================== training +class _IndexStream: + """Deterministic endless stream of shuffled example indices (one permutation per epoch).""" + + def __init__(self, n: int, generator: torch.Generator) -> None: + self.n = int(n) + self.g = generator + self.buf = torch.empty(0, dtype=torch.long) + self.drawn = 0 + + def take(self, k: int) -> torch.Tensor: + parts = [] + while k > 0: + if self.buf.numel() == 0: + self.buf = torch.randperm(self.n, generator=self.g) + part, self.buf = self.buf[:k], self.buf[k:] + parts.append(part) + k -= part.numel() + out = torch.cat(parts) + self.drawn += int(out.numel()) + return out + + +@functools.lru_cache(maxsize=1) +def _fused_adamw_available() -> bool: + """Whether this torch build runs the fused CPU AdamW kernel (several times faster for tiny models).""" + try: + p = nn.Parameter(torch.zeros(2)) + p.grad = torch.ones(2) + torch.optim.AdamW([p], lr=1e-3, fused=True).step() + return bool(torch.isfinite(p).all()) + except (RuntimeError, TypeError, ValueError): + return False + + +def _optimizer(model: nn.Module, cfg: Mapping[str, Any]) -> torch.optim.Optimizer: + kw: dict[str, Any] = dict(lr=float(cfg['lr']), betas=(0.9, 0.95), weight_decay=float(cfg['weight_decay'])) + if _fused_adamw_available(): + kw['fused'] = True + return torch.optim.AdamW(model.parameters(), **kw) + + +def _answer_loss(logits: torch.Tensor, target: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Mean cell cross-entropy and the per-example "every cell correct" indicator.""" + cells = logits.view(-1, CELLS, DIGITS) + ce = F.cross_entropy(cells.reshape(-1, DIGITS), target.reshape(-1)) + exact = (cells.argmax(-1) == target).all(-1) + return ce, exact + + +def _step(model: nn.Module, opt: torch.optim.Optimizer, loss: torch.Tensor, clip: float) -> None: + opt.zero_grad(set_to_none=True) + loss.backward() + if clip > 0: + torch.nn.utils.clip_grad_norm_(model.parameters(), clip) + opt.step() + + +def _tail_loss(losses: list[float]) -> float: + return float(np.mean(losses[-max(1, len(losses) // 10):])) + + +def train_recursive(model: TinyRecursiveModel, x: torch.Tensor, target: torch.Tensor, cfg: Mapping[str, Any], + generator: torch.Generator) -> dict[str, Any]: + """Deep supervision with ACT halting (TRM style). + + A batch of ``batch_size`` slots is carried across optimiser updates. Each update is one supervision + step for every slot; a slot halts when its halting logit is positive (and its random minimum step + count is reached) or after ``supervision_steps`` steps, and is then refilled with a fresh example + from the index stream with re-initialised ``(y, z)``.""" + updates, batch = int(cfg['updates']), int(cfg['batch_size']) + n_sup, explore, clip = model.supervision_steps, float(cfg['halt_exploration']), float(cfg['grad_clip']) + opt = _optimizer(model, cfg) + stream = _IndexStream(x.shape[0], generator) + halt_gen = torch.Generator().manual_seed(int(cfg['_seed']) + _HALT_OFFSET) + + def min_steps(k: int) -> torch.Tensor: + explore_mask = torch.rand(k, generator=halt_gen) < explore + drawn = torch.randint(2, max(3, n_sup + 1), (k,), generator=halt_gen) + return torch.where(explore_mask, drawn.clamp(max=n_sup), torch.ones(k, dtype=torch.long)) + + idx = stream.take(batch) + xb, tb = x[idx], target[idx] + y, z = model.initial_state(batch) + steps = torch.zeros(batch, dtype=torch.long) + mins = min_steps(batch) + finished_steps: list[int] = [] + losses: list[float] = [] + model.train() + for _ in range(updates): + e = model.embed(xb) + y, z, logits, q = model.supervision_step(e, y, z) + ce, exact = _answer_loss(logits, tb) + loss = ce + F.binary_cross_entropy_with_logits(q, exact.float()) + _step(model, opt, loss, clip) + losses.append(float(loss.detach())) + steps += 1 + halted = ((q.detach() > 0) & (steps >= mins)) | (steps >= n_sup) + k = int(halted.sum()) + if k: + finished_steps.extend(steps[halted].tolist()) + fresh = stream.take(k) + xb, tb = xb.clone(), tb.clone() + xb[halted], tb[halted] = x[fresh], target[fresh] + reset = halted.view(-1, *([1] * (y.ndim - 1))) + y = torch.where(reset, model.y_init.expand_as(y), y) + z = torch.where(reset, model.z_init.expand_as(z), z) + steps[halted] = 0 + mins[halted] = min_steps(k) + return {'updates': updates, 'examples_drawn': stream.drawn, 'final_loss': _tail_loss(losses), + 'mean_supervision_steps_per_finished_example': float(np.mean(finished_steps)) if finished_steps else None} + + +def train_unrolled(model: TinyRecursiveModel, x: torch.Tensor, target: torch.Tensor, cfg: Mapping[str, Any], + generator: torch.Generator) -> dict[str, Any]: + """Same network, no deep supervision: one loss at the end of the full unroll, backpropagated through + every recursion; one fresh minibatch per optimiser update.""" + updates, batch, clip = int(cfg['updates']), int(cfg['batch_size']), float(cfg['grad_clip']) + opt = _optimizer(model, cfg) + stream = _IndexStream(x.shape[0], generator) + losses: list[float] = [] + model.train() + for _ in range(updates): + idx = stream.take(batch) + logits, q = model.unrolled(x[idx]) + ce, exact = _answer_loss(logits, target[idx]) + loss = ce + F.binary_cross_entropy_with_logits(q, exact.float()) + _step(model, opt, loss, clip) + losses.append(float(loss.detach())) + return {'updates': updates, 'examples_drawn': stream.drawn, 'final_loss': _tail_loss(losses)} + + +def train_single_pass(model: SinglePassMLP, x: torch.Tensor, target: torch.Tensor, cfg: Mapping[str, Any], + generator: torch.Generator) -> dict[str, Any]: + updates, batch, clip = int(cfg['updates']), int(cfg['batch_size']), float(cfg['grad_clip']) + opt = _optimizer(model, cfg) + stream = _IndexStream(x.shape[0], generator) + losses: list[float] = [] + model.train() + for _ in range(updates): + idx = stream.take(batch) + ce, _ = _answer_loss(model(x[idx]), target[idx]) + _step(model, opt, ce, clip) + losses.append(float(ce.detach())) + return {'updates': updates, 'examples_drawn': stream.drawn, 'final_loss': _tail_loss(losses)} + + +# ====================================================================== evaluation +def _cell_metrics(pred: torch.Tensor, target: torch.Tensor, blank: torch.Tensor) -> tuple[float, float]: + correct = pred == target + cell_acc = float((correct & blank).sum()) / max(1, int(blank.sum())) + exact = float(correct.all(-1).float().mean()) + return cell_acc, exact + + +@torch.no_grad() +def evaluate_recursive(model: TinyRecursiveModel, x: torch.Tensor, target: torch.Tensor, + puzzles: np.ndarray) -> dict[str, Any]: + """Final-step and per-step metrics, halting-head calibration and halting-based (adaptive) answers.""" + model.eval() + out = model(x) + steps = out['step_logits'].shape[0] + pred = out['step_logits'].view(steps, -1, CELLS, DIGITS).argmax(-1) # (S, N, 16) + blank = torch.from_numpy(np.asarray(puzzles) == 0) + per_step_exact = (pred == target).all(-1) # (S, N) + cell_acc, exact = _cell_metrics(pred[-1], target, blank) + halt = out['halt_prob'] # (S, N) + above = halt > 0.5 + first = torch.where(above.any(0), above.float().argmax(0), torch.full_like(above[0], steps - 1, dtype=torch.long)) + chosen = pred.gather(0, first.view(1, -1, 1).expand(1, -1, CELLS)).squeeze(0) + a_cell, a_exact = _cell_metrics(chosen, target, blank) + brier = float(((halt - per_step_exact.float()) ** 2).mean()) + decided = float(((halt > 0.5) == per_step_exact).float().mean()) + return {'cell_accuracy': cell_acc, 'exact_solve': exact, + 'per_step_exact_solve': per_step_exact.float().mean(-1).tolist(), + 'adaptive_cell_accuracy': a_cell, 'adaptive_exact_solve': a_exact, + 'adaptive_mean_steps': float((first + 1).float().mean()), + 'halting_brier': brier, 'halting_decision_accuracy': decided, + 'halt_prob_range': [float(halt.min()), float(halt.max())]} + + +@torch.no_grad() +def evaluate_single_pass(model: SinglePassMLP, x: torch.Tensor, target: torch.Tensor, + puzzles: np.ndarray) -> dict[str, Any]: + model.eval() + pred = model(x).view(-1, CELLS, DIGITS).argmax(-1) + blank = torch.from_numpy(np.asarray(puzzles) == 0) + cell_acc, exact = _cell_metrics(pred, target, blank) + return {'cell_accuracy': cell_acc, 'exact_solve': exact} + + +# ====================================================================== experiment +DEFAULTS: dict[str, Any] = { + 'train_grids': 160, 'val_grids': 32, 'test_grids': 96, + 'train_puzzles': 4096, 'val_puzzles': 512, 'test_puzzles': 1024, 'train_eval_puzzles': 512, + 'min_blanks': 8, 'max_blanks': 12, + 'latent_dim': 24, 'hidden': 48, 'token_hidden': 24, 'n_latent_steps': 2, 'recursions': 2, + 'supervision_steps': 4, 'mlp_depth': 2, 'updates': 600, 'batch_size': 32, 'lr': 2e-3, 'weight_decay': 0.01, + 'grad_clip': 1.0, 'halt_exploration': 0.1, 'param_tolerance': 0.10, +} +QUICK: dict[str, Any] = {**DEFAULTS, 'train_puzzles': 1024, 'val_puzzles': 128, 'test_puzzles': 256, + 'train_eval_puzzles': 128, 'latent_dim': 16, 'hidden': 32, 'token_hidden': 16, + 'n_latent_steps': 1, 'supervision_steps': 2, 'updates': 100, 'batch_size': 64, 'lr': 4e-3} +_INT_KEYS = {'train_grids': (1, 286), 'val_grids': (1, 286), 'test_grids': (1, 286), 'train_puzzles': (8, 1 << 20), + 'val_puzzles': (8, 1 << 20), 'test_puzzles': (8, 1 << 20), 'train_eval_puzzles': (8, 1 << 20), + 'min_blanks': (1, 12), 'max_blanks': (1, 12), 'latent_dim': (2, 1024), 'hidden': (1, 4096), + 'token_hidden': (1, 1024), 'n_latent_steps': (1, 16), 'recursions': (1, 16), 'supervision_steps': (1, 32), + 'mlp_depth': (1, 8), 'updates': (1, 100_000), 'batch_size': (1, 4096)} +_FLOAT_KEYS = {'lr': (1e-6, 1.0), 'weight_decay': (0.0, 10.0), 'grad_clip': (0.0, 1e6), 'halt_exploration': (0.0, 1.0), + 'param_tolerance': (0.0, 1.0)} + + +def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + cfg = dict(QUICK if quick else DEFAULTS) + unknown = set(overrides) - set(cfg) + if unknown: + raise ValueError(f'unknown recursive_refiner options: {sorted(unknown)}') + cfg.update(overrides) + for k, (lo, hi) in _INT_KEYS.items(): + _check_int(k, cfg[k], lo, hi) + for k, (lo, hi) in _FLOAT_KEYS.items(): + v = cfg[k] + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)) or not lo <= v <= hi: + raise ValueError(f'{k} must be a number in [{lo}, {hi}]') + cfg[k] = float(v) + if cfg['train_grids'] + cfg['val_grids'] + cfg['test_grids'] > GRID_COUNT: + raise ValueError('train_grids + val_grids + test_grids must not exceed 288') + if cfg['min_blanks'] > cfg['max_blanks']: + raise ValueError('min_blanks must not exceed max_blanks') + return cfg + + +@contextlib.contextmanager +def _single_thread() -> Iterator[None]: + previous = torch.get_num_threads() + try: + if previous != 1: + torch.set_num_threads(1) + yield + finally: + if torch.get_num_threads() != previous: + torch.set_num_threads(previous) + + +def _seed_data(seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]: + table = _grid_table() + order = np.random.default_rng(seed + _SPLIT_OFFSET).permutation(len(table)) + a, b = cfg['train_grids'], cfg['train_grids'] + cfg['val_grids'] + split = {'train': order[:a], 'val': order[a:b], 'test': order[b:b + cfg['test_grids']]} + rng = np.random.default_rng(seed + _PUZZLE_OFFSET) + data: dict[str, Any] = {'split': split} + sizes = {'train': cfg['train_puzzles'], 'val': cfg['val_puzzles'], 'test': cfg['test_puzzles']} + for name in ('train', 'val', 'test'): + p, s = make_puzzles(table[split[name]], sizes[name], rng=rng, min_blanks=cfg['min_blanks'], + max_blanks=cfg['max_blanks']) + data[name] = (p, s, encode_puzzles(p), _targets(s)) + k = min(cfg['train_eval_puzzles'], cfg['train_puzzles']) + p, s, xt, tt = data['train'] + data['train_eval'] = (p[:k], s[:k], xt[:k], tt[:k]) + return data + + +def _models(seed: int, cfg: Mapping[str, Any]) -> tuple[dict[str, nn.Module], int]: + """The four arms for one seed: trm / unrolled / shallow share the network and initial weights.""" + net = dict(latent_dim=cfg['latent_dim'], hidden=cfg['hidden'], n_latent_steps=cfg['n_latent_steps'], + tokens=CELLS, token_hidden=cfg['token_hidden'], seed=seed) + depth = dict(supervision_steps=cfg['supervision_steps'], recursions=cfg['recursions']) + models: dict[str, nn.Module] = { + 'trm': TinyRecursiveModel(DIGITS + 1, DIGITS, **net, **depth), + 'unrolled': TinyRecursiveModel(DIGITS + 1, DIGITS, **net, **depth), + 'shallow': TinyRecursiveModel(DIGITS + 1, DIGITS, **net, supervision_steps=1, recursions=1), + } + mlp_hidden = matched_mlp_hidden(models['trm'].parameter_count(), INPUT_DIM, ANSWER_DIM, cfg['mlp_depth']) + models['mlp'] = SinglePassMLP(INPUT_DIM, ANSWER_DIM, mlp_hidden, depth=cfg['mlp_depth'], seed=seed) + return models, mlp_hidden + + +def _run_seed(seed: int, cfg: dict[str, Any]) -> dict[str, Any]: + data = _seed_data(seed, cfg) + _, _, x_train, t_train = data['train'] + models, mlp_hidden = _models(seed, cfg) + plan = {'trm': (train_recursive, evaluate_recursive), 'unrolled': (train_unrolled, evaluate_recursive), + 'shallow': (train_unrolled, evaluate_recursive), 'mlp': (train_single_pass, evaluate_single_pass)} + tcfg = {**cfg, '_seed': seed} + arms: dict[str, dict[str, Any]] = {} + for name in ARMS: + model = models[name] + trainer, evaluator = plan[name] + gen = torch.Generator().manual_seed(seed + _STREAM_OFFSET) # same example stream for every arm + t0 = time.perf_counter() + log = trainer(model, x_train, t_train, tcfg, gen) + t1 = time.perf_counter() + evals = {split: evaluator(model, data[split][2], data[split][3], data[split][0]) + for split in ('train_eval', 'val', 'test')} + t2 = time.perf_counter() + arms[name] = {'seed': int(seed), 'parameters': model.parameter_count(), 'training': log, + 'train': evals['train_eval'], 'val': evals['val'], 'heldout': evals['test'], + 'estimated_inference_macs_per_puzzle': model.inference_macs(), + 'measured_wallclock_s': {'train': t1 - t0, 'eval': t2 - t1}} + blanks = {name: float(np.mean(np.sum(data[name][0] == 0, axis=1))) for name in ('train', 'val', 'test')} + split = data['split'] + overlap = (len(set(split['train'].tolist()) & set(split['test'].tolist())) + + len(set(split['train'].tolist()) & set(split['val'].tolist())) + + len(set(split['val'].tolist()) & set(split['test'].tolist()))) + return {'arms': arms, 'mlp_hidden': mlp_hidden, 'mean_blanks': blanks, 'grid_overlap': int(overlap)} + + +def _arm_summary(per_seed: list[dict[str, Any]]) -> dict[str, Any]: + def mean(split: str, metric: str) -> float | None: + vals = [r[split].get(metric) for r in per_seed] + vals = [float(v) for v in vals if v is not None] + return float(np.mean(vals)) if vals else None + out = {f'{split}_{metric}': mean(split, metric) for split in ('train', 'val', 'heldout') + for metric in ('cell_accuracy', 'exact_solve')} + if 'adaptive_exact_solve' in per_seed[0]['heldout']: + out['heldout_adaptive_exact_solve'] = mean('heldout', 'adaptive_exact_solve') + out['heldout_adaptive_mean_steps'] = mean('heldout', 'adaptive_mean_steps') + out['heldout_halting_brier'] = mean('heldout', 'halting_brier') + out['heldout_halting_decision_accuracy'] = mean('heldout', 'halting_decision_accuracy') + steps = np.mean([r['heldout']['per_step_exact_solve'] for r in per_seed], axis=0) + out['heldout_per_step_exact_solve'] = [float(v) for v in steps] + return out + + +def run_experiment(*, quick: bool = False, seeds: Iterable[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """TRM vs the same network unrolled / shallow vs a single-pass MLP on 4x4 Sudoku (held-out grids). + + Returns a sealed frontier receipt. ``overrides`` may change any key of ``DEFAULTS``.""" + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = tuple(seeds) + 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): + raise ValueError('seeds must be unique non-negative ints') + cfg = _config(quick, overrides) + probe, _ = _models(seeds[0], cfg) # budgets do not depend on the seed: check before training + params = {n: probe[n].parameter_count() for n in ARMS} + gap = max(abs(params[n] - params['trm']) / params['trm'] for n in ARMS) + if gap > cfg['param_tolerance']: + raise ValueError(f'the single-pass MLP cannot match the recursive model budget: {params} ' + f'(gap {gap:.3f} > param_tolerance {cfg["param_tolerance"]})') + t_start = time.perf_counter() + with _single_thread(): + runs = [_run_seed(s, cfg) for s in seeds] + per_arm = {n: [r['arms'][n] for r in runs] for n in ARMS} + if any(a['parameters'] != params[n] for n in ARMS for a in per_arm[n]): + raise RuntimeError('built models do not match the computed parameter budget') + summaries = {n: _arm_summary(per_arm[n]) for n in ARMS} + baselines = ARMS[1:] + best = max(baselines, key=lambda n: (summaries[n]['val_exact_solve'], -baselines.index(n))) + exact = {n: [a['heldout']['exact_solve'] for a in per_arm[n]] for n in ARMS} + cells = {n: [a['heldout']['cell_accuracy'] for a in per_arm[n]] for n in ARMS} + comparisons = {'trm_vs_best_baseline': harness.compare(exact['trm'], exact[best])} + for n in baselines: + comparisons[f'trm_vs_{n}'] = harness.compare(exact['trm'], exact[n]) + comparisons['trm_vs_best_baseline_cell_accuracy'] = harness.compare(cells['trm'], cells[best]) + receipt = harness.base_receipt(MODULE_ID, 'model_comparison', { + **cfg, 'quick': quick, 'seeds': list(seeds), 'task': 'sudoku_4x4_completion', 'arms': list(ARMS), + 'metric': 'heldout_exact_solve', 'input_encoding': 'one_hot_blank_plus_4_digits_per_cell', + 'trm_tokens': CELLS, 'optimizer': 'AdamW(betas=(0.9, 0.95))', 'torch_threads': 1}) + receipt['data'] = {'grid_count': GRID_COUNT, 'split': 'disjoint grids per seed (train / val / held-out)', + 'grid_overlap_between_splits': [r['grid_overlap'] for r in runs], + 'mean_blanks': [r['mean_blanks'] for r in runs], + 'uniqueness': 'every puzzle has exactly one solution among the 288 grids'} + receipt['parameter_budget'] = {'trainable_parameters': params, 'mlp_hidden': runs[0]['mlp_hidden'], + 'max_relative_gap_vs_trm': gap, 'tolerance': cfg['param_tolerance'], + 'within_tolerance': bool(gap <= cfg['param_tolerance'])} + receipt['arms'] = {n: {'per_seed': per_arm[n], 'summary': summaries[n]} for n in ARMS} + receipt['best_baseline'] = {'arm': best, 'selected_by': 'highest mean validation exact-solve (held-out grids unused)'} + receipt['comparisons'] = comparisons + receipt['verdict'] = comparisons['trm_vs_best_baseline']['verdict'] + receipt['verdict_basis'] = f'trm_vs_best_baseline({best}): paired 95% t interval on held-out exact-solve over seeds' + n_sup, rec, n_lat = cfg['supervision_steps'], cfg['recursions'], cfg['n_latent_steps'] + deep = n_sup * rec * (n_lat + 1) + receipt['estimated_cost'] = { + 'inference_macs_per_puzzle': {n: per_arm[n][0]['estimated_inference_macs_per_puzzle'] for n in ARMS}, + 'network_applications_per_puzzle': {'trm': deep, 'unrolled': deep, 'shallow': n_lat + 1, 'mlp': 1}, + 'backpropagated_applications_per_update': {'trm': n_lat + 1, 'unrolled': deep, 'shallow': n_lat + 1, + 'mlp': 1}, + 'optimizer_updates_per_arm': cfg['updates'], + 'trm_examples_drawn': [a['training']['examples_drawn'] for a in per_arm['trm']], + } + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t_start, + 'train_per_arm': {n: float(np.sum([a['measured_wallclock_s']['train'] + for a in per_arm[n]])) for n in ARMS}} + receipt['notes'] = ( + 'Synthetic 4x4 Sudoku benchmark inspired by TRM (Jolicoeur-Martineau, 2025) and HRM (Wang et al., 2025); ' + 'not a reproduction. Tiny 1-block mixer net (token-mixing MLP + channel MLP, ReLU, affine-free layer norm) ' + 'on 16 cell tokens; no EMA, no augmentation (it would map training grids onto held-out grids). All arms: ' + 'same data, same example stream, same number of AdamW updates; trm, unrolled and shallow share the network ' + 'and initial weights; mlp is a flat MLP width-matched on trainable parameters, so trm_vs_mlp mixes the ' + 'recursion effect with the per-cell weight sharing, while trm_vs_unrolled isolates deep supervision and ' + 'trm_vs_shallow isolates recursion depth. TRM draws fewer distinct examples per update (each example gets ' + 'up to supervision_steps updates); unrolled backpropagates through the whole unroll (more compute per ' + 'update). Halting is trained (ACT, no Q-continue head); headline metrics use all supervision steps, ' + 'adaptive_* use the first step with halting probability > 0.5. With few seeds the paired t interval is wide.') + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/rigl.py b/synapse/frontier/rigl.py new file mode 100644 index 0000000000000000000000000000000000000000..9ecaaf42bb1e5b02a5a2786c471b7715546036c8 --- /dev/null +++ b/synapse/frontier/rigl.py @@ -0,0 +1,661 @@ +"""Dynamic sparse training with RigL-style prune-and-regrow for ``nn.Linear`` layers, plus an MLP benchmark. + +Inspired by (citation verified 2026-11-17, see ``docs/frontier/modules/rigl_sparse.md``): + +* U. Evci, T. Gale, J. Menick, P. S. Castro, E. Elsen, "Rigging the Lottery: Making All Tickets Winners", + Proceedings of the 37th International Conference on Machine Learning (ICML 2020), PMLR 119:2943-2952, + July 2020, https://proceedings.mlr.press/v119/evci20a.html (reference code: github.com/google-research/rigl) + +The sibling project ``sonapse-evo`` (``src/sonapse_evo/evaluation/rigl.py``, ``AuthenticRigL``) applies the same +drop/regrow idea to a recurrent edge vector. This module follows the paper more closely: seeded per-layer masks +with a uniform or Erdos-Renyi-Kernel (ERK) allocation, zero-initialised regrowth and no optimiser step on +connectivity-update iterations (Algorithm 1 of the paper). + +For a managed layer ``l`` with ``N_l`` weights of which ``a_l`` are active, training iterations ``t = 1, 2, ...``:: + + update iteration: t % delta_t == 0 and t < t_end + f(t) = alpha / 2 * (1 + cos(pi * t / t_end)) cosine-decayed update fraction + k_l = floor(f(t) * a_l) + drop = the k_l active weights with the smallest |w| (ties: lower flat index) + grow = the k_l weights with the largest |dL/dw| among all weights not kept (ties: lower flat index) + mask = (active - drop) | grow (a_l never changes) + +Newly activated weights start at exactly zero (so the network output is unchanged); a weight dropped and regrown +in the same update keeps its value, as in the reference code's default. On ordinary iterations the gradients are +masked before ``optimizer.step()`` and the weights are masked after it, so inactive weights stay exactly zero. +Optimiser state tensors shaped like a managed weight (momentum, Adam moments) are zeroed at inactive and newly +activated positions on every update. Biases stay dense, as in the paper. + +This is a synthetic computational abstraction: masks over dense tensors (no sparse kernels, so no measured +speed-up) and a small procedural benchmark. It does not reproduce any published result. +""" +from __future__ import annotations + +import collections +import copy +import hashlib +import math +import time +from contextlib import contextmanager +from typing import Any, Callable, Iterable, Iterator, Mapping, Sequence + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from . import harness + +__all__ = ['MODULE_ID', 'DISTRIBUTIONS', 'STATE_SCHEMA', 'cosine_drop_fraction', 'layer_densities', + 'layer_active_counts', 'RigLScheduler', 'run_experiment', 'EXPERIMENTS', 'DEFAULT_CONFIG', 'QUICK_CONFIG'] + +MODULE_ID = 'rigl_sparse' +DISTRIBUTIONS = ('uniform', 'erk') +STATE_SCHEMA = 'RigLSchedulerStateV1' +_MAX_HISTORY = 4096 +_MASK_OFFSET, _DATA_OFFSET, _TEACHER_OFFSET, _MODEL_OFFSET, _BATCH_OFFSET = 61_001, 61_103, 61_207, 61_301, 61_409 +_GUARD = 1e-9 # protects floor() against floating-point round-down of exact products + + +# ====================================================================== validation helpers +def _real(name: str, value: Any, *, low: float, high: float, low_open: bool = False, high_open: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a real number') + v = float(value) + if not math.isfinite(v) or v < low or v > high or (low_open and v == low) or (high_open and v == high): + lb, hb = '(' if low_open else '[', ')' if high_open else ']' + raise ValueError(f'{name} must be finite and in {lb}{low}, {high}{hb}') + return v + + +def _int(name: str, value: Any, low: int, high: int) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return value + + +# ====================================================================== schedule and allocation +def cosine_drop_fraction(t: int, alpha: float, t_end: int) -> float: + """RigL's ``f_decay(t; alpha, T_end) = alpha / 2 * (1 + cos(pi * t / T_end))``; 0 from ``t_end`` on.""" + _int('t', t, 0, 2**62) + a = _real('alpha', alpha, low=0.0, high=1.0) + _int('t_end', t_end, 1, 2**62) + if t >= t_end: + return 0.0 + return a / 2.0 * (1.0 + math.cos(math.pi * t / t_end)) + + +def _shapes(shapes: Iterable[Sequence[int]]) -> list[tuple[int, int]]: + out = [] + for s in shapes: + s = tuple(s) + if len(s) != 2 or any(type(v) is not int or v < 1 for v in s): + raise ValueError('layer shapes must be (out_features, in_features) pairs of positive ints') + out.append(s) + if not out: + raise ValueError('at least one layer shape is needed') + return out + + +def layer_densities(shapes: Iterable[Sequence[int]], sparsity: float, distribution: str = 'erk') -> list[float]: + """Fraction of active weights per layer for a target overall ``sparsity``. + + ``'uniform'`` gives every layer density ``1 - sparsity``. ``'erk'`` (Erdos-Renyi-Kernel; for linear layers the + Erdos-Renyi rule) makes density proportional to ``(n_in + n_out) / (n_in * n_out)`` with one scale ``eps`` + chosen so the total active count matches the uniform budget; a layer whose density would exceed 1 is made + dense and ``eps`` is recomputed for the rest (as in the reference implementation).""" + shp = _shapes(shapes) + s = _real('sparsity', sparsity, low=0.0, high=1.0, high_open=True) + if distribution not in DISTRIBUTIONS: + raise ValueError(f'distribution must be one of {DISTRIBUTIONS}') + if distribution == 'uniform': + return [1.0 - s] * len(shp) + sizes = [o * i for o, i in shp] + raw = [(o + i) / (o * i) for o, i in shp] + dense: set[int] = set() + eps = 0.0 + while True: + rhs = divisor = 0.0 + for j, n in enumerate(sizes): + zeros = math.floor(s * n + _GUARD) + if j in dense: + rhs -= zeros + else: + rhs += n - zeros + divisor += raw[j] * n + if divisor <= 0.0: # every layer had to be dense + return [1.0] * len(shp) + eps = rhs / divisor + free = [j for j in range(len(shp)) if j not in dense] + top = max(raw[j] for j in free) + if eps * top <= 1.0: + break + dense.update(j for j in free if raw[j] == top) + return [1.0 if j in dense else min(1.0, max(0.0, eps * raw[j])) for j in range(len(shp))] + + +def layer_active_counts(shapes: Iterable[Sequence[int]], sparsity: float, distribution: str = 'erk') -> list[int]: + """Active weights per layer: ``N - floor((1 - density) * N)``, at least 1 and at most ``N``.""" + shp = _shapes(shapes) + counts = [] + for (o, i), d in zip(shp, layer_densities(shp, sparsity, distribution)): + n = o * i + counts.append(n if d >= 1.0 else min(n, max(1, n - math.floor((1.0 - d) * n + _GUARD)))) + return counts + + +# ====================================================================== scheduler +class RigLScheduler: + """Masks, schedule and prune/regrow updates for the ``nn.Linear`` layers of a model. + + Usage, once per training iteration after ``loss.backward()``:: + + scheduler.step(optimizer) # returns False on connectivity-update iterations (no optimiser step) + + ``layers`` defaults to every ``nn.Linear`` of ``model`` (in ``model.modules()`` order). The initial masks are + drawn from ``numpy.random.default_rng(seed + offset)`` and applied to the weights at construction. + ``dynamic=False`` keeps the initial masks for the whole run (static sparse training with identical masks). + At most ``history`` update records are kept. + """ + + def __init__(self, model: nn.Module, sparsity: float, delta_t: int = 100, alpha: float = 0.3, t_end: int = 1000, + distribution: str = 'erk', *, layers: Sequence[nn.Linear] | None = None, seed: int = 0, + dynamic: bool = True, history: int = 256) -> None: + if not isinstance(model, nn.Module): + raise ValueError('model must be a torch.nn.Module') + sparsity = _real('sparsity', sparsity, low=0.0, high=1.0, high_open=True) + _int('delta_t', delta_t, 1, 10**9) + alpha = _real('alpha', alpha, low=0.0, high=1.0) + _int('t_end', t_end, 1, 10**12) + if distribution not in DISTRIBUTIONS: + raise ValueError(f'distribution must be one of {DISTRIBUTIONS}') + _int('seed', seed, 0, 2**31 - 1) + if type(dynamic) is not bool: + raise ValueError('dynamic must be a bool') + _int('history', history, 1, _MAX_HISTORY) + modules = list(model.modules()) + if layers is None: + chosen, explicit = [m for m in modules if isinstance(m, nn.Linear)], False + else: + if isinstance(layers, nn.Module): + raise ValueError('layers must be a sequence of nn.Linear modules') + chosen, explicit = list(layers), True + known = {id(m) for m in modules} + if not all(isinstance(m, nn.Linear) and id(m) in known for m in chosen): + raise ValueError('layers must be nn.Linear modules of model') + seen: set[int] = set() + managed: list[nn.Linear] = [] + for m in chosen: + if id(m.weight) in seen: + if explicit: + raise ValueError('layers must not repeat a weight') + continue # a module reused in the graph is managed once + seen.add(id(m.weight)) + managed.append(m) + if not managed: + raise ValueError('model has no nn.Linear layer to sparsify') + if not all(m.weight.is_floating_point() for m in managed): + raise ValueError('managed weights must be floating point') + shapes = [tuple(int(v) for v in m.weight.shape) for m in managed] + self.sparsity, self.delta_t, self.alpha, self.t_end = sparsity, delta_t, alpha, t_end + self.distribution, self.seed, self.dynamic = distribution, seed, dynamic + self.layers: list[nn.Linear] = managed + self.shapes: list[tuple[int, int]] = shapes + self.densities: list[float] = layer_densities(shapes, sparsity, distribution) + self.target_counts: list[int] = layer_active_counts(shapes, sparsity, distribution) + rng = np.random.default_rng(seed + _MASK_OFFSET) + masks = [] + for m, count in zip(managed, self.target_counts): + flat = np.zeros(m.weight.numel(), dtype=bool) + flat[rng.permutation(flat.size)[:count]] = True + masks.append(torch.from_numpy(flat.reshape(m.weight.shape)).to(m.weight.device)) + self._masks: list[torch.Tensor] = masks + self._sparse = [c < m.weight.numel() for m, c in zip(managed, self.target_counts)] + self.t = 0 + self.n_updates = 0 + self._history: collections.deque[dict[str, Any]] = collections.deque(maxlen=history) + self.apply_masks() + + # ------------------------------------------------------------------ introspection + @property + def masks(self) -> list[torch.Tensor]: + """Copies of the boolean masks (``True`` = active), one per managed layer.""" + return [m.clone() for m in self._masks] + + @property + def history(self) -> list[dict[str, Any]]: + return copy.deepcopy(list(self._history)) + + def active_counts(self) -> list[int]: + return [int(m.sum()) for m in self._masks] + + def is_update_step(self, t: int) -> bool: + """Whether training iteration ``t`` (1-based) is a connectivity update.""" + _int('t', t, 0, 2**62) + return bool(self.dynamic and any(self._sparse) and t >= 1 and t % self.delta_t == 0 and t < self.t_end) + + def drop_fraction(self, t: int) -> float: + return cosine_drop_fraction(t, self.alpha, self.t_end) + + def parameter_budget(self) -> dict[str, Any]: + """Active managed weights, managed totals and dense biases of the managed layers.""" + active = self.active_counts() + total = [m.weight.numel() for m in self.layers] + biases = int(sum(m.bias.numel() for m in self.layers if m.bias is not None)) + return {'active_weights': int(sum(active)), 'managed_weights': int(sum(total)), 'biases': biases, + 'density': float(sum(active) / sum(total)), 'per_layer_active': active, + 'per_layer_total': total, 'per_layer_density': [a / n for a, n in zip(active, total)]} + + def summary(self) -> dict[str, Any]: + return {'sparsity': self.sparsity, 'distribution': self.distribution, 'delta_t': self.delta_t, + 'alpha': self.alpha, 't_end': self.t_end, 'dynamic': self.dynamic, 'seed': self.seed, 't': self.t, + 'n_updates': self.n_updates, 'shapes': [list(s) for s in self.shapes], + 'target_counts': list(self.target_counts), **self.parameter_budget(), + 'last_update': copy.deepcopy(self._history[-1]) if self._history else None} + + # ------------------------------------------------------------------ masking + @torch.no_grad() + def apply_masks(self) -> None: + """Set every inactive managed weight to exactly zero.""" + for layer, mask in zip(self.layers, self._masks): + layer.weight.masked_fill_(~mask, 0.0) + + @torch.no_grad() + def mask_gradients(self) -> None: + """Zero the gradients of inactive weights (call after ``backward``, before ``optimizer.step``).""" + for layer, mask in zip(self.layers, self._masks): + grad = layer.weight.grad + if grad is None: + continue + if grad.is_sparse: + raise ValueError('sparse gradients are not supported') + grad.masked_fill_(~mask, 0.0) + + # ------------------------------------------------------------------ prune and regrow + @torch.no_grad() + def update_connections(self, fraction: float, optimizer: torch.optim.Optimizer | None = None) -> dict[str, Any]: + """Drop ``floor(fraction * a_l)`` smallest-magnitude active weights per layer and grow as many by dense + gradient magnitude. Needs the dense gradients of the current batch (before :meth:`mask_gradients`). + Everything is validated before any mask, weight or optimiser state changes.""" + f = _real('fraction', fraction, low=0.0, high=1.0) + if optimizer is not None and not isinstance(optimizer, torch.optim.Optimizer): + raise ValueError('optimizer must be a torch.optim.Optimizer or None') + grads = [] + for layer in self.layers: + grad = layer.weight.grad + if grad is None or grad.is_sparse or grad.shape != layer.weight.shape: + raise ValueError('a RigL update needs the dense gradient of every managed layer') + if not bool(torch.isfinite(grad).all()): + raise ValueError('non-finite gradient: connectivity update refused (nothing changed)') + grads.append(grad) + plans: list[tuple[int, torch.Tensor] | None] = [] + for layer, mask, grad, sparse in zip(self.layers, self._masks, grads, self._sparse): + flat = mask.reshape(-1) + n_active = int(flat.sum()) + k = int(math.floor(f * n_active + _GUARD)) + if k == 0 or not sparse: + plans.append(None) + continue + active_idx = torch.nonzero(flat).reshape(-1) # ascending flat indices + weight = layer.weight.detach().reshape(-1) + drop = active_idx[torch.sort(weight[active_idx].abs(), stable=True).indices[:k]] + keep = flat.clone() + keep[drop] = False + candidates = torch.nonzero(~keep).reshape(-1) # inactive + just dropped + score = grad.detach().reshape(-1)[candidates].abs() + grow = candidates[torch.sort(score, descending=True, stable=True).indices[:k]] + new = keep.clone() + new[grow] = True + plans.append((k, new.reshape(mask.shape))) + records = [] + for i, (layer, plan) in enumerate(zip(self.layers, plans)): + if plan is None: + records.append({'k': 0, 'activated': 0, 'regrown_same': 0}) + continue + k, new_mask = plan + activated = new_mask & ~self._masks[i] + layer.weight.masked_fill_(activated, 0.0) # newly activated weights start at zero + layer.weight.masked_fill_(~new_mask, 0.0) # dropped weights are removed + self._masks[i] = new_mask + if optimizer is not None: + _reset_optimizer_state(optimizer, layer.weight, new_mask & ~activated) + n_new = int(activated.sum()) + records.append({'k': k, 'activated': n_new, 'regrown_same': k - n_new}) + self.n_updates += 1 + record = {'t': self.t + 1, 'fraction': f, 'layers': records} + self._history.append(record) + return copy.deepcopy(record) + + def step(self, optimizer: torch.optim.Optimizer) -> bool: + """Process one training iteration after ``loss.backward()``. + + On an update iteration the connectivity is updated and the optimiser step is skipped (RigL Algorithm 1); + otherwise gradients are masked and ``optimizer.step()`` runs. Masks are re-applied to the weights either + way. Returns ``True`` when the optimiser stepped.""" + if not isinstance(optimizer, torch.optim.Optimizer): + raise ValueError('optimizer must be a torch.optim.Optimizer') + t = self.t + 1 + if self.is_update_step(t): + self.update_connections(self.drop_fraction(t), optimizer) + stepped = False + else: + self.mask_gradients() + optimizer.step() + stepped = True + self.apply_masks() + self.t = t + return stepped + + # ------------------------------------------------------------------ persistence + def _config(self) -> dict[str, Any]: + return {'sparsity': self.sparsity, 'delta_t': self.delta_t, 'alpha': self.alpha, 't_end': self.t_end, + 'distribution': self.distribution, 'seed': self.seed, 'dynamic': self.dynamic, + 'shapes': [list(s) for s in self.shapes]} + + def state_dict(self) -> dict[str, Any]: + return {'schema': STATE_SCHEMA, 'config': self._config(), 't': self.t, 'n_updates': self.n_updates, + 'masks': [m.detach().cpu().clone() for m in self._masks], 'history': self.history} + + def load_state_dict(self, state: Mapping[str, Any]) -> None: + """Validate everything (configuration, mask shapes and per-layer budgets), then load and re-apply masks.""" + if not isinstance(state, Mapping) or state.get('schema') != STATE_SCHEMA: + raise ValueError('not a RigL scheduler state') + if state.get('config') != self._config(): + raise ValueError('RigL state was saved with a different configuration or model') + t, n_updates = state.get('t'), state.get('n_updates') + if type(t) is not int or not 0 <= t <= 2**62 or type(n_updates) is not int or not 0 <= n_updates <= 2**62: + raise ValueError('RigL state has invalid step counters') + masks = state.get('masks') + if not isinstance(masks, (list, tuple)) or len(masks) != len(self.layers): + raise ValueError('RigL state has the wrong number of masks') + for mask, layer, count in zip(masks, self.layers, self.target_counts): + if (not isinstance(mask, torch.Tensor) or mask.dtype != torch.bool or mask.shape != layer.weight.shape + or int(mask.sum()) != count): + raise ValueError('RigL masks must be boolean, shaped like their weights and keep the layer budget') + history = state.get('history') + if (not isinstance(history, (list, tuple)) or len(history) > _MAX_HISTORY + or not all(isinstance(h, Mapping) for h in history)): + raise ValueError('RigL state has an invalid history') + self._masks = [m.detach().clone().to(layer.weight.device) for m, layer in zip(masks, self.layers)] + self.t, self.n_updates = t, n_updates + self._history = collections.deque(copy.deepcopy(list(history)), maxlen=self._history.maxlen) + self.apply_masks() + + +def _reset_optimizer_state(optimizer: torch.optim.Optimizer, weight: torch.Tensor, keep: torch.Tensor) -> None: + """Zero every per-element optimiser state tensor of ``weight`` outside ``keep``.""" + state = optimizer.state.get(weight) + if not state: + return + for value in state.values(): + if isinstance(value, torch.Tensor) and value.shape == weight.shape and value.is_floating_point(): + value.masked_fill_(~keep, 0.0) + + +# ====================================================================== benchmark +DEFAULT_CONFIG: dict[str, Any] = { + 'n_inputs': 64, 'n_informative': 8, 'n_classes': 4, 'teacher_hidden': 16, 'teacher_gain': 2.0, + 'hidden': 128, 'n_train': 4096, 'n_val': 1024, 'n_test': 2048, 'steps': 2000, 'batch_size': 64, + 'lr': 0.05, 'momentum': 0.9, 'weight_decay': 1e-4, 'sparsity': 0.9, 'distribution': 'erk', + 'delta_t': 50, 'alpha': 0.3, 't_end_fraction': 0.75, +} +QUICK_CONFIG: dict[str, Any] = {'hidden': 64, 'n_train': 1024, 'n_val': 256, 'n_test': 512, 'steps': 300, + 'delta_t': 25} +ARMS = ('dense', 'static_sparse', 'rigl') + + +@contextmanager +def _one_torch_thread() -> Iterator[None]: + """Run with one intra-op thread (stable float results, no oversubscription); restore the caller's count.""" + before = torch.get_num_threads() + try: + if before != 1: + torch.set_num_threads(1) + yield + finally: + if torch.get_num_threads() != before: + torch.set_num_threads(before) + + +def _seeds(seeds: Any) -> tuple[int, ...]: + out = tuple(seeds) + if not out or any(type(s) is not int or not 0 <= s <= 2**31 - 1 for s in out) or len(set(out)) != len(out): + raise ValueError('seeds must be a non-empty sequence of unique ints in [0, 2**31 - 1]') + return out + + +def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + unknown = set(overrides) - set(DEFAULT_CONFIG) + if unknown: + raise ValueError(f'unknown rigl_sparse options: {sorted(unknown)}') + cfg = {**DEFAULT_CONFIG, **(QUICK_CONFIG if quick else {}), **dict(overrides)} + _int('n_inputs', cfg['n_inputs'], 2, 4096) + _int('n_informative', cfg['n_informative'], 1, cfg['n_inputs']) + _int('n_classes', cfg['n_classes'], 2, 64) + _int('teacher_hidden', cfg['teacher_hidden'], 1, 1024) + cfg['teacher_gain'] = _real('teacher_gain', cfg['teacher_gain'], low=0.0, high=100.0, low_open=True) + _int('hidden', cfg['hidden'], 2, 4096) + for name in ('n_train', 'n_val', 'n_test'): + _int(name, cfg[name], 8, 1_000_000) + _int('steps', cfg['steps'], 1, 1_000_000) + _int('batch_size', cfg['batch_size'], 1, 65_536) + cfg['lr'] = _real('lr', cfg['lr'], low=0.0, high=10.0, low_open=True) + cfg['momentum'] = _real('momentum', cfg['momentum'], low=0.0, high=1.0, high_open=True) + cfg['weight_decay'] = _real('weight_decay', cfg['weight_decay'], low=0.0, high=1.0) + cfg['sparsity'] = _real('sparsity', cfg['sparsity'], low=0.0, high=1.0, high_open=True) + if cfg['distribution'] not in DISTRIBUTIONS: + raise ValueError(f'distribution must be one of {DISTRIBUTIONS}') + _int('delta_t', cfg['delta_t'], 1, 10**9) + cfg['alpha'] = _real('alpha', cfg['alpha'], low=0.0, high=1.0) + cfg['t_end_fraction'] = _real('t_end_fraction', cfg['t_end_fraction'], low=0.0, high=1.0, low_open=True) + return cfg + + +def _task(seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]: + """Procedural ``sparse_teacher`` classification: Gaussian inputs, of which only ``n_informative`` (a seeded + random subset) drive the label; the label is the argmax of a fixed random tanh teacher on those inputs, with + class logits centred on the training split. Every other input is a distractor.""" + rng = np.random.default_rng(seed + _DATA_OFFSET) + d, m, c, h = cfg['n_inputs'], cfg['n_informative'], cfg['n_classes'], cfg['teacher_hidden'] + informative = np.sort(rng.choice(d, size=m, replace=False)) + n = {k: cfg[f'n_{k}'] for k in ('train', 'val', 'test')} + x = {k: rng.standard_normal((n[k], d)) for k in ('train', 'val', 'test')} + trng = np.random.default_rng(seed + _TEACHER_OFFSET) + a = trng.standard_normal((m, h)) * (cfg['teacher_gain'] / math.sqrt(m)) + b = trng.standard_normal(h) * 0.5 + w = trng.standard_normal((h, c)) / math.sqrt(h) + logits = {k: np.tanh(v[:, informative] @ a + b) @ w for k, v in x.items()} + centre = logits['train'].mean(axis=0, keepdims=True) + y = {k: np.argmax(v - centre, axis=1) for k, v in logits.items()} + batches = np.random.default_rng(seed + _BATCH_OFFSET).integers(0, n['train'], size=(cfg['steps'], cfg['batch_size'])) + freq = np.bincount(y['train'], minlength=c) / n['train'] + return {'x': {k: torch.from_numpy(v.astype(np.float32)) for k, v in x.items()}, + 'y': {k: torch.from_numpy(v.astype(np.int64)) for k, v in y.items()}, + 'batches': torch.from_numpy(batches), 'informative': informative.tolist(), + 'class_frequencies_train': freq.tolist(), + 'majority_rate_test': float(np.bincount(y['test'], minlength=c).max() / n['test'])} + + +def _mlp(cfg: Mapping[str, Any], generator: torch.Generator) -> nn.Sequential: + """``n_inputs -> hidden -> hidden -> n_classes`` ReLU MLP with PyTorch's default ``nn.Linear`` distribution, + drawn from ``generator`` only (the global torch RNG is left untouched).""" + with torch.random.fork_rng(devices=[]): # nn.Linear construction draws from the global RNG: restore it + net = nn.Sequential(nn.Linear(cfg['n_inputs'], cfg['hidden']), nn.ReLU(), + nn.Linear(cfg['hidden'], cfg['hidden']), nn.ReLU(), + nn.Linear(cfg['hidden'], cfg['n_classes'])) + with torch.no_grad(): + for m in net.modules(): + if isinstance(m, nn.Linear): + bound = 1.0 / math.sqrt(m.in_features) + m.weight.copy_((torch.rand(m.weight.shape, generator=generator) * 2.0 - 1.0) * bound) + m.bias.copy_((torch.rand(m.bias.shape, generator=generator) * 2.0 - 1.0) * bound) + return net + + +def _accuracy(net: nn.Module, x: torch.Tensor, y: torch.Tensor) -> float: + with torch.no_grad(): + return float((net(x).argmax(dim=1) == y).double().mean()) + + +def _informative_share(first: nn.Linear, mask: torch.Tensor | None, informative: Sequence[int]) -> float: + """Share of the first layer's active connections that read an informative input (chance: m / d).""" + m = torch.ones_like(first.weight, dtype=torch.bool) if mask is None else mask + return float(m[:, list(informative)].sum() / m.sum()) + + +def _train_arm(arm: str, seed: int, task: Mapping[str, Any], cfg: Mapping[str, Any], t_end: int) -> dict[str, Any]: + net = _mlp(cfg, torch.Generator().manual_seed(seed + _MODEL_OFFSET)) + opt = torch.optim.SGD(net.parameters(), lr=cfg['lr'], momentum=cfg['momentum'], weight_decay=cfg['weight_decay']) + sched = None + if arm != 'dense': + sched = RigLScheduler(net, cfg['sparsity'], cfg['delta_t'], cfg['alpha'], t_end, cfg['distribution'], + seed=seed, dynamic=(arm == 'rigl'), history=_MAX_HISTORY) + first = net[0] + initial_masks = None if sched is None else sched.masks + x, y = task['x']['train'], task['y']['train'] + optimizer_steps, last_loss, diverged = 0, None, False + for t in range(cfg['steps']): + idx = task['batches'][t] + loss = F.cross_entropy(net(x[idx]), y[idx]) + if not bool(torch.isfinite(loss)): + diverged = True + break + opt.zero_grad(set_to_none=True) + loss.backward() + if sched is None: + opt.step() + optimizer_steps += 1 + else: + optimizer_steps += int(sched.step(opt)) + last_loss = float(loss.detach()) + linears = [m for m in net if isinstance(m, nn.Linear)] + out: dict[str, Any] = { + 'seed': seed, 'diverged': diverged, 'final_train_loss': last_loss, 'optimizer_steps': optimizer_steps, + 'train_accuracy': _accuracy(net, x, y), + 'val_accuracy': _accuracy(net, task['x']['val'], task['y']['val']), + 'test_accuracy': _accuracy(net, task['x']['test'], task['y']['test'])} + if sched is None: + active = [m.weight.numel() for m in linears] + out['informative_share_initial'] = out['informative_share_final'] = _informative_share( + first, None, task['informative']) + else: + masks = sched.masks + inactive_zero = all(not bool(layer.weight.detach()[~mask].any()) for layer, mask in zip(sched.layers, masks)) + active = sched.active_counts() + hist = sched.history + out.update({ + 'informative_share_initial': _informative_share(first, initial_masks[0], task['informative']), + 'informative_share_final': _informative_share(first, masks[0], task['informative']), + 'initial_mask_digest': _mask_digest(initial_masks), 'final_mask_digest': _mask_digest(masks), + 'connectivity_updates': sched.n_updates, + 'connections_activated': int(sum(r['activated'] for h in hist for r in h['layers'])), + 'update_trace': [{'t': h['t'], 'fraction': h['fraction'], 'k': [r['k'] for r in h['layers']], + 'activated': [r['activated'] for r in h['layers']]} for h in hist], + 'budget_constant': bool(active == sched.target_counts), 'inactive_weights_zero': inactive_zero}) + out['active_weights_per_layer'] = [int(a) for a in active] + out['parameters'] = int(sum(active) + sum(m.bias.numel() for m in linears)) + return out + + +def _mask_digest(masks: Sequence[torch.Tensor]) -> str: + h = hashlib.sha256() + for m in masks: + h.update(np.packbits(m.detach().cpu().numpy().reshape(-1)).tobytes()) + return h.hexdigest() + + +def _flops(shapes: Sequence[tuple[int, int]], active: Sequence[int], batch: int, delta_t: int, t_end: int, + steps: int) -> dict[str, Any]: + """Analytic training FLOPs per iteration, assuming ideal sparse kernels (this module uses dense matmuls).""" + dense = sum(o * i for o, i in shapes) + act = int(sum(active)) + updates = sum(1 for t in range(1, steps + 1) if t % delta_t == 0 and t < t_end) + # ordinary iteration: forward 2BA + input-gradient 2BA + weight-gradient 2BA (A = active weights); + # update iteration: forward and input-gradient sparse, weight-gradient dense (2BN), no optimiser step. + return {'dense_per_iteration': 6 * batch * dense, 'static_sparse_per_iteration': 6 * batch * act, + 'rigl_mean_per_iteration': int(round(((steps - updates) * 6 * batch * act + + updates * (4 * batch * act + 2 * batch * dense)) / steps)), + 'rigl_update_iterations': updates, + 'note': 'analytic estimates (multiply-adds x2) for ideal sparse kernels; not measured'} + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """RigL (candidate) vs static random sparse (same initial masks and budget) vs dense, held-out accuracy. + + For every seed a procedural ``sparse_teacher`` task is generated; the three arms share the network + initialisation, the minibatch sequence, the optimiser (SGD with momentum) and the number of training + iterations. The verdict is the paired 95 % t interval of RigL minus static-sparse test accuracy.""" + if type(quick) is not bool: + raise ValueError('quick must be a bool') + seeds = _seeds(seeds) + cfg = _config(quick, overrides) + t_end = max(1, int(math.floor(cfg['t_end_fraction'] * cfg['steps'] + _GUARD))) + t0 = time.perf_counter() + walls = {arm: 0.0 for arm in ARMS} + per_arm: dict[str, list[dict[str, Any]]] = {arm: [] for arm in ARMS} + tasks = {} + with _one_torch_thread(): + for seed in seeds: + task = _task(seed, cfg) + tasks[str(seed)] = {'informative_inputs': task['informative'], + 'class_frequencies_train': task['class_frequencies_train'], + 'majority_rate_test': task['majority_rate_test']} + for arm in ARMS: + t1 = time.perf_counter() + per_arm[arm].append(_train_arm(arm, seed, task, cfg, t_end)) + walls[arm] += time.perf_counter() - t1 + probe = RigLScheduler(_mlp(cfg, torch.Generator().manual_seed(0)), cfg['sparsity'], cfg['delta_t'], + cfg['alpha'], t_end, cfg['distribution'], seed=0) + acc = {arm: [r['test_accuracy'] for r in per_arm[arm]] for arm in ARMS} + diverged = {arm: [r['seed'] for r in per_arm[arm] if r['diverged']] for arm in ARMS} + comparisons = {'rigl_vs_static_sparse': harness.compare(acc['rigl'], acc['static_sparse']), + 'rigl_vs_dense': harness.compare(acc['rigl'], acc['dense']), + 'static_sparse_vs_dense': harness.compare(acc['static_sparse'], acc['dense'])} + verdict = comparisons['rigl_vs_static_sparse']['verdict'] + basis = 'rigl_vs_static_sparse_paired_t95_on_heldout_test_accuracy' + if diverged['rigl'] or diverged['static_sparse']: + verdict = 'worse' if diverged['rigl'] and not diverged['static_sparse'] else 'no_detectable_difference' + basis = 'training_diverged' + receipt = harness.base_receipt(MODULE_ID, 'sparse_training_comparison', { + 'quick': quick, 'seeds': list(seeds), **cfg, 't_end': t_end, + 'task': 'sparse_teacher_classification (seeded informative-input subset; others are distractors)', + 'model': f"MLP {cfg['n_inputs']}-{cfg['hidden']}-{cfg['hidden']}-{cfg['n_classes']} (ReLU)", + 'optimizer': 'torch.optim.SGD(lr, momentum, weight_decay), identical in every arm', + 'metric': 'heldout_test_accuracy (higher is better)', 'arms': list(ARMS), + 'candidate': 'rigl', 'reference': 'static_sparse (same initial masks, same budget)'}) + receipt['arms'] = {arm: {'per_seed': per_arm[arm], 'diverged_seeds': diverged[arm], 'summary': { + 'test_accuracy': harness._mean(acc[arm]), + 'val_accuracy': harness._mean(r['val_accuracy'] for r in per_arm[arm]), + 'train_accuracy': harness._mean(r['train_accuracy'] for r in per_arm[arm]), + 'informative_share_final': harness._mean(r['informative_share_final'] for r in per_arm[arm]), + 'parameters': per_arm[arm][0]['parameters']}} for arm in ARMS} + receipt['comparisons'] = comparisons + receipt['verdict'] = verdict + receipt['verdict_basis'] = basis + budget = probe.parameter_budget() + receipt['budget'] = {'sparse_parameters': budget['active_weights'] + budget['biases'], + 'dense_parameters': budget['managed_weights'] + budget['biases'], + 'active_weights': budget['active_weights'], 'managed_weights': budget['managed_weights'], + 'realised_density': budget['density'], 'per_layer_active': budget['per_layer_active'], + 'per_layer_density': budget['per_layer_density'], + 'static_and_rigl_share_initial_masks': all( + a['initial_mask_digest'] == b['initial_mask_digest'] + for a, b in zip(per_arm['static_sparse'], per_arm['rigl'])), + 'rigl_budget_constant': all(r['budget_constant'] for r in per_arm['rigl']), + 'inactive_weights_zero': all(r['inactive_weights_zero'] + for arm in ('static_sparse', 'rigl') for r in per_arm[arm])} + receipt['estimated_cost'] = _flops(probe.shapes, budget['per_layer_active'], cfg['batch_size'], cfg['delta_t'], + t_end, cfg['steps']) + receipt['task'] = tasks + receipt['notes'] = ('Synthetic procedural classification in which only a seeded subset of inputs carries the ' + 'label, chosen so that which connections exist matters; inspired by RigL (Evci et al., ' + '2020), not a reproduction. Equal training iterations, shared initialisation and minibatches; ' + 'RigL skips the optimiser step on its connectivity-update iterations (Algorithm 1), so it ' + 'takes slightly fewer optimiser steps. Masks are applied to dense tensors, so there is no ' + 'measured speed-up. Quick mode is a pipeline check; its verdict is weak evidence. Results may ' + 'not transfer to other tasks, sparsities or optimisers.') + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0, **{f'{arm}_runs': walls[arm] for arm in ARMS}} + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/runtime.py b/synapse/frontier/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..9be33d839fe3993ea0e4d563cbd9dab6e47a897e --- /dev/null +++ b/synapse/frontier/runtime.py @@ -0,0 +1,386 @@ +"""Live read-only observer hub and unified experiment registry for the Sonapse frontier pack. + +Contract rules enforced here (see ``docs/frontier/CONTRACT.md``): + +1. **Additive and default-off.** When ``spec.enabled`` is ``False`` (or ``spec`` has no observer modules), + :meth:`FrontierObserverHub.observe` is a no-op and returns ``False``. +2. **Read-only live observers.** :meth:`FrontierObserverHub.observe` copies a deterministic unit subsample + out of the brain activity vector (NumPy array or PyTorch tensor) before passing it to each observer, + and never mutates the caller's array/tensor, the brain, the graft bus, the actor or global RNG state. +3. **Validate-before-mutate persistence.** :meth:`FrontierObserverHub.import_state` validates the incoming + checkpoint on a fresh detached candidate hub before swapping state into ``self``. +4. **Verified lab receipts.** :func:`run_frontier_experiment` and :func:`run_all_frontier_experiments` + verify every receipt with :func:`synapse.frontier.harness.verify_receipt` before returning it. +""" +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping +from copy import deepcopy +import importlib +from typing import Any + +import numpy as np + +from .harness import _jsonable, receipt_digest, verify_receipt +from .spec import (EVIDENCE_TIER, LAB_SCHEMA, MODULE_IDS, MODULES, OBSERVER_MODULE_IDS, + FrontierSpecV1) + +__all__ = [ + 'OBSERVER_SUMMARY_SCHEMA', 'OBSERVER_CHECKPOINT_SCHEMA', 'LABORATORY_SCHEMA', + 'MODULE_FILES', 'OBSERVER_CLASSES', 'FrontierObserverHub', 'load_frontier_module', + 'make_observer', 'discover_experiments', 'experiment_catalog', + 'run_frontier_experiment', 'run_all_frontier_experiments', 'run_frontier_laboratory', +] + +OBSERVER_SUMMARY_SCHEMA = 'FrontierObserverSummaryV1' +OBSERVER_CHECKPOINT_SCHEMA = 'FrontierObserverCheckpointV1' +LABORATORY_SCHEMA = 'FrontierLaboratoryReceiptV1' +_HUB_SUBSAMPLE_OFFSET = 50_021 + +MODULE_FILES: dict[str, str] = { + 'synchrony': 'synchrony', + 'continuum_memory': 'continuum_memory', + 'btsp_memory': 'btsp', + 'kuramoto_binding': 'kuramoto', + 'recursive_refiner': 'recursive_refiner', + 'dendritic_layer': 'dendritic', + 'muon_optimizer': 'muon', + 'rigl_sparse': 'rigl', + 'sparse_dictionary': 'sparse_dictionary', + 'anytime_inference': 'anytime', + 'experiment_design': 'experiment_design', + 'quality_diversity': 'quality_diversity', + 'morphogenesis': 'morphogenesis', + 'connectomics': 'connectomics', + 'causal_emergence': 'causal_emergence', + 'hh_cable': 'hh_cable', + 'nir_export': 'nir_export', + 'joint_failure': 'joint_failure', +} + +OBSERVER_CLASSES: dict[str, tuple[str, str]] = { + 'synchrony': ('synchrony', 'SynchronyObserver'), + 'kuramoto_binding': ('kuramoto', 'KuramotoObserver'), + 'sparse_dictionary': ('sparse_dictionary', 'SparseDictionaryObserver'), + 'connectomics': ('connectomics', 'ConnectivityObserver'), + 'causal_emergence': ('causal_emergence', 'CausalEmergenceObserver'), +} + + +def load_frontier_module(module_id: str) -> Any: + """Import ``synapse.frontier.`` for a module id.""" + if module_id not in MODULE_FILES: + raise KeyError(f'unknown frontier module: {module_id!r}') + file_stem = MODULE_FILES[module_id] + return importlib.import_module(f'{__package__}.{file_stem}') + + +def make_observer(module_id: str, n_units: int, spec: FrontierSpecV1) -> Any: + """Instantiate a single read-only observer for ``module_id`` sized from ``spec``.""" + if not isinstance(spec, FrontierSpecV1): + raise ValueError('spec must be a FrontierSpecV1') + if module_id not in OBSERVER_CLASSES or module_id not in OBSERVER_MODULE_IDS: + raise ValueError(f'{module_id!r} is not a registered observer module') + file_stem, cls_name = OBSERVER_CLASSES[module_id] + mod = importlib.import_module(f'{__package__}.{file_stem}') + cls = getattr(mod, cls_name) + if hasattr(cls, 'from_spec'): + return cls.from_spec(n_units, spec) + return cls(n_units, seed=int(spec.seed), history=int(spec.history)) + + +def _extract_1d_activity(x: Any, expected_len: int) -> np.ndarray: + """Return a validated 1-D float64 NumPy view/copy of ``x`` without mutating the input.""" + if hasattr(x, 'detach') and hasattr(x, 'cpu') and hasattr(x, 'numpy'): + arr = np.asarray(x.detach().cpu().numpy(), dtype=np.float64) + else: + arr = np.asarray(x, dtype=np.float64) + if arr.ndim != 1 or arr.shape[0] != expected_len: + raise ValueError(f'activity must be a 1-D vector of length {expected_len}') + if not np.all(np.isfinite(arr)): + raise ValueError('activity must be finite') + return arr + + +class FrontierObserverHub: + """Manages the active read-only frontier observers attached to a Sonapse brain.""" + + def __init__(self, spec: FrontierSpecV1, n_units: int) -> None: + if not isinstance(spec, FrontierSpecV1): + raise ValueError('spec must be a FrontierSpecV1') + if type(n_units) is not int or not 2 <= n_units <= 1_000_000: + raise ValueError('n_units must be an int in [2, 1000000]') + self.spec = spec + self.n_units = n_units + self.observed_unit_count = min(n_units, int(spec.max_observed_units)) + if self.observed_unit_count == n_units: + indices = np.arange(n_units, dtype=np.int64) + else: + rng = np.random.default_rng(int(spec.seed) + _HUB_SUBSAMPLE_OFFSET) + indices = np.sort(rng.choice(n_units, size=self.observed_unit_count, replace=False)).astype(np.int64) + indices.setflags(write=False) + self._unit_indices = indices + self.observers: dict[str, Any] = {} + if spec.enabled: + for mod_id in spec.modules: + self.observers[mod_id] = make_observer(mod_id, self.observed_unit_count, spec) + self.agent_steps = 0 + self.observed_steps = 0 + + @property + def enabled(self) -> bool: + return bool(self.spec.enabled) + + @property + def unit_indices(self) -> np.ndarray: + return self._unit_indices.copy() + + def reset(self) -> None: + self.agent_steps = 0 + self.observed_steps = 0 + for obs in self.observers.values(): + obs.reset() + + def observe(self, activity: Any) -> bool: + """Read a copy of ``activity`` into active observers on every ``observe_every``-th step.""" + arr = _extract_1d_activity(activity, self.n_units) + if not self.spec.enabled or not self.observers: + return False + step_idx = self.agent_steps + self.agent_steps += 1 + if step_idx % int(self.spec.observe_every) != 0: + return False + sample = np.array(arr[self._unit_indices], dtype=np.float64, copy=True) + for obs in self.observers.values(): + obs.observe(sample.copy()) + self.observed_steps += 1 + return True + + def summary(self) -> dict[str, Any]: + return _jsonable({ + 'schema': OBSERVER_SUMMARY_SCHEMA, + 'schema_version': 1, + 'enabled': bool(self.spec.enabled), + 'spec_digest': self.spec.spec_digest, + 'n_units': self.n_units, + 'observed_unit_count': self.observed_unit_count, + 'observe_every': int(self.spec.observe_every), + 'agent_steps': self.agent_steps, + 'observed_steps': self.observed_steps, + 'modules': list(self.spec.modules), + 'observers': {mod_id: obs.summary() for mod_id, obs in self.observers.items()}, + 'evidence_tier': EVIDENCE_TIER, + }) + + def telemetry(self, *, heavy_every: int = 32) -> dict[str, Any]: + """Deterministic low-overhead step telemetry for ``agent.last_telemetry['frontier']``. + + Sub-millisecond observers are summarized every step; null-calibrated observers + (``causal_emergence``) run full summaries below ``heavy_every`` and on multiples + of ``heavy_every`` so high-step loops stay fast while preserving exact replay + determinism across checkpoints. Call :meth:`summary` for an unconditional full view. + """ + obs_out: dict[str, Any] = {} + for mod_id, obs in self.observers.items(): + if mod_id == 'causal_emergence' and self.observed_steps >= heavy_every and (self.observed_steps % heavy_every) != 0: + obs_out[mod_id] = { + 'module': mod_id, + 'observed_steps': self.observed_steps, + 'deferred': True, + 'next_full_summary_at': ((self.observed_steps // heavy_every) + 1) * heavy_every, + } + else: + obs_out[mod_id] = obs.summary() + return _jsonable({ + 'schema': OBSERVER_SUMMARY_SCHEMA, + 'schema_version': 1, + 'enabled': bool(self.spec.enabled), + 'spec_digest': self.spec.spec_digest, + 'n_units': self.n_units, + 'observed_unit_count': self.observed_unit_count, + 'observe_every': int(self.spec.observe_every), + 'agent_steps': self.agent_steps, + 'observed_steps': self.observed_steps, + 'modules': list(self.spec.modules), + 'observers': obs_out, + 'evidence_tier': EVIDENCE_TIER, + }) + + def export_state(self) -> dict[str, Any]: + return deepcopy(_jsonable({ + 'schema': OBSERVER_CHECKPOINT_SCHEMA, + 'schema_version': 1, + 'spec': self.spec.to_dict(), + 'spec_digest': self.spec.spec_digest, + 'n_units': self.n_units, + 'agent_steps': self.agent_steps, + 'observed_steps': self.observed_steps, + 'unit_indices': self._unit_indices.tolist(), + 'observers': {mod_id: obs.export_state() for mod_id, obs in self.observers.items()}, + })) + + def import_state(self, state: Mapping[str, Any]) -> None: + if not isinstance(state, Mapping): + raise ValueError('observer hub state must be a mapping') + if state.get('schema') != OBSERVER_CHECKPOINT_SCHEMA or state.get('schema_version') != 1: + raise ValueError('unsupported observer hub checkpoint schema') + if state.get('n_units') != self.n_units: + raise ValueError('observer hub n_units mismatch') + if state.get('spec_digest') != self.spec.spec_digest or state.get('spec') != self.spec.to_dict(): + raise ValueError('observer hub spec_digest mismatch') + agent_steps = state.get('agent_steps') + observed_steps = state.get('observed_steps') + if type(agent_steps) is not int or agent_steps < 0: + raise ValueError('agent_steps must be a non-negative int') + if type(observed_steps) is not int or not 0 <= observed_steps <= agent_steps: + raise ValueError('observed_steps must be an int in [0, agent_steps]') + expected_observed = (agent_steps + self.spec.observe_every - 1) // self.spec.observe_every \ + if (self.spec.enabled and self.observers and agent_steps > 0) else 0 + if observed_steps != expected_observed: + raise ValueError('observed_steps is inconsistent with agent_steps and observe_every') + if state.get('unit_indices') != self._unit_indices.tolist(): + raise ValueError('observer hub unit_indices mismatch') + saved_obs = state.get('observers') + if not isinstance(saved_obs, Mapping) or set(saved_obs) != set(self.observers): + raise ValueError('observer hub modules mismatch') + candidate = FrontierObserverHub(self.spec, self.n_units) + for mod_id, obs in candidate.observers.items(): + obs.import_state(deepcopy(saved_obs[mod_id])) + obs_summary = obs.summary() + obs_count = obs_summary.get('observed_steps', obs_summary.get('observed')) + if type(obs_count) is int and obs_count != observed_steps: + raise ValueError(f'observer {mod_id!r} step count does not match hub observed_steps') + candidate.agent_steps = agent_steps + candidate.observed_steps = observed_steps + self.observers = candidate.observers + self.agent_steps = candidate.agent_steps + self.observed_steps = candidate.observed_steps + + +# ---------------------------------------------------------------------- experiment registry & runner + +def discover_experiments(*, include_unregistered: bool = False) -> dict[str, tuple[str, Callable[..., dict[str, Any]]]]: + """Return ``{experiment_id: (module_id, runner)}`` across available frontier modules.""" + out: dict[str, tuple[str, Callable[..., dict[str, Any]]]] = {} + ids = list(MODULE_IDS) + if include_unregistered: + for mid in MODULE_FILES: + if mid not in ids: + ids.append(mid) + for mod_id in ids: + try: + mod = load_frontier_module(mod_id) + except ModuleNotFoundError: + continue + exps = getattr(mod, 'EXPERIMENTS', None) + if not isinstance(exps, Mapping): + continue + for exp_id, fn in exps.items(): + if callable(fn): + out[str(exp_id)] = (mod_id, fn) + return out + + +def experiment_catalog(*, include_unregistered: bool = False) -> list[dict[str, Any]]: + """Metadata list for every available frontier experiment.""" + by_id = {m.id: m for m in MODULES} + discovered = discover_experiments(include_unregistered=include_unregistered) + catalog: list[dict[str, Any]] = [] + for exp_id, (mod_id, _) in discovered.items(): + info = by_id.get(mod_id) + catalog.append({ + 'experiment_id': exp_id, + 'module_id': mod_id, + 'is_primary': exp_id == mod_id, + 'title': info.title if info else mod_id, + 'kind': info.kind if info else 'addon', + 'origin': info.origin if info else 'portfolio', + 'source': info.source if info else '', + 'description': info.description if info else '', + 'observer': bool(info.observer) if info else False, + }) + return catalog + + +def run_frontier_experiment(experiment_id: str, *, quick: bool = False, + seeds: Iterable[int] = (0, 1, 2), + include_unregistered: bool = True, + **overrides: Any) -> dict[str, Any]: + """Run one frontier experiment by id and verify its sealed receipt.""" + discovered = discover_experiments(include_unregistered=include_unregistered) + if experiment_id not in discovered: + raise KeyError(f'unknown frontier experiment: {experiment_id!r}') + _, runner = discovered[experiment_id] + receipt = runner(quick=quick, seeds=tuple(seeds), **overrides) + if not isinstance(receipt, dict) or receipt.get('schema') != LAB_SCHEMA or not verify_receipt(receipt): + raise RuntimeError(f'experiment {experiment_id!r} returned an unverified receipt') + return receipt + + +def run_all_frontier_experiments(*, quick: bool = True, seeds: Iterable[int] = (0, 1, 2), + primary_only: bool = True, + module_ids: Iterable[str] | None = None, + include_unregistered: bool = False) -> list[dict[str, Any]]: + """Run all (or selected) frontier experiments and return their verified receipts.""" + discovered = discover_experiments(include_unregistered=include_unregistered) + allowed = None if module_ids is None else set(module_ids) + seeds = tuple(seeds) + receipts: list[dict[str, Any]] = [] + for exp_id, (mod_id, _) in discovered.items(): + if allowed is not None and mod_id not in allowed and exp_id not in allowed: + continue + if primary_only and exp_id != mod_id and (allowed is None or exp_id not in allowed): + continue + receipts.append(run_frontier_experiment( + exp_id, quick=quick, seeds=seeds, include_unregistered=include_unregistered)) + return receipts + + +def run_frontier_laboratory(spec: FrontierSpecV1 | None = None, *, + hub: FrontierObserverHub | None = None, + experiments: bool = False, + quick: bool = True, + seeds: Iterable[int] = (0, 1), + module_ids: Iterable[str] | None = None) -> dict[str, Any]: + """Build a sealed frontier-pack summary receipt for CLI, server or Max Mode.""" + active_spec = FrontierSpecV1() if spec is None else spec + if not isinstance(active_spec, FrontierSpecV1): + raise ValueError('spec must be a FrontierSpecV1 or None') + exp_summary: dict[str, Any] + if experiments: + runs = run_all_frontier_experiments(quick=quick, seeds=seeds, primary_only=True, module_ids=module_ids) + counts: dict[str, int] = {} + for r in runs: + v = str(r.get('verdict', 'unknown')) + counts[v] = counts.get(v, 0) + 1 + exp_summary = { + 'executed': len(runs), + 'quick': bool(quick), + 'verdict_counts': counts, + 'experiments': [ + { + 'experiment_id': r['experiment_id'], + 'kind': r['kind'], + 'verdict': r['verdict'], + 'verdict_basis': r.get('verdict_basis', ''), + 'digest': r['digest'], + } + for r in runs + ], + } + else: + exp_summary = {'skipped': 'experiments=False'} + payload = _jsonable({ + 'schema': LABORATORY_SCHEMA, + 'schema_version': 1, + 'section': '07 · Frontier Pack Laboratory', + 'evidence_tier': EVIDENCE_TIER, + 'spec': active_spec.to_dict(), + 'spec_digest': active_spec.spec_digest, + 'catalog_count': len(MODULES), + 'available_experiments': [c['experiment_id'] for c in experiment_catalog()], + 'live_observers': hub.summary() if hub is not None else {'skipped': 'no live observer hub attached'}, + 'experiments': exp_summary, + }) + payload['digest'] = receipt_digest(payload) + return payload diff --git a/synapse/frontier/sparse_dictionary.py b/synapse/frontier/sparse_dictionary.py new file mode 100644 index 0000000000000000000000000000000000000000..894733d5311f9530b62cc7da329af78bc879f66a --- /dev/null +++ b/synapse/frontier/sparse_dictionary.py @@ -0,0 +1,1066 @@ +"""Sparse dictionary of brain activity: online TopK sparse autoencoders and causal feature ablation. + +Inspired by -- not a reproduction of -- the TopK sparse autoencoders of Gao et al., *Scaling and +evaluating sparse autoencoders* (arXiv:2406.04093, June 2024; ICLR 2025). What is taken from that paper: + +* the TopK encoder ``z = ReLU(TopK_k(W_enc (x - b_pre) + b_enc))`` and decoder ``x_hat = W_dec z + b_pre`` + (``L0 <= k``; ``b_enc`` is optional: the paper's main equation omits it and its Appendix C.3 reports it + does not change the converged MSE, while the authors' reference code keeps it as ``latent_bias``); +* unit-norm decoder columns (at initialisation and after every step) with the gradient component + parallel to each decoder column projected out before the optimiser step; +* the encoder initialised to the transpose of the decoder and ``b_pre`` to the geometric median of a + data sample (Weiszfeld iterations); +* the AuxK auxiliary loss for dead latents: a latent is *dead* once it has not fired (``z > 1e-3``) for + ``dead_after`` training samples; the top-``k_aux`` dead latents (by pre-activation, ReLU applied) model + the main residual ``e = x - x_hat`` and the loss is + ``mse_scale * MSE(x, x_hat) + aux_coef * mean_i ||e_i - e_hat_i||^2 / ||e_i||^2`` + (main normalisation computed once from the initial data sample, AuxK normalised per sample, a + non-finite AuxK term is dropped; ``aux_coef = 1/32`` as in the paper); +* Adam (beta1 0.9, beta2 0.999, eps 6.25e-10) with a constant learning rate; normalised MSE, i.e. the + fraction of variance unexplained (FVU), as the reconstruction metric. + +Gao et al. describe AuxK as similar to "ghost grads" (Jermyn & Templeton, *Ghost Grads: An improvement +on resampling*, Transformer Circuits Thread, January 2024); TopK itself follows the k-sparse autoencoders +of Makhzani & Frey (arXiv:1312.5663, 2013). The firing threshold ``1e-3`` follows the authors' reference +code (github.com/openai/sparse_autoencoder). Not implemented: weight EMA, encoder-magnitude matching at +initialisation, power-of-two ``k_aux`` (here ``d // 2``), Multi-TopK. + +Scale, data and purpose differ completely from the paper: float64 NumPy on one CPU thread, tens of +units and tens of latents, online updates on live NEUROWEAVE / Sonapse unit activity. Global-norm +gradient clipping (default 1.0) and parameter clipping are added for bounded online behaviour. + +Three entry points: + +* :class:`TopKSAE` -- the autoencoder (online ``partial_fit`` or epoch ``fit``, Adam or SGD, + ``evaluate`` -> FVU / L0 / dead fraction / usage histogram, validated ``export_state`` / ``import_state``). +* :class:`SparseDictionaryObserver` -- read-only live observer (frontier observer contract): copies + activity into a bounded ring buffer and trains the dictionary online with replay mini-batches. +* :func:`run_experiment` -- lab experiment: a dictionary of a NEUROWEAVE engine's unit outputs on a temporal + task, the features most correlated with the task target on the *training* stream, and causal ablation + of those features' decoder contributions on frozen engine clones over held-out streams, against + random-feature ablation of the same size and no ablation. + +Everything is a synthetic computational abstraction (``evidence_tier='synthetic_abstraction'``): +dictionary features are directions in a toy model's activity space, not biological cell types. +""" +from __future__ import annotations + +import math +import time +from typing import Any, Iterable, Mapping, Sequence + +import numpy as np + +from ..neuroweave.engine import NeuroWeaveEngine +from ..neuroweave.experiments import (_LOG_EPS, ReadoutHead, _budget, _estimated_cost, _mean, _state_digest, + clone_engine, make_spec, run_task_phase) +from ..neuroweave.spec import TOPOLOGIES +from ..neuroweave.tasks import TASKS, TaskStream, chance_accuracy, make_stream +from .harness import base_receipt, compare, seal +from .spec import EVIDENCE_TIER, FrontierSpecV1 + +__all__ = ['MODULE_ID', 'EXPERIMENTS', 'DEFAULTS', 'QUICK', 'TopKSAE', 'SparseDictionaryObserver', 'topk_relu', + 'geometric_median', 'fraction_of_variance_unexplained', 'usage_histogram', 'select_predictive_features', + 'refit_readout', 'ablation_phase', 'run_experiment', 'USAGE_BINS', 'MAX_SAE_WEIGHTS'] + +MODULE_ID = 'sparse_dictionary' +SAE_STATE_SCHEMA = 'TopKSAEStateV1' +OBSERVER_STATE_SCHEMA = 'SparseDictionaryObserverStateV1' +MAX_ABS_INPUT = 1e6 # inputs beyond this magnitude are rejected (keeps squares finite) +MAX_SAE_WEIGHTS = 1 << 20 # n_inputs * n_features cap per dictionary (memory / state-size bound) +USAGE_BINS = ('never', '(0, 1e-3]', '(1e-3, 1e-2]', '(1e-2, 1e-1]', '(1e-1, 1]') +_SINCE_CAP = 1 << 40 +_COUNT_CAP = 1 << 53 +_SAE_INIT_OFFSET = 51_001 +_SAE_SHUFFLE_OFFSET = 51_013 +_OBS_SAE_OFFSET = 51_029 +_OBS_REPLAY_OFFSET = 51_031 +_EXP_SAE_OFFSET = 51_043 +_EXP_RANDOM_OFFSET = 51_047 +_PARAMS = ('W_enc', 'b_enc', 'W_dec', 'b_pre') + + +# ====================================================================== validation helpers +def _int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _float(name: str, value: Any, low: float, high: float, *, open_low: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number') + v = float(value) + if not math.isfinite(v) or v < low or v > high or (open_low and v == low): + raise ValueError(f'{name} must be a finite number in {"(" if open_low else "["}{low}, {high}]') + return v + + +def _array(name: str, value: Any, shape: tuple[int, ...], *, max_abs: float | None = None) -> np.ndarray: + try: + a = np.array(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + if a.shape != shape or not np.all(np.isfinite(a)): + raise ValueError(f'{name} must be a finite array of shape {shape}') + if max_abs is not None and a.size and float(np.max(np.abs(a))) > max_abs: + raise ValueError(f'{name} exceeds the bound {max_abs}') + return a + + +def _int_array(name: str, value: Any, shape: tuple[int, ...], low: int, high: int) -> np.ndarray: + if not isinstance(value, (list, tuple, np.ndarray)): + raise ValueError(f'{name} must be a list of ints') + raw = np.asarray(value, dtype=object).ravel() + if any(isinstance(v, bool) or not isinstance(v, (int, np.integer)) for v in raw): + raise ValueError(f'{name} must contain ints') + a = np.asarray(value, dtype=np.int64) + if a.shape != shape or (a.size and (int(a.min()) < low or int(a.max()) > high)): + raise ValueError(f'{name} must be ints in [{low}, {high}] of shape {shape}') + return a + + +def _batch(name: str, value: Any, dim: int | None = None, *, max_rows: int = 1_000_000) -> np.ndarray: + try: + a = np.asarray(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + if a.ndim == 1: + a = a[None, :] + if a.ndim != 2 or a.shape[0] < 1 or a.shape[1] < 1 or a.shape[0] > max_rows: + raise ValueError(f'{name} must be a vector or a (rows <= {max_rows}, dim) matrix') + if dim is not None and a.shape[1] != dim: + raise ValueError(f'{name} must have {dim} columns, got {a.shape[1]}') + if not np.all(np.isfinite(a)) or float(np.max(np.abs(a))) > MAX_ABS_INPUT: + raise ValueError(f'{name} must be finite with |values| <= {MAX_ABS_INPUT:g}') + return a + + +# ====================================================================== primitives +def _topk(pre: np.ndarray, k: int) -> tuple[np.ndarray, np.ndarray]: + idx = np.argsort(-pre, axis=1, kind='stable')[:, :k] # descending; ties -> lower index first + z = np.zeros_like(pre) + np.put_along_axis(z, idx, np.maximum(np.take_along_axis(pre, idx, axis=1), 0.0), axis=1) + return z, idx + + +def topk_relu(pre: Any, k: int) -> tuple[np.ndarray, np.ndarray]: + """TopK activation of Gao et al.: keep the ``k`` largest pre-activations of every row, apply ReLU to them + and zero the rest. Ties are broken towards the lower index. Returns ``(z, idx)`` with ``idx`` the selected + columns per row in descending pre-activation order (so ``L0 <= k``).""" + p = _batch('pre', pre) + return _topk(p, _int('k', k, 1, p.shape[1])) + + +def geometric_median(points: Any, *, max_iter: int = 256, tol: float = 1e-10) -> np.ndarray: + """Geometric median (minimiser of the summed Euclidean distance) by Weiszfeld iterations from the mean. + + Distances are floored at 1e-12, so an iterate that lands on a data point stays there (adequate for the + initialisation of ``b_pre``, which is its only use here).""" + x = _batch('points', points) + max_iter = _int('max_iter', max_iter, 1, 100_000) + y = x.mean(axis=0) + for _ in range(max_iter): + w = 1.0 / np.maximum(np.sqrt(((x - y) ** 2).sum(axis=1)), 1e-12) + nxt = (w[:, None] * x).sum(axis=0) / w.sum() + shift = float(np.sqrt(((nxt - y) ** 2).sum())) + y = nxt + if shift <= tol * (1.0 + float(np.sqrt((y ** 2).sum()))): + break + return y + + +def _fvu(x: np.ndarray, x_hat: np.ndarray) -> float | None: + num = float(((x - x_hat) ** 2).sum()) + den = float(((x - x.mean(axis=0)) ** 2).sum()) + if den <= 1e-300: + return 0.0 if num <= 1e-300 else None + return num / den + + +def fraction_of_variance_unexplained(x: Any, x_hat: Any) -> float | None: + """Normalised MSE of Gao et al.: reconstruction error divided by the error of always predicting the + per-dimension mean (``None`` when the data has no variance but the reconstruction has error).""" + a = _batch('x', x) + b = _batch('x_hat', x_hat, a.shape[1]) + if a.shape != b.shape: + raise ValueError('x and x_hat must have the same shape') + return _fvu(a, b) + + +def usage_histogram(rates: Any) -> dict[str, Any]: + """Number of features per firing-rate bin (``USAGE_BINS``); rates are fractions of samples in [0, 1].""" + r = np.asarray(rates, dtype=np.float64).ravel() + if not np.all(np.isfinite(r)) or (r.size and (float(r.min()) < 0.0 or float(r.max()) > 1.0)): + raise ValueError('rates must be finite fractions in [0, 1]') + counts = [int(np.sum(r <= 0.0)), int(np.sum((r > 0.0) & (r <= 1e-3))), int(np.sum((r > 1e-3) & (r <= 1e-2))), + int(np.sum((r > 1e-2) & (r <= 1e-1))), int(np.sum(r > 1e-1))] + return {'bins': list(USAGE_BINS), 'counts': counts} + + +# ====================================================================== TopK sparse autoencoder +class TopKSAE: + """Online TopK sparse autoencoder (NumPy, float64, deterministic, bounded). + + Shapes: ``W_enc`` (features, inputs), ``b_enc`` (features,), ``W_dec`` (inputs, features) with unit-norm + columns, ``b_pre`` (inputs,). All randomness comes from ``default_rng(seed + offset)`` streams (decoder + directions) and per-epoch generators seeded by ``(seed + offset, epoch)`` (shuffles), so the object holds + no generator state and export/import round-trips exactly.""" + + def __init__(self, n_inputs: int, n_features: int, k: int, *, seed: int = 0, optimizer: str = 'adam', + lr: float = 1e-3, k_aux: int | None = None, aux_coef: float = 1.0 / 32.0, dead_after: int = 1024, + encoder_bias: bool = True, grad_clip: float | None = 1.0, betas: Sequence[float] = (0.9, 0.999), + eps: float = 6.25e-10, fire_threshold: float = 1e-3, max_param: float = 1e3) -> None: + n_inputs = _int('n_inputs', n_inputs, 1, MAX_SAE_WEIGHTS) + n_features = _int('n_features', n_features, 1, MAX_SAE_WEIGHTS) + if n_inputs * n_features > MAX_SAE_WEIGHTS: + raise ValueError(f'n_inputs * n_features must be <= {MAX_SAE_WEIGHTS}') + k = _int('k', k, 1, n_features) + if optimizer not in ('adam', 'sgd'): + raise ValueError("optimizer must be 'adam' or 'sgd'") + if type(encoder_bias) is not bool: + raise ValueError('encoder_bias must be a boolean') + if not isinstance(betas, (list, tuple)) or len(betas) != 2: + raise ValueError('betas must be a pair') + self.config: dict[str, Any] = { + 'n_inputs': n_inputs, 'n_features': n_features, 'k': k, 'seed': _int('seed', seed, 0, 2**31 - 1), + 'optimizer': optimizer, 'lr': _float('lr', lr, 0.0, 10.0, open_low=True), + 'k_aux': max(1, min(n_features, n_inputs // 2)) if k_aux is None else _int('k_aux', k_aux, 1, n_features), + 'aux_coef': _float('aux_coef', aux_coef, 0.0, 100.0), + 'dead_after': _int('dead_after', dead_after, 1, _SINCE_CAP), 'encoder_bias': encoder_bias, + 'grad_clip': None if grad_clip is None else _float('grad_clip', grad_clip, 0.0, 1e6, open_low=True), + 'betas': [_float('beta1', betas[0], 0.0, 0.999999), _float('beta2', betas[1], 0.0, 0.999999)], + 'eps': _float('eps', eps, 0.0, 1.0, open_low=True), + 'fire_threshold': _float('fire_threshold', fire_threshold, 0.0, 1e3), + 'max_param': _float('max_param', max_param, 1.0, 1e6), + } + self._reset() + + # ------------------------------------------------------------------ configuration accessors + n_inputs = property(lambda self: self.config['n_inputs']) + n_features = property(lambda self: self.config['n_features']) + k = property(lambda self: self.config['k']) + k_aux = property(lambda self: self.config['k_aux']) + seed = property(lambda self: self.config['seed']) + dead_after = property(lambda self: self.config['dead_after']) + fire_threshold = property(lambda self: self.config['fire_threshold']) + + def _reset(self) -> None: + d, f = self.n_inputs, self.n_features + rng = np.random.default_rng(self.seed + _SAE_INIT_OFFSET) + w = rng.standard_normal((d, f)) + self.W_dec = w / np.maximum(np.sqrt((w ** 2).sum(axis=0, keepdims=True)), 1e-12) + self.W_enc = self.W_dec.T.copy() # encoder = decoder transpose (Gao et al., Sec. 2.4) + self.b_enc = np.zeros(f) + self.b_pre = np.zeros(d) + self.mse_scale = 1.0 + self.initialized = False + self.updates = 0 + self.samples_seen = 0 + self.fit_epochs = 0 + self.adam_t = 0 + self.since_fired = np.zeros(f, dtype=np.int64) + self.fire_count = np.zeros(f, dtype=np.int64) + adam = self.config['optimizer'] == 'adam' + self._m = {p: np.zeros_like(getattr(self, p)) for p in _PARAMS} if adam else None + self._v = {p: np.zeros_like(getattr(self, p)) for p in _PARAMS} if adam else None + + # ------------------------------------------------------------------ accounting + @property + def parameter_count(self) -> int: + bias = self.b_enc.size if self.config['encoder_bias'] else 0 + return int(self.W_enc.size + self.W_dec.size + self.b_pre.size + bias) + + @property + def state_numbers(self) -> int: + moments = 2 * sum(getattr(self, p).size for p in _PARAMS) if self._m is not None else 0 + return int(sum(getattr(self, p).size for p in _PARAMS) + moments + 2 * self.n_features + 6) + + def decoder_norms(self) -> np.ndarray: + return np.sqrt((self.W_dec ** 2).sum(axis=0)) + + def dead_mask(self) -> np.ndarray: + """Latents that have not fired for ``dead_after`` training samples (all False before any training).""" + return self.since_fired >= self.dead_after + + def dead_fraction(self) -> float: + return float(np.mean(self.dead_mask())) + + # ------------------------------------------------------------------ forward + def _pre(self, x: np.ndarray) -> np.ndarray: + pre = (x - self.b_pre) @ self.W_enc.T + return pre + self.b_enc if self.config['encoder_bias'] else pre + + def pre_activations(self, x: Any) -> np.ndarray: + return self._pre(_batch('x', x, self.n_inputs)) + + def encode(self, x: Any) -> np.ndarray: + """Sparse codes ``z`` (same leading shape as ``x``: a vector gives a vector).""" + a = np.asarray(x) if isinstance(x, np.ndarray) else x + xb = _batch('x', a, self.n_inputs) + z = _topk(self._pre(xb), self.k)[0] + return z[0] if np.ndim(a) == 1 else z + + def decode(self, z: Any) -> np.ndarray: + zb = _batch('z', z, self.n_features) + out = zb @ self.W_dec.T + self.b_pre + return out[0] if np.ndim(z) == 1 else out + + def reconstruct(self, x: Any) -> np.ndarray: + xb = _batch('x', x, self.n_inputs) + out = _topk(self._pre(xb), self.k)[0] @ self.W_dec.T + self.b_pre + return out[0] if np.ndim(x) == 1 else out + + # ------------------------------------------------------------------ training + def init_from_data(self, x: Any) -> None: + """``b_pre`` <- geometric median of the sample; main-loss scale <- 1 / (per-element variance).""" + xb = _batch('x', x, self.n_inputs) + if xb.shape[0] < 2: + raise ValueError('init_from_data needs at least 2 samples') + b_pre = np.clip(geometric_median(xb), -self.config['max_param'], self.config['max_param']) + var = float(np.mean((xb - xb.mean(axis=0)) ** 2)) + self.b_pre = b_pre + self.mse_scale = float(min(1e12, 1.0 / max(var, 1e-12))) + self.initialized = True + + def partial_fit(self, x: Any) -> dict[str, Any]: + """One optimiser step on a mini-batch (initialises from the batch first if needed, which takes >= 2 rows). + + Returns pre-update batch metrics plus the batch codes ``z`` and per-row MSE ``row_mse`` (arrays).""" + xb = _batch('x', x, self.n_inputs, max_rows=65_536) + if not self.initialized: + self.init_from_data(xb) + cfg = self.config + b, d = xb.shape + c = xb - self.b_pre + pre = c @ self.W_enc.T + if cfg['encoder_bias']: + pre += self.b_enc + z = _topk(pre, self.k)[0] + err = xb - (z @ self.W_dec.T + self.b_pre) + # firing statistics first (the AuxK dead mask uses them, as in the reference implementation) + fired = z > cfg['fire_threshold'] + anyf = fired.any(axis=0) + self.since_fired = np.where(anyf, np.argmax(fired[::-1], axis=0), + np.minimum(self.since_fired + b, _SINCE_CAP)).astype(np.int64) + self.fire_count = np.minimum(self.fire_count + fired.sum(axis=0), _COUNT_CAP).astype(np.int64) + self.samples_seen = int(min(self.samples_seen + b, _COUNT_CAP)) + dead = self.since_fired >= cfg['dead_after'] + # main loss mse_scale * MSE(x, x_hat) + g_out = (-2.0 * self.mse_scale / (b * d)) * err + g_dec = g_out.T @ z + g_pre_bias = g_out.sum(axis=0) + dpre = (g_out @ self.W_dec) * (z > 0.0) + g_enc = dpre.T @ c + g_benc = dpre.sum(axis=0) + g_pre_bias -= (dpre @ self.W_enc).sum(axis=0) + loss = self.mse_scale * float(np.mean(err ** 2)) + aux_loss = 0.0 + n_dead = int(dead.sum()) + if cfg['aux_coef'] > 0.0 and n_dead: + didx = np.flatnonzero(dead) + za = np.zeros_like(z) + za[:, didx] = _topk(pre[:, didx], min(cfg['k_aux'], n_dead))[0] + enorm = np.maximum((err ** 2).sum(axis=1), 1e-12) + resid = za @ self.W_dec.T - err + aux = float(np.mean((resid ** 2).sum(axis=1) / enorm)) + g_aux = (2.0 * cfg['aux_coef'] / b) * resid / enorm[:, None] + if math.isfinite(aux) and np.all(np.isfinite(g_aux)): # a non-finite AuxK term is dropped + aux_loss = aux + if np.any(za > 0.0): + g_dec += g_aux.T @ za + dpa = (g_aux @ self.W_dec) * (za > 0.0) + g_enc += dpa.T @ c + g_benc += dpa.sum(axis=0) + g_pre_bias -= (dpa @ self.W_enc).sum(axis=0) + if not cfg['encoder_bias']: + g_benc = np.zeros_like(g_benc) + g_dec -= self.W_dec * np.sum(g_dec * self.W_dec, axis=0, keepdims=True) # project out parallel part + grads = {'W_enc': g_enc, 'b_enc': g_benc, 'W_dec': g_dec, 'b_pre': g_pre_bias} + if cfg['grad_clip'] is not None: + norm = math.sqrt(sum(float((g ** 2).sum()) for g in grads.values())) + if norm > cfg['grad_clip']: + grads = {n: g * (cfg['grad_clip'] / norm) for n, g in grads.items()} + self._apply(grads) + self.updates += 1 + return {'loss': loss, 'aux_loss': aux_loss, 'mse': float(np.mean(err ** 2)), + 'l0': float(np.mean(np.count_nonzero(z, axis=1))), 'n_dead': n_dead, 'z': z, + 'row_mse': (err ** 2).mean(axis=1)} + + def _apply(self, grads: Mapping[str, np.ndarray]) -> None: + cfg = self.config + lr = cfg['lr'] + if self._m is None: + for name, g in grads.items(): + getattr(self, name).__isub__(lr * g) + else: + self.adam_t += 1 + b1, b2 = cfg['betas'] + c1, c2 = 1.0 - b1 ** self.adam_t, 1.0 - b2 ** self.adam_t + for name, g in grads.items(): + m, v = self._m[name], self._v[name] + m *= b1 + m += (1.0 - b1) * g + v *= b2 + v += (1.0 - b2) * g * g + getattr(self, name).__isub__(lr * (m / c1) / (np.sqrt(v / c2) + cfg['eps'])) + self.W_dec /= np.maximum(self.decoder_norms()[None, :], 1e-12) + mp = cfg['max_param'] + for name in ('W_enc', 'b_enc', 'b_pre'): + np.clip(getattr(self, name), -mp, mp, out=getattr(self, name)) + if not cfg['encoder_bias']: + self.b_enc[:] = 0.0 + + def fit(self, x: Any, *, epochs: int = 1, batch_size: int = 32) -> dict[str, Any]: + """Epochs of shuffled mini-batch ``partial_fit`` calls (shuffle generator seeded by ``(seed + offset, epoch)``).""" + xb = _batch('x', x, self.n_inputs) + epochs = _int('epochs', epochs, 1, 100_000) + batch_size = _int('batch_size', batch_size, 1, 65_536) + if not self.initialized: + self.init_from_data(xb) + n = xb.shape[0] + last: dict[str, float] = {} + for _ in range(epochs): + order = np.random.default_rng((self.seed + _SAE_SHUFFLE_OFFSET, self.fit_epochs)).permutation(n) + tot = {'loss': 0.0, 'aux_loss': 0.0, 'mse': 0.0, 'l0': 0.0} + for s in range(0, n, batch_size): + rows = order[s:s + batch_size] + r = self.partial_fit(xb[rows]) + for key in tot: + tot[key] += r[key] * rows.size + self.fit_epochs += 1 + last = {f'last_epoch_{key}': val / n for key, val in tot.items()} + return {'epochs': epochs, 'updates': self.updates, **last} + + # ------------------------------------------------------------------ evaluation + def evaluate(self, x: Any) -> dict[str, Any]: + """FVU, MSE, L0, never-fired fraction and usage histogram on ``x`` (plus the training dead fraction).""" + xb = _batch('x', x, self.n_inputs) + z = _topk(self._pre(xb), self.k)[0] + rates = (z > self.fire_threshold).mean(axis=0) + return {'samples': int(xb.shape[0]), 'fvu': _fvu(xb, z @ self.W_dec.T + self.b_pre), + 'mse': float(np.mean((xb - z @ self.W_dec.T - self.b_pre) ** 2)), + 'l0': float(np.mean(np.count_nonzero(z, axis=1))), 'never_fired_fraction': float(np.mean(rates <= 0.0)), + 'usage': rates.tolist(), 'usage_histogram': usage_histogram(rates), + 'dead_fraction_training': self.dead_fraction()} + + # ------------------------------------------------------------------ persistence + def export_state(self) -> dict[str, Any]: + state: dict[str, Any] = { + 'schema': SAE_STATE_SCHEMA, 'config': {**self.config, 'betas': list(self.config['betas'])}, + 'initialized': bool(self.initialized), 'mse_scale': float(self.mse_scale), 'updates': int(self.updates), + 'samples_seen': int(self.samples_seen), 'fit_epochs': int(self.fit_epochs), 'adam_t': int(self.adam_t), + 'since_fired': self.since_fired.tolist(), 'fire_count': self.fire_count.tolist(), + 'adam_m': None if self._m is None else {p: self._m[p].tolist() for p in _PARAMS}, + 'adam_v': None if self._v is None else {p: self._v[p].tolist() for p in _PARAMS}, + } + for p in _PARAMS: + state[p] = getattr(self, p).tolist() + return state + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate ``state`` completely, then replace this autoencoder's state (configuration must match).""" + if not isinstance(state, Mapping) or state.get('schema') != SAE_STATE_SCHEMA: + raise ValueError('not a TopKSAE state') + cfg = state.get('config') + mine = {**self.config, 'betas': list(self.config['betas'])} + if not isinstance(cfg, Mapping) or dict(cfg) != mine: + raise ValueError('state configuration does not match this autoencoder') + d, f, mp = self.n_inputs, self.n_features, self.config['max_param'] + shapes = {'W_enc': (f, d), 'b_enc': (f,), 'W_dec': (d, f), 'b_pre': (d,)} + params = {p: _array(p, state.get(p), shapes[p], max_abs=None if p == 'W_dec' else mp) for p in _PARAMS} + if float(np.max(np.abs(np.sqrt((params['W_dec'] ** 2).sum(axis=0)) - 1.0))) > 1e-6: + raise ValueError('decoder columns must have unit norm') + if not self.config['encoder_bias'] and np.any(params['b_enc'] != 0.0): + raise ValueError('b_enc must be zero without an encoder bias') + initialized = state.get('initialized') + if type(initialized) is not bool: + raise ValueError('initialized must be a boolean') + mse_scale = _float('mse_scale', state.get('mse_scale'), 0.0, 1e12, open_low=True) + counters = {n: _int(n, state.get(n), 0, _COUNT_CAP) for n in ('updates', 'samples_seen', 'fit_epochs', 'adam_t')} + since = _int_array('since_fired', state.get('since_fired'), (f,), 0, _SINCE_CAP) + count = _int_array('fire_count', state.get('fire_count'), (f,), 0, _COUNT_CAP) + moments: dict[str, dict[str, np.ndarray] | None] = {'adam_m': None, 'adam_v': None} + for key in moments: + raw = state.get(key) + if self._m is None: + if raw is not None: + raise ValueError(f'{key} must be null for SGD') + continue + if not isinstance(raw, Mapping) or set(raw) != set(_PARAMS): + raise ValueError(f'{key} must map every parameter') + moments[key] = {p: _array(f'{key}.{p}', raw[p], shapes[p]) for p in _PARAMS} + if key == 'adam_v' and any(float(a.min()) < 0.0 for a in moments[key].values() if a.size): + raise ValueError('adam_v must be non-negative') + for p in _PARAMS: + setattr(self, p, params[p]) + self.initialized, self.mse_scale = initialized, mse_scale + self.updates, self.samples_seen = counters['updates'], counters['samples_seen'] + self.fit_epochs, self.adam_t = counters['fit_epochs'], counters['adam_t'] + self.since_fired, self.fire_count = since, count + if self._m is not None: + self._m, self._v = moments['adam_m'], moments['adam_v'] + + @classmethod + def from_state(cls, state: Mapping[str, Any]) -> 'TopKSAE': + if not isinstance(state, Mapping) or not isinstance(state.get('config'), Mapping): + raise ValueError('not a TopKSAE state') + cfg = dict(state['config']) + try: + sae = cls(cfg.pop('n_inputs'), cfg.pop('n_features'), cfg.pop('k'), **cfg) + except (KeyError, TypeError) as exc: + raise ValueError('incomplete or unknown TopKSAE configuration') from exc + sae.import_state(state) + return sae + + +# ====================================================================== live observer +class SparseDictionaryObserver: + """Read-only live observer: an online TopK dictionary of the observed unit activity. + + ``observe`` copies the activity vector into a bounded ring buffer (``history`` rows) and, once ``warmup`` + rows exist (``min(history, 32)``), initialises the dictionary (``b_pre`` = geometric median of the buffer) + and takes one optimiser step per ``train_every`` observations on a mini-batch made of the new vector plus + ``batch_size - 1`` replayed buffer rows. FVU, L0 and per-feature usage are exponential moving averages + over *new* vectors, measured before the update on them (prequential). Nothing is written back anywhere.""" + + module_id = MODULE_ID + TOP_FEATURES = 8 + TOP_UNITS = 5 + + def __init__(self, n_units: int, *, seed: int = 7, history: int = 256, features: int = 64, k: int = 8, + lr: float = 3e-3, batch_size: int = 8, train_every: int = 1, dead_after: int | None = None, + aux_coef: float = 1.0 / 32.0, ema: float = 0.02) -> None: + n_units = _int('n_units', n_units, 1, 4096) + history = _int('history', history, 16, 8192) + features = _int('features', features, 4, 4096) + batch_size = _int('batch_size', batch_size, 1, 256) + if n_units * features > MAX_SAE_WEIGHTS: + raise ValueError(f'n_units * features must be <= {MAX_SAE_WEIGHTS}') + self.config: dict[str, Any] = { + 'n_units': n_units, 'seed': _int('seed', seed, 0, 2**31 - 1), 'history': history, 'features': features, + 'k': _int('k', k, 1, features), 'lr': _float('lr', lr, 0.0, 1.0, open_low=True), 'batch_size': batch_size, + 'train_every': _int('train_every', train_every, 1, 10_000), + 'dead_after': batch_size * history if dead_after is None else _int('dead_after', dead_after, 1, _SINCE_CAP), + 'aux_coef': _float('aux_coef', aux_coef, 0.0, 100.0), 'ema': _float('ema', ema, 0.0, 1.0, open_low=True), + } + self.warmup = min(history, 32) + self.reset() + + @classmethod + def from_spec(cls, n_units: int, spec: FrontierSpecV1) -> 'SparseDictionaryObserver': + """Observer sized from a :class:`FrontierSpecV1` (``seed``, ``history``, ``sae_features``, ``sae_k``).""" + if not isinstance(spec, FrontierSpecV1): + raise ValueError('spec must be a FrontierSpecV1') + return cls(n_units, seed=spec.seed, history=spec.history, features=spec.sae_features, k=spec.sae_k) + + n_units = property(lambda self: self.config['n_units']) + history = property(lambda self: self.config['history']) + + def _new_sae(self) -> TopKSAE: + c = self.config + return TopKSAE(c['n_units'], c['features'], c['k'], seed=c['seed'] + _OBS_SAE_OFFSET, lr=c['lr'], + aux_coef=c['aux_coef'], dead_after=c['dead_after']) + + def reset(self) -> None: + """Return to the freshly constructed state (empty buffer, untrained dictionary, same seed).""" + n = self.n_units + self._buf = np.zeros((self.history, n)) + self._head = 0 + self._filled = 0 + self.observed = 0 + self._trained = 0 + self._mean = np.zeros(n) + self._var = np.zeros(n) + self._mse_ema: float | None = None + self._l0_ema: float | None = None + self._fire_ema = np.zeros(self.config['features']) + self._sae = self._new_sae() + + def _validate(self, x: Any) -> np.ndarray: + try: + v = np.array(x, dtype=np.float64) # always a copy: the observer never aliases the caller's array + except (TypeError, ValueError) as exc: + raise ValueError('activity must be numeric') from exc + if v.ndim != 1 or v.size != self.n_units: + raise ValueError(f'activity must be a 1-D vector of length {self.n_units}') + if not np.all(np.isfinite(v)) or (v.size and float(np.max(np.abs(v))) > MAX_ABS_INPUT): + raise ValueError(f'activity must be finite with |values| <= {MAX_ABS_INPUT:g}') + return v + + def _chronological(self) -> np.ndarray: + return self._buf[(self._head - self._filled + np.arange(self._filled)) % self.history] + + def observe(self, x: np.ndarray) -> None: + v = self._validate(x) + h = self.history + self._buf[self._head] = v + self._head = (self._head + 1) % h + self._filled = min(h, self._filled + 1) + self.observed += 1 + a = max(self.config['ema'], 1.0 / self.observed) # running mean first, then EMA + delta = v - self._mean + self._mean += a * delta + self._var = (1.0 - a) * (self._var + a * delta * delta) + sae = self._sae + if not sae.initialized and self._filled >= self.warmup: + sae.init_from_data(self._chronological()) + if not sae.initialized or self.observed % self.config['train_every']: + return + batch = v[None, :] + if self.config['batch_size'] > 1: + rng = np.random.default_rng((self.config['seed'] + _OBS_REPLAY_OFFSET, self.observed)) + pos = rng.integers(0, self._filled, size=self.config['batch_size'] - 1) # chronological positions + batch = np.vstack([batch, self._buf[(self._head - self._filled + pos) % h]]) + res = sae.partial_fit(batch) + self._trained += 1 + b = max(self.config['ema'], 1.0 / self._trained) + z0 = res['z'][0] + mse0, l00 = float(res['row_mse'][0]), float(np.count_nonzero(z0)) + self._mse_ema = mse0 if self._mse_ema is None else (1.0 - b) * self._mse_ema + b * mse0 + self._l0_ema = l00 if self._l0_ema is None else (1.0 - b) * self._l0_ema + b * l00 + self._fire_ema = (1.0 - b) * self._fire_ema + b * (z0 > sae.fire_threshold) + + def summary(self) -> dict[str, Any]: + sae = self._sae + var = float(np.mean(self._var)) if self.observed else 0.0 + fvu = None if self._mse_ema is None or var <= 1e-12 else float(self._mse_ema / var) + top = [] + if self._trained: + usage = self._fire_ema + for j in [int(i) for i in np.argsort(-usage, kind='stable')[:self.TOP_FEATURES] if usage[i] > 0.0]: + col = sae.W_dec[:, j] + units = np.argsort(-np.abs(col), kind='stable')[:self.TOP_UNITS] + top.append({'feature': j, 'usage': float(usage[j]), + 'top_units': [{'unit': int(u), 'weight': float(col[u])} for u in units]}) + return { + 'module': MODULE_ID, 'n_units': self.n_units, 'features': self.config['features'], 'k': self.config['k'], + 'history': self.history, 'observed': int(self.observed), 'history_fill': int(self._filled), + 'ready': bool(sae.initialized), 'steps': int(sae.updates), 'samples_trained': int(sae.samples_seen), + 'fvu_ema': fvu, 'mse_ema': self._mse_ema, 'l0_ema': self._l0_ema, 'dead_fraction': sae.dead_fraction(), + 'dead_after': self.config['dead_after'], 'k_aux': sae.k_aux, + 'decoder_norm_max_error': float(np.max(np.abs(sae.decoder_norms() - 1.0))), + 'top_features': top, 'usage_histogram': usage_histogram(self._fire_ema) if self._trained else None, + 'evidence_tier': EVIDENCE_TIER, + } + + def export_state(self) -> dict[str, Any]: + return {'module': MODULE_ID, 'schema': OBSERVER_STATE_SCHEMA, 'config': dict(self.config), + 'observed': int(self.observed), 'trained': int(self._trained), 'buffer': self._chronological().tolist(), + 'mean': self._mean.tolist(), 'var': self._var.tolist(), 'mse_ema': self._mse_ema, + 'l0_ema': self._l0_ema, 'fire_ema': self._fire_ema.tolist(), 'sae': self._sae.export_state()} + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate ``state`` completely, then replace this observer's state (configuration must match).""" + if (not isinstance(state, Mapping) or state.get('module') != MODULE_ID + or state.get('schema') != OBSERVER_STATE_SCHEMA): + raise ValueError('not a sparse_dictionary observer state') + if not isinstance(state.get('config'), Mapping) or dict(state['config']) != self.config: + raise ValueError('state configuration does not match this observer') + n, f = self.n_units, self.config['features'] + observed = _int('observed', state.get('observed'), 0, _COUNT_CAP) + trained = _int('trained', state.get('trained'), 0, observed) + raw = state.get('buffer') + if not isinstance(raw, (list, tuple)) or len(raw) != min(self.history, observed): + raise ValueError('buffer must hold exactly min(history, observed) rows') + buf = _array('buffer', raw, (len(raw), n), max_abs=MAX_ABS_INPUT) if raw else np.zeros((0, n)) + mean = _array('mean', state.get('mean'), (n,), max_abs=MAX_ABS_INPUT) + var = _array('var', state.get('var'), (n,), max_abs=4.0 * MAX_ABS_INPUT ** 2) + fire = _array('fire_ema', state.get('fire_ema'), (f,)) + if float(var.min()) < 0.0 or float(fire.min()) < 0.0 or float(fire.max()) > 1.0: + raise ValueError('var must be >= 0 and fire_ema in [0, 1]') + emas = {} + for key, hi in (('mse_ema', 4.0 * MAX_ABS_INPUT ** 2), ('l0_ema', float(self.config['k']))): + val = state.get(key) + emas[key] = None if val is None else _float(key, val, 0.0, hi) + if (emas[key] is None) != (trained == 0): + raise ValueError(f'{key} must be null exactly when nothing was trained') + sae = self._new_sae() + sae.import_state(state.get('sae')) + if sae.initialized != (len(raw) >= self.warmup) or sae.updates != trained: + raise ValueError('dictionary state does not match the buffer or the training count') + self._buf = np.zeros((self.history, n)) + self._buf[:len(raw)] = buf + self._filled = len(raw) + self._head = self._filled % self.history + self.observed, self._trained = observed, trained + self._mean, self._var, self._fire_ema = mean, var, fire + self._mse_ema, self._l0_ema = emas['mse_ema'], emas['l0_ema'] + self._sae = sae + + @property + def dictionary(self) -> TopKSAE: + """The underlying autoencoder (read it, do not train it from outside).""" + return self._sae + + +# ====================================================================== experiment helpers +def select_predictive_features(codes: Any, target: Any, count: int, *, min_fires: int = 1) -> dict[str, Any]: + """Rank features by |Pearson correlation| between activation and a binary target (training data only). + + Only features that fired (``z > 0``) on at least ``min_fires`` rows are eligible ("alive"); ties go to the + lower index. Returns ``targeted`` (rank order), the eligible ``pool`` (ascending), ``corr`` and ``fires``.""" + z = _batch('codes', codes) + y = np.asarray(target, dtype=np.float64).ravel() + if y.shape != (z.shape[0],) or not np.all(np.isfinite(y)): + raise ValueError('target must be a finite vector with one entry per row of codes') + count = _int('count', count, 1, z.shape[1]) + min_fires = _int('min_fires', min_fires, 1, max(1, z.shape[0])) + fires = np.count_nonzero(z > 0.0, axis=0) + zc, yc = z - z.mean(axis=0), y - y.mean() + den = np.sqrt((zc ** 2).sum(axis=0) * float((yc ** 2).sum())) + corr = np.divide(zc.T @ yc, den, out=np.zeros(z.shape[1]), where=den > 1e-12) + pool = np.flatnonzero(fires >= min_fires) + ranked = sorted(pool.tolist(), key=lambda j: (-abs(float(corr[j])), j)) + return {'targeted': ranked[:count], 'pool': pool.tolist(), 'corr': corr, 'fires': fires} + + +def refit_readout(head: ReadoutHead, features: Any, targets: Any, *, l2: float = 1e-2, iters: int = 50) -> dict[str, Any]: + """Refit a lab :class:`ReadoutHead` by L2-regularised logistic regression (damped Newton, warm-started from + the head; bias unregularised; weights clipped to the head's [-8, 8] bound). Deterministic.""" + x = _batch('features', features, head.dim) + y = np.asarray(targets, dtype=np.float64).ravel() + if y.shape != (x.shape[0],) or not np.all((y == 0.0) | (y == 1.0)): + raise ValueError('targets must be 0/1 with one entry per feature row') + l2 = _float('l2', l2, 0.0, 1e3, open_low=True) + xb = np.hstack([x, np.ones((x.shape[0], 1))]) + reg = np.full(xb.shape[1], l2) + reg[-1] = 0.0 + w = np.concatenate([head.w, [head.b]]) + + def objective(wv: np.ndarray) -> tuple[float, np.ndarray]: + z = np.clip(xb @ wv, -40.0, 40.0) + p = 1.0 / (1.0 + np.exp(-z)) + ll = float(np.mean(np.logaddexp(0.0, z) - y * z)) + return ll + 0.5 * float(np.sum(reg * wv * wv)), p + + obj, p = objective(w) + it = 0 + for it in range(1, _int('iters', iters, 1, 1000) + 1): + g = xb.T @ (p - y) / x.shape[0] + reg * w + hess = (xb.T * (p * (1.0 - p))) @ xb / x.shape[0] + np.diag(reg + 1e-9) + step = np.linalg.solve(hess, g) + t = 1.0 + while True: + cand = w - t * step + new_obj, new_p = objective(cand) + if new_obj <= obj or t < 1e-6: + break + t *= 0.5 + converged = abs(obj - new_obj) < 1e-12 + w, obj, p = cand, new_obj, new_p + if converged: + break + head.w = np.clip(w[:-1], -8.0, 8.0) + head.b = float(np.clip(w[-1], -8.0, 8.0)) + return {'iterations': it, 'objective': obj} + + +def _constant_log_loss(y: np.ndarray) -> float: + p = float(np.mean(y)) if y.size else 0.0 + return 0.0 if p <= 0.0 or p >= 1.0 else -(p * math.log(p) + (1.0 - p) * math.log(1.0 - p)) + + +def _score_rows(head: ReadoutHead, features: np.ndarray, targets: np.ndarray) -> dict[str, float | None]: + correct, losses = [], [] + for x, y in zip(features, targets.astype(int)): + p = head.predict(x) + correct.append(1.0 if (p >= 0.5) == (y == 1) else 0.0) + pc = min(max(p, _LOG_EPS), 1.0 - _LOG_EPS) + losses.append(-(y * math.log(pc) + (1 - y) * math.log(1.0 - pc))) + return {'accuracy': _mean(correct), 'log_loss': _mean(losses)} + + +def ablation_phase(engine: NeuroWeaveEngine, head: ReadoutHead, stream: TaskStream, task: str, *, + sae: TopKSAE | None = None, ablate: Iterable[int] = (), record: bool = False) -> dict[str, Any]: + """Frozen evaluation of ``head`` on a **clone** of ``engine`` (the original is never stepped). + + Mirrors ``run_task_phase(..., learn=False)`` step for step. With ``ablate`` features, after every engine step + the dictionary codes of the first ``head.n0`` unit outputs are computed and those features' decoder + contributions ``sum_j z_j W_dec[:, j]`` are subtracted from the clone's ``brain.cells.output`` (clipped to + the cells' [-1, 1] output range) before the readout reads it -- the same place ``run_task_phase``'s + ``silence`` zeroes units, so the change also reaches the next step's recurrent input.""" + if task not in TASKS: + raise ValueError(f'task must be one of {TASKS}') + if type(record) is not bool: + raise ValueError('record must be a boolean') + idx = np.asarray(sorted({_int('feature', j, 0, MAX_SAE_WEIGHTS) for j in ablate}), dtype=np.int64) + if idx.size: + if not isinstance(sae, TopKSAE): + raise ValueError('feature ablation needs a TopKSAE') + if sae.n_inputs != head.n0 or int(idx.max()) >= sae.n_features: + raise ValueError('dictionary does not match the head or the ablated features') + eng, hd = clone_engine(engine), head.copy() + n0, steps = hd.n0, stream.steps + w_abl = sae.W_dec[:, idx] if idx.size else None + targets = stream.target(task) + correct, losses, briers, removed = [], [], [], [] + outs = np.zeros((steps, n0)) if record else None + feats = np.zeros((steps, hd.dim)) if record else None + for i in range(steps): + res = eng.step(stream.inputs[i], stream.sensory[i], reward=0.0, learn=False) + out = res['output'] + m = min(n0, out.size) + if w_abl is not None: + x = np.zeros(n0) + x[:m] = out[:m] + z = sae.encode(x) + new = np.clip(x - w_abl @ z[idx], -1.0, 1.0) + eng.brain.cells.output[:m] = new[:m] + out = out.copy() + out[:m] = new[:m] + removed.append(float(np.sqrt(np.sum((new - x) ** 2)))) + xf = hd.features(eng, out) + p = hd.predict(xf) + y = int(targets[i]) + correct.append(1.0 if (p >= 0.5) == (y == 1) else 0.0) + pc = min(max(p, _LOG_EPS), 1.0 - _LOG_EPS) + losses.append(-(y * math.log(pc) + (1 - y) * math.log(1.0 - pc))) + briers.append((p - y) ** 2) + if record: + outs[i, :m] = out[:m] + feats[i] = xf + result: dict[str, Any] = {'steps': steps, 'accuracy': _mean(correct), 'log_loss': _mean(losses), + 'brier': _mean(briers), 'chance_accuracy': chance_accuracy(targets), + 'constant_log_loss': _constant_log_loss(targets.astype(np.float64)), + 'removed_norm': _mean(removed) if removed else 0.0, 'ablated': idx.tolist()} + if record: + result['outputs'], result['head_features'] = outs, feats + return result + + +# ====================================================================== experiment +DEFAULTS: dict[str, Any] = { + 'task': 'delayed_recall', 'heldout_seeds': (100, 101), 'steps': 300, 'heldout_steps': 150, 'neurons': 48, + 'topology': 'clustered', 'mechanisms': (), 'features': 64, 'k': 8, 'k_aux': None, 'aux_coef': 1.0 / 32.0, + 'dead_after': None, 'sae_lr': 3e-3, 'sae_epochs': 60, 'sae_batch': 32, 'n_ablate': 4, 'random_draws': 4, + 'readout': 'refit', 'readout_l2': 1e-2, 'min_fire_rate': 0.02, +} +QUICK: dict[str, Any] = {**DEFAULTS, 'heldout_seeds': (100,), 'steps': 120, 'heldout_steps': 60, 'neurons': 24, + 'features': 32, 'k': 4, 'n_ablate': 3, 'random_draws': 2, 'sae_epochs': 40, 'sae_batch': 16} + + +def _config(quick: bool, seeds: Iterable[int], overrides: Mapping[str, Any]) -> dict[str, Any]: + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + unknown = set(overrides) - set(DEFAULTS) + if unknown: + raise ValueError(f'unknown overrides: {sorted(unknown)}') + cfg = {**(QUICK if quick else DEFAULTS), **overrides} + try: + seeds_t = tuple(_int('seed', s, 0, 2**31 - 1) for s in seeds) + held = tuple(_int('heldout seed', s, 0, 2**31 - 1) for s in cfg['heldout_seeds']) + mechanisms = tuple(cfg['mechanisms']) + except TypeError as exc: + raise ValueError('seeds, heldout_seeds and mechanisms must be iterables') from exc + if not seeds_t or len(set(seeds_t)) != len(seeds_t) or not held or len(set(held)) != len(held): + raise ValueError('seeds and heldout_seeds must be non-empty and unique') + if set(seeds_t) & set(held): + raise ValueError('heldout_seeds must be disjoint from seeds') + if cfg['task'] not in TASKS: + raise ValueError(f'task must be one of {TASKS}') + if cfg['topology'] not in TOPOLOGIES: + raise ValueError(f'topology must be one of {TOPOLOGIES}') + if cfg['readout'] not in ('refit', 'online'): + raise ValueError("readout must be 'refit' or 'online'") + steps = _int('steps', cfg['steps'], 16, 100_000) + features = _int('features', cfg['features'], 4, 4096) + neurons = _int('neurons', cfg['neurons'], 8, 4096) + if neurons * features > MAX_SAE_WEIGHTS: + raise ValueError(f'neurons * features must be <= {MAX_SAE_WEIGHTS}') + out = { + 'task': cfg['task'], 'seeds': seeds_t, 'heldout_seeds': held, 'steps': steps, + 'heldout_steps': _int('heldout_steps', cfg['heldout_steps'], 4, 100_000), 'neurons': neurons, + 'topology': cfg['topology'], 'mechanisms': mechanisms, 'features': features, + 'k': _int('k', cfg['k'], 1, features), + 'k_aux': None if cfg['k_aux'] is None else _int('k_aux', cfg['k_aux'], 1, features), + 'aux_coef': _float('aux_coef', cfg['aux_coef'], 0.0, 100.0), + 'dead_after': steps if cfg['dead_after'] is None else _int('dead_after', cfg['dead_after'], 1, _SINCE_CAP), + 'sae_lr': _float('sae_lr', cfg['sae_lr'], 0.0, 1.0, open_low=True), + 'sae_epochs': _int('sae_epochs', cfg['sae_epochs'], 1, 10_000), + 'sae_batch': _int('sae_batch', cfg['sae_batch'], 1, 4096), + 'n_ablate': _int('n_ablate', cfg['n_ablate'], 1, features), + 'random_draws': _int('random_draws', cfg['random_draws'], 1, 64), 'readout': cfg['readout'], + 'readout_l2': _float('readout_l2', cfg['readout_l2'], 0.0, 1e3, open_low=True), + 'min_fire_rate': _float('min_fire_rate', cfg['min_fire_rate'], 0.0, 1.0), 'quick': quick, + } + make_spec(mechanisms, seed=seeds_t[0], neurons=neurons, topology=out['topology'], steps=steps) # validates mechanisms + return out + + +def _arm_metrics(runs: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + return {key: _mean(r[key] for r in runs) for key in ('accuracy', 'log_loss', 'brier', 'chance_accuracy', + 'constant_log_loss', 'removed_norm')} + + +def _train_energy(sae: TopKSAE, codes: np.ndarray, feats: Sequence[int]) -> float: + idx = np.asarray(sorted(feats), dtype=np.int64) + if not idx.size: + return 0.0 + contrib = codes[:, idx] @ sae.W_dec[:, idx].T + return float(np.mean((contrib ** 2).sum(axis=1))) + + +def _run_seed(seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]: + t0 = time.perf_counter() + task = cfg['task'] + spec = make_spec(cfg['mechanisms'], seed=seed, neurons=cfg['neurons'], topology=cfg['topology'], steps=cfg['steps']) + engine = NeuroWeaveEngine(spec) + head = ReadoutHead(engine.n, seed) + stream = make_stream(seed, cfg['steps']) + online = run_task_phase(engine, {task: head}, stream, learn=True)['tasks'][task] + digest_before = _state_digest(engine) + t_train = time.perf_counter() + # Frozen replay of the *training* stream on a clone: dictionary data, readout refit data, selection data. + rec = ablation_phase(engine, head, stream, task, record=True) + x_tr, f_tr = rec['outputs'], rec['head_features'] + y_tr = stream.target(task).astype(np.float64) + readout_fit = refit_readout(head, f_tr, y_tr, l2=cfg['readout_l2']) if cfg['readout'] == 'refit' else None + train_frozen = _score_rows(head, f_tr, y_tr) + sae = TopKSAE(head.n0, cfg['features'], cfg['k'], seed=seed + _EXP_SAE_OFFSET, lr=cfg['sae_lr'], + k_aux=cfg['k_aux'], aux_coef=cfg['aux_coef'], dead_after=cfg['dead_after']) + sae.init_from_data(x_tr) + fit = sae.fit(x_tr, epochs=cfg['sae_epochs'], batch_size=cfg['sae_batch']) + t_sae = time.perf_counter() + z_tr = sae.encode(x_tr) + train_eval = sae.evaluate(x_tr) + min_fires = max(1, int(math.ceil(cfg['min_fire_rate'] * x_tr.shape[0]))) + sel = select_predictive_features(z_tr, y_tr, cfg['n_ablate'], min_fires=min_fires) + targeted = sel['targeted'] + pool = np.asarray(sel['pool'], dtype=np.int64) + rng = np.random.default_rng(seed + _EXP_RANDOM_OFFSET) + size = min(len(targeted), pool.size) + random_sets = [sorted(int(j) for j in rng.choice(pool, size=size, replace=False)) for _ in range(cfg['random_draws'])] + # Causal ablation on frozen clones over held-out streams (never trained on). + arms: dict[str, list[dict[str, Any]]] = {'none': [], 'targeted': [], 'random': []} + heldout_x = [] + for hs in cfg['heldout_seeds']: + hstream = make_stream(hs, cfg['heldout_steps']) + base = ablation_phase(engine, head, hstream, task, record=True) + heldout_x.append(base.pop('outputs')) + base.pop('head_features') + arms['none'].append(base) + arms['targeted'].append(ablation_phase(engine, head, hstream, task, sae=sae, ablate=targeted)) + draws = [ablation_phase(engine, head, hstream, task, sae=sae, ablate=s) for s in random_sets] + arms['random'].append(_arm_metrics(draws)) + digest_after = _state_digest(engine) + held_fvu = sae.evaluate(np.vstack(heldout_x))['fvu'] + heldout = {name: _arm_metrics(runs) for name, runs in arms.items()} + for name in ('targeted', 'random'): + heldout[name]['delta_log_loss_vs_none'] = heldout[name]['log_loss'] - heldout['none']['log_loss'] + heldout[name]['delta_accuracy_vs_none'] = heldout[name]['accuracy'] - heldout['none']['accuracy'] + t_end = time.perf_counter() + return { + 'seed': int(seed), 'train_stream_digest': stream.digest, 'engine_state_digest': digest_before, + 'original_engine_unchanged': digest_after == digest_before, + 'readout': {'kind': cfg['readout'], + 'online_prequential': {k: online[k] for k in ('accuracy', 'log_loss', 'chance_accuracy')}, + 'train_frozen': train_frozen, 'constant_log_loss_train': _constant_log_loss(y_tr), + 'refit': readout_fit}, + 'dictionary': {'train_fvu': train_eval['fvu'], 'heldout_fvu': held_fvu, 'train_l0': train_eval['l0'], + 'never_fired_train_fraction': train_eval['never_fired_fraction'], + 'dead_fraction_training': train_eval['dead_fraction_training'], + 'usage_histogram_train': train_eval['usage_histogram'], 'updates': int(sae.updates), + 'last_epoch_loss': fit.get('last_epoch_loss'), 'last_epoch_aux_loss': fit.get('last_epoch_aux_loss'), + 'decoder_norm_max_error': float(np.max(np.abs(sae.decoder_norms() - 1.0)))}, + 'selection': {'min_fires': min_fires, 'pool_size': int(pool.size), + 'targeted': [{'feature': int(j), 'corr': float(sel['corr'][j]), 'fires': int(sel['fires'][j])} + for j in targeted], + 'random_sets': random_sets, 'targeted_train_energy': _train_energy(sae, z_tr, targeted), + 'random_train_energy': _mean(_train_energy(sae, z_tr, s) for s in random_sets), + 'random_overlap_with_targeted': _mean(len(set(s) & set(targeted)) / max(1, len(targeted)) + for s in random_sets)}, + 'heldout': heldout, + 'budget': {'dictionary_parameters': sae.parameter_count, 'dictionary_state_numbers': sae.state_numbers, + 'engine': _budget(engine, head)}, + 'estimated_cost': {**_estimated_cost(engine, cfg['steps'], head.dim), + 'engine_steps': int(2 * cfg['steps'] + len(cfg['heldout_seeds']) * cfg['heldout_steps'] + * (2 + cfg['random_draws'])), + 'dictionary_train_ops': int(6 * sae.n_inputs * sae.n_features * x_tr.shape[0] + * cfg['sae_epochs']), + 'ablation_encode_ops': int(2 * sae.n_inputs * sae.n_features * len(cfg['heldout_seeds']) + * cfg['heldout_steps'] * (1 + cfg['random_draws']))}, + 'measured_wallclock_s': {'engine_train': t_train - t0, 'replay_refit_dictionary': t_sae - t_train, + 'selection_ablation': t_end - t_sae}, + } + + +_NOTES = ( + "Protocol per seed: a NEUROWEAVE engine and the lab ReadoutHead are trained prequentially on the training stream " + "(run_task_phase, learn=True). A frozen clone then replays the training stream to record the first n0 unit outputs " + "and the head features; with readout='refit' the head is refit on those features by L2 logistic regression (a " + "competent frozen probe; held-out streams are never used for fitting). A TopK sparse autoencoder (Gao et al. 2024) " + "is fit to the recorded outputs, and the n_ablate alive features with the largest |Pearson r| with the training " + "target are 'targeted'. On held-out streams, frozen clones run three arms: no ablation, targeted ablation and random " + "ablation (random_draws uniform draws of the same number of alive features; draws may overlap the targeted set). " + "Ablation subtracts the chosen features' decoder contributions from the clone's brain.cells.output after every step " + "(clipped to [-1, 1]; it also feeds the next step's recurrence). VERDICT MEANING: 'improved' means only that " + "ablating the targeted features raised held-out log-loss MORE than ablating random features (paired 95% t interval " + "over seeds excludes zero) -- i.e. the targeted features matter more to the frozen readout than random ones. It does " + "not mean any model got better. Limits: targeted features may carry more activity energy than random ones " + "(compare selection.targeted_train_energy, random_train_energy and heldout.*.removed_norm before reading the effect " + "as feature-specific); tiny engines, few hundred samples, few seeds; dictionary features are directions in a toy " + "model's activity space, not cell types; synthetic abstraction only.") + + +def run_experiment(*, quick: bool = False, seeds: Iterable[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Targeted vs random vs no SAE-feature ablation of a frozen NEUROWEAVE readout (sealed frontier receipt).""" + cfg = _config(quick, seeds, overrides) + t0 = time.perf_counter() + per_seed = [_run_seed(s, cfg) for s in cfg['seeds']] + wall = time.perf_counter() - t0 + + def col(arm: str, metric: str) -> list[float]: + return [p['heldout'][arm][metric] for p in per_seed] + + def cmp(cand: list[float], ref: list[float], higher: bool, meaning: str) -> dict[str, Any]: + out = compare(cand, ref, higher_is_better=higher) + sd = out.get('sd') + out['cohen_dz'] = (out['mean'] / sd) if out.get('mean') is not None and sd else None + out['improved_means'] = meaning + return out + + comparisons = { + 'targeted_vs_random_log_loss': cmp(col('targeted', 'log_loss'), col('random', 'log_loss'), True, + 'targeted ablation raised held-out log-loss more than random ablation'), + 'targeted_vs_random_accuracy': cmp(col('targeted', 'accuracy'), col('random', 'accuracy'), False, + 'targeted ablation lowered held-out accuracy more than random ablation'), + 'targeted_vs_none_log_loss': cmp(col('targeted', 'log_loss'), col('none', 'log_loss'), True, + 'targeted ablation raised held-out log-loss'), + 'random_vs_none_log_loss': cmp(col('random', 'log_loss'), col('none', 'log_loss'), True, + 'random ablation raised held-out log-loss'), + } + head = comparisons['targeted_vs_random_log_loss'] + receipt = base_receipt(MODULE_ID, 'feature_ablation', {k: (list(v) if isinstance(v, tuple) else v) + for k, v in cfg.items()}) + receipt['title'] = 'Sparse dictionary of brain activity: targeted vs random feature ablation' + receipt['source'] = ('Inspired by TopK sparse autoencoders with the AuxK dead-latent loss: Gao et al., "Scaling and ' + 'evaluating sparse autoencoders", arXiv:2406.04093 (June 2024), ICLR 2025') + receipt['per_seed'] = per_seed + receipt['arms'] = {arm: {'heldout_accuracy': _mean(col(arm, 'accuracy')), + 'heldout_log_loss': _mean(col(arm, 'log_loss')), + 'heldout_removed_norm': _mean(col(arm, 'removed_norm'))} + for arm in ('none', 'targeted', 'random')} + receipt['arms']['none']['heldout_constant_log_loss'] = _mean(col('none', 'constant_log_loss')) + receipt['arms']['none']['heldout_chance_accuracy'] = _mean(col('none', 'chance_accuracy')) + receipt['comparisons'] = comparisons + receipt['verdict'] = head['verdict'] + receipt['verdict_basis'] = ('targeted_vs_random_heldout_log_loss: paired 95% t interval over seeds of (held-out ' + 'log-loss with the targeted features ablated) - (with the same number of random alive ' + "features ablated); 'improved' = the targeted features matter more to the frozen readout " + "than random ones (interval above zero), 'worse' = they matter less, nothing else") + receipt['integrity'] = { + 'original_engines_unchanged': all(p['original_engine_unchanged'] for p in per_seed), + 'decoder_columns_unit_norm': all(p['dictionary']['decoder_norm_max_error'] < 1e-9 for p in per_seed), + 'readout_skill_over_constant': _mean(p['heldout']['none']['constant_log_loss'] - p['heldout']['none']['log_loss'] + for p in per_seed), + } + receipt['budget'] = per_seed[0]['budget'] + receipt['estimated_cost'] = {k: int(sum(p['estimated_cost'][k] for p in per_seed)) + for k in per_seed[0]['estimated_cost']} + receipt['measured_wallclock_s'] = {'total': wall} + receipt['notes'] = _NOTES + return seal(receipt) + + +EXPERIMENTS = {MODULE_ID: run_experiment} diff --git a/synapse/frontier/spec.py b/synapse/frontier/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..336af815bf442d6971b577d4a24718cd6f0cb729 --- /dev/null +++ b/synapse/frontier/spec.py @@ -0,0 +1,199 @@ +"""Versioned specification and registry for the Sonapse frontier pack. + +The frontier pack is an *additive, default-off* set of experimental modules +drawn from 2024-2026 research and from sibling ``kai9987kai`` projects. Nothing +here changes Sonapse or NEUROWEAVE behaviour unless a caller opts in: + +* ``SynapseConfig().frontier`` is ``None`` and is omitted from ``to_dict()``. +* The live runtime hook is **observer-only**: it reads brain activity and never + writes into the brain, the graft bus or the actor. +* Modules that can influence computation do so only as explicitly attached + NEUROWEAVE engine extensions inside lab experiments, or through explicitly + selected opt-in options. + +Every module is a synthetic computational abstraction. Titles name the research +idea a module is inspired by; they are not claims of reproducing published +results. +""" +from __future__ import annotations + +from dataclasses import asdict, dataclass, replace +import hashlib +import json +from typing import Any, Mapping + +SPEC_SCHEMA = 'FrontierSpecV1' +SPEC_VERSION = 1 +EVIDENCE_TIER = 'synthetic_abstraction' +LAB_SCHEMA = 'FrontierLabReceiptV1' + + +@dataclass(frozen=True) +class ModuleInfo: + id: str + title: str + kind: str # extension | analysis | model | methodology | discovery | tool | reference + origin: str # literature | portfolio + source: str # short human-readable provenance (full citations: docs/frontier/REFERENCES.md) + description: str + observer: bool = False # can run as a read-only live observer + + +def _m(id: str, title: str, kind: str, origin: str, source: str, description: str, observer: bool = False) -> ModuleInfo: + return ModuleInfo(id, title, kind, origin, source, description, observer) + + +MODULES: tuple[ModuleInfo, ...] = ( + _m('synchrony', 'Synchronisation representation and neuron-level models', 'extension', 'literature', + 'Continuous Thought Machines (Darlow et al., 2025)', + 'Pairwise decayed synchronisation of unit activity as a readout representation, plus private per-neuron history models and internal ticks.', + observer=True), + _m('continuum_memory', 'Continuum memory system', 'extension', 'literature', + 'Nested Learning / HOPE (Behrouz et al., 2025); Titans (Behrouz et al., 2025)', + 'A chain of associative memories updated at geometrically spaced frequencies with surprise-gated writes and decay.'), + _m('btsp_memory', 'One-shot BTSP memory with binary synapses', 'extension', 'literature', + 'Behavioural time-scale synaptic plasticity model (Wu & Maass, 2025)', + 'Plateau-gated stochastic flips of binary synapses give one-shot content-addressable memory.'), + _m('kuramoto_binding', 'Oscillatory binding units', 'extension', 'literature', + 'Artificial Kuramoto Oscillatory Neurons (Miyato et al., 2025)', + 'Unit-vector oscillators with tangent-space Kuramoto updates; synchrony clusters bind related inputs.', + observer=True), + _m('recursive_refiner', 'Recursive latent refinement', 'model', 'literature', + 'Tiny Recursive Model (Jolicoeur-Martineau, 2025); Hierarchical Reasoning Model (Wang et al., 2025)', + 'One tiny network repeatedly refines a latent and an answer with deep supervision and a halting head.'), + _m('dendritic_layer', 'Structured dendritic layer', 'model', 'literature', + 'Dendritic ANNs (Chavlis & Poirazi, 2025)', + 'Dendrites sample restricted receptive fields and feed a soma; compared against dense layers at equal parameters.'), + _m('muon_optimizer', 'Orthogonalised-momentum optimiser', 'tool', 'literature', + 'Muon (Jordan et al., 2024; Liu et al., 2025)', + 'Newton-Schulz orthogonalised momentum for matrix parameters with an AdamW fallback for the rest.'), + _m('rigl_sparse', 'Dynamic sparse training', 'tool', 'literature', + 'RigL (Evci et al., 2020), as used in sonapse-evo', + 'Periodic magnitude pruning and gradient-magnitude regrowth at a fixed parameter budget.'), + _m('sparse_dictionary', 'Sparse dictionary of brain activity', 'analysis', 'literature', + 'TopK sparse autoencoders (Gao et al., 2024)', + 'Online TopK sparse autoencoder over unit activity with dead-feature handling and causal feature ablation.', + observer=True), + _m('anytime_inference', 'Anytime-valid inference', 'methodology', 'literature', + 'Betting confidence sequences (Waudby-Smith & Ramdas, 2024); e-values (Ramdas et al., 2023)', + 'E-processes and confidence sequences that stay valid under optional stopping.'), + _m('experiment_design', 'Decision-sensitive experiment selection', 'methodology', 'portfolio', + 'COUNTERFORM and Mnemorph (kai9987kai)', + 'Chooses the next experiment by expected reduction in downstream decision risk, with abstention.'), + _m('quality_diversity', 'Quality-diversity architecture search', 'discovery', 'portfolio', + 'SONAPSE-ORIGIN and sonapse-evo (kai9987kai); MAP-Elites (Mouret & Clune, 2015); Darwin Godel Machine (Zhang et al., 2025)', + 'A MAP-Elites archive over NEUROWEAVE configurations with novelty-weighted parent selection and verifier-gated admission.'), + _m('morphogenesis', 'Developmental growth and regeneration', 'discovery', 'portfolio', + 'morpheus, prometheus-alpha, GenesisEngine and MOLT (kai9987kai); growing neural cellular automata (Mordvintsev et al., 2020)', + 'Grows a connectome from a compact developmental program and regrows it after lesions with a stored pattern memory.'), + _m('connectomics', 'Structural, functional and effective connectivity', 'analysis', 'portfolio', + 'SONAPSE-CONNECTOME (kai9987kai)', + 'Functional, dynamic-functional and lagged effective connectivity kept separate from structure, with structure-function coupling.', + observer=True), + _m('causal_emergence', 'Effective information and causal emergence', 'analysis', 'portfolio', + 'GhostInTheMachine and SONAPSE-ORIGIN (kai9987kai); effective information (Hoel et al., 2013)', + 'Effective information of micro and coarse-grained transition models with shuffle-null calibration.', + observer=True), + _m('hh_cable', 'Hodgkin-Huxley cable reference', 'reference', 'portfolio', + 'NeuroPulse-CableLab (kai9987kai); Hodgkin & Huxley (1952)', + 'Multi-compartment Hodgkin-Huxley cable used as a biophysical reference for the abstract cell model.'), + _m('nir_export', 'Neuromorphic interchange export', 'tool', 'literature', + 'Neuromorphic Intermediate Representation (Pedersen et al., 2024)', + 'Exports spiking and NEUROWEAVE graphs as a NIR-style graph; writes real NIR files when the optional package is installed.'), + _m('joint_failure', 'Joint-failure ensemble selection', 'methodology', 'portfolio', + 'FAULTLINE (kai9987kai)', + 'Selects voting panels from condition-indexed joint-failure observations instead of individual accuracy.'), +) +MODULE_IDS: tuple[str, ...] = tuple(m.id for m in MODULES) +OBSERVER_MODULE_IDS: tuple[str, ...] = tuple(m.id for m in MODULES if m.observer) +assert len(set(MODULE_IDS)) == len(MODULE_IDS) + +GRAFT_OPTIMIZERS = ('adam', 'muon') + + +def _check_int(name: str, value: Any, low: int, high: int) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return value + + +@dataclass(frozen=True) +class FrontierSpecV1: + """Immutable frontier configuration. Defaults are fully neutral (disabled, no modules).""" + + enabled: bool = False + seed: int = 7 + modules: tuple[str, ...] = () # live read-only observers (subset of OBSERVER_MODULE_IDS) + observe_every: int = 1 # observe every k-th executed agent step + max_observed_units: int = 256 # deterministic unit subsample fed to observers (bounds cost) + history: int = 256 # bounded activity history kept by observers + sae_features: int = 64 + sae_k: int = 8 + sync_pairs: int = 64 + fc_window: int = 128 + graft_optimizer: str = 'adam' # opt-in optimiser for the live neural-graft fit ('muon' = frontier) + + def __post_init__(self) -> None: + if type(self.enabled) is not bool: + raise ValueError('enabled must be a boolean') + _check_int('seed', self.seed, 0, 2**31 - 1) + _check_int('observe_every', self.observe_every, 1, 10_000) + _check_int('max_observed_units', self.max_observed_units, 8, 4096) + _check_int('history', self.history, 16, 8192) + _check_int('sae_features', self.sae_features, 4, 4096) + _check_int('sae_k', self.sae_k, 1, self.sae_features) + _check_int('sync_pairs', self.sync_pairs, 1, 4096) + _check_int('fc_window', self.fc_window, 8, 8192) + if self.graft_optimizer not in GRAFT_OPTIMIZERS: + raise ValueError(f'graft_optimizer must be one of {GRAFT_OPTIMIZERS}') + mods = tuple(self.modules) + unknown = [m for m in mods if m not in MODULE_IDS] + if unknown: + raise ValueError(f'unknown frontier modules: {unknown}') + not_observer = [m for m in mods if m not in OBSERVER_MODULE_IDS] + if not_observer: + raise ValueError(f'modules without a live observer: {not_observer} (observers: {OBSERVER_MODULE_IDS})') + object.__setattr__(self, 'modules', tuple(m for m in MODULE_IDS if m in set(mods))) + + def has(self, module: str) -> bool: + if module not in MODULE_IDS: + raise KeyError(module) + return module in self.modules + + def with_modules(self, modules) -> 'FrontierSpecV1': + return replace(self, modules=tuple(modules)) + + def to_dict(self) -> dict[str, Any]: + data = asdict(self) + data['modules'] = list(self.modules) + data['schema'] = SPEC_SCHEMA + data['schema_version'] = SPEC_VERSION + return data + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> 'FrontierSpecV1': + if not isinstance(data, Mapping): + raise ValueError('frontier spec must be a mapping') + payload = dict(data) + if payload.pop('schema', SPEC_SCHEMA) != SPEC_SCHEMA or payload.pop('schema_version', SPEC_VERSION) != SPEC_VERSION: + raise ValueError('unsupported frontier spec schema') + extra = set(payload) - set(cls.__dataclass_fields__) + if extra: + raise ValueError(f'unknown frontier spec fields: {sorted(extra)}') + if 'modules' in payload: + payload['modules'] = tuple(payload['modules']) + return cls(**payload) + + @property + def spec_digest(self) -> str: + return hashlib.sha256(json.dumps(self.to_dict(), sort_keys=True).encode('utf-8')).hexdigest() + + @classmethod + def max_preset(cls, seed: int = 7) -> 'FrontierSpecV1': + """Max Mode preset: every live observer on. Observers are read-only, so this + does not change the actor's trajectory; the opt-in graft optimiser stays at its default.""" + return cls(enabled=True, seed=seed, modules=OBSERVER_MODULE_IDS) + + +def module_catalog() -> list[dict[str, Any]]: + return [asdict(m) for m in MODULES] diff --git a/synapse/frontier/synchrony.py b/synapse/frontier/synchrony.py new file mode 100644 index 0000000000000000000000000000000000000000..80f15f80defeaec34027ef335c9d0a819862ffbf --- /dev/null +++ b/synapse/frontier/synchrony.py @@ -0,0 +1,1111 @@ +"""Synchronisation representation, neuron-level models and internal ticks (frontier module ``synchrony``). + +Inspired by *Continuous Thought Machines* (CTM): Luke Darlow, Ciaran Regan, Sebastian Risi, Jeffrey Seely and +Llion Jones (Sakana AI), NeurIPS 2025 (spotlight), arXiv:2505.05522 (v1 8 May 2025, v4 3 October 2025), +https://arxiv.org/abs/2505.05522 ; reference code https://github.com/SakanaAI/continuous-thought-machines . +This module borrows the CTM's ideas at toy scale. It does not reproduce the paper's models, scale or results. + +Three pieces +------------ +1. :class:`SynchronyExtension` (engine extension ``'synchrony'``): the CTM's recursive, exponentially decayed + pairwise synchronisation of a NEUROWEAVE brain's unit outputs, exposed as extra readout features. Decay + rates are fixed per pair (the CTM learns them) and spread log-uniformly over several timescales. +2. :class:`SynchronyObserver`: a read-only live observer. It z-scores every observed unit online and tracks + multi-timescale synchrony and decayed correlation for a deterministic sample of unit pairs. +3. ``MiniCTM`` (PyTorch): a small CTM with private neuron-level models over pre-activation histories, + internal ticks, a synapse model, attention over the whole input, and outputs read from a learnable-decay + synchronisation representation. :func:`run_ctm_benchmark` compares it with parameter-matched GRU and MLP + baselines on cumulative parity. The PyTorch classes are created on first attribute access, so importing + this module does not import PyTorch. + +Synchronisation (CTM Sec. 3.4, eq. 10; App. H, eqs. 13-17) +---------------------------------------------------------- +For a pair (i, j) with decay rate r >= 0 and post-activations z^1..z^t:: + + S_ij^t = sum_tau exp(-r (t - tau)) z_i^tau z_j^tau / sqrt( sum_tau exp(-r (t - tau)) ) + +computed recursively as ``alpha <- exp(-r) alpha + z_i z_j``, ``beta <- exp(-r) beta + 1`` and +``S = alpha / sqrt(beta)``. :func:`decayed_synchrony` is the closed form; tests check that the recursions in +the extension and in ``MiniCTM`` equal it. +""" +from __future__ import annotations + +import math +import time +from typing import Any, Callable, Mapping, Sequence + +import numpy as np + +from .extension import EngineExtension + +__all__ = ['MODULE_ID', 'SynchronyExtension', 'SynchronyObserver', 'sample_pairs', 'log_uniform_timescales', + 'decayed_synchrony', 'observer_timescales', 'cumulative_parity_data', 'ctm_tick_loss', + 'run_experiment', 'run_ctm_benchmark', 'EXPERIMENTS'] +# Lazy (PyTorch) names, resolved by the module-level __getattr__ below. They are left out of __all__ so a +# star import stays free of PyTorch. +_TORCH_NAMES = ('MiniCTM', 'AttentiveGRU', 'ParityMLP', 'SequenceReader', 'NeuronLevelModels') + +MODULE_ID = 'synchrony' +FEATURE_SCALES = ('ctm', 'unit') +OBSERVER_STATE_SCHEMA = 'SynchronyObserverStateV1' +_PAIR_OFFSET = 51_001 +_TAU_OFFSET = 51_011 +_OBS_OFFSET = 51_021 +_CTM_OFFSET = 51_031 +_GRU_OFFSET = 51_041 +_MLP_OFFSET = 51_051 +_DATA_OFFSET = 51_061 +_BATCH_OFFSET = 51_071 +_READER_OFFSET = 51_081 +_NLM_OFFSET = 51_091 +_TOP_PAIRS = 8 + + +# ====================================================================== validation helpers +def _check_int(name: str, value: Any, low: int, high: int) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high: + raise ValueError(f'{name} must be an int in [{low}, {high}]') + return int(value) + + +def _check_float(name: str, value: Any, low: float, high: float) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)): + raise ValueError(f'{name} must be a number in [{low}, {high}]') + v = float(value) + if not (math.isfinite(v) and low <= v <= high): + raise ValueError(f'{name} must be a finite number in [{low}, {high}]') + return v + + +def _check_seeds(seeds: Any) -> tuple[int, ...]: + try: + out = tuple(_check_int('seed', s, 0, 2**31 - 1) for s in seeds) + except TypeError as exc: + raise ValueError('seeds must be an iterable of ints') from exc + if not out or len(set(out)) != len(out): + raise ValueError('seeds must be non-empty and unique') + return out + + +def _finite_array(name: str, value: Any, shape: tuple[int, ...]) -> np.ndarray: + try: + arr = np.array(value, dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be numeric') from exc + if arr.shape != shape or not np.all(np.isfinite(arr)): + raise ValueError(f'{name} must be a finite array of shape {shape}') + return arr + + +def _int_array(name: str, value: Any, size: int, high: int) -> np.ndarray: + try: + arr = np.array(value) + except (TypeError, ValueError) as exc: + raise ValueError(f'{name} must be an integer array') from exc + if arr.shape != (size,) or (size and (arr.dtype.kind not in 'iu' or arr.min() < 0 or arr.max() >= high)): + raise ValueError(f'{name} must be {size} integers in [0, {high})') + return arr.astype(np.int64) + + +# ====================================================================== shared maths +def sample_pairs(n: int, pairs: int, self_pairs: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]: + """Deterministic pair sample in the spirit of the CTM's *random pairing* (App. C.2). + + Returns ``(left, right)`` index arrays of length ``pairs``. The first ``self_pairs`` entries are self pairs + (i, i) on distinct units, as in the CTM, which keeps a snapshot of single-unit activity in the + representation. The rest are distinct unordered cross pairs i < j. Unlike the CTM code, which samples + with replacement, cross pairs repeat only when ``pairs - self_pairs`` exceeds n(n-1)/2. With ``n == 1`` + every pair is (0, 0).""" + n = _check_int('n', n, 1, 10_000_000) + pairs = _check_int('pairs', pairs, 1, 1_000_000) + self_pairs = _check_int('self_pairs', self_pairs, 0, pairs) + s_units = rng.choice(n, size=min(self_pairs, n), replace=False).astype(np.int64) + if self_pairs > n: + s_units = np.concatenate([s_units, rng.integers(0, n, self_pairs - n)]) + need = pairs - self_pairs + if n == 1: + cl = cr = np.zeros(need, np.int64) + else: + max_distinct = n * (n - 1) // 2 + take = min(need, max_distinct) + if 2 * take >= max_distinct: + # dense regime (max_distinct <= 2 * pairs, so enumeration is small): seeded order over all pairs + iu, ju = np.triu_indices(n, 1) + order = rng.permutation(max_distinct)[:take] + cl, cr = iu[order].astype(np.int64), ju[order].astype(np.int64) + else: + # sparse regime: rejection sampling of unordered distinct pairs (acceptance >= 1/4 per draw) + seen: set[tuple[int, int]] = set() + lst_l: list[int] = [] + lst_r: list[int] = [] + while len(lst_l) < take: + k = 2 * (take - len(lst_l)) + 8 + a, b = rng.integers(0, n, k).tolist(), rng.integers(0, n, k).tolist() + for x, y in zip(a, b): + if x == y: + continue + key = (x, y) if x < y else (y, x) + if key in seen: + continue + seen.add(key) + lst_l.append(key[0]) + lst_r.append(key[1]) + if len(lst_l) == take: + break + cl, cr = np.array(lst_l, np.int64), np.array(lst_r, np.int64) + if need > take: + extra = rng.integers(0, take, need - take) + cl, cr = np.concatenate([cl, cl[extra]]), np.concatenate([cr, cr[extra]]) + return np.concatenate([s_units, cl]).astype(np.int64), np.concatenate([s_units, cr]).astype(np.int64) + + +def log_uniform_timescales(count: int, low: float, high: float, rng: np.random.Generator) -> np.ndarray: + """``count`` timescales spread log-uniformly over [low, high] (stratified), in a seeded random order.""" + count = _check_int('count', count, 1, 1_000_000) + low = _check_float('low', low, 1e-3, 1e6) + high = _check_float('high', high, low, 1e6) + q = (np.arange(count) + 0.5) / count + tau = low * (high / low) ** q + return tau[rng.permutation(count)] + + +def decayed_synchrony(history: Any, left: Any, right: Any, decay: Any) -> np.ndarray: + """Closed-form CTM synchronisation of a ``(t, n)`` post-activation history for the given pairs. + + ``decay[p] = exp(-r_p)``. Returns ``S_p = sum_tau decay_p^(t - tau) z_i z_j / sqrt(sum_tau decay_p^(t - tau))``.""" + Z = np.asarray(history, dtype=np.float64) + if Z.ndim != 2 or Z.shape[0] < 1: + raise ValueError('history must be a (t, n) array with t >= 1') + left, right = np.asarray(left, dtype=np.int64), np.asarray(right, dtype=np.int64) + d = np.asarray(decay, dtype=np.float64) + t = Z.shape[0] + w = d[None, :] ** (t - 1 - np.arange(t))[:, None] + return (w * Z[:, left] * Z[:, right]).sum(0) / np.sqrt(w.sum(0)) + + +def observer_timescales(history: int) -> tuple[float, ...]: + """Observer timescales ``2 * 4^k`` steps up to ``max(2, history / 2)``: (2, 8, 32, 128) for history 256.""" + history = _check_int('history', history, 4, 65_536) + out = [2.0] + while out[-1] * 4.0 <= history / 2.0: + out.append(out[-1] * 4.0) + return tuple(out) + + +# ====================================================================== engine extension +class SynchronyExtension(EngineExtension): + """CTM-style decayed pairwise synchronisation of brain unit outputs as extra readout features. + + ``pairs`` unit pairs are sampled deterministically from the units present at :meth:`bind`. Units born + later are ignored, so the shape stays fixed. ``self_pairs`` of them are (i, i). Pair ``p`` has a fixed + decay ``exp(-1/tau_p)``, with ``tau_p`` spread log-uniformly over ``timescales`` steps. The CTM learns + these rates; here they are fixed, so nothing adapts and ``ctx['learn']`` changes nothing. The accumulators + still follow activity, which is inference, not learning. + + ``features()`` returns ``S`` (CTM scale, ``feature_scale='ctm'``, clipped to [-10, 10]) or + ``S * sqrt(1 - decay)`` (``'unit'``). The 'unit' factor is a fixed per-pair constant, so it does not change + what a linear readout can represent. It does bound every feature by max|z|^2 <= 1, the same range as the + random-trace control, so a fixed-learning-rate readout sees comparable scales. Brain outputs already lie in + [-1, 1]; the clip of z to [-1, 1] only guards other callers.""" + + id = 'synchrony' + + def __init__(self, pairs: int = 32, *, seed: int = 0, self_pairs: int | None = None, + timescales: Sequence[float] = (1.0, 32.0), feature_scale: str = 'ctm') -> None: + self.pairs = _check_int('pairs', pairs, 1, 4096) + self.self_pairs = self.pairs // 8 if self_pairs is None else _check_int('self_pairs', self_pairs, 0, self.pairs) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + try: + lo, hi = (float(v) for v in timescales) + except (TypeError, ValueError) as exc: + raise ValueError('timescales must be a (low, high) pair of numbers') from exc + lo = _check_float('timescales[0]', lo, 0.05, 1e5) + hi = _check_float('timescales[1]', hi, lo, 1e5) + if feature_scale not in FEATURE_SCALES: + raise ValueError(f'feature_scale must be one of {FEATURE_SCALES}') + self.timescales = (lo, hi) + self.feature_scale = feature_scale + self.feature_dim = self.pairs + self._tau = log_uniform_timescales(self.pairs, lo, hi, np.random.default_rng(self.seed + _TAU_OFFSET)) + self._decay = np.exp(-1.0 / self._tau) + self._scale = np.ones(self.pairs) if feature_scale == 'ctm' else np.sqrt(1.0 - self._decay) + self._n = 0 + self._left = np.zeros(0, np.int64) + self._right = np.zeros(0, np.int64) + self._num = np.zeros(self.pairs) + self._den = np.zeros(self.pairs) + self._steps = 0 + + # ------------------------------------------------------------------ lifecycle + def bind(self, engine: Any) -> None: + n = _check_int('engine.n', int(engine.n), 1, 10_000_000) + left, right = sample_pairs(n, self.pairs, self.self_pairs, np.random.default_rng(self.seed + _PAIR_OFFSET)) + self._n, self._left, self._right = n, left, right + self.reset() + + def reset(self) -> None: + self._num = np.zeros(self.pairs) + self._den = np.zeros(self.pairs) + self._steps = 0 + + # ------------------------------------------------------------------ hooks + def after_step(self, output: np.ndarray, ctx: Mapping[str, Any] | None = None) -> None: + if self._n == 0: + raise ValueError('synchrony extension is not bound to an engine') + out = np.asarray(output, dtype=np.float64) + if out.ndim != 1 or not np.all(np.isfinite(out)): + raise ValueError('output must be a finite 1-D array') + z = np.zeros(self._n) + m = min(self._n, out.size) # neurons born later are ignored (fixed shape) + z[:m] = np.clip(out[:m], -1.0, 1.0) + self._num = self._decay * self._num + z[self._left] * z[self._right] + self._den = self._decay * self._den + 1.0 + self._steps += 1 + + def synchronisation(self) -> np.ndarray: + """Current CTM synchronisation ``S = alpha / sqrt(beta)`` per pair (zeros before the first step).""" + if self._steps == 0: + return np.zeros(self.pairs) + return self._num / np.sqrt(self._den) + + def features(self) -> np.ndarray: + return np.clip(self.synchronisation() * self._scale, -10.0, 10.0) + + # ------------------------------------------------------------------ accounting / persistence + @property + def pair_indices(self) -> tuple[np.ndarray, np.ndarray]: + return self._left.copy(), self._right.copy() + + @property + def decays(self) -> np.ndarray: + return self._decay.copy() + + def parameter_count(self) -> int: + return 0 # nothing is trained + + def state_numbers(self) -> int: + return int(self._left.size + self._right.size + self._decay.size + self._num.size + self._den.size) + + def telemetry(self) -> dict[str, Any]: + s = self.synchronisation() + return {'id': self.id, 'pairs': self.pairs, 'self_pairs': self.self_pairs, 'n': self._n, + 'steps': self._steps, 'feature_scale': self.feature_scale, 'timescales': list(self.timescales), + 'mean_abs_sync': float(np.abs(s).mean()), 'max_abs_sync': float(np.abs(s).max())} + + def _config(self) -> dict[str, Any]: + return {'pairs': self.pairs, 'self_pairs': self.self_pairs, 'seed': self.seed, + 'timescales': list(self.timescales), 'feature_scale': self.feature_scale, 'n': self._n} + + def export_state(self) -> dict[str, Any]: + return {'id': self.id, **self._config(), 'left': self._left.tolist(), 'right': self._right.tolist(), + 'num': self._num.tolist(), 'den': self._den.tolist(), 'steps': self._steps} + + def import_state(self, state: Mapping[str, Any]) -> None: + super().import_state(state) + for key, value in self._config().items(): + if state.get(key) != value: + raise ValueError(f'synchrony state does not match this extension ({key})') + P = self.pairs + left = _int_array('left', state.get('left'), P, max(1, self._n)) + right = _int_array('right', state.get('right'), P, max(1, self._n)) + if not (np.array_equal(left, self._left) and np.array_equal(right, self._right)): + raise ValueError('synchrony state pairs do not match this extension') + num = _finite_array('num', state.get('num'), (P,)) + den = _finite_array('den', state.get('den'), (P,)) + steps = _check_int('steps', state.get('steps'), 0, 2**62) + expect = (1.0 - self._decay ** steps) / (1.0 - self._decay) + if not np.allclose(den, expect, rtol=1e-6, atol=1e-9) or np.any(np.abs(num) > den + 1e-9): + raise ValueError('synchrony state is inconsistent (den does not match steps or |num| > den)') + self._num, self._den, self._steps = num, den, steps + + +# ====================================================================== live observer +class SynchronyObserver: + """Read-only live observer: online z-scoring per unit plus multi-timescale pairwise synchrony. + + * z-scores use a running mean and variance with window ``history``. They are exact (Welford) for the first + ``history`` observations and exponentially weighted with rate ``1/history`` afterwards. Values are + clipped to [-zclip, zclip]. + * ``pairs`` unit pairs, of which ``self_pairs`` are (i, i) and the rest distinct cross pairs, are sampled + once from ``seed``. At every timescale in :func:`observer_timescales` each pair keeps the CTM recursion + ``alpha <- d alpha + z_i z_j``, ``beta <- d beta + 1`` with ``d = exp(-1/tau)``, and every unit in a pair + keeps ``q_u <- d q_u + z_u^2``. + * ``summary()`` reports, per timescale over the cross pairs, the CTM-scaled synchrony S = alpha/sqrt(beta) + (it grows like sqrt(window) for a steady product) and the decayed correlation + C = alpha/sqrt(q_i q_j), which lies in [-1, 1] by Cauchy-Schwarz. It also reports a global synchrony index + (mean |C| over cross pairs at the slowest timescale), the 8 most synchronised cross pairs (by |C| at the + slowest timescale), the normalised entropy of |C| across cross pairs, and the number of observed steps. + + The observer never writes to its input. All buffers have fixed size.""" + + module_id = MODULE_ID + + def __init__(self, n_units: int, *, seed: int = 7, history: int = 256, pairs: int = 64, + self_pairs: int | None = None, zclip: float = 5.0) -> None: + self.n_units = _check_int('n_units', n_units, 1, 1_000_000) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + self.history = _check_int('history', history, 4, 65_536) + self.pairs = _check_int('pairs', pairs, 1, 4096) + self.self_pairs = self.pairs // 8 if self_pairs is None else _check_int('self_pairs', self_pairs, 0, self.pairs) + self.zclip = _check_float('zclip', zclip, 1.0, 100.0) + self.timescales = observer_timescales(self.history) + self._decay = np.exp(-1.0 / np.asarray(self.timescales)) + self._left, self._right = sample_pairs(self.n_units, self.pairs, self.self_pairs, + np.random.default_rng(self.seed + _OBS_OFFSET)) + units, inverse = np.unique(np.concatenate([self._left, self._right]), return_inverse=True) + self._units = units.astype(np.int64) # units that appear in a pair (<= 2 * pairs) + self._pos_left = inverse[:self.pairs].astype(np.int64) + self._pos_right = inverse[self.pairs:].astype(np.int64) + self.reset() + + @classmethod + def from_spec(cls, n_units: int, spec: Any) -> 'SynchronyObserver': + """Build from a ``FrontierSpecV1`` (``seed``, ``history``, ``sync_pairs``).""" + return cls(n_units, seed=int(spec.seed), history=int(spec.history), pairs=int(spec.sync_pairs)) + + def reset(self) -> None: + K = len(self.timescales) + self._mean = np.zeros(self.n_units) + self._var = np.zeros(self.n_units) + self._num = np.zeros((K, self.pairs)) + self._sq = np.zeros((K, self._units.size)) + self._den = np.zeros(K) + self._steps = 0 + + @property + def observed_steps(self) -> int: + return self._steps + + @property + def pair_indices(self) -> tuple[np.ndarray, np.ndarray]: + return self._left.copy(), self._right.copy() + + def observe(self, x: np.ndarray) -> None: + v = np.array(x, dtype=np.float64) # private copy: the caller's array is never touched + if v.shape != (self.n_units,) or not np.all(np.isfinite(v)): + raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}') + a = 1.0 / min(self._steps + 1, self.history) + delta = v - self._mean + mean = self._mean + a * delta + var = (1.0 - a) * (self._var + a * delta * delta) + z = np.clip((v - mean) / np.sqrt(var + 1e-12), -self.zclip, self.zclip) + zu = z[self._units] + d = self._decay[:, None] + self._mean, self._var = mean, var + self._num = d * self._num + (z[self._left] * z[self._right])[None, :] + self._sq = d * self._sq + (zu * zu)[None, :] + self._den = self._decay * self._den + 1.0 + self._steps += 1 + + def synchrony(self) -> tuple[np.ndarray, np.ndarray]: + """``(S, C)``, each of shape (timescales, pairs): CTM-scaled synchrony and decayed correlation in [-1, 1].""" + if self._steps == 0: + z = np.zeros_like(self._num) + return z, z.copy() + S = self._num / np.sqrt(self._den)[:, None] + norm = np.sqrt(self._sq[:, self._pos_left] * self._sq[:, self._pos_right]) + C = np.divide(self._num, norm, out=np.zeros_like(self._num), where=norm > 1e-12) + return S, np.clip(C, -1.0, 1.0) + + def summary(self) -> dict[str, Any]: + S, C = self.synchrony() + cross = np.flatnonzero(self._left != self._right) + sel = cross if cross.size else np.arange(self.pairs) + per_ts = [{'tau': float(tau), 'mean_abs_S': float(np.abs(S[k, sel]).mean()), + 'max_abs_S': float(np.abs(S[k, sel]).max()), 'mean_abs_corr': float(np.abs(C[k, sel]).mean()), + 'max_abs_corr': float(np.abs(C[k, sel]).max())} for k, tau in enumerate(self.timescales)] + gsi, entropy, top = 0.0, None, [] + if cross.size and self._steps: + mag = np.abs(C[-1, cross]) + gsi = float(mag.mean()) + total = float(mag.sum()) + if total > 0.0 and cross.size >= 2: + q = mag[mag > 0.0] / total + entropy = float(np.clip(-(q * np.log(q)).sum() / math.log(cross.size), 0.0, 1.0)) + for p in cross[np.argsort(-mag, kind='stable')[:_TOP_PAIRS]]: + top.append({'i': int(self._left[p]), 'j': int(self._right[p]), 'corr': float(C[-1, p]), + 'corr_by_tau': [float(c) for c in C[:, p]], 'S_by_tau': [float(s) for s in S[:, p]]}) + return {'module': MODULE_ID, 'n_units': self.n_units, 'pairs': self.pairs, 'self_pairs': self.self_pairs, + 'cross_pairs': int(cross.size), 'timescales': [float(t) for t in self.timescales], + 'zscore_window': self.history, 'observed_steps': self._steps, 'per_timescale': per_ts, + 'global_synchrony_index': gsi, 'synchrony_entropy': entropy, 'top_pairs': top} + + def _config(self) -> dict[str, Any]: + return {'n_units': self.n_units, 'seed': self.seed, 'history': self.history, 'pairs': self.pairs, + 'self_pairs': self.self_pairs, 'zclip': self.zclip} + + def export_state(self) -> dict[str, Any]: + return {'module': MODULE_ID, 'schema': OBSERVER_STATE_SCHEMA, **self._config(), + 'left': self._left.tolist(), 'right': self._right.tolist(), 'mean': self._mean.tolist(), + 'var': self._var.tolist(), 'num': self._num.tolist(), 'sq': self._sq.tolist(), + 'den': self._den.tolist(), 'steps': self._steps} + + def import_state(self, state: Mapping[str, Any]) -> None: + """Validate the whole state first; nothing changes unless every check passes.""" + if not isinstance(state, Mapping) or state.get('module') != MODULE_ID or state.get('schema') != OBSERVER_STATE_SCHEMA: + raise ValueError('state is not a synchrony observer state') + for key, value in self._config().items(): + if state.get(key) != value: + raise ValueError(f'synchrony observer state does not match this observer ({key})') + K, P, n, U = len(self.timescales), self.pairs, self.n_units, self._units.size + left = _int_array('left', state.get('left'), P, n) + right = _int_array('right', state.get('right'), P, n) + if not (np.array_equal(left, self._left) and np.array_equal(right, self._right)): + raise ValueError('synchrony observer state pairs do not match this observer') + mean = _finite_array('mean', state.get('mean'), (n,)) + var = _finite_array('var', state.get('var'), (n,)) + num = _finite_array('num', state.get('num'), (K, P)) + sq = _finite_array('sq', state.get('sq'), (K, U)) + den = _finite_array('den', state.get('den'), (K,)) + steps = _check_int('steps', state.get('steps'), 0, 2**62) + expect = (1.0 - self._decay ** steps) / (1.0 - self._decay) + if np.any(var < 0.0) or np.any(sq < 0.0) or not np.allclose(den, expect, rtol=1e-6, atol=1e-9): + raise ValueError('synchrony observer state is inconsistent (negative moments or den/steps mismatch)') + bound = np.sqrt(sq[:, self._pos_left] * sq[:, self._pos_right]) + if np.any(sq > self.zclip ** 2 * den[:, None] * (1.0 + 1e-9) + 1e-9) or np.any(np.abs(num) > bound * (1.0 + 1e-9) + 1e-9): + raise ValueError('synchrony observer state is out of bounds') + self._mean, self._var, self._num, self._sq, self._den, self._steps = mean, var, num, sq, den, steps + + +# ====================================================================== PyTorch models (created lazily) +_TORCH_CLASSES: dict[str, type] = {} + + +def _torch() -> Any: + import torch + return torch + + +def _generator(seed: int) -> Any: + """A private seeded ``torch.Generator``. Parameter initialisation never reads or writes the global RNG.""" + return _torch().Generator().manual_seed(int(seed)) + + +def _normalised_entropy(logits: Any) -> Any: + """Normalised entropy per tick, averaged over output positions: (B, T, L, C) -> (B, T) in [0, 1].""" + torch = _torch() + logp = torch.log_softmax(logits, dim=-1) + ent = -(logp.exp() * logp).sum(-1) / math.log(logits.shape[-1]) + return ent.mean(-1) + + +def ctm_tick_loss(logits: Any, targets: Any, certainty: Any = None) -> tuple[Any, dict[str, Any]]: + """CTM loss (Sec. 3.5, eq. 11; reference ``parity_loss``): cross-entropy averaged over positions at every + tick, then the mean of the losses at each sample's minimum-loss tick t1 and its maximum-certainty tick t2 + (certainty = 1 - normalised entropy, averaged over positions). With one tick this is plain cross-entropy. + + ``logits``: (B, T, L, C); ``targets``: (B, L) class indices. Returns ``(loss, info)``. ``info`` holds + ``per_tick_loss`` (B, T) and the selected ``min_loss_tick`` and ``most_certain_tick`` (B,).""" + torch = _torch() + if logits.ndim != 4 or targets.shape != (logits.shape[0], logits.shape[2]): + raise ValueError('logits must be (B, T, L, C) and targets (B, L)') + B, T, L, C = logits.shape + tgt = targets[:, None, :].expand(B, T, L).reshape(-1) + ce = torch.nn.functional.cross_entropy(logits.reshape(B * T * L, C), tgt, reduction='none').view(B, T, L).mean(-1) + if certainty is None: + certainty = 1.0 - _normalised_entropy(logits) + t1 = ce.detach().argmin(1) + t2 = certainty.detach().argmax(1) + rows = torch.arange(B) + loss = 0.5 * (ce[rows, t1].mean() + ce[rows, t2].mean()) + return loss, {'per_tick_loss': ce, 'min_loss_tick': t1, 'most_certain_tick': t2} + + +def _define_torch_classes() -> dict[str, type]: + if _TORCH_CLASSES: + return _TORCH_CLASSES + torch = _torch() + nn = torch.nn + F = torch.nn.functional + + def check_tokens(tokens: Any, seq_len: int, vocab: int) -> None: + if not isinstance(tokens, torch.Tensor) or tokens.dtype != torch.long or tokens.ndim != 2 \ + or tokens.shape[1] != seq_len or tokens.shape[0] < 1: + raise ValueError(f'tokens must be a LongTensor of shape (batch, {seq_len})') + if int(tokens.min()) < 0 or int(tokens.max()) >= vocab: + raise ValueError(f'token values must lie in [0, {vocab})') + + def check_ticks(ticks: Any, default: int) -> int: + return default if ticks is None else _check_int('ticks', ticks, 1, 1024) + + def uniform(shape: tuple[int, ...], bound: float, g: Any) -> Any: + return nn.Parameter(torch.empty(shape).uniform_(-bound, bound, generator=g)) + + # Layers that own their parameters and draw them from a private generator. They use the distributions of + # PyTorch's default initialisation, but never touch the global RNG (``nn.Linear`` and friends initialise + # from it in their constructors). Tests check each one against its ``torch.nn`` counterpart. + class Linear(nn.Module): + """``x W^T + b`` with W and b ~ U(+-1/sqrt(fan_in)), as ``nn.Linear``.""" + + def __init__(self, fan_in: int, fan_out: int, g: Any) -> None: + super().__init__() + self.in_features, self.out_features = fan_in, fan_out + b = 1.0 / math.sqrt(fan_in) + self.weight = uniform((fan_out, fan_in), b, g) + self.bias = uniform((fan_out,), b, g) + + def forward(self, x: Any) -> Any: + return F.linear(x, self.weight, self.bias) + + class LayerNorm(nn.Module): + """Layer normalisation over the last axis with a learnable gain (1) and bias (0), as ``nn.LayerNorm``.""" + + def __init__(self, dim: int) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(dim)) + self.bias = nn.Parameter(torch.zeros(dim)) + + def forward(self, x: Any) -> Any: + return F.layer_norm(x, self.weight.shape, self.weight, self.bias) + + class GRUCell(nn.Module): + """``torch.gru_cell`` (the kernel behind ``nn.GRUCell``), all weights ~ U(+-1/sqrt(hidden)).""" + + def __init__(self, input_size: int, hidden: int, g: Any) -> None: + super().__init__() + b = 1.0 / math.sqrt(hidden) + self.weight_ih = uniform((3 * hidden, input_size), b, g) + self.weight_hh = uniform((3 * hidden, hidden), b, g) + self.bias_ih = uniform((3 * hidden,), b, g) + self.bias_hh = uniform((3 * hidden,), b, g) + + def forward(self, x: Any, h: Any) -> Any: + return torch.gru_cell(x, h, self.weight_ih, self.weight_hh, self.bias_ih, self.bias_hh) + + class SequenceReader(nn.Module): + """Whole-input feature extractor shared by the tick models (CTM App. F.4 parity setup): token + learned + position embeddings -> Linear -> LayerNorm give identical keys and values. :meth:`attend` is single-head + scaled dot-product attention with a query supplied by the core. Token embeddings ~ N(0, 1), as + ``nn.Embedding``.""" + + def __init__(self, seq_len: int, vocab: int, d_input: int, *, seed: int = 0) -> None: + super().__init__() + self.scale = 1.0 / math.sqrt(d_input) + g = _generator(_check_int('seed', seed, 0, 2**31 - 1) + _READER_OFFSET) + self.token = nn.Parameter(torch.empty(vocab, d_input).normal_(generator=g)) + self.position = uniform((seq_len, d_input), 0.5, g) + self.proj = Linear(d_input, d_input, g) + self.norm = LayerNorm(d_input) + + def keys(self, tokens: Any) -> Any: + return self.norm(self.proj(F.embedding(tokens, self.token) + self.position)) + + def attend(self, query: Any, kv: Any, *, weights: bool = False) -> tuple[Any, Any]: + """``softmax(kv q / sqrt(d)) kv`` for a query (B, d) over identical keys and values (B, L, d), as one + fused ``scaled_dot_product_attention`` call. Returns ``(o, w)``; the attention weights ``w`` (B, L) are + computed (separately, same formula) only when ``weights`` is true, else ``None``.""" + o = F.scaled_dot_product_attention(query.unsqueeze(1), kv, kv).squeeze(1) + if not weights: + return o, None + return o, torch.softmax(torch.bmm(kv, query.unsqueeze(-1)).squeeze(-1) * self.scale, dim=-1) + + class NeuronLevelModels(nn.Module): + """Private per-neuron MLPs (CTM NLMs, Sec. 3.3 and Listing 2; reference ``SuperLinear`` stack). + + Neuron d maps its own last M pre-activations through M -> 2H -> GLU -> H -> 2 -> GLU -> 1 with weights + ``w1[d]`` (M, 2H) and ``w2[d]`` (H, 2) that belong to it alone. Input and output are neuron-major, + (D, B, M) -> (D, B). Each layer is one batched einsum over the neuron axis ('dbm,dmh->dbh'): the + reference's einsum('BDM,MHD->BDH') with the neuron axis first, which maps onto one batched matmul.""" + + def __init__(self, d_model: int, memory: int, hidden: int, *, seed: int = 0) -> None: + super().__init__() + self.d_model = _check_int('d_model', d_model, 1, 65_536) + self.memory = _check_int('memory', memory, 1, 1024) + self.hidden = _check_int('hidden', hidden, 1, 1024) + b1, b2 = 1.0 / math.sqrt(memory + 2 * hidden), 1.0 / math.sqrt(hidden + 2) + g = _generator(_check_int('seed', seed, 0, 2**31 - 1) + _NLM_OFFSET) + self.w1 = uniform((d_model, memory, 2 * hidden), b1, g) + self.w2 = uniform((d_model, hidden, 2), b2, g) + self.b1 = nn.Parameter(torch.zeros(d_model, 1, 2 * hidden)) + self.b2 = nn.Parameter(torch.zeros(d_model, 1, 2)) + + def forward(self, history: Any) -> Any: + h = F.glu(torch.einsum('dbm,dmh->dbh', history, self.w1) + self.b1, dim=-1) + return F.glu(torch.einsum('dbh,dhk->dbk', h, self.w2) + self.b2, dim=-1).squeeze(-1) + + class MiniCTM(nn.Module): + """A small Continuous Thought Machine for sequence-in, per-position-classes-out tasks. + + Each internal tick follows the reference code's order: action synchrony -> query -> attention over the + whole input -> synapse model on [z, o] (Linear -> GLU -> LayerNorm, the CTM's depth-1 synapse used for + parity) -> append the pre-activation to the M-step FIFO history -> private NLMs -> output synchrony -> + linear readout. Synchrony uses random pairing with ``self_pairs`` self pairs per representation and a + per-pair decay ``exp(-r)`` with ``r = softplus(rho)`` learnable (the reference clamps ``r`` to [0, 15] + and starts it at 0; here ``r`` starts log-uniform in ``decay_init``). Action and output pairs share one + recursion state because both read the same post-activations: the action representation at tick t equals + the output representation of tick t - 1 on the action pairs, and both start from the learnable start + state ``start_z`` exactly as in the reference. The start state and the start history are learnable. + + ``forward(tokens, ticks=None, track=False)`` returns ``(logits (B, T, L, C), certainty (B, T))`` plus, + with ``track``, a dict of detached post-activations (B, T, D), output and action synchrony + (B, T, n_sync_out) and (B, T, n_sync_action), and attention weights (B, T, L).""" + + def __init__(self, seq_len: int, *, vocab: int = 2, classes: int = 2, d_model: int = 32, memory: int = 4, + nlm_hidden: int = 4, ticks: int = 8, d_input: int = 16, n_sync_out: int = 32, + n_sync_action: int = 16, self_pairs: int = 4, decay_init: Sequence[float] = (0.03, 1.0), + seed: int = 0) -> None: + super().__init__() + self.seq_len = _check_int('seq_len', seq_len, 1, 4096) + self.vocab = _check_int('vocab', vocab, 1, 1_000_000) + self.classes = _check_int('classes', classes, 2, 1024) + self.d_model = _check_int('d_model', d_model, 2, 4096) + self.memory = _check_int('memory', memory, 1, 256) + self.nlm_hidden = _check_int('nlm_hidden', nlm_hidden, 1, 256) + self.ticks = _check_int('ticks', ticks, 1, 1024) + self.d_input = _check_int('d_input', d_input, 2, 4096) + self.n_sync_out = _check_int('n_sync_out', n_sync_out, 2, 65_536) + self.n_sync_action = _check_int('n_sync_action', n_sync_action, 2, 65_536) + self.self_pairs = _check_int('self_pairs', self_pairs, 0, min(self.n_sync_out, self.n_sync_action) - 1) + try: + r_lo_raw, r_hi_raw = decay_init + except (TypeError, ValueError) as exc: + raise ValueError('decay_init must be a (low, high) pair of rates') from exc + r_lo = _check_float('decay_init[0]', r_lo_raw, 1e-4, 10.0) + r_hi = _check_float('decay_init[1]', r_hi_raw, r_lo, 10.0) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + D, L, d, Pa, Po = self.d_model, self.seq_len, self.d_input, self.n_sync_action, self.n_sync_out + rng = np.random.default_rng(self.seed + _CTM_OFFSET) + la, ra = sample_pairs(D, Pa, self.self_pairs, rng) + lo, ro = sample_pairs(D, Po, self.self_pairs, rng) + rates = 1.0 / log_uniform_timescales(Pa + Po, 1.0 / r_hi, 1.0 / r_lo, rng) + # pair layout: the first n_sync_action pairs feed the attention query, the rest feed the output + self.register_buffer('pair_left', torch.as_tensor(np.concatenate([la, lo]), dtype=torch.long)) + self.register_buffer('pair_right', torch.as_tensor(np.concatenate([ra, ro]), dtype=torch.long)) + self.rho = nn.Parameter(torch.as_tensor(np.log(np.expm1(rates)), dtype=torch.float32)) + self.reader = SequenceReader(L, self.vocab, d, seed=self.seed) + self.nlm = NeuronLevelModels(D, self.memory, self.nlm_hidden, seed=self.seed) + g = _generator(self.seed + _CTM_OFFSET) + self.synapse = nn.Sequential(Linear(D + d, 2 * D, g), nn.GLU(), LayerNorm(D)) + self.start_z = uniform((D,), math.sqrt(1.0 / D), g) + self.start_trace = uniform((D, self.memory), math.sqrt(1.0 / (D + self.memory)), g) + self.query = Linear(Pa, d, g) + self.output = Linear(Po, L * self.classes, g) + + def decay_rates(self) -> tuple[Any, Any]: + """Current ``r = softplus(rho)`` for the action pairs and the output pairs.""" + r = F.softplus(self.rho) + return r[:self.n_sync_action], r[self.n_sync_action:] + + def forward(self, tokens: Any, ticks: int | None = None, *, track: bool = False) -> Any: + check_tokens(tokens, self.seq_len, self.vocab) + T = check_ticks(ticks, self.ticks) + B, D, Pa = tokens.shape[0], self.d_model, self.n_sync_action + kv = self.reader.keys(tokens) # identical keys and values + rates = F.softplus(self.rho) + decay = torch.exp(-rates) + # beta_t = sum_{k <= t} exp(-r k) is data independent: one (T + 1, P) table of 1/sqrt(beta) + k = torch.arange(T + 1, dtype=rates.dtype) + inv_norm = torch.rsqrt(torch.cumsum(torch.exp(-k[:, None] * rates[None, :]), dim=0)) + inv_act = inv_norm[:T, :Pa] + z = self.start_z.expand(B, D) + trace = self.start_trace.unsqueeze(1).expand(D, B, self.memory) # neuron-major FIFO (D, B, M) + alpha = z.index_select(1, self.pair_left) * z.index_select(1, self.pair_right) + alphas, record = [], [] + for t in range(T): + s_act = alpha[:, :Pa] * inv_act[t] + o, w = self.reader.attend(self.query(s_act), kv, weights=track) + a = self.synapse(torch.cat([z, o], dim=-1)) # pre-activations (B, D) + trace = torch.cat([trace[:, :, 1:], a.t().unsqueeze(-1)], dim=-1) + z = self.nlm(trace).t() # post-activations (B, D) + prod = z.index_select(1, self.pair_left) * z.index_select(1, self.pair_right) + alpha = torch.addcmul(prod, decay, alpha) # alpha <- exp(-r) alpha + z_i z_j + alphas.append(alpha) + if track: + record.append((z.detach(), s_act.detach(), w.detach())) + s_out = torch.stack(alphas, dim=1)[:, :, Pa:] * inv_norm[1:, Pa:] # (B, T, n_sync_out) + logits = self.output(s_out).view(B, T, self.seq_len, self.classes) + cert = 1.0 - _normalised_entropy(logits) + if track: + zs, acts, ws = zip(*record) + return logits, cert, {'post_activations': torch.stack(zs, 1), 'sync_out': s_out.detach(), + 'sync_action': torch.stack(acts, 1), 'attention': torch.stack(ws, 1)} + return logits, cert + + class AttentiveGRU(nn.Module): + """Baseline: a GRU cell unrolled for the same internal ticks. It reads the whole input through the + same attention reader as :class:`MiniCTM`, with the query taken from the hidden state. This mirrors the + CTM paper's parameter-matched recurrent baselines (single-layer LSTMs run for the same number of ticks, + App. F.4), with a GRU in place of the LSTM.""" + + def __init__(self, seq_len: int, *, hidden: int, vocab: int = 2, classes: int = 2, ticks: int = 8, + d_input: int = 16, seed: int = 0) -> None: + super().__init__() + self.seq_len = _check_int('seq_len', seq_len, 1, 4096) + self.vocab = _check_int('vocab', vocab, 1, 1_000_000) + self.classes = _check_int('classes', classes, 2, 1024) + self.hidden = _check_int('hidden', hidden, 1, 8192) + self.ticks = _check_int('ticks', ticks, 1, 1024) + self.d_input = _check_int('d_input', d_input, 2, 4096) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + self.reader = SequenceReader(self.seq_len, self.vocab, self.d_input, seed=self.seed) + g = _generator(self.seed + _GRU_OFFSET) + self.cell = GRUCell(self.d_input, self.hidden, g) + self.query = Linear(self.hidden, self.d_input, g) + self.start_h = uniform((self.hidden,), math.sqrt(1.0 / self.hidden), g) + self.output = Linear(self.hidden, self.seq_len * self.classes, g) + + def forward(self, tokens: Any, ticks: int | None = None) -> Any: + check_tokens(tokens, self.seq_len, self.vocab) + T = check_ticks(ticks, self.ticks) + B = tokens.shape[0] + kv = self.reader.keys(tokens) + h = self.start_h.unsqueeze(0).expand(B, -1).contiguous() + hs = [] + for _ in range(T): + o, _w = self.reader.attend(self.query(h), kv) + h = self.cell(o, h) + hs.append(h) + out = self.output(torch.stack(hs, dim=1)).view(B, T, self.seq_len, self.classes) + return out, 1.0 - _normalised_entropy(out) + + class ParityMLP(nn.Module): + """Baseline: a one-hidden-layer ReLU MLP that reads the whole sequence (as +/-1 values) at once, with no + ticks. Its logits have a single tick, so the CTM loss reduces to cross-entropy.""" + + def __init__(self, seq_len: int, *, hidden: int, vocab: int = 2, classes: int = 2, seed: int = 0) -> None: + super().__init__() + self.seq_len = _check_int('seq_len', seq_len, 1, 4096) + self.vocab = _check_int('vocab', vocab, 2, 2) + self.classes = _check_int('classes', classes, 2, 1024) + self.hidden = _check_int('hidden', hidden, 1, 1_000_000) + self.seed = _check_int('seed', seed, 0, 2**31 - 1) + g = _generator(self.seed + _MLP_OFFSET) + self.net = nn.Sequential(Linear(self.seq_len, self.hidden, g), nn.ReLU(), + Linear(self.hidden, self.seq_len * self.classes, g)) + + def forward(self, tokens: Any, ticks: int | None = None) -> Any: + check_tokens(tokens, self.seq_len, self.vocab) + B = tokens.shape[0] + out = self.net(tokens.to(torch.float32) * 2.0 - 1.0).view(B, 1, self.seq_len, self.classes) + return out, 1.0 - _normalised_entropy(out) + + for cls in (SequenceReader, NeuronLevelModels, MiniCTM, AttentiveGRU, ParityMLP): + cls.__module__ = __name__ + cls.__qualname__ = cls.__name__ + for cls in (Linear, LayerNorm, GRUCell): # private building blocks (not module attributes) + cls.__module__ = __name__ + cls.__qualname__ = f'_{cls.__name__}' + _TORCH_CLASSES.update({'SequenceReader': SequenceReader, 'NeuronLevelModels': NeuronLevelModels, + 'MiniCTM': MiniCTM, 'AttentiveGRU': AttentiveGRU, 'ParityMLP': ParityMLP, + '_Linear': Linear, '_LayerNorm': LayerNorm, '_GRUCell': GRUCell}) + return _TORCH_CLASSES + + +def __getattr__(name: str) -> Any: + if name in _TORCH_NAMES: + cls = _define_torch_classes()[name] + globals()[name] = cls + return cls + raise AttributeError(f'module {__name__!r} has no attribute {name!r}') + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(_TORCH_NAMES)) + + +# ====================================================================== cumulative-parity benchmark +def cumulative_parity_data(seq_len: int, seed: int, heldout: int) -> dict[str, np.ndarray]: + """All 2^L bit sequences, split by a seeded permutation into ``heldout`` held-out and the rest for training. + + Inputs are token ids (bit 0/1; the MLP sees them as -1/+1). The target at position l is the parity of bits + 0..l (the CTM paper's *cumulative parity*, Sec. 6 and App. F.3).""" + seq_len = _check_int('seq_len', seq_len, 2, 16) + seed = _check_int('seed', seed, 0, 2**31 - 1) + total = 2 ** seq_len + heldout = _check_int('heldout', heldout, 1, total - 1) + ids = np.random.default_rng(seed + _DATA_OFFSET).permutation(total) + bits = ((ids[:, None] >> np.arange(seq_len)[None, :]) & 1).astype(np.int64) + parity = np.cumsum(bits, axis=1) % 2 + return {'heldout_x': bits[:heldout], 'heldout_y': parity[:heldout], + 'train_x': bits[heldout:], 'train_y': parity[heldout:]} + + +# Sized for one CPU thread: the default takes about 3 minutes for three seeds and quick mode about 10-15 s +# (measured 2026-11-17, Snapdragon X Plus, Windows 11 on ARM64, torch 2.11 CPU, under load from other jobs). +_CTM_FULL: dict[str, Any] = {'seq_len': 12, 'ticks': 8, 'd_model': 32, 'memory': 4, 'nlm_hidden': 4, 'd_input': 16, + 'n_sync_out': 32, 'n_sync_action': 16, 'self_pairs': 4, 'steps': 800, 'batch': 64, + 'lr': 1e-2, 'weight_decay': 0.01, 'grad_clip': 1.0, 'heldout': 512, 'train_eval': 512} +_CTM_QUICK: dict[str, Any] = {**_CTM_FULL, 'seq_len': 8, 'ticks': 4, 'd_model': 24, 'd_input': 12, 'n_sync_out': 24, + 'n_sync_action': 12, 'self_pairs': 3, 'steps': 100, 'batch': 32, 'heldout': 64, + 'train_eval': 192} + + +def _ctm_config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]: + cfg = dict(_CTM_QUICK if quick else _CTM_FULL) + unknown = sorted(set(overrides) - set(cfg)) + if unknown: + raise ValueError(f'unknown run_ctm_benchmark overrides: {unknown}') + cfg.update(overrides) + for key, lo, hi in (('seq_len', 2, 16), ('ticks', 1, 64), ('d_model', 2, 512), ('memory', 1, 64), + ('nlm_hidden', 1, 64), ('d_input', 2, 256), ('n_sync_out', 2, 4096), ('n_sync_action', 2, 4096), + ('steps', 1, 100_000), ('batch', 1, 4096), ('train_eval', 1, 65_536)): + cfg[key] = _check_int(key, cfg[key], lo, hi) + cfg['self_pairs'] = _check_int('self_pairs', cfg['self_pairs'], 0, min(cfg['n_sync_out'], cfg['n_sync_action']) - 1) + cfg['heldout'] = _check_int('heldout', cfg['heldout'], 1, 2 ** cfg['seq_len'] - 1) + cfg['lr'] = _check_float('lr', cfg['lr'], 1e-6, 1.0) + cfg['weight_decay'] = _check_float('weight_decay', cfg['weight_decay'], 0.0, 1.0) + cfg['grad_clip'] = _check_float('grad_clip', cfg['grad_clip'], 1e-3, 100.0) + return cfg + + +def _reader_params(seq_len: int, d_input: int, vocab: int = 2) -> int: + return vocab * d_input + seq_len * d_input + d_input * d_input + d_input + 2 * d_input + + +def _ctm_params(cfg: Mapping[str, Any], classes: int = 2) -> int: + """Analytic trainable-parameter count of :class:`MiniCTM` for a benchmark config.""" + L, D, M, H, d = cfg['seq_len'], cfg['d_model'], cfg['memory'], cfg['nlm_hidden'], cfg['d_input'] + pa, po = cfg['n_sync_action'], cfg['n_sync_out'] + synapse = (D + d) * 2 * D + 2 * D + 2 * D + nlm = D * M * 2 * H + D * 2 * H + D * H * 2 + D * 2 + return (_reader_params(L, d) + synapse + nlm + D + D * M + (pa + po) + pa * d + d + + po * L * classes + L * classes) + + +def _gru_params(seq_len: int, d_input: int, hidden: int, classes: int = 2) -> int: + return (_reader_params(seq_len, d_input) + 3 * hidden * (d_input + hidden + 2) + hidden * d_input + d_input + + hidden + hidden * seq_len * classes + seq_len * classes) + + +def _mlp_params(seq_len: int, hidden: int, classes: int = 2) -> int: + return seq_len * hidden + hidden + hidden * seq_len * classes + seq_len * classes + + +def _closest_width(count: Callable[[int], int], target: int, high: int) -> int: + best, gap = 1, abs(count(1) - target) + for w in range(2, high + 1): + g = abs(count(w) - target) + if g < gap: + best, gap = w, g + elif count(w) > target: + break + return best + + +def _trainable(model: Any) -> int: + return int(sum(p.numel() for p in model.parameters() if p.requires_grad)) + + +def _ctm_forward_macs(cfg: Mapping[str, Any]) -> int: + L, T, D, M, H, d = cfg['seq_len'], cfg['ticks'], cfg['d_model'], cfg['memory'], cfg['nlm_hidden'], cfg['d_input'] + po, pa = cfg['n_sync_out'], cfg['n_sync_action'] + per_tick = (pa + po) * 2 + pa * d + 2 * L * d + (D + d) * 2 * D + D * (M * 2 * H + H * 2) + po * L * 2 + return int(L * d * d + T * per_tick) + + +def _gru_forward_macs(cfg: Mapping[str, Any], hidden: int) -> int: + L, T, d = cfg['seq_len'], cfg['ticks'], cfg['d_input'] + return int(L * d * d + T * (hidden * d + 2 * L * d + 3 * hidden * (d + hidden) + hidden * L * 2)) + + +def _mlp_forward_macs(cfg: Mapping[str, Any], hidden: int) -> int: + L = cfg['seq_len'] + return int(L * hidden + hidden * L * 2) + + +def _evaluate(torch: Any, model: Any, x: Any, y: Any) -> dict[str, Any]: + model.eval() + with torch.no_grad(): + logits, cert = model(x) + N = logits.shape[0] + t_star = cert.argmax(1) + pred = logits[torch.arange(N), t_star].argmax(-1) + correct = (pred == y).to(torch.float64) + last = (logits[:, -1].argmax(-1) == y).to(torch.float64) + return {'accuracy': float(correct.mean()), 'per_position_accuracy': [float(v) for v in correct.mean(0)], + 'sequence_accuracy': float(correct.min(1).values.mean()), 'last_tick_accuracy': float(last.mean()), + 'mean_most_certain_tick': float(t_star.to(torch.float64).mean()) + 1.0} + + +def _make_optimizer(torch: Any, params: list[Any], cfg: Mapping[str, Any]) -> tuple[Any, str]: + """AdamW, fused CPU kernel when this torch build has it (same update rule, fewer kernel launches).""" + try: + return torch.optim.AdamW(params, lr=cfg['lr'], weight_decay=cfg['weight_decay'], fused=True), 'fused' + except (RuntimeError, TypeError, ValueError): + return torch.optim.AdamW(params, lr=cfg['lr'], weight_decay=cfg['weight_decay']), 'default' + + +def _train_model(torch: Any, model: Any, data: Mapping[str, Any], batches: np.ndarray, cfg: Mapping[str, Any]) -> dict[str, Any]: + params = [p for p in model.parameters() if p.requires_grad] + opt, impl = _make_optimizer(torch, params, cfg) + xtr, ytr = data['train_x'], data['train_y'] + curve: list[float] = [] + every = max(1, len(batches) // 10) + t0 = time.perf_counter() + model.train() + for step, idx in enumerate(batches): + ib = torch.as_tensor(idx) + logits, cert = model(xtr[ib]) + loss, _ = ctm_tick_loss(logits, ytr[ib], cert) + opt.zero_grad(set_to_none=True) + loss.backward() + torch.nn.utils.clip_grad_norm_(params, cfg['grad_clip']) + opt.step() + if step % every == 0 or step == len(batches) - 1: + curve.append(float(loss.detach())) + train_wall = time.perf_counter() - t0 + k = min(int(cfg['train_eval']), int(xtr.shape[0])) + return {'heldout': _evaluate(torch, model, data['heldout_x'], data['heldout_y']), + 'train': _evaluate(torch, model, xtr[:k], ytr[:k]), 'loss_curve': curve, + 'final_train_loss': curve[-1], 'optimizer_impl': impl, 'measured_wallclock_s': train_wall} + + +def run_ctm_benchmark(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """MiniCTM vs parameter-matched GRU and MLP baselines on cumulative parity of L-bit sequences presented whole. + + Per seed, all three models share the train/held-out split, the minibatch sequence, the optimiser (AdamW), + learning rate, step count, gradient clip and loss (the CTM tick loss; for the one-tick MLP it is plain + cross-entropy). The GRU (attention reader + ticks) and the MLP are sized to the MiniCTM's trainable-parameter + count (within 10 %, else ``ValueError``). Tick models are read out at each sample's most certain tick. The + verdict is ``harness.compare`` on per-seed held-out per-position accuracy, MiniCTM vs the best baseline + (the higher mean over seeds, chosen after the fact, which favours the baseline). PyTorch runs on one thread + and the caller's thread count is restored. The global RNG is never used: models draw their initialisation + from private seeded ``torch.Generator`` objects, and data and minibatches come from NumPy generators.""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds(seeds) + cfg = _ctm_config(quick, overrides) + torch = _torch() + classes = _define_torch_classes() + L, d = cfg['seq_len'], cfg['d_input'] + ctm_kw = {k: cfg[k] for k in ('ticks', 'd_model', 'memory', 'nlm_hidden', 'd_input', 'n_sync_out', + 'n_sync_action', 'self_pairs')} + p_ctm = _ctm_params(cfg) + h_gru = _closest_width(lambda h: _gru_params(L, d, h), p_ctm, 4096) + h_mlp = _closest_width(lambda h: _mlp_params(L, h), p_ctm, 1_000_000) + budget = {'mini_ctm': p_ctm, 'gru': _gru_params(L, d, h_gru), 'mlp': _mlp_params(L, h_mlp)} + gaps = {k: abs(v - p_ctm) / p_ctm for k, v in budget.items()} + if max(gaps.values()) > 0.10: + raise ValueError(f'cannot match parameter counts within 10 %: {budget}') + makers: dict[str, Callable[[int], Any]] = { + 'mini_ctm': lambda s: classes['MiniCTM'](L, seed=s, **ctm_kw), + 'gru': lambda s: classes['AttentiveGRU'](L, hidden=h_gru, ticks=cfg['ticks'], d_input=d, seed=s), + 'mlp': lambda s: classes['ParityMLP'](L, hidden=h_mlp, seed=s), + } + results: dict[str, list[dict[str, Any]]] = {name: [] for name in makers} + prev_threads = torch.get_num_threads() + t_start = time.perf_counter() + try: + torch.set_num_threads(1) + for s in seeds: + raw = cumulative_parity_data(L, s, cfg['heldout']) + data = {k: torch.as_tensor(v, dtype=torch.long) for k, v in raw.items()} + n_train = raw['train_x'].shape[0] + batches = np.random.default_rng(s + _BATCH_OFFSET).integers(0, n_train, (cfg['steps'], cfg['batch'])) + for name, make in makers.items(): + model = make(s) + count = _trainable(model) + if count != budget[name]: + raise RuntimeError(f'{name} parameter count {count} != analytic {budget[name]}') + results[name].append({'seed': s, **_train_model(torch, model, data, batches, cfg)}) + finally: + torch.set_num_threads(prev_threads) + total_wall = time.perf_counter() - t_start + + def acc(name: str) -> list[float]: + return [r['heldout']['accuracy'] for r in results[name]] + + def mean(xs: Sequence[float]) -> float: + return float(np.mean(xs)) + + means = {name: mean(acc(name)) for name in results} + best = max(('gru', 'mlp'), key=lambda name: (means[name], name == 'gru')) + comparisons = {'mini_ctm_vs_gru': harness.compare(acc('mini_ctm'), acc('gru')), + 'mini_ctm_vs_mlp': harness.compare(acc('mini_ctm'), acc('mlp'))} + comparisons['mini_ctm_vs_best_baseline'] = {**comparisons[f'mini_ctm_vs_{best}'], 'best_baseline': best} + verdict = comparisons['mini_ctm_vs_best_baseline']['verdict'] + models: dict[str, Any] = {} + for name, runs in results.items(): + L_pos = len(runs[0]['heldout']['per_position_accuracy']) + models[name] = { + 'trainable_parameters': budget[name], 'per_seed': runs, + 'summary': {'heldout_accuracy': means[name], + 'heldout_sequence_accuracy': mean([r['heldout']['sequence_accuracy'] for r in runs]), + 'heldout_last_tick_accuracy': mean([r['heldout']['last_tick_accuracy'] for r in runs]), + 'heldout_per_position_accuracy': [mean([r['heldout']['per_position_accuracy'][i] for r in runs]) + for i in range(L_pos)], + 'train_accuracy': mean([r['train']['accuracy'] for r in runs]), + 'mean_most_certain_tick': mean([r['heldout']['mean_most_certain_tick'] for r in runs])}} + models['gru']['hidden'] = h_gru + models['mlp']['hidden'] = h_mlp + fwd = {'mini_ctm': _ctm_forward_macs(cfg), 'gru': _gru_forward_macs(cfg, h_gru), 'mlp': _mlp_forward_macs(cfg, h_mlp)} + receipt = harness.base_receipt('synchrony_ctm', 'standalone_model_comparison', { + **cfg, 'quick': quick, 'seeds': list(seeds), 'task': 'cumulative_parity', 'presentation': 'whole_sequence', + 'optimizer': 'AdamW', 'readout': 'most_certain_tick', 'loss': 'ctm_min_loss_plus_max_certainty', + 'torch_threads': 1, 'torch_version': str(torch.__version__), 'train_pool_size': 2 ** L - cfg['heldout']}) + receipt.update({ + 'models': models, + 'parameter_budget': {**budget, 'max_relative_gap': max(gaps.values()), 'matched_within_10pct': True}, + 'comparisons': comparisons, 'verdict': verdict, + 'verdict_basis': f'mini_ctm_vs_best_baseline({best})_heldout_per_position_accuracy', + 'estimated_cost': {'forward_macs_per_sequence': fwd, + 'training_macs': {k: int(3 * v * cfg['batch'] * cfg['steps']) for k, v in fwd.items()}}, + 'measured_wallclock_s': {'total': total_wall}, + 'notes': ('Toy-scale study inspired by the CTM parity experiment (Darlow et al., NeurIPS 2025, Sec. 6 and ' + 'App. F), which used 64-bit sequences, d_model 1024, up to 100 ticks and 200k AdamW steps. Here ' + f'L = {L}, d_model = {cfg["d_model"]}, {cfg["ticks"]} ticks and {cfg["steps"]} AdamW steps of ' + f'batch {cfg["batch"]} at a constant learning rate on one CPU thread, so this measures early ' + 'learning of short parities, not the paper\'s result. The GRU baseline uses the same ' + 'attention reader and the same tick loss (the paper trained its LSTM baselines on the final ' + 'tick); the MLP sees the whole +/-1 sequence at once. Held-out sequences are disjoint from ' + 'training sequences; for parity, memorising neighbours predicts the wrong held-out parity, so ' + 'held-out accuracy can fall below 0.5. The best baseline is chosen after the fact on held-out ' + 'accuracy, which favours the baseline. Accuracy is per position (mean over positions and ' + 'held-out sequences).'), + }) + return harness.seal(receipt) + + +# ====================================================================== NEUROWEAVE extension experiment +_EXT_DEFAULTS: dict[str, Any] = {'pairs': 32, 'self_pairs': None, 'timescales': (1.0, 32.0), 'feature_scale': 'unit'} +_RUN_DEFAULTS: dict[str, Any] = {'task': 'rhythm', 'heldout_seeds': (100, 101), 'steps': 300, 'heldout_steps': None, + 'neurons': 48, 'topology': 'clustered', 'mechanisms': ()} + + +def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]: + """Baseline vs ``SynchronyExtension`` readout features vs the random-trace capacity control on a NEUROWEAVE + temporal task (default ``rhythm``), through ``harness.run_extension_experiment``. + + Extension overrides: ``pairs``, ``self_pairs``, ``timescales``, ``feature_scale``. Harness overrides: + ``task``, ``heldout_seeds``, ``steps``, ``heldout_steps``, ``neurons``, ``topology``, ``mechanisms``. + Quick mode uses the harness ``QUICK_ARGS`` sizes (except the seeds, which are the caller's) and 16 pairs.""" + from . import harness + if type(quick) is not bool: + raise ValueError('quick must be a boolean') + seeds = _check_seeds(seeds) + ext_cfg, run_cfg = dict(_EXT_DEFAULTS), dict(_RUN_DEFAULTS) + if quick: + ext_cfg['pairs'] = 16 + run_cfg.update({k: v for k, v in harness.QUICK_ARGS.items() if k != 'seeds'}) + unknown = sorted(set(overrides) - set(ext_cfg) - set(run_cfg)) + if unknown: + raise ValueError(f'unknown run_experiment overrides: {unknown}') + for key, value in overrides.items(): + (ext_cfg if key in ext_cfg else run_cfg)[key] = value + probe = SynchronyExtension(ext_cfg['pairs'], seed=0, self_pairs=ext_cfg['self_pairs'], + timescales=ext_cfg['timescales'], feature_scale=ext_cfg['feature_scale']) + ext_cfg['self_pairs'] = probe.self_pairs + ext_cfg['timescales'] = list(probe.timescales) + + def factory(seed: int) -> SynchronyExtension: + return SynchronyExtension(ext_cfg['pairs'], seed=seed, self_pairs=ext_cfg['self_pairs'], + timescales=ext_cfg['timescales'], feature_scale=ext_cfg['feature_scale']) + + t0 = time.perf_counter() + receipt = harness.run_extension_experiment( + MODULE_ID, factory, seeds=seeds, control='random_trace', metric='accuracy', notes=( + 'Readout-only extension: decayed pairwise synchronisation of brain unit outputs (CTM-style, fixed ' + 'log-uniform per-pair decays, self pairs included) is appended to the shared logistic readout. It never ' + 'changes the brain drive. The control gets the same number of random leaky-trace features. ' + "feature_scale='unit' multiplies S by the constant sqrt(1 - decay) per pair, which keeps features in " + '[-1, 1] like the control. Small synthetic task; the verdict is a paired 95 % t interval over seeds.'), + **run_cfg) + receipt = dict(receipt) + receipt['config'] = {**receipt['config'], 'quick': quick, 'extension': ext_cfg} + receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0} + return harness.seal(receipt) + + +EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment, + f'{MODULE_ID}_ctm': run_ctm_benchmark} diff --git a/synapse/frontier/workbench_api.py b/synapse/frontier/workbench_api.py new file mode 100644 index 0000000000000000000000000000000000000000..d45491211c8faefb4cd6668963a1493bd8a2822d --- /dev/null +++ b/synapse/frontier/workbench_api.py @@ -0,0 +1,385 @@ +"""Workbench HTTP API for the Sonapse Frontier Pack (``/api/frontier/*``, opt-in, additive). + +Follows the same dual-source contract as ``NeuroWeaveWorkbenchAPI``: + +* the **live** observer hub on ``runtime.agent.frontier_hub`` (when ``SynapseConfig.frontier`` is configured + and enabled) is read under the workbench runtime lock and is never mutated or stepped from this API; +* an isolated **lab** :class:`FrontierObserverHub` lives on the workbench, built lazily and replaced only by + ``POST /api/frontier/configure``, so users can step observers and run experiments in the browser without + touching the live agent. +""" +from __future__ import annotations + +from collections.abc import Mapping +from copy import deepcopy +import threading +import time +from typing import Any +import uuid + +import numpy as np + +from .harness import _jsonable +from .runtime import ( + FrontierObserverHub, + discover_experiments, + experiment_catalog, + run_all_frontier_experiments, + run_frontier_experiment, +) +from .spec import ( + EVIDENCE_TIER, + GRAFT_OPTIMIZERS, + MODULE_IDS, + OBSERVER_MODULE_IDS, + FrontierSpecV1, + module_catalog, +) + +__all__ = [ + 'API_SCHEMA', + 'MAX_LAB_UNITS', + 'MAX_STEP_COUNT', + 'MAX_EXPERIMENT_SEEDS', + 'default_frontier_lab_spec', + 'frontier_experiment_row', + 'FrontierWorkbenchAPI', +] + +API_SCHEMA = 'FrontierWorkbenchApiV1' +MAX_LAB_UNITS = 512 +MAX_STEP_COUNT = 256 +MAX_EXPERIMENT_SEEDS = 3 +_LAB_STREAM_OFFSET = 71_023 + + +def default_frontier_lab_spec(seed: int = 7) -> FrontierSpecV1: + """Default workbench lab spec: all available read-only observers enabled at bounded sizes.""" + avail_obs: list[str] = [] + for mod_id in OBSERVER_MODULE_IDS: + try: + from .runtime import load_frontier_module + load_frontier_module(mod_id) + avail_obs.append(mod_id) + except ModuleNotFoundError: + continue + return FrontierSpecV1( + enabled=True, + seed=seed, + modules=tuple(avail_obs), + max_observed_units=64, + history=128, + fc_window=64, + sae_features=32, + sae_k=4, + sync_pairs=32, + ) + + +def _int(value: Any, name: str, low: int, high: int) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f'{name} must be an integer in [{low}, {high}]') + return value + + +def _bool(value: Any, name: str) -> bool: + if type(value) is not bool: + raise ValueError(f'{name} must be a boolean') + return value + + +def _seeds(value: Any, default: tuple[int, ...], cap: int = MAX_EXPERIMENT_SEEDS) -> tuple[int, ...]: + if value is None: + return default + if isinstance(value, int) and not isinstance(value, bool): + _int(value, 'seeds', 1, cap) + return tuple(range(value)) + if not isinstance(value, list) or not 1 <= len(value) <= cap: + raise ValueError(f'seeds must be a count in [1, {cap}] or a list of 1..{cap} integers') + out = tuple(_int(s, 'seed', 0, 99) for s in value) + if len(set(out)) != len(out): + raise ValueError('seeds must be distinct') + return out + + +def _check_passed(value: Any) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, Mapping): + for key in ('passed', 'ok', 'pass'): + if isinstance(value.get(key), bool): + return bool(value[key]) + return False + + +def frontier_experiment_row(receipt: Mapping[str, Any]) -> dict[str, Any]: + """Compact table row summarising a sealed frontier lab receipt.""" + comparisons = receipt.get('comparisons') or {} + first_cmp_name = next(iter(comparisons), None) + first_cmp = comparisons.get(first_cmp_name) if first_cmp_name else None + if not isinstance(first_cmp, Mapping): + first_cmp = {} + row: dict[str, Any] = { + 'experiment_id': receipt.get('experiment_id'), + 'kind': receipt.get('kind'), + 'verdict': receipt.get('verdict'), + 'verdict_basis': receipt.get('verdict_basis'), + 'primary_comparison': first_cmp_name, + 'mean_difference': first_cmp.get('mean'), + 'ci95': first_cmp.get('ci95'), + 'n': first_cmp.get('n'), + 'digest': receipt.get('digest'), + 'evidence_tier': receipt.get('evidence_tier'), + } + checks = receipt.get('checks') + if first_cmp_name is None and isinstance(checks, Mapping) and checks: + total = len(checks) + passed = sum(1 for val in checks.values() if _check_passed(val)) + row['primary_comparison'] = f'{passed}/{total} checks passed' + row['n'] = total + row['checks_passed'] = passed + row['checks_total'] = total + return _jsonable(row) + + +class FrontierWorkbenchAPI: + """Route handler for ``/api/frontier/*`` bound to a Sonapse ``Workbench``.""" + + PREFIX = '/api/frontier/' + + def __init__(self, workbench: Any) -> None: + self.wb = workbench + self.lab_lock = threading.RLock() + self.run_lock = threading.Lock() + self._lab_hub: FrontierObserverHub | None = None + self._lab_rng: np.random.Generator | None = None + + def _seed(self) -> int: + seed = getattr(getattr(self.wb.runtime, 'config', None), 'seed', 7) + return seed if type(seed) is int and 0 <= seed < 2**31 else 7 + + def lab(self) -> FrontierObserverHub: + with self.lab_lock: + if self._lab_hub is None: + self._set_lab(default_frontier_lab_spec(self._seed()), n_units=64) + assert self._lab_hub is not None + return self._lab_hub + + def _set_lab(self, spec: FrontierSpecV1, n_units: int = 64) -> None: + hub = FrontierObserverHub(spec, n_units=n_units) + with self.lab_lock: + self._lab_hub = hub + self._lab_rng = np.random.default_rng(int(spec.seed) + _LAB_STREAM_OFFSET) + + def _live_hub(self) -> FrontierObserverHub | None: + agent = getattr(self.wb.runtime, 'agent', None) + hub = getattr(agent, 'frontier_hub', None) + return hub if hub is not None and getattr(hub, 'enabled', False) else None + + def catalog(self) -> dict[str, Any]: + return _jsonable({ + 'schema': API_SCHEMA, + 'modules': module_catalog(), + 'module_ids': list(MODULE_IDS), + 'observer_module_ids': list(OBSERVER_MODULE_IDS), + 'graft_optimizers': list(GRAFT_OPTIMIZERS), + 'experiments': experiment_catalog(include_unregistered=True), + 'limits': { + 'lab_units': MAX_LAB_UNITS, + 'step': MAX_STEP_COUNT, + 'experiment_seeds': MAX_EXPERIMENT_SEEDS, + }, + 'evidence_tier': EVIDENCE_TIER, + }) + + def status(self) -> dict[str, Any]: + with self.wb.lock: + cfg = getattr(self.wb.runtime, 'config', None) + spec = getattr(cfg, 'frontier', None) + live_hub = self._live_hub() + live = { + 'configured': spec is not None, + 'enabled': live_hub is not None, + 'spec': spec.to_dict() if spec is not None else None, + } + if live_hub is not None: + live['summary'] = live_hub.summary() + with self.lab_lock: + lab = None + if self._lab_hub is not None: + lab = { + 'spec': self._lab_hub.spec.to_dict(), + 'spec_digest': self._lab_hub.spec.spec_digest, + 'n_units': self._lab_hub.n_units, + 'summary': self._lab_hub.summary(), + } + with self.wb.job_lock: + jobs = [ + {'id': j['id'], 'kind': j.get('kind'), 'status': j['status']} + for j in self.wb.jobs.values() + if str(j.get('kind', '')).startswith('frontier_') + ] + return _jsonable({ + 'schema': API_SCHEMA, + 'live': live, + 'lab': lab, + 'lab_built': lab is not None, + 'observed_source': 'live' if live['enabled'] else 'lab', + 'run_active': self.run_lock.locked(), + 'jobs': jobs, + 'evidence_tier': EVIDENCE_TIER, + }) + + def observers(self, source: str = 'auto') -> dict[str, Any]: + if source not in ('auto', 'live', 'lab'): + raise ValueError("source must be 'auto', 'live' or 'lab'") + if source in ('auto', 'live'): + with self.wb.lock: + live_hub = self._live_hub() + if live_hub is not None: + return _jsonable({'source': 'live', 'summary': live_hub.summary()}) + if source == 'live': + raise ValueError('the live runtime has no enabled frontier observer hub (start with --frontier)') + with self.lab_lock: + hub = self.lab() + return _jsonable({'source': 'lab', 'summary': hub.summary()}) + + def configure(self, data: Mapping[str, Any]) -> dict[str, Any]: + payload = dict(data) + n_units = _int(payload.pop('n_units', 64), 'n_units', 8, MAX_LAB_UNITS) + payload.setdefault('enabled', True) + spec = FrontierSpecV1.from_dict(payload) + with self.lab_lock: + self._set_lab(spec, n_units=n_units) + return self.observers('lab') + + def step(self, data: Mapping[str, Any]) -> dict[str, Any]: + extra = set(data) - {'steps', 'reset'} + if extra: + raise ValueError(f'unknown step fields: {sorted(extra)}') + steps = _int(data.get('steps', 8), 'steps', 1, MAX_STEP_COUNT) + reset = _bool(data.get('reset', False), 'reset') + with self.lab_lock: + hub = self.lab() + if reset: + hub.reset() + self._lab_rng = np.random.default_rng(int(hub.spec.seed) + _LAB_STREAM_OFFSET) + assert self._lab_rng is not None + for _ in range(steps): + vec = np.tanh(self._lab_rng.standard_normal(hub.n_units)) + hub.observe(vec) + return _jsonable({'source': 'lab', 'stepped': steps, 'summary': hub.summary()}) + + def _run(self, kind: str, fn: Any, background: bool, params: dict[str, Any]) -> dict[str, Any]: + if not background: + if not self.run_lock.acquire(blocking=False): + raise ValueError('another frontier run is active; wait for it to finish') + try: + return _jsonable(fn()) + finally: + self.run_lock.release() + wb = self.wb + with wb.job_lock: + if any(j['status'] in ('queued', 'running') for j in wb.jobs.values()): + raise ValueError('a background job is already active') + if self.run_lock.locked(): + raise ValueError('another frontier run is active; wait for it to finish') + ident = uuid.uuid4().hex + event = threading.Event() + wb.cancel[ident] = event + job = { + 'id': ident, + 'kind': f'frontier_{kind}', + 'status': 'queued', + 'created': time.time(), + 'config': _jsonable(params), + 'progress': {'phase': 'queued'}, + 'result': None, + 'error': None, + } + wb.jobs[ident] = job + wb.persist(job) + + def worker() -> None: + try: + with self.run_lock: + if event.is_set(): + with wb.job_lock: + job.update(status='cancelled') + return + with wb.job_lock: + job.update(status='running', progress={'phase': kind}) + wb.persist(job) + result = _jsonable(fn()) + with wb.job_lock: + job.update( + status='cancelled' if event.is_set() else 'completed', + result=result, + progress={'phase': 'done'}, + ) + except Exception as exc: + with wb.job_lock: + job.update(status='failed', error=f'{type(exc).__name__}: {exc}') + finally: + with wb.job_lock: + job['finished'] = time.time() + wb.persist(job) + + threading.Thread(target=worker, daemon=True, name=f'frontier-{kind}-{ident[:8]}').start() + with wb.job_lock: + return deepcopy(job) + + def experiment(self, data: Mapping[str, Any]) -> dict[str, Any]: + extra = set(data) - {'id', 'quick', 'seeds', 'background'} + if extra: + raise ValueError(f'unknown experiment fields: {sorted(extra)}') + eid = data.get('id', 'synchrony') + discovered = discover_experiments(include_unregistered=True) + if eid != 'all' and eid not in discovered: + raise ValueError(f'id must be one of {sorted(discovered)} or "all"') + quick = _bool(data.get('quick', True), 'quick') + background = _bool(data.get('background', False), 'background') + if eid == 'all' and not background: + raise ValueError("id 'all' runs only as a background job (background: true)") + seeds = _seeds(data.get('seeds'), (0, 1) if quick else (0, 1, 2), MAX_EXPERIMENT_SEEDS) + + def run() -> dict[str, Any]: + if eid == 'all': + receipts = run_all_frontier_experiments( + quick=quick, seeds=seeds, primary_only=True, include_unregistered=True) + else: + receipts = [run_frontier_experiment( + str(eid), quick=quick, seeds=seeds, include_unregistered=True)] + return { + 'experiment': eid, + 'quick': quick, + 'seeds': list(seeds), + 'rows': [frontier_experiment_row(r) for r in receipts], + 'receipts': receipts, + 'evidence_tier': EVIDENCE_TIER, + } + + return self._run('experiment', run, background, {'id': eid, 'quick': quick, 'seeds': list(seeds)}) + + def get(self, path: str) -> dict[str, Any]: + if path == '/api/frontier/catalog': + return self.catalog() + if path == '/api/frontier/status': + return self.status() + if path == '/api/frontier/observers': + return self.observers('auto') + if path == '/api/frontier/observers/lab': + return self.observers('lab') + raise KeyError('unknown frontier endpoint') + + def post(self, path: str, data: Mapping[str, Any]) -> dict[str, Any]: + if not isinstance(data, Mapping): + raise ValueError('JSON body must be an object') + handlers = { + '/api/frontier/configure': self.configure, + '/api/frontier/step': self.step, + '/api/frontier/experiment': self.experiment, + } + if path not in handlers: + raise KeyError('unknown frontier endpoint') + return handlers[path](data) diff --git a/synapse/neural_graft.py b/synapse/neural_graft.py index aed716cab471cb569b84783c7ba1cadd2c02375d..e0dffb603881e6e95930b67e41ce14ddfe377bca 100644 --- a/synapse/neural_graft.py +++ b/synapse/neural_graft.py @@ -57,7 +57,7 @@ class NeuralResidualGraft: proposals changed by a planner or final action governor. """ def __init__(self, seed=7, hidden_dim=256, residual_scale=.25, capacity=4096, - learning_rate=3e-4, gamma=.97, exploration_std=.55): + learning_rate=3e-4, gamma=.97, exploration_std=.55, optimizer_kind='adam'): _integer(seed, 'seed', 0, 2**31-1) _integer(hidden_dim, 'hidden_dim', 32, 1024) _integer(capacity, 'capacity', 16, 65536) @@ -65,13 +65,21 @@ class NeuralResidualGraft: or not 0 < residual_scale <= .35 or not 0 < learning_rate <= .01 or not 0 <= gamma < 1 or not .05 <= exploration_std <= 2): raise ValueError('invalid neural graft hyperparameters') + if optimizer_kind not in ('adam', 'muon'): + raise ValueError("optimizer_kind must be 'adam' or 'muon'") self.settings = {'seed': seed, 'hidden_dim': hidden_dim, 'residual_scale': float(residual_scale), 'capacity': capacity, 'learning_rate': float(learning_rate), 'gamma': float(gamma), 'exploration_std': float(exploration_std)} + if optimizer_kind != 'adam': + self.settings['optimizer_kind'] = optimizer_kind with torch.random.fork_rng(devices=[]): torch.manual_seed(seed + 417) self.network = _ResidualNetwork(hidden_dim) - self.optimizer = torch.optim.Adam(self.network.parameters(), lr=learning_rate) + if optimizer_kind == 'muon': + from .frontier.muon import make_graft_optimizer + self.optimizer = make_graft_optimizer(self.network, kind='muon', lr=learning_rate) + else: + self.optimizer = torch.optim.Adam(self.network.parameters(), lr=learning_rate) self.rng = np.random.default_rng(seed + 913) self.replay = [] self.pending = None @@ -342,6 +350,8 @@ class NeuralResidualGraft: candidate = type(self)(**state['settings']) if candidate.settings['hidden_dim'] != self.settings['hidden_dim']: raise ValueError('neural graft architecture mismatch') + if candidate.settings.get('optimizer_kind', 'adam') != self.settings.get('optimizer_kind', 'adam'): + raise ValueError('neural graft optimizer mismatch') candidate.network.load_state_dict(state['network']) candidate.optimizer.load_state_dict(state['optimizer']) for parameter, moments in candidate.optimizer.state.items(): diff --git a/synapse/neuroweave/brain.py b/synapse/neuroweave/brain.py index b3ebcb16a6541dffe29025247654dabb03bfd1c3..3bd60fe7aef159b2df22b26a81dc557e74457d5f 100644 --- a/synapse/neuroweave/brain.py +++ b/synapse/neuroweave/brain.py @@ -189,7 +189,7 @@ class NeuroWeaveBrain: # ------------------------------------------------------------------ dynamics def step(self, external: Any = None, *, reward: float = 0.0, controls: Mapping[str, Any] | None = None, learn: bool = True, uncertainty: float = 0.0, route_gain: Any = None, - unit_gain: Any = None) -> np.ndarray: + unit_gain: Any = None, unit_input: Any = None) -> np.ndarray: started = time.perf_counter() reward = float(reward) uncertainty = float(uncertainty) @@ -205,6 +205,14 @@ class NeuroWeaveBrain: if ug.size != n or not np.all(np.isfinite(ug)): raise ValueError(f'unit_gain must be a finite vector of length {n}') ug = np.clip(ug, 0.0, 4.0) + ui = None + if unit_input is not None: + # optional per-unit additive feed-forward input (the engine's associative-recall and + # fast-weight reads); None leaves the update exactly as before + ui = np.asarray(unit_input, dtype=np.float64).ravel() + if ui.size != n or not np.all(np.isfinite(ui)): + raise ValueError(f'unit_input must be a finite vector of length {n}') + ui = np.clip(ui, -10.0, 10.0) prev = self.cells.output.copy() ext = self.project_input(external) gate = float(np.clip(1.0 / (1.0 + 2.2 * max(0.0, uncertainty)), 0.58, 1.0)) if 'uncertainty_gating' in flags else 1.0 @@ -218,6 +226,8 @@ class NeuroWeaveBrain: if 'context_attention' in flags: drive.apical = drive.apical + 0.3 * self.context_attention(prev) drive.external = ext if ug is None else ext * ug + if ui is not None: + drive.external = drive.external + ui # added after any per-unit gain sparse_k = max(1, int(round(n * self.spec.sparsity))) out = self.cells.step(drive, flags, controls, sparse_k=sparse_k) self.synapses.push(out) diff --git a/synapse/neuroweave/engine.py b/synapse/neuroweave/engine.py index 76435a79c98c9119fab4105c0d79ba0637f8ca29..52c105b152f46d9bc3f72a7af9b65acdf771ff80 100644 --- a/synapse/neuroweave/engine.py +++ b/synapse/neuroweave/engine.py @@ -22,6 +22,16 @@ into one step. Every coupling is causal and gated by its mechanism flag: forecasts, confirms forecasts when the outcome arrives and feeds verified recall into the drive; predictive replay (``predictive_replay``) replays the memory schedule into the predictors every ``spec.sleep_interval`` steps; +* associative trace memory (``associative_memory``): a bounded FIFO of + (drive key, unit output) episodes, stored on learning steps whose reward + exceeds 0.35 on every 12th step and recalled by cosine similarity of this + step's drive key; a match above 0.35 adds ``0.11 * similarity * state`` to + the per-unit drive (:class:`AssociativeTraceMemory`); +* universal fast weights (``fast_weights``): an 8x8 value/key matrix written on + learning steps with nonzero reward + (``M <- clip(0.999 M + 0.0012 |R| R outer(v, k), -1, 1)``) whose read + ``0.03 * (M k)[i mod 8]`` is added to the per-unit drive + (:class:`FastWeightMemory`); * region route gains for ``multi_region_routing`` are modulated by attention and gain controls; * structural plasticity / neurogenesis run inside the brain at @@ -50,7 +60,8 @@ from .sensory import SensoryHub from .spec import (AFFECT_VARIABLES, DENDRITES, EVIDENCE_TIER, NEUROMODULATORS, REGIONS, SENSORY_CHANNEL_IDS, SENSORY_DIM, SOMA_ROLES, TASK_INPUT_DIM, NeuroWeaveSpecV1) -__all__ = ['NeuroWeaveEngine', 'ENGINE_SCHEMA', 'ACTION_DIM', 'DRIVE_DIM', 'ENGINE_FLAGS'] +__all__ = ['NeuroWeaveEngine', 'ENGINE_SCHEMA', 'ACTION_DIM', 'DRIVE_DIM', 'ENGINE_FLAGS', 'AssociativeTraceMemory', + 'FastWeightMemory'] ENGINE_SCHEMA = 'NeuroWeaveEngineStateV1' ACTION_DIM = 2 # [thrust, turn] @@ -64,7 +75,7 @@ ENGINE_FLAGS: tuple[str, ...] = ( 'receptor_heterogeneity', 'predictive_ensemble', 'hierarchical_prediction', 'uncertainty_gating', 'counterfactual_prediction', 'efference_self_model', 'micro_collective', 'expert_routing', 'meta_plasticity', 'specialist_graft', 'memory_ecology', 'predictive_replay', 'representation_fusion', 'multi_region_routing', - 'transmitter_inference', + 'transmitter_inference', 'associative_memory', 'fast_weights', ) _PREDICTION_FLAGS = frozenset({'predictive_ensemble', 'hierarchical_prediction', 'uncertainty_gating', 'counterfactual_prediction', 'predictive_replay'}) @@ -113,6 +124,187 @@ def _rng_state(rng: np.random.Generator) -> dict: return rng.bit_generator.state +# ---- associative trace memory and universal fast weights ------------------------------------------------ +# Constants of the NEUROWEAVE-LAB 0.4.0 ``memory`` / ``fastWeights`` switches as recorded by the sibling +# SONAPSE-EVO port (memory/associative.py, memory/fast_weights.py, memory/stores.py ``cosine``); the +# original JavaScript was not available to this build. +ASSOC_KEY_DIM = 32 +ASSOC_CAPACITY = 32 +ASSOC_THRESHOLD = 0.35 +ASSOC_GAIN = 0.11 +ASSOC_REWARD_THRESHOLD = 0.35 +ASSOC_STORE_EVERY = 12 +ASSOC_COSINE_EPS = 1e-9 # cosine = a.b / (|a| |b| + eps), as in the reference port +FAST_DIM = 8 +FAST_READ_GAIN = 0.03 +FAST_ETA = 0.0012 +FAST_DECAY = 0.999 + + +def _obs_key(src: np.ndarray, dim: int) -> np.ndarray: + """First ``dim`` values of the drive (zero-padded), clipped to [-1, 1].""" + return np.clip(_fit(src, dim), -1.0, 1.0) + + +class AssociativeTraceMemory: + """Bounded episode store recalled by cosine similarity (``associative_memory``). + + * :meth:`maybe_store` keeps ``(key, unit outputs)`` only when the step index is a multiple of + ``ASSOC_STORE_EVERY`` and the reward exceeds ``ASSOC_REWARD_THRESHOLD``; at most + ``ASSOC_CAPACITY`` episodes are kept (the oldest is dropped first). + * :meth:`recall` picks the episode whose key has the highest cosine similarity + ``k.q / (|k| |q| + ASSOC_COSINE_EPS)`` to this step's key ``q`` (the earliest one on ties). Above + ``ASSOC_THRESHOLD`` it returns the per-unit input ``ASSOC_GAIN * similarity * state`` (state + zero-padded / truncated to the current population); otherwise ``None``, so an empty store or a + weak match contributes exactly nothing. + * Keys and states are clipped to [-1, 1], so one recall adds at most ``ASSOC_GAIN`` per unit. + """ + + def __init__(self) -> None: + self.episodes: list[dict[str, Any]] = [] + self.hits = 0 + self.stores = 0 + + def recall(self, key: np.ndarray, n: int) -> tuple[np.ndarray | None, dict[str, Any]]: + info: dict[str, Any] = {'similarity': 0.0, 'episode': None, 'hit': False} + if not self.episodes: + return None, info + keys = np.stack([ep['key'] for ep in self.episodes]) + sims = (keys @ key) / (np.linalg.norm(keys, axis=1) * float(np.linalg.norm(key)) + ASSOC_COSINE_EPS) + best = int(np.argmax(sims)) + sim = float(sims[best]) + info.update(similarity=sim, episode=int(self.episodes[best]['step'])) + if not sim > ASSOC_THRESHOLD: + return None, info + self.hits += 1 + info['hit'] = True + return ASSOC_GAIN * sim * _fit(self.episodes[best]['state'], n), info + + def maybe_store(self, key: np.ndarray, state: np.ndarray, reward: float, step: int) -> bool: + if not (reward > ASSOC_REWARD_THRESHOLD and step % ASSOC_STORE_EVERY == 0): + return False + self.episodes.append({'key': np.array(key, dtype=np.float64), + 'state': np.clip(np.asarray(state, dtype=np.float64).ravel(), -1.0, 1.0), + 'reward': float(reward), 'step': int(step)}) + if len(self.episodes) > ASSOC_CAPACITY: + del self.episodes[0] + self.stores += 1 + return True + + def summary(self) -> dict[str, Any]: + return {'episodes': len(self.episodes), 'capacity': ASSOC_CAPACITY, 'hits': int(self.hits), + 'stores': int(self.stores), + 'last_store_step': int(self.episodes[-1]['step']) if self.episodes else None} + + def export_state(self) -> dict[str, Any]: + return {'episodes': [{'key': ep['key'].tolist(), 'state': ep['state'].tolist(), 'reward': float(ep['reward']), + 'step': int(ep['step'])} for ep in self.episodes], + 'hits': int(self.hits), 'stores': int(self.stores)} + + @classmethod + def from_state(cls, state: Any, *, max_units: int, before_step: int) -> 'AssociativeTraceMemory': + """Validated copy of an exported state (raises ``ValueError``; never partially built). + + Besides shapes and bounds it checks the store invariants: every episode was stored on a step + that is a multiple of ``ASSOC_STORE_EVERY``, earlier than ``before_step`` (the engine step of + the state), in increasing order, with a reward above ``ASSOC_REWARD_THRESHOLD``; there is at + most one recall hit per step and at most one store per scheduled step before ``before_step``; + and, since episodes leave only through the FIFO, exactly ``min(stores, ASSOC_CAPACITY)`` remain.""" + if not isinstance(state, Mapping) or set(state) != {'episodes', 'hits', 'stores'}: + raise ValueError('associative_memory state must have exactly episodes, hits and stores') + hits, stores = state['hits'], state['stores'] + if type(hits) is not int or type(stores) is not int or hits < 0 or stores < 0: + raise ValueError('associative_memory hits/stores must be non-negative ints') + if hits > before_step or stores > (before_step + ASSOC_STORE_EVERY - 1) // ASSOC_STORE_EVERY: + raise ValueError(f'associative_memory hits/stores exceed what {before_step} engine steps allow') + eps = state['episodes'] + if not isinstance(eps, (list, tuple)) or len(eps) != min(ASSOC_CAPACITY, stores): + raise ValueError(f'associative_memory must hold min(stores, {ASSOC_CAPACITY}) episodes') + out = cls() + last_step = -1 + for ep in eps: + if not isinstance(ep, Mapping) or set(ep) != {'key', 'state', 'reward', 'step'}: + raise ValueError('associative_memory episode must have exactly key, state, reward and step') + key = _finite_vec('associative_memory key', ep['key'], max_len=ASSOC_KEY_DIM) + st = _finite_vec('associative_memory state', ep['state'], max_len=max_units) + if key.size != ASSOC_KEY_DIM or st.size == 0 or np.abs(key).max() > 1.0 or np.abs(st).max() > 1.0: + raise ValueError(f'associative_memory key must have {ASSOC_KEY_DIM} values and state 1..{max_units} ' + 'values, all in [-1, 1]') + reward = _finite_scalar('associative_memory reward', ep['reward']) + if not ASSOC_REWARD_THRESHOLD < reward <= 1.0: + raise ValueError(f'associative_memory reward must be in ({ASSOC_REWARD_THRESHOLD}, 1]') + step = ep['step'] + if (type(step) is not int or step % ASSOC_STORE_EVERY or not last_step < step < before_step): + raise ValueError(f'associative_memory steps must be increasing multiples of {ASSOC_STORE_EVERY} ' + f'below the engine step {before_step}') + last_step = step + out.episodes.append({'key': key, 'state': st, 'reward': reward, 'step': step}) + out.hits, out.stores = hits, stores + return out + + +class FastWeightMemory: + """Reward-gated 8x8 value/key association matrix (``fast_weights``). + + * :meth:`read`: ``f = M k`` for this step's key ``k``; unit ``i`` receives + ``FAST_READ_GAIN * f[i mod 8]``. A zero matrix returns ``None`` (contributes exactly nothing). + * :meth:`write` (called on learning steps with reward ``R != 0``, ``R`` in [-1, 1]): + ``M <- clip(FAST_DECAY * M + FAST_ETA * |R| * R * outer(v, k), -1, 1)``, where the value ``v`` is + the first eight pooled readout features after the step (clipped to [-1, 1]). + * Entries of ``M`` and ``k`` lie in [-1, 1], so one read adds at most ``FAST_READ_GAIN * FAST_DIM`` + (0.24) per unit. + """ + + def __init__(self) -> None: + self.matrix = np.zeros((FAST_DIM, FAST_DIM)) + self.updates = 0 + + def read(self, key: np.ndarray, n: int) -> tuple[np.ndarray | None, np.ndarray]: + if not np.any(self.matrix): + return None, np.zeros(FAST_DIM) + f = self.matrix @ key + return FAST_READ_GAIN * f[np.arange(n) % FAST_DIM], f + + def write(self, value: np.ndarray, key: np.ndarray, reward: float) -> float: + """Apply one write; returns the largest absolute change of any matrix entry.""" + new = np.clip(FAST_DECAY * self.matrix + FAST_ETA * abs(reward) * reward * np.outer(value, key), -1.0, 1.0) + change = float(np.abs(new - self.matrix).max()) + self.matrix = new + self.updates += 1 + return change + + def summary(self) -> dict[str, Any]: + return {'updates': int(self.updates), 'matrix_norm': float(np.linalg.norm(self.matrix)), + 'matrix_max_abs': float(np.abs(self.matrix).max())} + + def export_state(self) -> dict[str, Any]: + return {'matrix': self.matrix.tolist(), 'updates': int(self.updates)} + + @classmethod + def from_state(cls, state: Any, *, max_updates: int | None = None) -> 'FastWeightMemory': + """Validated copy of an exported state (raises ``ValueError``; never partially built). + + ``max_updates`` (the engine step of the state) bounds ``updates``: at most one write per step. + A non-zero matrix needs at least one recorded update (the matrix starts at zero).""" + if not isinstance(state, Mapping) or set(state) != {'matrix', 'updates'}: + raise ValueError('fast_weights state must have exactly matrix and updates') + updates = state['updates'] + if type(updates) is not int or updates < 0 or (max_updates is not None and updates > max_updates): + raise ValueError('fast_weights updates must be a non-negative int, at most one per engine step') + try: + m = np.asarray(state['matrix'], dtype=np.float64) + except (TypeError, ValueError) as exc: + raise ValueError('fast_weights matrix must be numeric') from exc + if m.shape != (FAST_DIM, FAST_DIM) or not np.all(np.isfinite(m)) or np.abs(m).max() > 1.0: + raise ValueError(f'fast_weights matrix must be a finite {FAST_DIM}x{FAST_DIM} array in [-1, 1]') + if updates == 0 and np.any(m): + raise ValueError('fast_weights matrix is non-zero but no update was recorded') + out = cls() + out.matrix = m.copy() + out.updates = updates + return out + + class NeuroWeaveEngine: """One causal NEUROWEAVE system built from a :class:`NeuroWeaveSpecV1`.""" @@ -142,8 +334,14 @@ class NeuroWeaveEngine: self.micro.attach_specialist(self.graft) self.fusion = RepresentationFusion(DRIVE_DIM, kinds=('predictive', 'uncertainty'), mode='learned', seed=spec.seed) + # engine-level memories read into the per-unit drive; absent (None) unless their flag is enabled + self.associative = AssociativeTraceMemory() if 'associative_memory' in f else None + self.fast_weights = FastWeightMemory() if 'fast_weights' in f else None self.events = EventBus(EVENT_HISTORY) self.ecology = None + # Optional, removable extensions (duck-typed; see synapse.frontier.extension). None are attached by + # default, and with none attached every code path below is exactly the pre-extension path. + self.extensions: list[Any] = [] self._rng = np.random.default_rng(spec.seed + ENGINE_OFFSET) self._reset_runtime() @@ -376,6 +574,24 @@ class NeuroWeaveEngine: else: external = x_task + # 7b. associative recall and fast-weight read, keyed by this step's drive (before any extension) + unit_input = None + assoc_key = fast_key = None + assoc_info: dict[str, Any] = {} + if self.associative is not None or self.fast_weights is not None: + src = np.zeros(0) if external is None else np.asarray(external, dtype=np.float64).ravel() + if self.associative is not None: + assoc_key = _obs_key(src, ASSOC_KEY_DIM) + assoc_read, assoc_info = self.associative.recall(assoc_key, self.brain.n) + if assoc_read is not None: + unit_input = assoc_read + bus.publish('memory', {'operation': 'associative_recall', 'id': assoc_info['episode']}, step=step) + if self.fast_weights is not None: + fast_key = _obs_key(src, FAST_DIM) + fast_input, fast_read = self.fast_weights.read(fast_key, self.brain.n) + if fast_input is not None: + unit_input = fast_input if unit_input is None else unit_input + fast_input + # 8. brain step with the applied controls uncertainty = 0.0 if 'uncertainty_gating' in f and pred_info['active']: @@ -397,8 +613,16 @@ class NeuroWeaveEngine: unit_gain = np.ones(self.brain.n) # neurons born after construction keep unit gain m = min(unit_gain.size, g.size) unit_gain[:m] = g[:m] + ext_ctx = None + if self.extensions: + ext_ctx = {'step': step, 'learn': learn, 'reward': float(eff_reward), 'raw_reward': reward, + 'task_input': None if x_task is None else x_task.copy(), 'sensory': value.copy(), + 'controls': controls, 'flags': f} + for ext in self.extensions: + external = self._checked_drive(ext, ext.transform_drive(external, ext_ctx), external) out = self.brain.step(external, reward=eff_reward, controls=brain_controls, learn=learn, - uncertainty=uncertainty, route_gain=route_gain, unit_gain=unit_gain) + uncertainty=uncertainty, route_gain=route_gain, unit_gain=unit_gain, + **({} if unit_input is None else {'unit_input': unit_input})) if learn and route_gain is not None and eff_reward != 0.0: # an explicit route gain bypasses the brain's own route learning; keep it learning lrs = float(np.clip(controls['learning_rate_scale'], 0.0, 4.0)) @@ -409,6 +633,24 @@ class NeuroWeaveEngine: prob = self.readout_probability(temperature) bus.publish('state', {'activity_mean': float(out.mean()), 'activity_std': float(out.std()), 'n': int(out.size), 'spike_rate': float(np.mean(self.brain.cells.spike != 0))}, step=step) + for ext in self.extensions: + ext.after_step(out.copy(), ext_ctx) + + # 8b. associative store and fast-weight write (learning steps only; raw reward clipped to [-1, 1]) + assoc_stored = fast_updated = False + fast_change = 0.0 + if learn and (self.associative is not None or self.fast_weights is not None): + r_mem = float(np.clip(reward, -1.0, 1.0)) + if self.associative is not None: + assoc_stored = self.associative.maybe_store(assoc_key, out, r_mem, step) + if assoc_stored: + bus.publish('memory', {'operation': 'associative_store', 'id': int(step)}, step=step) + if self.fast_weights is not None and r_mem != 0.0: + fast_value = np.clip(self.brain.readout_features()[:FAST_DIM], -1.0, 1.0) + fast_change = self.fast_weights.write(fast_value, fast_key, r_mem) + fast_updated = True + bus.publish('learning', {'kind': 'fast_weights', 'magnitude': fast_change, + 'updates': int(self.fast_weights.updates)}, step=step) # 9. memory writes (SENSORY observation, PREDICTED forecast) if 'memory_ecology' in f and learn: @@ -448,6 +690,18 @@ class NeuroWeaveEngine: 'counterfactual': counterfactual, 'replayed': replayed, 'effective_reward': float(eff_reward), 'events': int(bus.sequence), 'evidence_tier': EVIDENCE_TIER, } + if self.associative is not None: + result['associative_memory'] = { + 'active': True, 'hit': bool(assoc_info.get('hit', False)), + 'similarity': float(assoc_info.get('similarity', 0.0)), 'episode': assoc_info.get('episode'), + 'stored': assoc_stored, 'episodes': len(self.associative.episodes), + 'hits': int(self.associative.hits), 'stores': int(self.associative.stores)} + if self.fast_weights is not None: + result['fast_weights'] = { + 'active': True, 'read_norm': float(np.linalg.norm(fast_read)), 'updated': fast_updated, + 'max_change': fast_change, **self.fast_weights.summary()} + if self.extensions: + result['extensions'] = [str(ext.id) for ext in self.extensions] self.last = {k: v for k, v in result.items() if k != 'output'} return result @@ -474,6 +728,43 @@ class NeuroWeaveEngine: self.memory.downscale(float(np.clip(1.0 - 0.02 / max(cons, 0.25), 0.9, 1.0))) return replayed + # ------------------------------------------------------------------ extensions (optional, removable) + @staticmethod + def _checked_drive(ext: Any, new: Any, old: Any) -> Any: + """An extension may reshape *values* of the external drive, never its presence or shape.""" + if old is None: + if new is not None: + raise ValueError(f'extension {ext.id!r} must return None when there is no external drive') + return None + arr = np.asarray(new, dtype=np.float64) + if arr.shape != np.asarray(old).shape or not np.all(np.isfinite(arr)): + raise ValueError(f'extension {ext.id!r} must return a finite drive with the same shape') + return arr + + def attach_extension(self, extension: Any, *, bind: bool = True) -> None: + """Attach a duck-typed extension (``id``, ``bind``, ``transform_drive``, ``after_step``). + + Extensions are not part of :meth:`export_state`; the caller owns their state. Attaching one + is the only way an extension can influence this engine, and :meth:`detach_extension` + removes that influence completely.""" + ext_id = getattr(extension, 'id', None) + if not isinstance(ext_id, str) or not ext_id: + raise ValueError('extension must have a non-empty string id') + for name in ('bind', 'transform_drive', 'after_step'): + if not callable(getattr(extension, name, None)): + raise ValueError(f'extension {ext_id!r} is missing {name}()') + if any(e.id == ext_id for e in self.extensions): + raise ValueError(f'extension {ext_id!r} is already attached') + if bind: + extension.bind(self) + self.extensions.append(extension) + + def detach_extension(self, extension_id: str) -> Any | None: + for i, ext in enumerate(self.extensions): + if ext.id == extension_id: + return self.extensions.pop(i) + return None + # ------------------------------------------------------------------ specialist / ecology def set_specialist_coupling(self, coupling: float) -> None: if self.graft is None: @@ -602,6 +893,10 @@ class NeuroWeaveEngine: 'structural_changes': dict(ledger.counts_by_kind), 'fusion_weights': dict(self.fusion.weights), 'counters': dict(self.counters), } + if self.associative is not None: + learning['associative_memory'] = self.associative.summary() + if self.fast_weights is not None: + learning['fast_weights'] = self.fast_weights.summary() out = {'schema': 'NeuroWeaveObservatoryV1', 'evidence_tier': EVIDENCE_TIER, 'step': self.step_count, 'mechanisms': list(self.spec.mechanisms), 'neural': neural, 'neuromodulation': neuromodulation, 'sensory': sensory, 'learning': learning, 'memory': self.memory.stats(), @@ -666,7 +961,7 @@ class NeuroWeaveEngine: # ------------------------------------------------------------------ persistence def export_state(self) -> dict[str, Any]: - return { + state = { 'schema': ENGINE_SCHEMA, 'schema_version': 1, 'evidence_tier': EVIDENCE_TIER, 'spec': self.spec.to_dict(), 'brain': self.brain.export_state(), 'neuromod': self.neuromod.export_state(), @@ -687,6 +982,12 @@ class NeuroWeaveEngine: 'counters': dict(self.counters), 'rng': _rng_state(self._rng), }, } + # present only when the flag is enabled, so states of engines without them are unchanged + if self.associative is not None: + state['associative_memory'] = self.associative.export_state() + if self.fast_weights is not None: + state['fast_weights'] = self.fast_weights.export_state() + return state def import_state(self, state: Mapping[str, Any]) -> None: """Rebuild every subsystem from ``state`` in a scratch engine, then swap (no partial mutation).""" @@ -769,15 +1070,30 @@ class NeuroWeaveEngine: raise ValueError('runtime.counters malformed') fresh.counters = {k: int(v) for k, v in counters.items()} fresh._rng.bit_generator.state = rt['rng'] + # associative / fast-weight memories: a state saved before they existed (key absent or None) + # keeps the fresh initial state (empty store, zero matrix) + assoc_state, fast_state = state.get('associative_memory'), state.get('fast_weights') + if assoc_state is not None: + if fresh.associative is None: + raise ValueError('state has an associative memory but the spec does not enable associative_memory') + fresh.associative = AssociativeTraceMemory.from_state(assoc_state, max_units=spec.max_neurons, + before_step=step) + if fast_state is not None: + if fresh.fast_weights is None: + raise ValueError('state has fast weights but the spec does not enable fast_weights') + fresh.fast_weights = FastWeightMemory.from_state(fast_state, max_updates=step) except ValueError: raise except (TypeError, KeyError, AttributeError, IndexError, OverflowError) as exc: raise ValueError(f'malformed engine state: {type(exc).__name__}: {exc}') from exc keep_subscribers = self.events + keep_extensions = self.extensions self.__dict__.update(fresh.__dict__) # runtime subscribers are kept (EventBus.import_state semantics) keep_subscribers.import_state(state['events']) self.events = keep_subscribers + # attached extensions stay attached; their own state is owned and restored by the caller + self.extensions = keep_extensions self.last = {} diff --git a/synapse/neuroweave/standalone.py b/synapse/neuroweave/standalone.py index afe80bfe2fe589679645271967132badade83fc5..9894371d9210f43ce06b576bfbccda95becc802f 100644 --- a/synapse/neuroweave/standalone.py +++ b/synapse/neuroweave/standalone.py @@ -112,8 +112,10 @@ _ENGINE_ONLY: dict[str, str] = { 'predictive_replay': 'replay is a learning-time process', 'representation_fusion': 'engine packet fusion of the 40-d drive is not run', 'transmitter_inference': 'connectivity analysis only; not part of the forward pass', - 'associative_memory': 'not consumed by the NumPy runtime either', - 'fast_weights': 'not consumed by the NumPy runtime either', + 'associative_memory': 'engine-level associative recall is not run: the episode store is engine state ' + '(NeuroWeaveEngine.export_state) that the package does not carry', + 'fast_weights': 'engine-level fast-weight read is not run: the 8x8 matrix is engine state ' + '(NeuroWeaveEngine.export_state) that the package does not carry', } diff --git a/synapse/server.py b/synapse/server.py index 5e0937a5695c7c9f62e9c8b2f073fc9d884af674..4ccea8f809b65a826e7e295e4f3033984b1ff322 100644 --- a/synapse/server.py +++ b/synapse/server.py @@ -364,13 +364,24 @@ class Workbench: from .neuroweave.workbench_api import NeuroWeaveWorkbenchAPI api=self._neuroweave_api=NeuroWeaveWorkbenchAPI(self) return api + def frontier_api(self): + """Lazily built Frontier Pack API (``/api/frontier/*``); never touches Sonapse defaults.""" + with self.lock: + if getattr(self, '_frontier_api', None) is None: + from .frontier.workbench_api import FrontierWorkbenchAPI + self._frontier_api = FrontierWorkbenchAPI(self) + return self._frontier_api # NEUROWEAVE Lab routes: GET /api/neuroweave/catalog, '/api/neuroweave/status', '/api/neuroweave/observatory', # '/api/neuroweave/ledger', '/api/neuroweave/ecology'; POST '/api/neuroweave/configure', '/api/neuroweave/step', # '/api/neuroweave/experiment', '/api/neuroweave/topology', '/api/neuroweave/lesion', '/api/neuroweave/sensory', # '/api/neuroweave/export', '/api/neuroweave/inspect', '/api/neuroweave/sequence-search'. + # Frontier Pack routes: GET '/api/frontier/catalog', '/api/frontier/status', '/api/frontier/observers', + # '/api/frontier/observers/lab'; POST '/api/frontier/configure', '/api/frontier/step', '/api/frontier/experiment'. def get(self,path): if path.startswith('/api/neuroweave/'): return self.neuroweave_api().get(path) + if path.startswith('/api/frontier/'): + return self.frontier_api().get(path) receipt_prefix='/api/planning-study/receipt/' if path.startswith(receipt_prefix): name=safe_name(path[len(receipt_prefix):]) @@ -640,6 +651,8 @@ class Workbench: def post(self,path,data): if path.startswith('/api/neuroweave/'): return self.neuroweave_api().post(path,data) + if path.startswith('/api/frontier/'): + return self.frontier_api().post(path,data) if path=='/api/export': return self.start_portable_export() if path=='/api/training/pretrain': return self.start_enhancement('pretrain',data) if path=='/api/rsi/live': return self.start_enhancement('rsi',data) @@ -928,6 +941,8 @@ class Workbench: cfg['dsag']=self.runtime.config.dsag if 'neuroweave' not in cfg: cfg['neuroweave']=getattr(self.runtime.config,'neuroweave',None) + if 'frontier' not in cfg: + cfg['frontier']=getattr(self.runtime.config,'frontier',None) from .runtime import LabRuntime self.runtime=LabRuntime(SynapseConfig(**cfg),output_root=self.root) if hasattr(self, 'sim_worker') and self.sim_worker is not None: diff --git a/synapse/shared_knowledge/vector_binding.py b/synapse/shared_knowledge/vector_binding.py index 2f9c92787abbedfa90433a95edf02e736ead6c55..f55cc17bf590e8c8a65c7fda8daac8d40c18ffd4 100644 --- a/synapse/shared_knowledge/vector_binding.py +++ b/synapse/shared_knowledge/vector_binding.py @@ -41,7 +41,7 @@ class VectorSymbolicBinder: return x_approx / norm @staticmethod - def bundle(vectors: List[torch.Tensor], weights: Optional[List[float]] = None) -> torch.Tensor: + def bundle(vectors: list[torch.Tensor], weights: list[float] | None = None) -> torch.Tensor: """Vector superposition / addition: s = sum w_i * v_i.""" if not vectors: raise ValueError("Empty vector list for bundling.") diff --git a/synapse/supermix_adapters.py b/synapse/supermix_adapters.py index 15c7df593b60aae6ee3d8ea7583e3e40a4c1bc90..ee0ea6273ea1144e79e732cc383cee62fdb0fc4f 100644 --- a/synapse/supermix_adapters.py +++ b/synapse/supermix_adapters.py @@ -18,6 +18,7 @@ from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn +import torch.nn.functional as F @dataclass diff --git a/synapse/tandem_max.py b/synapse/tandem_max.py index 1ba1f799296ce7905131eeaf4f011555a954482d..154cd817ef7bc3ea7af28eb843deda8c571cccc5 100644 --- a/synapse/tandem_max.py +++ b/synapse/tandem_max.py @@ -766,6 +766,7 @@ def run_tandem_max_orchestration(workbench, data: Optional[Dict[str, Any]] = Non neuroweave_experiments = _bounded_mode_int(data, 'neuroweave_experiments', 0, 0, 1) neuroweave_lesion = _bounded_mode_int(data, 'neuroweave_lesion', 0, 0, 1) neuroweave_agent_steps = _bounded_mode_int(data, 'neuroweave_agent_steps', 4, 0, 64) + frontier_experiments = _bounded_mode_int(data, 'frontier_experiments', 0, 0, 1) default_tasks = ['forage', 'maze', 'push', 'delayed_match', 'ecosystem', 'continental_biosphere'] omnibus_tasks = data.get('omnibus_tasks') or default_tasks six_arm_tasks = data.get('six_arm_tasks', ['forage', 'push', 'ecosystem']) @@ -1049,6 +1050,21 @@ def run_tandem_max_orchestration(workbench, data: Optional[Dict[str, Any]] = Non if getattr(max_cfg, 'neuroweave', None) is not None else {'section': '06 · NEUROWEAVE Laboratory', 'skipped': 'neuroweave not configured'}) + # ------------------------------------------------------------------- + # SECTION 07 (additive, read-only): Frontier Pack laboratory + # ------------------------------------------------------------------- + if getattr(max_cfg, 'frontier', None) is not None: + from .frontier.runtime import run_frontier_laboratory + section_07 = run_frontier_laboratory( + max_cfg.frontier, + hub=getattr(runtime.agent, 'frontier_hub', None), + experiments=bool(frontier_experiments), + quick=True, + seeds=(0, 1), + ) + else: + section_07 = {'section': '07 · Frontier Pack Laboratory', 'skipped': 'frontier not configured'} + # ------------------------------------------------------------------- # SECTION 05: Exact Mid-Episode Checkpoint & Cryptographic Digest # ------------------------------------------------------------------- @@ -1100,6 +1116,7 @@ def run_tandem_max_orchestration(workbench, data: Optional[Dict[str, Any]] = Non 'section_05': section_05, # Additive: sections_completed keeps its historical five entries. 'section_06': section_06, + 'section_07': section_07, 'state': final_state, } workbench.last_tandem_receipt = receipt diff --git a/synapse/web/app.js b/synapse/web/app.js index 5e8c76e6a017bd140937835a39c7b016e9090476..7de1ac81f23e662f279483ba27efd3c113d9642e 100644 --- a/synapse/web/app.js +++ b/synapse/web/app.js @@ -3,6 +3,47 @@ const $ = id => document.getElementById(id); const pretty = x => JSON.stringify(x, null, 2); +// ------------------------------------------------------------------------- +// Theme selector (additive). Dark is the default and leaves untouched; +// Light and System set data-theme for the theme layer at the end of style.css. +// Runs first so the stored choice applies before the rest of the workbench +// initialises; storage failures (private mode, policy, quota) are ignored. +// ------------------------------------------------------------------------- +(() => { + const KEY = 'synapse_theme_v1'; + const MODES = ['dark', 'light', 'system']; + const root = document.documentElement; + const select = document.getElementById('theme-select'); + function applyTheme(mode) { + const choice = MODES.includes(mode) ? mode : 'dark'; + if (choice === 'dark') root.removeAttribute('data-theme'); + else root.setAttribute('data-theme', choice); + if (select && select.value !== choice) select.value = choice; + return choice; + } + let stored = null; + try { + stored = window.localStorage.getItem(KEY); + } catch (_) { + stored = null; + } + applyTheme(stored); + if (select) { + select.addEventListener('change', () => { + const choice = applyTheme(select.value); + try { + if (choice === 'dark') window.localStorage.removeItem(KEY); + else window.localStorage.setItem(KEY, choice); + } catch (_) { + // The theme still applies for this page view without storage. + } + }); + } + window.addEventListener('storage', event => { + if (event.key === KEY) applyTheme(event.newValue); + }); +})(); + let state = {}; let running = false; let busy = false; @@ -5462,9 +5503,13 @@ function updateSimSpeed() { // Navigation & Core Controls // ------------------------------------------------------------------------- document.querySelectorAll('nav button').forEach(b => b.onclick = () => { - document.querySelectorAll('.tab,nav button').forEach(n => n.classList.remove('active')); + document.querySelectorAll('.tab,nav button').forEach(n => { + n.classList.remove('active'); + if (n.tagName === 'BUTTON') n.removeAttribute('aria-current'); + }); $(b.dataset.tab).classList.add('active'); b.classList.add('active'); + b.setAttribute('aria-current', 'page'); $('title').textContent = b.querySelector('span').textContent; if (b.dataset.tab === 'overview') { window.requestAnimationFrame(() => render(state)); @@ -7674,3 +7719,171 @@ if ($('neuroweave')) { }); window.addEventListener('beforeunload', () => { nwlWebcamStop(); nwlMicStop(); }); } + +// ------------------------------------------------------------------------- +// Frontier Pack Lab (additive; every control calls /api/frontier/*) +// ------------------------------------------------------------------------- +(() => { + const section = $('frontier'); + if (!section) return; + const frl = { catalog: null, rows: [], receipts: [] }; + + function frlCell(text) { + const td = document.createElement('td'); + td.textContent = text === null || text === undefined ? '—' : String(text); + return td; + } + + function frlFmt(v, digits = 4) { + if (v === null || v === undefined) return '—'; + return typeof v === 'number' && Number.isFinite(v) ? v.toFixed(digits) : String(v); + } + + function frlRenderObservers(obsPayload) { + const host = $('frl-observers-grid'); + if (!host) return; + host.textContent = ''; + const summary = obsPayload && obsPayload.summary ? obsPayload.summary : null; + if (!summary) return; + const observers = summary.observers || {}; + const entries = Object.entries(observers); + const meta = document.createElement('div'); + meta.textContent = `source: ${obsPayload.source} · steps: ${summary.observed_steps}/${summary.agent_steps} · units: ${summary.observed_unit_count}/${summary.n_units} · active observers: ${entries.length}`; + host.appendChild(meta); + entries.forEach(([modId, data]) => { + const card = document.createElement('div'); + const strong = document.createElement('strong'); + strong.textContent = modId; + card.appendChild(strong); + const detail = document.createElement('div'); + detail.className = 'muted'; + const parts = []; + for (const key of ['observed_steps', 'observed', 'global_synchrony_index', 'R_last', 'metastability_index', 'fvu_ema', 'mean_abs_fc', 'ce', 'ce_excess']) { + if (data && Object.prototype.hasOwnProperty.call(data, key) && data[key] !== null && data[key] !== undefined) { + parts.push(`${key}=${frlFmt(data[key], 3)}`); + } + } + detail.textContent = parts.length ? parts.join(' · ') : 'ready'; + card.appendChild(detail); + host.appendChild(card); + }); + } + + function frlRenderResults() { + const tbody = $('frl-results-body'); + if (!tbody) return; + tbody.textContent = ''; + frl.rows.forEach((row) => { + const tr = document.createElement('tr'); + const ci = Array.isArray(row.ci95) && row.ci95.length === 2 + ? `[${frlFmt(row.ci95[0], 4)}, ${frlFmt(row.ci95[1], 4)}]` : '—'; + tr.appendChild(frlCell(row.experiment_id)); + tr.appendChild(frlCell(row.kind)); + tr.appendChild(frlCell(row.primary_comparison)); + tr.appendChild(frlCell(frlFmt(row.mean_difference, 4))); + tr.appendChild(frlCell(ci)); + tr.appendChild(frlCell(row.n)); + tr.appendChild(frlCell(row.verdict)); + tbody.appendChild(tr); + }); + } + + async function frlLoadCatalog() { + if (frl.catalog) return frl.catalog; + const c = await api('frontier/catalog'); + frl.catalog = c; + const sel = $('frl-exp-select'); + if (sel) { + sel.textContent = ''; + (c.experiments || []).forEach((exp) => { + const opt = document.createElement('option'); + opt.value = exp.experiment_id; + opt.textContent = `${exp.experiment_id} (${exp.kind})`; + sel.appendChild(opt); + }); + } + const modBody = $('frl-modules-body'); + if (modBody) { + modBody.textContent = ''; + (c.modules || []).forEach((m) => { + const tr = document.createElement('tr'); + tr.appendChild(frlCell(m.id)); + tr.appendChild(frlCell(m.title)); + tr.appendChild(frlCell(m.kind)); + tr.appendChild(frlCell(m.observer ? 'yes' : 'no')); + tr.appendChild(frlCell(m.origin)); + tr.appendChild(frlCell(m.source)); + modBody.appendChild(tr); + }); + } + return c; + } + + async function frlRefresh() { + await frlLoadCatalog(); + const [status, obs] = await Promise.all([api('frontier/status'), api('frontier/observers')]); + $('frl-status').textContent = `Observing ${status.observed_source} hub · live runtime frontier ${status.live && status.live.enabled ? 'enabled' : 'off (default)'} · ${(frl.catalog.experiments || []).length} experiments ready.`; + frlRenderObservers(obs); + } + + async function frlWaitJob(jobId) { + const start = Date.now(); + while (Date.now() - start < 900000) { + await new Promise((r) => setTimeout(r, 400)); + const jobs = await api('jobs'); + const job = (jobs.jobs || []).find((j) => j.id === jobId); + if (job) { + if (job.status === 'completed') return job.result; + if (job.status === 'failed') throw Error(job.error || 'Frontier job failed'); + if (job.status === 'cancelled') throw Error('Frontier job cancelled'); + } + } + throw Error('Frontier job timed out'); + } + + const navBtn = document.querySelector('nav button[data-tab="frontier"]'); + if (navBtn) navBtn.addEventListener('click', () => action(frlRefresh)); + $('frl-refresh').onclick = () => action(frlRefresh); + $('frl-step-run').onclick = () => action(async () => { + const steps = Math.max(1, Math.min(256, Number($('frl-step-count').value) || 16)); + const r = await api('frontier/step', { steps }); + $('frl-status').textContent = `Lab hub stepped ${r.stepped} times → observed_steps=${r.summary.observed_steps}.`; + frlRenderObservers(r); + }); + $('frl-step-reset').onclick = () => action(async () => { + const r = await api('frontier/step', { steps: 1, reset: true }); + $('frl-status').textContent = `Lab hub reset and stepped once → observed_steps=${r.summary.observed_steps}.`; + frlRenderObservers(r); + }); + $('frl-exp-run').onclick = () => action(async () => { + await frlLoadCatalog(); + const id = $('frl-exp-select').value || 'anytime_inference'; + const seeds = Math.max(1, Math.min(3, Number($('frl-exp-seeds').value) || 2)); + const quick = $('frl-exp-quick').checked; + const background = $('frl-exp-background').checked; + $('frl-exp-status').textContent = `Running ${id} (${seeds} seeds, quick=${quick})…`; + const resp = await api('frontier/experiment', { id, seeds, quick, background }); + const result = background && resp && resp.id ? await frlWaitJob(resp.id) : resp; + if (result && Array.isArray(result.rows)) frl.rows.push(...result.rows); + if (result && Array.isArray(result.receipts)) frl.receipts.push(...result.receipts); + frlRenderResults(); + show('frl-lab-out', result); + const first = result && Array.isArray(result.rows) && result.rows[0] ? result.rows[0] : null; + $('frl-exp-status').textContent = first + ? `${first.experiment_id}: verdict=${first.verdict} · digest=${String(first.digest || '').slice(0, 12)}` + : `Completed ${id}.`; + }); + $('frl-export-json').onclick = () => { + if (!frl.receipts.length) { + $('frl-exp-status').textContent = 'No frontier receipts to export yet.'; + return; + } + const blob = new Blob([JSON.stringify(frl.receipts, null, 2)], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = 'frontier_experiment_receipts.json'; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + }; +})(); diff --git a/synapse/web/index.html b/synapse/web/index.html index d5c013646bd7b4d799913403b777d2bb9c64a28c..006d9fe3baeb08dc8dee733da30ed21a46d59bec 100644 --- a/synapse/web/index.html +++ b/synapse/web/index.html @@ -8,17 +8,27 @@ +