diff --git a/research/algernon/HM_SANDBOX_HANDOFF.md b/research/algernon/HM_SANDBOX_HANDOFF.md new file mode 100644 index 000000000..4d0271baa --- /dev/null +++ b/research/algernon/HM_SANDBOX_HANDOFF.md @@ -0,0 +1,41 @@ +# H-M0/H-M1 sandbox handoff and evidence status + +This branch exists to bridge the independently executed ChatGPT CPU sandbox experiments into the Algernon research workflow. Based on Algernon PR #33; **no H-M2 results are verified**. + +## Artifact custody + +The complete archive is named `algernon_claude_handoff.zip`, SHA-256 `88d8e23581f0445aca9ac7b7b9a9c7f8d7df34f00bbc5126fced84511053f7b4`. It contains the original `algernon_hm1_revision_sandbox.zip` payload, whose SHA-256 is `68954e95d8b4c50ac480e22c0ab085e8deaa6f12f959ebc4fc24158df860ac22`, plus a handoff note. Source-only reproducibility archive `algernon_hm_source.tar.gz` has SHA-256 `432b45e513d00eef3b83d41ef1407074d763aa35b373daa5555298b1cc685578`. + +**Current GitHub status:** This commit contains the custody manifest and reproduction instructions. The original ZIP and its binaries/raw records have **not** been uploaded to GitHub. They are attached to the ChatGPT conversation as sandbox downloads. Do not claim the data are hosted here until a separate upload has been hash-verified. + +## Verified scope + +- H-M0 baseline, terminal-utility, and stopping-comparison code and records exist in the original ZIP. +- H-M1 bounded grammar expansion code, trained-policy checkpoint, held-out and confirmation records, metrics, reports, and tests exist in the ZIP. +- The extracted archive's registry validator passed; 5 registry tests and 27 experimental tests passed on CPU. +- These checks establish executable contract tests, not an independent retraining or numerical reproduction. +- H-M2 was described in conversation, but no H-M2 code, manifest, checkpoint or records are available. Its reported numerical scores are **unverified**. +- There is no execution receipt for the actual Qwenputer-4B compiled processor or the Qwen3.5-0.8B recurrent graft. + +## Download-to-checkout procedure + +Download the attached `algernon_claude_handoff.zip` from the ChatGPT conversation, verify its SHA-256 above, extract the inner archive, and copy the `experiments/` directory plus provenance reports into a local scratch branch. Keep the raw records and model weights in an ignored or release-artifact location rather than the main Git tree. + +On Windows PowerShell: + +```powershell +$archive = Join-Path $HOME 'Documents\Codex\algernon_claude_handoff.zip' +(Get-FileHash $archive -Algorithm SHA256).Hash.ToLower() +Expand-Archive -LiteralPath $archive -DestinationPath (Join-Path $HOME 'Documents\Codex\algernon_handoff') -Force +# Inspect README within extracted archive for the inner ZIP and expand it. +cd (Join-Path $HOME 'Documents\Codex\algernon_handoff\algernon_sandbox') +python -m research.algernon.validate_register +python -m unittest discover -s research/algernon/tests -v +python -m unittest discover -s experiments/tests -v +``` + +Compare hashes, do not mix experiments with the four unrun H-C/H-R/H-W/H-J hypotheses, and retain held-out splits. Import source into the research tree only after checks pass. + +## Next publication decision + +Place the experimental implementation and small receipts in `research/algernon/metacognition/` under a dedicated PR, with raw larger records in a hash-addressed artifact store. A university exploratory paper can cite these after independent reruns, full source/seed inspection, and protocol review. H-M2 must be rerun under a newly frozen specification and named as a new experiment. diff --git a/research/algernon/metacognition/README.md b/research/algernon/metacognition/README.md new file mode 100644 index 000000000..59590bbf6 --- /dev/null +++ b/research/algernon/metacognition/README.md @@ -0,0 +1,24 @@ +# Algernon H-M0/H-M1: recovered CPU experiment implementation + +This folder contains byte-identical imports of the original ChatGPT sandbox's runnable H-M0/H-M1 experimental implementation and the CPU toy contracts. Every imported file has been checked against the archived Git blob hash. See [RECOVERY_STATUS.md](RECOVERY_STATUS.md) for SHA identities, split/seed commands, and exact local setup. + +**Now available:** the H-M0 information-gain pruner, terminal-utility controller, cost-aware stopping control, H-M1 bounded grammar revision controller, and all five associated test modules. The optional historical timing benchmark script is still missing. + +**Evidence boundary:** these are synthetic CPU experiments. The original raw JSONL records and PyTorch checkpoint binaries remain in the chat sandbox archive and are not yet in this GitHub branch. They can be regenerated from the preserved scripts and seed ranges; independent reproduction should record the new environment and hashes. H-M2 still lacks its original implementation and receipts, so previously reported H-M2 numbers are unverified. + +## Run tests + +From the Compactification-Theory checkout root, with `numpy` and CPU `torch` installed: + +```bash +PYTHONPATH=research/algernon/metacognition python -m unittest discover -s research/algernon/metacognition/experiments/tests -v +``` + +On PowerShell: + +```powershell +$env:PYTHONPATH = "research/algernon/metacognition" +python -m unittest discover -s research/algernon/metacognition/experiments/tests -v +``` + +The original extracted source suite passes 27/27 unit tests in the sandbox. Rerun the GitHub copy independently before treating its results as a reproduced observation. Training commands are in RECOVERY_STATUS.md. diff --git a/research/algernon/metacognition/RECOVERY_STATUS.md b/research/algernon/metacognition/RECOVERY_STATUS.md new file mode 100644 index 000000000..faa6319eb --- /dev/null +++ b/research/algernon/metacognition/RECOVERY_STATUS.md @@ -0,0 +1,45 @@ +# H-M0/H-M1 executable recovery status + +This branch is the direct import of the preserved ChatGPT sandbox experiments into Algernon. GitHub blob IDs for the files below were checked against the original ZIP bytes, not rewritten implementations. + +| Experiment source | Original Git blob SHA | On GitHub | +| --- | --- | --- | +| `experiments/toy_contracts.py` | `16a92153570e943c4b2e4287bcd7f8ab66c309bb` | yes | +| `experiments/tests/test_toy_contracts.py` | `21805955f4ab283cc0501d608081b177fba57192` | yes | +| `experiments/h_m0_pruner.py` | `d62a43c27f5fa6c1f67208c5f52ae5f5678bbd9f` | yes | +| `experiments/h_m0_terminal.py` | `8e601a330f6e11610ee89e63a4a57689f22ee3ad` | yes | +| `experiments/h_m0_fair_baselines.py` | `36ce308cbc1a22b014d87578be8a864a5d8c9760` | yes | +| `experiments/h_m1_revision.py` | `d438519c0a79aad649302d27704be1a6200efef7` | yes | +| `experiments/tests/test_h_m0_pruner.py` | `f94a8a31cb9277f7b8323cc9241f64ac3ef88c90` | yes | +| `experiments/tests/test_h_m0_terminal.py` | `f71f94145fe7ae1b9cf11dc6786d6fa4e9ecc4cb` | yes | +| `experiments/tests/test_h_m0_fair_baselines.py` | `9628e47be2cfce37ace36770031de16547c31284` | yes | +| `experiments/tests/test_h_m1_revision.py` | `5e1eaec37744423424466e8061638179f560e49c` | yes | +| `experiments/benchmark_terminal_runtime.py` | `ffb3d462bf813cd6ad99b9ff51e73193700d4744` | pending; optional timing script | + +The original archive is SHA-256 `88d8e23581f0445aca9ac7b7b9a9c7f8d7df34f00bbc5126fced84511053f7b4`. H-M0/H-M1 original binary weights and full JSONL records remain outside GitHub until a separately verified artifact transfer. **H-M2 remains unverified and requires a new frozen protocol.** + +## Commands (CPU) + +Use a detached checkout of this branch. From the repository root: + +```powershell +$env:PYTHONPATH = "research/algernon/metacognition" +python -m unittest discover -s research/algernon/metacognition/experiments/tests -v + +# H-M0 initial policy; creates original predecessor checkpoint in the expected location. +python -m experiments.h_m0_pruner --output research/algernon/metacognition/results/h_m0_01 --train-states 4000 --test-episodes 1000 --epochs 18 --seed 20261103 + +# H-M0 terminal policy. Expected predecessor checkpoint is results/h_m0_01/policy.pt +# under metacognition/, so copy or symlink the generated initial checkpoint into that layout. +python -m experiments.h_m0_terminal --output research/algernon/metacognition/results/h_m0_02 --train-worlds 700 --validation-worlds 150 --test-worlds 1000 --oracle-test-worlds 100 --rollouts 2 --epochs 18 --seed 20261104 + +# Second independent held-out stopping comparison. +python -m experiments.h_m0_fair_baselines + +# H-M1 grammar-revision study, self-contained and independent of H-M0 checkpoint. +python -m experiments.h_m1_revision --out research/algernon/metacognition/results/h_m1_01 --train 2400 --val 350 --test 1200 --confirm 1000 --epochs 28 --seed 20261103 +``` + +The source imports use `experiments`; `PYTHONPATH` makes that package visible. The generated outputs are research artifacts and should be excluded from normal Git commits. Preserve exact seed ranges and do not tune on the final test/confirmation ranges. + +**Scientific status:** the code and tests are on GitHub; results require independent rerun, and old observed measurements await raw-record publication. These are synthetic CPU studies only, distinct from Qwenputer and Qwen3.5 graft benchmarks. diff --git a/research/algernon/metacognition/SOURCE_RECOVERY.md b/research/algernon/metacognition/SOURCE_RECOVERY.md new file mode 100644 index 000000000..40b50b005 --- /dev/null +++ b/research/algernon/metacognition/SOURCE_RECOVERY.md @@ -0,0 +1,23 @@ +# H-M experiment source recovery + +The historical ChatGPT sandbox archive has 11 Python files (70,774 source bytes) under `experiments/`, including the H-M0 baseline/pruner, H-M0 terminal-utility model, cost-aware stopping comparisons, H-M1 revision environment, toy contracts, and five test modules. + +The corresponding full archive remains in ChatGPT's sandbox. This repository currently holds the handoff and upload instructions, not the full source or all results. + +**Reproduction caveat:** H-M2 was reported in conversation without a retained runnable source or evaluation record. Recreate and register it separately. + +The GitHub connector supports text file writes. A reliable transfer requires importing the files from a host with access to the original archive. The SHA-256 of the full archive is `88d8e23581f0445aca9ac7b7b9a9c7f8d7df34f00bbc5126fced84511053f7b4`. + +## Inventory + +- `benchmark_terminal_runtime.py` +- `h_m0_fair_baselines.py` +- `h_m0_pruner.py` +- `h_m0_terminal.py` +- `h_m1_revision.py` +- `toy_contracts.py` +- `tests/test_h_m0_fair_baselines.py` +- `tests/test_h_m0_pruner.py` +- `tests/test_h_m0_terminal.py` +- `tests/test_h_m1_revision.py` +- `tests/test_toy_contracts.py` diff --git a/research/algernon/metacognition/experiments/h_m0_fair_baselines.py b/research/algernon/metacognition/experiments/h_m0_fair_baselines.py new file mode 100644 index 000000000..36ce308cb --- /dev/null +++ b/research/algernon/metacognition/experiments/h_m0_fair_baselines.py @@ -0,0 +1,82 @@ +"""H-M0 v2 post-hoc fairness follow-up: fresh 500M worlds and greedy MAP stop. + +This study was designed after the 400M final test but before inspecting 500M outcomes. +The exact already-trained terminal model stays frozen. The new baseline can stop +and maximizes one-step expected *terminal MAP decision utility* per probe. +""" +from __future__ import annotations +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from experiments.h_m0_pruner import N_H, N_PROBES, BUDGET, make_episode, posterior_update +from experiments.h_m0_terminal import ( + COST_PENALTY, Selector, TerminalPlanner, paired_interval, results_summary, + run as run_existing, legal_actions, posterior_from_outcomes, +) + + +def greedy_map(ep): + mask, outcomes, spent, probes = 0, 0, 0., [] + while True: + p=posterior_from_outcomes(ep,mask,outcomes) + legal=legal_actions(ep,mask,spent) + if not legal:break + gains=[] + for i in legal: + pi=float(np.dot(p,ep.likelihoods[i])) + pu=posterior_update(p,ep.likelihoods[i],1) + pn=posterior_update(p,ep.likelihoods[i],0) + accuracy_gain=pi*pu.max()+(1-pi)*pn.max()-p.max() + gains.append(float(accuracy_gain-COST_PENALTY*ep.costs[i])) + index=int(np.argmax(gains)) + if gains[index]<=1e-10:break + a=legal[index] + spent+=float(ep.costs[a]);mask|=1< float: + pp = np.clip(p, 1e-12, 1) + return float(-np.sum(pp * np.log(pp))) + + +def posterior_update(p: np.ndarray, likelihood: np.ndarray, observed: int) -> np.ndarray: + likelihood = likelihood if observed else 1.0 - likelihood + updated = p * np.clip(likelihood, 1e-12, 1) + return updated / updated.sum() + + +def information_gain(p: np.ndarray, likelihood: np.ndarray) -> float: + prob_pos = float(np.dot(p, likelihood)) + p_pos = posterior_update(p, likelihood, 1) + p_neg = posterior_update(p, likelihood, 0) + ig = entropy(p) - (prob_pos * entropy(p_pos) + (1 - prob_pos) * entropy(p_neg)) + return max(0.0, ig) + + +@dataclass +class Episode: + prior: np.ndarray + likelihoods: np.ndarray + costs: np.ndarray + truth: int + observations: np.ndarray + seed: int + + +def make_episode(seed: int) -> Episode: + rng = np.random.default_rng(seed) + prior = rng.dirichlet(np.full(N_H, 0.85)) + baseline = rng.beta(1.5, 1.5, size=(N_PROBES, 1)) + sharp = rng.beta(0.5, 0.5, size=(N_PROBES, N_H)) + mix = rng.uniform(0.15, 1.0, size=(N_PROBES, 1)) + likelihoods = np.clip((1.0 - mix) * baseline + mix * sharp, 0.015, 0.985) + costs = rng.choice(COST_OPTIONS, size=N_PROBES, replace=True) + truth = int(rng.choice(N_H, p=prior)) + # Fixed common random numbers per episode and probe across policy arms. + observations = (rng.uniform(size=N_PROBES) < likelihoods[:, truth]).astype(np.int64) + return Episode(prior, likelihoods, costs, truth, observations, seed) + + +def feature(p: np.ndarray, rates: np.ndarray, cost: float, remaining: float) -> np.ndarray: + return np.concatenate((p, rates, [cost / 3.0, remaining / BUDGET, entropy(p) / np.log(N_H), float(p.max())])).astype(np.float32) + + +def make_train_samples(n_states: int, seed: int): + rng = np.random.default_rng(seed) + xs, ys = [], [] + for k in range(n_states): + ep = make_episode(seed * 100000 + k) + p = ep.prior.copy() + remaining = BUDGET + selected = set() + # Sample a random legal history so the learner sees intermediate beliefs. + for _ in range(int(rng.integers(0, 4))): + legal = [i for i in range(N_PROBES) if i not in selected and ep.costs[i] <= remaining] + if not legal: + break + i = int(rng.choice(legal)) + selected.add(i) + remaining -= ep.costs[i] + p = posterior_update(p, ep.likelihoods[i], int(ep.observations[i])) + for i in range(N_PROBES): + if i in selected or ep.costs[i] > remaining: + continue + xs.append(feature(p, ep.likelihoods[i], ep.costs[i], remaining)) + ys.append(information_gain(p, ep.likelihoods[i]) / ep.costs[i]) + return np.stack(xs), np.asarray(ys, dtype=np.float32) + + +def learn_policy(train_size: int, seed: int, epochs: int): + torch.manual_seed(seed) + torch.set_num_threads(1) + xs, ys = make_train_samples(train_size, seed) + x = torch.from_numpy(xs) + y = torch.from_numpy(ys[:, None] * 20) + model = nn.Sequential(nn.Linear(12, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1)) + optimizer = torch.optim.Adam(model.parameters(), lr=0.003) + rng = np.random.default_rng(seed + 100) + for ep in range(epochs): + for idx in np.array_split(rng.permutation(len(xs)), max(1, len(xs) // 768)): + pred = model(x[idx]) + loss = (pred - y[idx]).square().mean() + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + model.eval() + with torch.no_grad(): + loss = ((model(x) - y) ** 2).mean().item() / 400 + params = sum(p.numel() for p in model.parameters()) + return model, {'n_train_states': train_size, 'n_train_probes': len(xs), 'epochs': epochs, 'train_mse': loss, 'policy_parameters': params} + + +def choose(arm: str, ep: Episode, p: np.ndarray, remaining: float, legal: list[int], model, initial_scores: np.ndarray, rng, frozen_model=None) -> int: + if arm == 'random': + return int(rng.choice(legal)) + if arm == 'fixed_heuristic': + return max(legal, key=lambda i: (initial_scores[i], -i)) + if arm == 'bayes_ig': + return max(legal, key=lambda i: (information_gain(p, ep.likelihoods[i]) / ep.costs[i], -i)) + if arm == 'cheapest': + return min(legal, key=lambda i: (ep.costs[i], i)) + if arm in ('learned', 'learned_shuffled_state', 'untrained'): + # A shuffled-state arm checks whether selection uses the *correct* posterior. + selection_p = np.roll(p, 1) if arm == 'learned_shuffled_state' else p + predictor = frozen_model if arm == 'untrained' else model + x = np.stack([feature(selection_p, ep.likelihoods[i], ep.costs[i], remaining) for i in legal]) + with torch.no_grad(): + scores = predictor(torch.from_numpy(x)).squeeze(-1).numpy() + return legal[int(np.argmax(scores))] + raise ValueError(arm) + + +def run_episode(arm: str, ep: Episode, model, frozen_model=None) -> dict: + rng = np.random.default_rng(10_000_000 + ep.seed) + p = ep.prior.copy() + remaining = BUDGET + chosen = [] + initial_scores = np.var(ep.likelihoods, axis=1) / ep.costs + while remaining >= COST_OPTIONS.min() and p.max() < 0.98: + legal = [i for i in range(N_PROBES) if i not in chosen and ep.costs[i] <= remaining + 1e-10] + if not legal: + break + i = choose(arm, ep, p, remaining, legal, model, initial_scores, rng, frozen_model) + chosen.append(i) + remaining -= float(ep.costs[i]) + p = posterior_update(p, ep.likelihoods[i], int(ep.observations[i])) + return { + 'seed': ep.seed, 'arm': arm, 'truth': ep.truth, 'predicted': int(np.argmax(p)), + 'correct': int(np.argmax(p) == ep.truth), + 'brier': float(np.sum((p - np.eye(N_H)[ep.truth]) ** 2)), + 'log_loss': float(-np.log(np.clip(p[ep.truth], 1e-12, 1.0))), + 'cost': float(BUDGET - remaining), 'probes': chosen, + 'posterior': np.round(p, 8).tolist(), 'initial_prior': np.round(ep.prior, 8).tolist(), + } + + +def paired_bootstrap(records: list[dict], a: str, b: str, metric: str, samples: int = 2000): + # A, B share episode seeds; use episode-level paired bootstrap. + by_a = {r['seed']: r[metric] for r in records if r['arm'] == a} + by_b = {r['seed']: r[metric] for r in records if r['arm'] == b} + keys = sorted(set(by_a) & set(by_b)) + differences = np.asarray([by_a[k] - by_b[k] for k in keys]) + rng = np.random.default_rng(392918) + vals = np.mean(differences[rng.integers(0, len(keys), (samples, len(keys)))], axis=1) + return {'delta': float(differences.mean()), 'paired_bootstrap_95pct': [float(x) for x in np.quantile(vals, [0.025, 0.975])]} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--output', type=Path, required=True) + ap.add_argument('--train-states', type=int, default=4000) + ap.add_argument('--test-episodes', type=int, default=1000) + ap.add_argument('--epochs', type=int, default=18) + ap.add_argument('--seed', type=int, default=20261103) + args = ap.parse_args() + args.output.mkdir(parents=True, exist_ok=True) + started = time.perf_counter() + model, train_details = learn_policy(args.train_states, args.seed, args.epochs) + torch.manual_seed(args.seed + 904) + untrained = nn.Sequential(nn.Linear(12, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1)) + untrained.eval() + arms = ['random', 'cheapest', 'fixed_heuristic', 'bayes_ig', 'untrained', 'learned_shuffled_state', 'learned'] + records = [] + # A held-out range separated from the training-seed generator arithmetic. + test_seeds = list(range(300_000_000, 300_000_000 + args.test_episodes)) + for seed in test_seeds: + ep = make_episode(seed) + for arm in arms: + records.append(run_episode(arm, ep, model, untrained)) + elapsed = time.perf_counter() - started + means = {arm: {metric: float(np.mean([r[metric] for r in records if r['arm'] == arm])) for metric in ('correct', 'brier', 'log_loss', 'cost')} for arm in arms} + comparison = {arm: paired_bootstrap(records, 'learned', arm, 'correct') for arm in arms if arm != 'learned'} + metrics = {'status': 'exploratory_synthetic_cpu', 'means': means, 'paired_correctness_deltas': comparison, 'training': train_details, 'wall_time_seconds': elapsed, 'total_probe_calls': sum(len(r['probes']) for r in records), 'notes': ['Known likelihoods; exact Bayes posterior updates; learned only experiment selection', 'One-step IG is a greedy comparator, not an optimal long-horizon policy', 'Model, data and simulator authored for this sandbox run; no Qwen inference', 'Training states and test generator seeds use disjoint ranges']} + here = Path(__file__) + manifest = {'project': 'Algernon H-M0', 'run_type': 'exploratory_synthetic_cpu', 'source_sha256': hashlib.sha256(here.read_bytes()).hexdigest(), 'seed': args.seed, 'train_states': args.train_states, 'test_episodes': args.test_episodes, 'test_seed_start': test_seeds[0], 'test_seed_end_inclusive': test_seeds[-1], 'budget': BUDGET, 'n_world_hypotheses': N_H, 'n_probes': N_PROBES, 'torch': torch.__version__, 'numpy': np.__version__, 'python': platform.python_version(), 'hardware': 'CPU; no CUDA'} + (args.output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') + (args.output / 'metrics.json').write_text(json.dumps(metrics, indent=2) + '\n') + with (args.output / 'records.jsonl').open('w') as f: + for r in records: + f.write(json.dumps(r) + '\n') + torch.save(model.state_dict(), args.output / 'policy.pt') + print(json.dumps({'accuracy': {a: round(means[a]['correct'], 4) for a in arms}, 'cost': {a: round(means[a]['cost'], 3) for a in arms}, 'learned_minus_random': comparison['random'], 'learned_minus_fixed': comparison['fixed_heuristic'], 'train': train_details, 'wall_seconds': round(elapsed, 2)}, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/research/algernon/metacognition/experiments/h_m0_terminal.py b/research/algernon/metacognition/experiments/h_m0_terminal.py new file mode 100644 index 000000000..8e601a330 --- /dev/null +++ b/research/algernon/metacognition/experiments/h_m0_terminal.py @@ -0,0 +1,343 @@ +"""Algernon H-M0 v2: learn a budgeted experiment policy from terminal decision utility. + +Sandbox-only synthetic CPU study. Outcomes follow independent Bernoulli likelihoods +conditional on one of four latent hypotheses. All selectors see the true likelihood +matrix; only probe choice is learned. The dynamic-programming expert optimizes the +expected terminal probability of correct MAP classification less cost penalty. +There is no Qwen or active GPU computation. +""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass +from functools import lru_cache +import hashlib +import json +import platform +import random +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn +import torch.nn.functional as F + +from experiments.h_m0_pruner import ( + N_H, N_PROBES, BUDGET, COST_OPTIONS, Episode, entropy, + information_gain, make_episode, posterior_update, run_episode as old_run, +) + +COST_PENALTY = 0.004 +STOP = N_PROBES + + +def legal_actions(ep: Episode, mask: int, spent: float) -> list[int]: + return [i for i in range(N_PROBES) if not (mask >> i) & 1 + and spent + float(ep.costs[i]) <= BUDGET + 1e-9] + + +def posterior_from_outcomes(ep: Episode, mask: int, outcomes: int) -> np.ndarray: + p = ep.prior.copy() + for i in range(N_PROBES): + if (mask >> i) & 1: + p = posterior_update(p, ep.likelihoods[i], (outcomes >> i) & 1) + return p + + +class TerminalPlanner: + """Exact finite-horizon expectation over future probe observations. + + Q is Bayes-optimal within this *known simulator* under capped experiment costs. + It is a mathematical comparison point, not a metacognitive neural learner. + """ + def __init__(self, ep: Episode, penalty: float = COST_PENALTY): + self.ep = ep + self.penalty = penalty + self.cost_by_mask = np.zeros(1 << N_PROBES, dtype=np.float64) + for mask in range(1, 1 << N_PROBES): + bit = mask & -mask + i = bit.bit_length() - 1 + self.cost_by_mask[mask] = self.cost_by_mask[mask ^ bit] + float(ep.costs[i]) + self.calls = 0 + + @lru_cache(maxsize=None) + def evaluate(self, mask: int = 0, outcomes: int = 0) -> tuple[float, int]: + self.calls += 1 + p = posterior_from_outcomes(self.ep, mask, outcomes) + cost = self.cost_by_mask[mask] + best_score = float(np.max(p) - self.penalty * cost) + best_action = STOP + # Legal to halt at any point, so both accuracy and probe costs matter. + for i in legal_actions(self.ep, mask, cost): + pi = float(np.dot(p, self.ep.likelihoods[i])) + post_mask = mask | (1 << i) + v_pos, _ = self.evaluate(post_mask, outcomes | (1 << i)) + v_neg, _ = self.evaluate(post_mask, outcomes) + value = pi * v_pos + (1 - pi) * v_neg + if value > best_score + 1e-10: + best_score, best_action = value, i + return best_score, best_action + + def action_scores(self, mask: int, outcomes: int) -> np.ndarray: + p = posterior_from_outcomes(self.ep, mask, outcomes) + cost = self.cost_by_mask[mask] + scores = np.full(N_PROBES + 1, -1e9, dtype=np.float64) + scores[STOP] = float(p.max() - self.penalty * cost) + for i in legal_actions(self.ep, mask, cost): + pi = float(np.dot(p, self.ep.likelihoods[i])) + vm, _ = self.evaluate(mask | 1 << i, outcomes | 1 << i) + vn, _ = self.evaluate(mask | 1 << i, outcomes) + scores[i] = pi * vm + (1 - pi) * vn + return scores + + +def inputs_for_state(ep: Episode, mask: int, outcomes: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]: + p = posterior_from_outcomes(ep, mask, outcomes) + spent = float(sum(float(ep.costs[i]) for i in range(N_PROBES) if (mask >> i) & 1)) + remaining = BUDGET - spent + legal = legal_actions(ep, mask, spent) + available = np.zeros(N_PROBES, dtype=np.float32) + available[legal] = 1.0 + # Each probe row has the same semantics. Pooling preserves permutation equivariance. + rows = [] + for i in range(N_PROBES): + L = ep.likelihoods[i] + rows.append(np.concatenate((p, L, + [float(ep.costs[i]) / 3.0, remaining / BUDGET, + float(available[i]), information_gain(p, L) / np.log(N_H), + float(L.max() - L.min()), p.max()])) ) + return np.stack(rows).astype(np.float32), available, p, remaining + + +class Selector(nn.Module): + def __init__(self): + super().__init__() + self.embed = nn.Sequential(nn.Linear(14, 48), nn.Tanh(), nn.Linear(48, 32), nn.Tanh()) + self.score = nn.Sequential(nn.Linear(32*2 + 6, 48), nn.Tanh(), nn.Linear(48, 1)) + self.stop = nn.Sequential(nn.Linear(32 + 6, 24), nn.Tanh(), nn.Linear(24, 1)) + + def forward(self, rows: torch.Tensor, available: torch.Tensor) -> torch.Tensor: + # rows [B, 8, 14], available [B, 8] + emb = self.embed(rows) + pooled = (emb * available[...,None]).sum(1) / available.sum(1).clamp_min(1)[:,None] + # global posterior and remaining budget are identical in every row + glob = torch.cat((rows[:,0,:4], rows[:,0,9:10], rows[:,0,13:14]), -1) + context = torch.cat((pooled, glob), -1) + expanded_context = context[:,None,:].expand(-1,N_PROBES,-1) + scores = self.score(torch.cat((emb,expanded_context),-1)).squeeze(-1) + scores = scores.masked_fill(available < 0.5, -1e6) + stop = self.stop(context).squeeze(-1) + return torch.cat((scores,stop[:,None]),1) + + +def collect_training_worlds(start: int, n: int, histories: int, seed: int): + """Expert labels from terminal optimal utility, for varied true observation histories.""" + rng = np.random.default_rng(seed) + rows, avails, labels = [], [], [] + diagnostics = {'expert_states':0,'teacher_stop':0,'expert_nodes':0} + for j in range(n): + ep = make_episode(start+j) + teacher = TerminalPlanner(ep) + for rollout in range(histories): + mask, outcomes, spent = 0, 0, 0.0 + # Mix on-policy teacher paths with random histories for covariate coverage. + for step in range(5): + feat, av, p, rem = inputs_for_state(ep,mask,outcomes) + decision = teacher.evaluate(mask,outcomes)[1] + rows.append(feat); avails.append(av); labels.append(decision) + diagnostics['expert_states'] += 1 + diagnostics['teacher_stop'] += int(decision == STOP) + legal=legal_actions(ep,mask,spent) + if not legal: break + if rollout == 0 or rng.random()<0.65: + action = decision + else: + action = int(rng.choice(legal)) + if action == STOP: break + outcomes |= int(ep.observations[action]) << action + mask |= 1 << action + spent += float(ep.costs[action]) + diagnostics['expert_nodes'] += teacher.calls + return np.asarray(rows,np.float32),np.asarray(avails,np.float32),np.asarray(labels,np.int64), diagnostics + + +def fit_policy(rows,available,labels,seed,epochs=16,batch_size=512,holdout=None): + torch.manual_seed(seed) + torch.set_num_threads(1) + model = Selector() + optimizer = torch.optim.AdamW(model.parameters(),lr=0.0015, weight_decay=1e-5) + r = torch.from_numpy(rows); m=torch.from_numpy(available); y=torch.from_numpy(labels) + history=[] + rng=np.random.default_rng(seed+11) + best = None; best_loss = float('inf'); best_epoch=None + for epoch in range(epochs): + model.train() + for inds in np.array_split(rng.permutation(len(y)),max(1,int(np.ceil(len(y)/batch_size)))): + logits=model(r[inds],m[inds]); loss=F.cross_entropy(logits,y[inds]); + optimizer.zero_grad(set_to_none=True); loss.backward(); optimizer.step() + model.eval() + with torch.no_grad(): + train_ce = float(F.cross_entropy(model(r,m),y)) + train_accuracy = float((model(r,m).argmax(1)==y).float().mean()) + if holdout: + vr,vm,vy=holdout + valid_ce=float(F.cross_entropy(model(torch.from_numpy(vr),torch.from_numpy(vm)),torch.from_numpy(vy))) + metric=valid_ce + else: + valid_ce=None; metric=train_ce + history.append({'epoch':epoch+1,'train_CE':train_ce,'train_action_accuracy':train_accuracy,'validation_CE':valid_ce}) + if metric dict: + rng = np.random.default_rng(10000000+ep.seed) + mask=0;outcomes=0;spent=0.0;probes=[];decision_count=0 + while len(probes)=0.98: + break # legacy baseline stop rule + decision=act(arm,ep,p,mask,outcomes,spent,model,old_model,rng,teacher,untrained_model) + decision_count += 1 + if decision==STOP:break + if decision not in legal_actions(ep,mask,spent):raise RuntimeError('policy violates budget or repeats probe') + probes.append(decision) + spent += float(ep.costs[decision]); mask|=1< World: + rng=np.random.default_rng(seed) + q=float(q_override if q_override is not None else rng.uniform(.12,.88)) + # Random within-family prior is visible in the task specification. + simple=rng.dirichlet(np.full(6,1.7)) + complex_=rng.dirichlet(np.full(6,1.7)) + prior=np.concatenate(((1-q)*simple,q*complex_)) + noise=rng.uniform(.025,.17,4) + costs=rng.choice([.65,.80,.95,1.10,1.30],4).astype(float) + expand_cost=float(rng.choice([.85,1.05,1.25])) + weights=rng.dirichlet(np.full(4,.85)) + truth=int(rng.choice(len(TABLE),p=prior)) + observed=(TABLE[truth] != (rng.random(4)float: + return float(sum(w.costs[i] for i in range(NQ) if mask & (1<np.ndarray: + # Full Bayes posteriors serve as the generative teacher's belief state; + # simple-only posteriors are used for actual unexpanded predictions. + n=12 if expanded else 6 + p=w.prior[:n].copy() + for i in range(NQ): + if mask&(1<>i)&1),1-w.noise[i],w.noise[i]) + p*=probs + total=p.sum() + assert total>0 and np.isfinite(total) + return p/total + + +def predicted_labels(w:World,mask:int,outcomes:int,expanded:bool)->np.ndarray: + p=posterior(w,mask,outcomes,expanded) + return (p@TABLE[:len(p),:] > .5).astype(np.int8) + + +def expected_accuracy(w:World,mask:int,outcomes:int,expanded:bool)->float: + # Judge prediction against ALL possible true rules using the full generative + # posterior. The unexpanded rule learner has to make simple-family predictions. + ptrue=posterior(w,mask,outcomes,True) + predicted=predicted_labels(w,mask,outcomes,expanded) + per_rule=((TABLE == predicted[None,:])*w.weights[None,:]).sum(1) + return float(np.dot(ptrue,per_rule)) + + +def legal(w:World,mask:int,expanded:bool)->list[int]: + cost=state_cost(w,mask,expanded) + x=[i for i in range(NQ) if not(mask&(1<tuple[float,int]: + self.calls+=1 + spent=state_cost(self.w,mask,expanded) + best=expected_accuracy(self.w,mask,outcomes,expanded)-PENALTY*spent + action=STOP + ptrue=posterior(self.w,mask,outcomes,True) + for i in legal(self.w,mask,expanded): + if i==STOP:continue + if i==EXPAND: + v,_=self.value(mask,outcomes,True) + else: + pos=float(np.dot(ptrue,np.where(TABLE[:,i]==1,1-self.w.noise[i],self.w.noise[i]))) + plus,_=self.value(mask|1<best+1e-10: best,action=v,i + return best,action + + +def feature(w:World,mask:int,outcomes:int,expanded:bool)->np.ndarray: + ps=posterior(w,mask,outcomes,expanded) + simple=posterior(w,mask,outcomes,False) + # A model is allowed to use the fixed grammar once expanded. Unexpanded + # features use simple posterior only. Both see source provenance and data. + obs=[] + for i in range(NQ): + observed=bool(mask&(1<>i)&1) if observed else .5, + float(w.costs[i]/BUDGET),float(w.noise[i]),float(w.weights[i])]) + slots=np.zeros(12,np.float32) + slots[:len(ps)]=ps + # Prior over the six currently unavailable compositions is hidden until expansion. + prior=np.asarray(w.prior if expanded else np.r_[w.prior[:6], np.zeros(6)],np.float32) + base=np.concatenate((simple,slots,prior,np.array(obs),[ + float(expanded),w.q,float((BUDGET-state_cost(w,mask,expanded))/BUDGET), + float(mask.bit_count()/4),float(w.expand_cost/BUDGET), + float(sum(w.weights[i]*max(float(ps@TABLE[:len(ps),i]),1-float(ps@TABLE[:len(ps),i])) for i in range(NQ))) + ])).astype(np.float32) + assert len(base)==56 + return base + + +def action_mask(w:World,mask:int,expanded:bool)->np.ndarray: + a=np.zeros(6,np.float32) + a[legal(w,mask,expanded)]=1 + return a + + +class Policy(nn.Module): + def __init__(self): + super().__init__() + self.net=nn.Sequential(nn.Linear(56,72),nn.Tanh(),nn.Linear(72,56),nn.Tanh(),nn.Linear(56,6)) + def forward(self,x,valid): + return self.net(x).masked_fill(valid<.5,-1e8) + + +def training_samples(start:int,n:int,seed:int,paths:int=4): + rng=np.random.default_rng(seed) + x,v,y=[],[],[] + diag={"profiles":n,"paths":paths,"teacher_calls":0,"label_count":{a:0 for a in ACTIONS}} + for s in range(start,start+n): + w=make_world(s) + planner=Planner(w) + for rollout in range(paths): + mask=outcomes=0;expanded=False + for turn in range(6): + lab=planner.value(mask,outcomes,expanded)[1] + x.append(feature(w,mask,outcomes,expanded)) + v.append(action_mask(w,mask,expanded)) + y.append(lab) + diag["label_count"][ACTIONS[lab]]+=1 + acts=legal(w,mask,expanded) + if rollout==0 or rng.random()<.66: + chosen=lab + else: + chosen=int(rng.choice(acts)) + if chosen==STOP:break + if chosen==EXPAND:expanded=True + else: + mask|=1<int: + available=legal(w,mask,expanded) + if arm=="oracle_dp":return teacher.value(mask,outcomes,expanded)[1] + if arm.startswith("policy"): + z=feature(w,mask,outcomes,expanded) + if arm=="policy_shuffled_feedback": + # Keep observed-mask fixed; invert the evidence bits seen by controller + # while actual inference uses the real observations. + wrong=outcomes^mask + z=feature(w,mask,wrong,expanded) + with torch.no_grad(): + score=policy(torch.from_numpy(z)[None],torch.from_numpy(action_mask(w,mask,expanded))[None]) + return int(score.argmax(1).item()) + if arm=="random":return int(rng.choice(available)) + if arm=="simple_only": + possible=[i for i in available if i<4] + if not possible:return STOP + # Variance under simple models: no representation of missing explanations. + p=posterior(w,mask,outcomes,False) + gains=[] + for i in possible: + b=float(np.dot(p,TABLE[:6,i]));gains.append((b*(1-b)*w.weights[i]/w.costs[i],i)) + return max(gains)[1] if max(gains)[0]>1e-4 else STOP + if arm=="always_expand": + if not expanded and EXPAND in available:return EXPAND + # After expansion, use myopic conditional improvement in terminal quality. + # This uses the true generative prior and is therefore a privileged comparator. + return myopic(w,mask,outcomes,expanded,exclude_expand=True) + if arm=="myopic_expand":return myopic(w,mask,outcomes,expanded) + if arm=="surprise_revision": + if not expanded and EXPAND in available and mask.bit_count()>=2: + # Threshold fixed before any testing, based on observed evidence under + # the primitive class. Does not consult hidden truth. + ll=np.ones(6) + for i in range(NQ): + if (mask>>i)&1: + ll*=np.where(TABLE[:6,i]==((outcomes>>i)&1),1-w.noise[i],w.noise[i]) + neg_log=-np.log(max(1e-9,float(np.dot(posterior(w,0,0,False),ll)))) + if neg_log>2.0:return EXPAND + # Query where current simple posterior is most uncertain, then stop. + opts=[i for i in available if i<4] + if not opts:return STOP + p=posterior(w,mask,outcomes,expanded) + rates=p@TABLE[:len(p),:] + scores=[(float(rates[i]*(1-rates[i])*w.weights[i]/w.costs[i]),i) for i in opts] + return max(scores)[1] if max(scores)[0]>.0001 else STOP + raise ValueError(arm) + + +def myopic(w:World,mask:int,outcomes:int,expanded:bool,exclude_expand:bool=False)->int: + # Privileged one-step oracle comparator, same probe and expansion costs. + score0=expected_accuracy(w,mask,outcomes,expanded)-PENALTY*state_cost(w,mask,expanded) + chosen=STOP; best=score0 + post=posterior(w,mask,outcomes,True) + for a in legal(w,mask,expanded): + if a==STOP or (exclude_expand and a==EXPAND):continue + if a==EXPAND: + v=expected_accuracy(w,mask,outcomes,True)-PENALTY*state_cost(w,mask,True) + else: + p1=float(np.dot(post,np.where(TABLE[:,a]==1,1-w.noise[a],w.noise[a]))) + plus=expected_accuracy(w,mask|1<best+1e-10:best=v;chosen=a + return chosen + + +def evaluate_episode(w:World,arm:str,model:Policy|None=None)->dict: + mask=0;outcomes=0;expanded=False;acts=[] + rng=np.random.default_rng(w.seed+34141) + teacher=Planner(w) if arm=="oracle_dp" else None + for _ in range(6): + a=action(w,arm,mask,outcomes,expanded,model,rng,teacher) + if a not in legal(w,mask,expanded):raise RuntimeError(f"illegal action {a} {arm}") + if a==STOP:break + acts.append(ACTIONS[a]) + if a==EXPAND:expanded=True + else: + mask|=1<=6 else "simple", + "weighted_accuracy":correct,"utility":float(correct-PENALTY*spent),"cost":spent, + "expanded":int(expanded),"probes":mask.bit_count(),"actions":acts,"predictions":pred.tolist(), + "evidence_mask":mask,"observations":outcomes} + + +def compare(records:list[dict],a:str,b:str,metric:str,boot:int=2000,seed:int=314159)->dict: + A={r['seed']:r[metric] for r in records if r['arm']==a}; B={r['seed']:r[metric] for r in records if r['arm']==b} + keys=sorted(A.keys()&B.keys());d=np.array([A[k]-B[k] for k in keys]) + g=np.random.default_rng(seed);draw=g.integers(0,len(d),size=(boot,len(d))) + return {"difference":float(d.mean()),"paired_95pct_CI":list(map(float,np.quantile(d[draw].mean(1),[.025,.975]))),"n":len(d)} + + +def output_json(path:Path,x):path.write_text(json.dumps(x,indent=2,sort_keys=True)+"\n") + + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument("--out",type=Path,required=True) + parser.add_argument("--train",type=int,default=1400) + parser.add_argument("--val",type=int,default=250) + parser.add_argument("--test",type=int,default=1200) + parser.add_argument("--confirm",type=int,default=1000) + parser.add_argument("--epochs",type=int,default=24) + parser.add_argument("--seed",type=int,default=20261103) + args=parser.parse_args();out=args.out;out.mkdir(parents=True,exist_ok=True) + start=time.perf_counter() + xd=training_samples(TRAIN_START,args.train,args.seed,paths=4) + vd=training_samples(VAL_START,args.val,args.seed+1,paths=2) + model,fit=train(xd,vd,args.seed,epochs=args.epochs) + torch.save(model.state_dict(),out/"policy.pt") + arms=["simple_only","random","surprise_revision","always_expand","myopic_expand","policy_shuffled_feedback","policy","oracle_dp"] + summary={} + for group,first,n in [("heldout",TEST_START,args.test),("confirmation",CONFIRM_START,args.confirm)]: + rows=[] + for s in range(first,first+n): + w=make_world(s) + for arm in arms: + rows.append(evaluate_episode(w,arm,model)) + with (out/f"{group}_records.jsonl").open("w") as f: + for r in rows:f.write(json.dumps(r,separators=(',',':'))+'\n') + summary[group]={ + "seed_range":[first,first+n-1],"n_worlds":n, + "means":{arm:{k:float(np.mean([r[k] for r in rows if r['arm']==arm])) for k in ("weighted_accuracy","utility","cost","expanded","probes")} for arm in arms}, + "family_accuracy":{arm:{fam:float(np.mean([r['weighted_accuracy'] for r in rows if r['arm']==arm and r['truth_family']==fam])) for fam in ("simple","composed")} for arm in arms}, + "comparisons":{arm:{k:compare(rows,"policy",arm,k) for k in ("utility","weighted_accuracy","cost")} for arm in arms if arm!="policy"}, + "family_counts":{fam:sum(1 for r in rows if r['arm']=="policy" and r['truth_family']==fam) for fam in ("simple","composed")}, + } + sec=time.perf_counter()-start + output_json(out/"metrics.json",{"status":"synthetic_CPU_exploratory_H-M1","hypothesis":"learned controller can use paid DSL expansion after multiple probes and improve held-out terminal accuracy per cost","summary":summary,"train":{"samples":len(xd[2]),"diagnostics":xd[3]},"validation":{"samples":len(vd[2]),"diagnostics":vd[3]},"fit":fit,"elapsed_seconds":sec,"semantics":{"prediction":"noiseless truth table weighted by world-specific query importance","utility":f"weighted_accuracy - {PENALTY}*total_probe_and_expand_cost","teacher":"exact-Bayesian finite horizon planning over known hypothesis class and observation noise","expansion":"paid enumeration of 6 predeclared Boolean compositions, with full replay of earlier observations"}}) + manifest={"project":"Algernon","hypothesis":"H-M1 / framework revision","status":"CPU synthetic exploratory","seed_ranges":{"train":[TRAIN_START,TRAIN_START+args.train-1],"validation":[VAL_START,VAL_START+args.val-1],"test":[TEST_START,TEST_START+args.test-1],"confirmation":[CONFIRM_START,CONFIRM_START+args.confirm-1]},"seed":args.seed,"budget":BUDGET,"cost_penalty":PENALTY,"grammar":{"primitive":SIMPLE,"compositions":COMPOSED},"source_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),"python":platform.python_version(),"torch":torch.__version__,"numpy":np.__version__,"device":"CPU","parameter_count":sum(p.numel() for p in model.parameters()),"seconds":sec} + output_json(out/"manifest.json",manifest) + print(json.dumps({"train_states":len(xd[2]),"n_parameters":manifest['parameter_count'],"seconds":round(sec,2),"summary":{group:{a:{k:round(v,4) for k,v in stats.items() if k in ('weighted_accuracy','utility','cost','expanded')} for a,stats in dat['means'].items()} for group,dat in summary.items()}},indent=2)) + +if __name__=="__main__":main() diff --git a/research/algernon/metacognition/experiments/tests/test_h_m0_fair_baselines.py b/research/algernon/metacognition/experiments/tests/test_h_m0_fair_baselines.py new file mode 100644 index 000000000..9628e47be --- /dev/null +++ b/research/algernon/metacognition/experiments/tests/test_h_m0_fair_baselines.py @@ -0,0 +1,30 @@ +import unittest +import numpy as np +from experiments.h_m0_pruner import make_episode +from experiments.h_m0_terminal import BUDGET +from experiments.h_m0_fair_baselines import greedy_map + +class FairStopTests(unittest.TestCase): + def test_uninformative_evidence_causes_stop(self): + ep=make_episode(975) + ep.likelihoods[:,:]=0.5 + r=greedy_map(ep) + self.assertEqual(r['probes'], []) + self.assertAlmostEqual(r['cost'],0) + + def test_greedy_cost_limit_and_one_use_per_probe(self): + for j in range(30): + r=greedy_map(make_episode(9750+j)) + self.assertLessEqual(r['cost'],BUDGET) + self.assertEqual(len(set(r['probes'])),len(r['probes'])) + + def test_immediate_accuracy_gain_is_nonnegative_without_penalty(self): + ep=make_episode(376) + p=ep.prior + for likelihood in ep.likelihoods: + p_pos=(p*likelihood)/(p@likelihood) + p_neg=(p*(1-likelihood))/(p@(1-likelihood)) + expected=(p@likelihood)*p_pos.max()+(p@(1-likelihood))*p_neg.max() + self.assertGreaterEqual(expected+1e-9,p.max()) + +if __name__=='__main__':unittest.main() diff --git a/research/algernon/metacognition/experiments/tests/test_h_m0_pruner.py b/research/algernon/metacognition/experiments/tests/test_h_m0_pruner.py new file mode 100644 index 000000000..f94a8a31c --- /dev/null +++ b/research/algernon/metacognition/experiments/tests/test_h_m0_pruner.py @@ -0,0 +1,43 @@ +import unittest +import numpy as np +from experiments.h_m0_pruner import posterior_update, information_gain, make_episode, run_episode + + +class Hm0SanityTests(unittest.TestCase): + def test_posterior_normalizes(self): + p = posterior_update(np.full(4, 0.25), np.array([0.1, 0.4, 0.9, 0.8]), 1) + self.assertAlmostEqual(sum(p), 1.0) + self.assertTrue(np.all(p > 0)) + + def test_information_gain_nonnegative(self): + for seed in (4, 100, 10000): + ep = make_episode(seed) + for likelihood in ep.likelihoods: + self.assertGreaterEqual(information_gain(ep.prior, likelihood), 0) + + def test_uninformative_probe_zero_gain(self): + p = np.array([0.1, 0.2, 0.3, 0.4]) + self.assertLess(information_gain(p, np.array([.6] * 4)), 1e-9) + + def test_duplicated_provenance_requires_deduplication(self): + # Copied testimony of the *same observation* counts once in a valid + # provenance-aware update. Repeat Bayes multiplication would overcount. + p = np.full(4, 0.25) + q = np.array([.05, .2, .8, .95]) + once = posterior_update(p, q, 1) + hundred_repetitions_naive = p.copy() + for _ in range(100): + hundred_repetitions_naive = posterior_update(hundred_repetitions_naive, q, 1) + self.assertGreater(100 * (once[3] - .25), 1.0) + self.assertGreater(float(hundred_repetitions_naive[3]), float(once[3])) + # This is a probe illustrating a vulnerability; main H-M0 simulator + # has independent probes and does not implement correlated-source updates. + + def test_budget_and_repeat_probes(self): + for seed in range(4): + rec = run_episode('random', make_episode(seed), None) + self.assertLessEqual(rec['cost'], 5.0) + self.assertEqual(len(rec['probes']), len(set(rec['probes']))) + +if __name__ == '__main__': + unittest.main() diff --git a/research/algernon/metacognition/experiments/tests/test_h_m0_terminal.py b/research/algernon/metacognition/experiments/tests/test_h_m0_terminal.py new file mode 100644 index 000000000..f71f94145 --- /dev/null +++ b/research/algernon/metacognition/experiments/tests/test_h_m0_terminal.py @@ -0,0 +1,62 @@ +"""Unit tests for exploratory H-M0 terminal utility experiment.""" +import unittest +import numpy as np +import torch +from experiments.h_m0_pruner import make_episode, posterior_update +from experiments.h_m0_terminal import ( + BUDGET, COST_PENALTY, N_PROBES, STOP, TerminalPlanner, Selector, + collect_training_worlds, inputs_for_state, posterior_from_outcomes, run, +) + + +class TerminalPolicyTests(unittest.TestCase): + def test_dp_never_worse_than_immediate_halt_in_expectation(self): + for seed in (2, 11, 24, 123): + ep = make_episode(seed) + oracle = TerminalPlanner(ep) + utility, action = oracle.evaluate() + self.assertGreaterEqual(utility + 1e-10, ep.prior.max()) + self.assertTrue(0 <= action <= STOP) + + def test_dp_identical_after_reordering_evidence(self): + ep = make_episode(52) + outcome1 = posterior_update(posterior_update(ep.prior, ep.likelihoods[0], 1), ep.likelihoods[3], 0) + outcome2 = posterior_update(posterior_update(ep.prior, ep.likelihoods[3], 0), ep.likelihoods[0], 1) + outcome3 = posterior_from_outcomes(ep, 1<<0 | 1<<3, 1<<0) + np.testing.assert_allclose(outcome1, outcome2, atol=1e-13) + np.testing.assert_allclose(outcome1, outcome3, atol=1e-13) + + def test_cost_penalty_makes_uninformative_probes_unwanted(self): + ep = make_episode(10) + ep.likelihoods[:,:] = 0.5 + planner = TerminalPlanner(ep) + value, action = planner.evaluate() + self.assertEqual(action, STOP) + self.assertAlmostEqual(value, ep.prior.max()) + + def test_optimal_action_is_legal_and_never_exceeds_budget(self): + for seed in (3, 7, 22, 111, 131): + ep = make_episode(seed) + r = run('exact_dp_oracle', ep, None, teacher=TerminalPlanner(ep)) + self.assertLessEqual(r['cost'], BUDGET+1e-9) + self.assertEqual(len(r['probes']), len(set(r['probes']))) + self.assertAlmostEqual(r['terminal_utility'], r['expected_correct'] - COST_PENALTY*r['cost']) + + def test_model_respects_permutation_of_probes(self): + torch.manual_seed(103) + ep = make_episode(14) + model = Selector() + rows, available, _, _ = inputs_for_state(ep,0,0) + logits = model(torch.tensor(rows[None,:]),torch.tensor(available[None,:]))[0].detach().numpy() + perm = np.array([3,4,1,2,6,5,7,0]) + logits_p = model(torch.tensor(rows[perm][None,:]),torch.tensor(available[perm][None,:]))[0].detach().numpy() + np.testing.assert_allclose(logits_p[:-1], logits[perm],atol=1e-6) + self.assertAlmostEqual(float(logits_p[-1]),float(logits[-1]),places=6) + + def test_expert_labels_are_legal(self): + x, m, y, _=collect_training_worlds(600, 5, 2, 777) + self.assertEqual(x.shape[1:],(N_PROBES,14)) + for mask,label in zip(m,y): + self.assertTrue(int(label)==STOP or mask[int(label)]==1) + +if __name__=='__main__':unittest.main() diff --git a/research/algernon/metacognition/experiments/tests/test_h_m1_revision.py b/research/algernon/metacognition/experiments/tests/test_h_m1_revision.py new file mode 100644 index 000000000..5e1eaec37 --- /dev/null +++ b/research/algernon/metacognition/experiments/tests/test_h_m1_revision.py @@ -0,0 +1,89 @@ +"""CPU correctness tests for synthetic grammar-revision environment.""" +import unittest +import numpy as np +import torch +from experiments.h_m1_revision import ( + TABLE,SIMPLE,COMPOSED,make_world,posterior,Planner,legal,EXPAND,STOP, + predicted_labels,expected_accuracy, state_cost,action_mask,feature,Policy, + evaluate_episode, BUDGET +) + +class RevisionTests(unittest.TestCase): + def test_grammar_is_distinct_and_compositional(self): + self.assertEqual(TABLE.shape,(12,4)) + self.assertEqual(len({tuple(x) for x in TABLE}),12) + np.testing.assert_array_equal(TABLE[8],[0,1,1,0]) + np.testing.assert_array_equal(TABLE[6],[0,0,0,1]) + + def test_priors_are_normalized_and_leakage_free(self): + for seed in [10,11,12,13]: + w=make_world(seed) + self.assertAlmostEqual(float(w.prior.sum()),1.) + self.assertAlmostEqual(float(w.weights.sum()),1.) + self.assertTrue(0<=w.truth<12) + self.assertTrue(np.isin(w.observed,[0,1]).all()) + + def test_expansion_replays_prior_evidence(self): + w=make_world(445) + p0=posterior(w,0,0,True) + np.testing.assert_allclose(p0,w.prior,rtol=1e-12) + mask=1|4;bits=int(w.observed[0])|int(w.observed[2])<<2 + p=posterior(w,mask,bits,True) + likelihood=np.prod([np.where(TABLE[:,i]==w.observed[i],1-w.noise[i],w.noise[i]) for i in (0,2)],axis=0) + expected=w.prior*likelihood;expected/=expected.sum() + np.testing.assert_allclose(p,expected,rtol=1e-12) + + def test_unexpanded_predictions_use_primitive_grammar(self): + w=make_world(441) + p=posterior(w,3,1,False) + self.assertEqual(len(p),6) + np.testing.assert_array_equal(predicted_labels(w,3,1,False),(p@TABLE[:6,:]>.5).astype(np.int8)) + + def test_unavailable_composition_priors_hidden_until_expand(self): + w=make_world(778) + from experiments.h_m1_revision import feature + before=feature(w,0,0,False) + after=feature(w,0,0,True) + np.testing.assert_array_equal(before[18:30],np.r_[w.prior[:6],np.zeros(6)].astype(np.float32)) + np.testing.assert_allclose(after[18:30],w.prior.astype(np.float32)) + + def test_pay_and_enforce_budget(self): + w=make_world(547) + self.assertEqual(state_cost(w,0,False),0) + self.assertAlmostEqual(state_cost(w,3,True),w.costs[0]+w.costs[1]+w.expand_cost) + for mask in range(16): + for expanded in (False,True): + if state_cost(w,mask,expanded)<=BUDGET+1e-10: + opts=legal(w,mask,expanded) + self.assertIn(STOP,opts) + for a in opts: + if a==STOP:continue + self.assertLessEqual(state_cost(w,mask|(1<= limit: + raise RuntimeError('instruction limit') + op, *arg = program[self.pc] + jumped = False + if op == 'li': + rd, imm = arg + self.reg[rd] = u32(imm) + elif op in {'add', 'sub', 'mul', 'xor'}: + rd, a, b = arg + if op == 'add': value = self.reg[a] + self.reg[b] + elif op == 'sub': value = self.reg[a] - self.reg[b] + elif op == 'mul': value = self.reg[a] * self.reg[b] + else: value = self.reg[a] ^ self.reg[b] + self.reg[rd] = u32(value) + elif op in {'sw', 'lw'}: + a, off = arg + if not 0 <= off <= len(self.mem) - 4 or off % 4: + raise ValueError('memory bounds/alignment') + if op == 'sw': + self.mem[off:off+4] = struct.pack(' str: + h = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + +def main(): + p = argparse.ArgumentParser() + p.add_argument("archive", type=Path, help="Path to algernon_claude_handoff.zip") + p.add_argument("--repo", default="AlephFunk/algernon-hm-sandbox-v1") + p.add_argument("--revision", default="main") + p.add_argument("--expected-sha256", default=EXPECTED_SHA256) + args = p.parse_args() + if not args.archive.is_file(): + p.error(f"archive missing: {args.archive}") + digest = sha256(args.archive) + if digest != args.expected_sha256: + p.error(f"SHA-256 mismatch: got {digest}, expected {args.expected_sha256}") + api = HfApi() + info = None + try: + info = api.repo_info(repo_id=args.repo, repo_type="dataset") + except Exception as e: + # Let create_repo check rights or whether the repo already exists. + print(f"Dataset lookup did not return metadata: {type(e).__name__}") + if info is not None and not getattr(info, "private", False): + p.error("Existing target dataset is public; refusing upload") + api.create_repo(repo_id=args.repo, repo_type="dataset", private=True, exist_ok=True) + info = api.repo_info(repo_id=args.repo, repo_type="dataset") + if not getattr(info, "private", False): + p.error("Target dataset could not be verified private") + path_in_repo = "archives/algernon_claude_handoff.zip" + commit = api.upload_file( + path_or_fileobj=str(args.archive), + path_in_repo=path_in_repo, + repo_id=args.repo, + repo_type="dataset", + revision=args.revision, + commit_message="Archive reproducible H-M0/H-M1 CPU experiments", + ) + verified = hf_hub_download( + repo_id=args.repo, + filename=path_in_repo, + repo_type="dataset", + revision=commit.oid, + force_download=True, + ) + downloaded_digest = sha256(Path(verified)) + if downloaded_digest != digest: + raise RuntimeError(f"Hub round-trip hash mismatch: {downloaded_digest}") + print(f"Verified private dataset: https://huggingface.co/datasets/{args.repo}/tree/{commit.oid}") + print(f"Archived SHA-256: {digest}") + print("H-M2 is NOT contained in this archive and is not independently reproducible.") + +if __name__ == "__main__": + main()