From d40aae9afdef339215d2a6ac944a4aab8cf782e7 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 22:59:47 +0800 Subject: [PATCH 1/7] docs(mono01): register HODGE evidence-order and one-shot repair study --- research/algernon/mono01/MONO_HODGE01.md | 106 +++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 research/algernon/mono01/MONO_HODGE01.md diff --git a/research/algernon/mono01/MONO_HODGE01.md b/research/algernon/mono01/MONO_HODGE01.md new file mode 100644 index 000000000..8b4f11eeb --- /dev/null +++ b/research/algernon/mono01/MONO_HODGE01.md @@ -0,0 +1,106 @@ +# MONO-HODGE-01: Bayesian evidence order and causal one-shot surgery + +**Protocol date:** 2026-11-04. **Execution status:** CPU mathematical prototype tested on explicitly synthetic affine operators. The 27B Hugging Face exports were not readable from the current runtime (the public pages and their raw files returned access errors); **no real-archive analysis or new Qwen edit has been executed**. No H100-hours were spent. + +## Public, fixed-source provenance + +These two archives come from separate checkpoints and experimental questions. Their existing evaluation sets are now public and cannot be called pristine holdouts. + +| Archive | HF dataset | Commit | Prior supplied finding | +| --- | --- | --- | --- | +| ALG-HODGE-27B-01 | [AlephFunk/alg-hodge-27b-01](https://huggingface.co/datasets/AlephFunk/alg-hodge-27b-01) | `09b4e483d9a7bb0f4f36871a2c9523a45623d05a` | Qwen3.5-27B posterior probe MAE 0.9510 nats; shuffled 1.504; constant 1.434; order dependence; tested edit gave no utility benefit | +| M-VOI-01 | [AlephFunk/m-voi-01-qwen3-8-27b](https://huggingface.co/datasets/AlephFunk/m-voi-01-qwen3-8-27b) | `906399c2b7934ca8316498d86ba0a8f4058cd204` | Qwen3.8-27B continuation advantage decodable but weaker than public-state signal; selected edit did not reliably improve stopping | + +The numerical findings above are from the operator-supplied experiment handoff, not measurements independently reproduced in this module. `repaired_v2/` is described as authoritative for HODGE; the initial capture is a failed historical run. **Before processing:** examine archive manifests, original schemas, retention notes and licenses; keep failed/superseded evidence separate and never merge rows from distinct versions. Commit fingerprints and actual fetched file hashes in the new receipts. + +## Distinguish three different mathematical quantities + +**1. Readout order sensitivity.** For a matched evidence multiset `{a,b}` with task-defined exchangeability, compare the two final prompted posterior readouts: + +\[ +D_{ab}=\widehat L(a,b)-\widehat L(b,a),\qquad +E_{ab}=\tfrac12\big(|\widehat L(a,b)-L^*|+|\widehat L(b,a)-L^*|\big). +\] + +The readout gap is observable from paired records and does not identify an internal transition operator. Even `D=0` can accompany a consistently wrong posterior. Equal or balanced token lengths, fixed prompt templates, same evidence multiset, a shared answer parser, and genuinely order-invariant task truth must be checked. Ordering can carry legitimate time or reliability information in other task families. + +**2. Order-antisymmetric activation geometry.** When both completed-prompt final hidden states share a valid activation basis at the same hook point, define rows of `D = h_ab - h_ba`, with a nominal reference matrix `X`. The most order-sensitive directions relative to reference variability solve + +\[ +D^\top D\,v/n=\lambda C v,\qquad C=X^\top X/N+\epsilon I. +\] + +Calculate the small Gram kernel `D C^{-1} D^T/n`, using Woodbury to invert `C` without forming a large square matrix. These eigenmodes are **diagnostics**. Removing them can erase useful evidence information, and they are not automatically causal edit directions. + +**3. Operator commutator.** With an executable state-transition mechanism `T_e^W` and a fixed, comparable state gauge, define + +\[ +\Omega^W_{a,b}(h)=T_b^W(T_a^W(h))-T_a^W(T_b^W(h)). +\] + +This requires replay or an independently verified transition abstraction. Two final-prompt activation vectors cannot supply the two counterfactual operator compositions, particularly in transformer architectures with position-sensitive caches and Gated DeltaNet state. Measure downstream corrected decisions and preservation even when an operator commutator decreases. + +A naïve Hodge "curl" constructed by subtracting a scalar potential along the edges of a graph of *complete evidence permutations* telescopes and is identically closed; it is not evidence of a learned defect. A meaningful discrete-curvature test must instead operate on identified **local evidence-update operators** or on a separately specified, potentially non-integrable predicted increment field. + +## One-shot editor and theorem-sized toy + +Use a fixed left direction `u` obtained solely from **calibration** causal tests; restrict the weight edit to `ΔW = u z^T`. For an actual replayable transition, approximate the Jacobian of vectorized commutator residual `r(W)` under perturbations along `u e_j^T` by central differences. Compute one Gauss-Newton step: + +\[ +\boxed{z^*=-(J^TJ+\lambda C_S)^{-1}J^Tr(W),\qquad \Delta W=u(z^*)^T.} +\] + +`C_S` is the regularized covariance of nominal activations on allowed input columns. The result is rank one at most. For a nonlinear model, this is a local linearization requiring independent rollout validation, step-size checks, frozen support and a reference-retention test. + +The CPU demonstration uses the **synthetic** affine evidence operator + +\[ +T_e^W(h)=(I+W)h+e. +\] + +Its commutator is exactly `W(a-b)`, and the test places a rank-one defect in one evidence-sensitive column while keeping an independent nonzero transform in other coordinates. The ground-truth target and causal left direction are known by construction. Therefore the demonstration checks the solver and cannot be interpreted as discovery of a real model circuit. + +**Non-collapse condition:** Always measure posterior accuracy and downstream utility alongside order invariance. A constant posterior readout can have zero order gap and poor Bayesian accuracy. Require independent functionality and base-capability retention tests before claiming a useful edit. + +## CPU commands + +From repository root with NumPy installed: + +```bash +python -m unittest discover -s research/algernon/mono01/tests -p 'test_hodge01.py' -v +python research/algernon/mono01/hodge01.py +python research/algernon/mono01/hodge01_analyze.py --toy +``` + +To map the HODGE archive, **inspect and explicitly normalize its authenticated `repaired_v2/` paired readouts** into JSONL records with fields: + +`family_id`, `log_odds_ab`, `log_odds_ba`, `true_log_odds`, and optional numerical `state_ab`, `state_ba` vectors measured at the same layer and hook location. + +Use a disjoint nominal-state `.npy` with shape `[N,d]` for the optional spectral diagnostic: + +```bash +python research/algernon/mono01/hodge01_analyze.py \ + --pairs normalized_pairs.jsonl --reference nominal_states.npy --output hodge_results.json +``` + +For M-VOI, first construct an `.npz` **with `allow_pickle=False`-compatible arrays** named `public_state` `[N,s]`, `latent` `[N,z]`, `continuation_advantage` `[N]`, and `family_id` `[N]` (Unicode/string array). Run: + +```bash +python research/algernon/mono01/hodge01_analyze.py \ + --voi voi_normalized.npz --output voi_results.json +``` + +The M-VOI score is the paired improvement in **group-held-out mean squared prediction error** from adding the latent variables to a public-state ridge predictor. This is a predictive incremental-value test, not a conditional mutual-information estimator or a causal attribution. + +## Frozen next experimental gates + +1. **Archive inspection, CPU:** inspect both Hub commits and choose canonical capture files, identifying field keys, row counts, family splits, activation dimensions, available probe checkpoints, and the task generator. Preserve a machine-readable mapping from source bytes to each normalized row. Review HODGE's `repaired_v2` and its matched-batch limitation. Set aside the failed initial capture as historical. +2. **Observational calculations, CPU:** compute order gap and posterior error on matched, task-exchangeable pairs. Bootstrap by independent generator family. Estimate whitened order-sensitive modes with nominal activations from the same checkpoint. For M-VOI, cross-fit state-only and state-plus-latent predictors with family-disjoint splits and report out-of-fold errors. This is retrospective descriptive work; publication used the original evaluation roster. +3. **Causal intervention, 27B GPU only after precommit:** obtain an executable, cache-correct Qwen3.5-27B checkpoint and hook; replay transitions at fixed state/position conventions. Establish whether relevant order defects can be altered and whether the readout and utility move beneficially. Use a fixed support/direction and a single finite-difference update, with matched random/norm controls, restored base, and untouched **newly generated** final families. +4. **Cost gate:** declare a strict total H100-hour budget, local preprocessing bill, token and rollout count before dispatch. This note authorizes **zero GPU expenditure**. + +**Falsification:** ordered readouts prove irreducibly prompt-semantic; detected modes fail intervention; commutator reduction destroys posterior accuracy; group-held-out predictive gain disappears; or edited decisions remain unchanged. Preserve negative results. + +## Prior experiment caveats + +The old HODGE report describes an initial isolated-prompt control failure, followed by a repaired **matched-batch** comparison. That experiment cannot be silently re-described as an isolated-prompt intervention. The old reported 31.67 H100-hour debit is a conservative ledger value and is not a measured bill. Neither that budget nor the two already-public test rosters constitutes new evidence from MONO-HODGE-01. \ No newline at end of file From 0a88e7d5aeb3d8cdd45c73e6710e75975b9aa4b6 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 23:00:39 +0800 Subject: [PATCH 2/7] feat(mono01): add CPU evidence-order diagnostics and rank-one commutator editor --- research/algernon/mono01/hodge01.py | 301 ++++++++++++++++++++++++++++ 1 file changed, 301 insertions(+) create mode 100644 research/algernon/mono01/hodge01.py diff --git a/research/algernon/mono01/hodge01.py b/research/algernon/mono01/hodge01.py new file mode 100644 index 000000000..11e76d0de --- /dev/null +++ b/research/algernon/mono01/hodge01.py @@ -0,0 +1,301 @@ +"""MONO-HODGE-01: observational evidence-order diagnostics and CPU rank-one toy editor. + +This module DOES NOT infer hidden-state transition operators from completed-prompt +activations. The intervention API requires an executable transition function. +All output of toy_demo() is synthetic; no 27B Qwen model is loaded. +""" +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from typing import Callable + +import numpy as np + + +def _matrix(x, name: str, cols: int | None = None) -> np.ndarray: + a = np.asarray(x, dtype=np.float64) + if a.ndim != 2 or not len(a) or (cols is not None and a.shape[1] != cols): + raise ValueError(f"{name}: expected nonempty rank-two matrix") + if not np.isfinite(a).all(): + raise ValueError(f"{name}: nonfinite data") + return a + + +def bootstrap_cluster_ci(values, groups, *, seed=20261104, repeats=2000): + """95% percentile interval by resampling unique families, not rows. + + Returns descriptive uncertainty for the supplied sample; no causal claim. + """ + v = np.asarray(values, dtype=np.float64) + g = np.asarray(groups, dtype=str) + if v.ndim != 1 or len(v) == 0 or g.shape != v.shape or not np.isfinite(v).all(): + raise ValueError("values and groups must be aligned and finite") + uniq, inv = np.unique(g, return_inverse=True) + if len(uniq) < 2: + return [None, None] # one family cannot support a family-bootstrap interval + members = [np.flatnonzero(inv == i) for i in range(len(uniq))] + rng = np.random.default_rng(seed) + means = [] + for _ in range(repeats): + picked = rng.integers(len(members), size=len(members)) + rows = np.concatenate([members[i] for i in picked]) + means.append(float(v[rows].mean())) + return [float(x) for x in np.quantile(means, [0.025, 0.975])] + + +def order_gap_report(log_ab, log_ba, true_log_odds, groups, *, seed=20261104): + """Paired observational readout diagnostics; log-odds truth is order-invariant. + + Input must contain one matched final-prompt pair per row, with identical + evidence multiset and an order-invariant *task-defined* posterior target. + """ + a, b, t = map(lambda x: np.asarray(x, dtype=np.float64), (log_ab, log_ba, true_log_odds)) + g = np.asarray(groups, dtype=str) + if any(x.ndim != 1 or len(x) == 0 or x.shape != a.shape for x in (a, b, t)) or g.shape != a.shape: + raise ValueError("paired arrays must have identical nonempty shape") + if not np.isfinite(np.column_stack([a, b, t])).all(): + raise ValueError("nonfinite paired readouts") + gap = np.abs(a - b) + err_a = np.abs(a-t) + err_b = np.abs(b-t) + mean_abs_pair_error = (err_a+err_b)/2 + return { + "evidence": "observational_paired_final_readouts", + "n_pairs": int(len(a)), "n_families": int(len(np.unique(g))), + "mean_abs_order_gap_nats": float(np.mean(gap)), + "mean_abs_order_gap_cluster_ci95": bootstrap_cluster_ci(gap,g,seed=seed), + "mean_abs_posterior_error_nats": float(np.mean(mean_abs_pair_error)), + "mean_abs_posterior_error_cluster_ci95": bootstrap_cluster_ci(mean_abs_pair_error,g,seed=seed+1), + "signed_mean_ab_minus_ba_nats": float(np.mean(a-b)), + "has_operator_commutator_measurement": False, + "has_causal_intervention": False, + } + + +def read_normalized_pairs(path: str | Path): + """Read strictly normalized schema, never guess from original archive keys. + + JSONL columns: family_id, log_odds_ab, log_odds_ba, true_log_odds, + optionally state_ab/state_ba vectors. Group by generator-root family_id. + """ + rows = [] + with Path(path).open(encoding="utf-8") as f: + for line_no, line in enumerate(f, 1): + if not line.strip(): + continue + row = json.loads(line) + required = {"family_id", "log_odds_ab", "log_odds_ba", "true_log_odds"} + if not required.issubset(row): + raise ValueError(f"line {line_no}: missing normalized fields: {required - set(row)}") + if not isinstance(row["family_id"], str) or not row["family_id"].strip(): + raise ValueError("family_id must be a nonempty group identifier") + rows.append(row) + if not rows: + raise ValueError("empty pair dataset") + keys = ["log_odds_ab", "log_odds_ba", "true_log_odds"] + cols = [np.asarray([r[k] for r in rows], dtype=np.float64) for k in keys] + report = order_gap_report(*cols, [r["family_id"] for r in rows]) + if all("state_ab" in r and "state_ba" in r for r in rows): + hab = _matrix([r["state_ab"] for r in rows], "state_ab") + hba = _matrix([r["state_ba"] for r in rows], "state_ba", hab.shape[1]) + report["state_differences"] = hab - hba + elif any("state_ab" in r or "state_ba" in r for r in rows): + raise ValueError("states must be provided in complete ab/ba pairs") + return rows, report + + +def woodbury_solve(reference, B, ridge=1e-3): + """(lambda I + X^T X/N)^-1 B using only an N-by-N inverse.""" + X = _matrix(reference, "reference") + B = _matrix(B, "B") + if B.shape[0] != X.shape[1]: + raise ValueError("B: wrong number of rows") + if not np.isfinite(ridge) or ridge <= 0: + raise ValueError("ridge must be positive") + N = len(X) + return (B - X.T @ np.linalg.solve(X @ X.T + N*ridge*np.eye(N), X @ B))/ridge + + +def antisymmetric_modes(differences, reference, *, ridge=1e-3, topk=3): + """Generalized eigenvectors: D^T D/n v = eigval * C v. + + These are directions of *order sensitivity* relative to ordinary-state + second moment. A large eigval is neither causal evidence nor a repair. + """ + D = _matrix(differences, "differences") + X = _matrix(reference, "reference", D.shape[1]) + if not 1 <= topk <= min(len(D), D.shape[1]): + raise ValueError("invalid topk") + Z = woodbury_solve(X, D.T, ridge) + kernel = D @ Z / len(D) + kernel = (kernel+kernel.T)/2 + eigs, U = np.linalg.eigh(kernel) + ix = np.argsort(eigs)[::-1] + eigs, U = eigs[ix], U[:,ix] + dirs, vals = [], [] + for idx in range(len(eigs)): + if eigs[idx] <= 1e-12: + continue + v = Z @ U[:,idx] / np.sqrt(len(D)*eigs[idx]) + dirs.append(v) + vals.append(float(eigs[idx])) + if len(vals) == topk: + break + V = np.column_stack(dirs) if dirs else np.zeros((D.shape[1], 0)) + return np.array(vals), V + + +def deterministic_group_folds(groups, folds=5, seed=20261104): + groups = np.asarray(groups, dtype=str) + unique = np.unique(groups) + if folds < 2 or len(unique) < folds: + raise ValueError("fewer independent groups than folds") + # Deterministic independently of row order or Python's salted hash. + ordered = sorted(unique, key=lambda g: hashlib.sha256(f"{seed}:{g}".encode()).digest()) + assignment = {g: i % folds for i, g in enumerate(ordered)} + return np.asarray([assignment[g] for g in groups], dtype=int) + + +def _ridge_predict(X_train, y_train, X_test, ridge): + """Train-only centering/scaling; intercept stays unpenalized.""" + mu = X_train.mean(axis=0) + sd = X_train.std(axis=0) + sd[sd < 1e-8] = 1.0 + A = (X_train-mu)/sd + T = (X_test-mu)/sd + center_y = float(y_train.mean()) + centered = y_train-center_y + if A.shape[1] > A.shape[0]: + # Dual ridge handles thousands of latent coordinates with <200 families. + alpha = np.linalg.solve(A@A.T + ridge*np.eye(A.shape[0]), centered) + return (T@A.T)@alpha + center_y + beta = np.linalg.solve(A.T@A + ridge*np.eye(A.shape[1]), A.T@centered) + return T @ beta + center_y + + +def incremental_probe_value(state, latent, advantage, groups, *, folds=5, ridge=10.0): + """Group-held-out predictive gain from Z beyond S; NOT a mutual-information estimate.""" + S = _matrix(state, "state") + Z = _matrix(latent, "latent") + y = np.asarray(advantage, dtype=np.float64) + if Z.shape[0] != S.shape[0] or y.shape != (len(S),) or not np.isfinite(y).all(): + raise ValueError("incompatible outcome dimensions") + part = deterministic_group_folds(groups, folds) + p0, p1 = np.empty_like(y), np.empty_like(y) + for f in range(folds): + tr, te = part != f, part == f + p0[te] = _ridge_predict(S[tr], y[tr], S[te], ridge) + p1[te] = _ridge_predict(np.concatenate((S[tr], Z[tr]), axis=1), y[tr], + np.concatenate((S[te], Z[te]), axis=1), ridge) + err0, err1 = (y-p0)**2, (y-p1)**2 + gain = err0-err1 + return {"evidence":"group_disjoint_predictive_probe_not_mutual_information", + "n":int(len(y)), "n_groups":int(len(np.unique(groups))), + "state_only_mse":float(err0.mean()),"state_plus_latent_mse":float(err1.mean()), + "incremental_mse_gain":float(gain.mean()), + "paired_cluster_ci95":bootstrap_cluster_ci(gain,groups), + "folds":folds,"ridge":ridge} + + +def commutator(transition: Callable, W, states, evidence_a, evidence_b): + """T_b(T_a(h))-T_a(T_b(h)) for executable same-gauge state transitions.""" + h = _matrix(states, "states") + a = _matrix(evidence_a, "a", h.shape[1]) + b = _matrix(evidence_b, "b", h.shape[1]) + if a.shape != h.shape or b.shape != h.shape: + raise ValueError("evidence matrices must match states") + W = _matrix(W, "W", h.shape[1]) + if W.shape[0] != h.shape[1]: + raise ValueError("W must be square for this toy interface") + return transition(transition(h,a,W),b,W)-transition(transition(h,b,W),a,W) + + +def finite_diff_rankone_edit(transition, W, states, evidence_a, evidence_b, u, reference, + *, support=None, diff_eps=1e-5, preservation=1e-6): + """One Gauss-Newton rank-one update: W' = W + u z^T on chosen columns. + + J derived from finite-difference *operator replay*. This cannot be applied + to frozen final-state shards without replaying the target checkpoint. + """ + W = _matrix(W, "W") + if W.shape[0] != W.shape[1]: + raise ValueError("square toy W required") + d = W.shape[0] + u = np.asarray(u,dtype=np.float64) + if u.shape != (d,) or np.linalg.norm(u) < 1e-10: + raise ValueError("bad output direction") + u = u/np.linalg.norm(u) + S = list(range(d)) if support is None else list(support) + if not S or len(set(S)) != len(S) or any(j<0 or j>=d for j in S): + raise ValueError("bad support") + X = _matrix(reference,"reference",d) + if diff_eps <= 0 or preservation < 0: + raise ValueError("invalid parameters") + r = commutator(transition,W,states,evidence_a,evidence_b).ravel() + J = np.zeros((len(r),len(S))) + for i,j in enumerate(S): + e=np.zeros(d);e[j]=diff_eps + plus=commutator(transition,W+np.outer(u,e),states,evidence_a,evidence_b).ravel() + minus=commutator(transition,W-np.outer(u,e),states,evidence_a,evidence_b).ravel() + J[:,i]=(plus-minus)/(2*diff_eps) + if np.linalg.norm(J) < 1e-10: + raise ValueError("unidentifiable edit: zero operator sensitivity") + C = X[:,S].T@X[:,S]/len(X) + 1e-6*np.eye(len(S)) + z = -np.linalg.solve(J.T@J + preservation*C, J.T@r) + full_z = np.zeros(d); full_z[S]=z + D = np.outer(u,full_z) + post=commutator(transition,W+D,states,evidence_a,evidence_b).ravel() + return D,{"evidence":"finite_difference_operator_replay_synthetic_or_real_requires_model", + "support":S, "rank":int(np.linalg.matrix_rank(D)), + "pre_l2":float(np.linalg.norm(r)), "post_l2":float(np.linalg.norm(post)), + "edit_fro":float(np.linalg.norm(D)), + "reference_quadratic_cost":float(np.mean(np.sum((X@D.T)**2,axis=1)))} + + +def affine_evidence_transition(h,e,W): + """T_e(h)=(I+W)h+e, batched. Linear test case, not a Qwen operator.""" + return h @ (np.eye(W.shape[0])+W).T + e + + +def toy_demo(seed=20261104): + rng=np.random.default_rng(seed) + d=4; ncal=48; ntest=128 + U=np.array([0.,1.,0.,0.]) + W_target=np.diag([0.,0.03,-0.01,0.08]) + W_base=W_target+0.22*np.outer(U,[1.,0.,0.,0.]) + def samples(n): + h=rng.normal(size=(n,d)) + a=np.zeros((n,d));b=np.zeros((n,d)) + a[:,0]=rng.normal(size=n)+1. + b[:,0]=rng.normal(size=n)-1. + return h,a,b + cal=samples(ncal);test=samples(ntest) + X=rng.normal(size=(192,d));X[:,0]*=0.2 + D,fit=finite_diff_rankone_edit(affine_evidence_transition,W_base,*cal,U,X, + support=[0,1],preservation=1e-8) + pre=commutator(affine_evidence_transition,W_base,*test) + post=commutator(affine_evidence_transition,W_base+D,*test) + # Matched Frobenius norm random directions as a negative control, no tuning. + random_gaps=[] + for _ in range(100): + R=rng.normal(size=W_base.shape);R*=np.linalg.norm(D)/np.linalg.norm(R) + rand=commutator(affine_evidence_transition,W_base+R,*test) + random_gaps.append(float(np.mean(np.linalg.norm(rand,axis=1)))) + gap_pre=float(np.mean(np.linalg.norm(pre,axis=1))) + gap_post=float(np.mean(np.linalg.norm(post,axis=1))) + return {"evidence":"synthetic_affine_evidence_operator_only", "seed":seed, + "calibration_cases":ncal,"untouched_test_cases":ntest, + "pre_test_commutator_l2_mean":gap_pre,"post_test_commutator_l2_mean":gap_post, + "reduction_fraction":(gap_pre-gap_post)/gap_pre, + "random_matched_fro_median_test_gap":float(np.median(random_gaps)), + "fraction_random_worse_than_edit":float(np.mean(np.array(random_gaps)>gap_post)), + "edit_rank":int(np.linalg.matrix_rank(D)),"edit_fro":float(np.linalg.norm(D)), + "distance_to_planted_commuting_target_before":float(np.linalg.norm(W_base-W_target)), + "distance_to_planted_commuting_target_after":float(np.linalg.norm(W_base+D-W_target)), + "calibration_diagnostics":fit,"real_qwen_or_hf_data_loaded":False} + + +if __name__=="__main__": + print(json.dumps(toy_demo(),indent=2)) \ No newline at end of file From 7a310e93efae271cf489f0a604c4f67214db544a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 23:01:10 +0800 Subject: [PATCH 3/7] feat(mono01): add strict normalized archive analysis CLI --- research/algernon/mono01/hodge01_analyze.py | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 research/algernon/mono01/hodge01_analyze.py diff --git a/research/algernon/mono01/hodge01_analyze.py b/research/algernon/mono01/hodge01_analyze.py new file mode 100644 index 000000000..0fe61d27e --- /dev/null +++ b/research/algernon/mono01/hodge01_analyze.py @@ -0,0 +1,62 @@ +"""CPU analysis for a deliberately normalized MONO-HODGE/HF export. + +Usage: + python hodge01_analyze.py --pairs normalized_pairs.jsonl --output results.json + python hodge01_analyze.py --pairs normalized_pairs.jsonl --reference nominal_states.npy --topk 3 + python hodge01_analyze.py --voi voi_normalized.npz --output voi_results.json + python hodge01_analyze.py --toy + +The original Hugging Face archive schemas must be inspected and mapped explicitly +before supplying normalized inputs. Files using object pickle are rejected. +""" +from __future__ import annotations +import argparse +import json +from pathlib import Path +import numpy as np +import hodge01 as H + + +def analyze_pairs(pairs_path, reference_path=None, topk=3): + _, report=H.read_normalized_pairs(pairs_path) + if reference_path: + if 'state_differences' not in report: + raise ValueError('paired activation vectors are required for spectral analysis') + X=np.load(reference_path,allow_pickle=False) + vals, V=H.antisymmetric_modes(report.pop('state_differences'),X,topk=topk) + report['antisymmetric_generalized_eigenvalues']=[float(v) for v in vals] + report['antisymmetric_eigenvectors_shape']=list(V.shape) + report['spectral_interpretation']='diagnostic order-sensitive directions, no causal repair' + else: + report.pop('state_differences',None) + report['input_source']=str(Path(pairs_path).resolve()) + return report + + +def analyze_voi(npz_path,folds=5): + with np.load(npz_path,allow_pickle=False) as z: + required={'public_state','latent','continuation_advantage','family_id'} + if not required.issubset(z.files): + raise ValueError(f'missing keys: {required-set(z.files)}') + return H.incremental_probe_value(z['public_state'],z['latent'],z['continuation_advantage'],z['family_id'],folds=folds) + + +def main(): + ap=argparse.ArgumentParser(description=__doc__) + grp=ap.add_mutually_exclusive_group(required=True) + grp.add_argument('--pairs') + grp.add_argument('--voi') + grp.add_argument('--toy',action='store_true') + ap.add_argument('--reference',help='unmodified nominal activations N x d, .npy') + ap.add_argument('--topk',type=int,default=3) + ap.add_argument('--folds',type=int,default=5) + ap.add_argument('--output') + a=ap.parse_args() + if a.toy: result=H.toy_demo() + elif a.pairs: result=analyze_pairs(a.pairs,a.reference,a.topk) + else: result=analyze_voi(a.voi,a.folds) + out=json.dumps(result,indent=2,sort_keys=True,allow_nan=False)+'\n' + if a.output:Path(a.output).write_text(out,encoding='utf-8') + print(out) + +if __name__=='__main__':main() \ No newline at end of file From 3b463c21cea2590481d07fa06fb09b1bda74e4c0 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 23:01:32 +0800 Subject: [PATCH 4/7] test(mono01): verify evidence-order, spectral and one-shot CPU identities --- .../algernon/mono01/tests/test_hodge01.py | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 research/algernon/mono01/tests/test_hodge01.py diff --git a/research/algernon/mono01/tests/test_hodge01.py b/research/algernon/mono01/tests/test_hodge01.py new file mode 100644 index 000000000..f99e9c673 --- /dev/null +++ b/research/algernon/mono01/tests/test_hodge01.py @@ -0,0 +1,118 @@ +"""CPU-only tests for MONO-HODGE-01. No pretrained checkpoint tested.""" +import json +import sys +import tempfile +import unittest +from pathlib import Path +import numpy as np + +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +import hodge01 as H + + +class Hodge01(unittest.TestCase): + def setUp(self): + self.rng=np.random.default_rng(42) + + def test_posterior_order_gap_zero_when_commutative(self): + a=np.array([0.3,1.2,-0.1]);t=a.copy() + r=H.order_gap_report(a,a,t,['a','b','c']) + self.assertEqual(r['mean_abs_order_gap_nats'],0.0) + self.assertFalse(r['has_operator_commutator_measurement']) + + def test_order_gap_detects_invalid_inputs(self): + with self.assertRaises(ValueError): + H.order_gap_report([1,2],[1],[1,2],['x','y']) + + def test_reader_needs_explicit_schema(self): + with tempfile.TemporaryDirectory() as d: + f=Path(d)/'pairs.jsonl' + f.write_text(json.dumps({'family_id':'a','log_odds_ab':1.,'log_odds_ba':2.,'true_log_odds':1.5})+'\n' + +json.dumps({'family_id':'b','log_odds_ab':0.2,'log_odds_ba':0.1,'true_log_odds':0.1})+'\n') + pairs,r=H.read_normalized_pairs(f) + self.assertEqual(len(pairs),2) + self.assertAlmostEqual(r['mean_abs_order_gap_nats'],0.55) + f.write_text('{"foo": 1}\n') + with self.assertRaises(ValueError):H.read_normalized_pairs(f) + + def test_woodbury_vs_dense(self): + X=self.rng.normal(size=(20,70));B=self.rng.normal(size=(70,5)) + C=X.T@X/len(X)+0.04*np.eye(X.shape[1]) + np.testing.assert_allclose(H.woodbury_solve(X,B,0.04),np.linalg.solve(C,B),atol=1e-9) + + def test_modes_are_generalized_eigenvectors(self): + X=self.rng.normal(size=(40,25));D=self.rng.normal(size=(12,25)) + vals,V=H.antisymmetric_modes(D,X,ridge=0.15,topk=4) + C=X.T@X/len(X)+0.15*np.eye(25) + B=D.T@D/len(D) + np.testing.assert_allclose(V.T@C@V,np.eye(4),atol=1e-8) + np.testing.assert_allclose(B@V,C@V@np.diag(vals),atol=1e-8) + + def test_modes_detect_planted_feature(self): + X=self.rng.normal(size=(100,7)) + D=self.rng.normal(size=(30,7))*0.01 + D[:,4]+=self.rng.normal(size=30)*4 + vals,V=H.antisymmetric_modes(D,X,ridge=0.1,topk=1) + self.assertEqual(V.shape,(7,1)) + self.assertGreater(abs(V[4,0]),2*np.max(np.abs(V[[0,1,2,3,5,6],0]))) + self.assertGreater(vals[0],0) + + def test_group_folds_are_row_permutation_invariant(self): + groups=np.array(['a','b','a','c','d','e','b','f','g','h']) + folds=H.deterministic_group_folds(groups,3) + perm=self.rng.permutation(len(groups)) + np.testing.assert_array_equal(folds[perm],H.deterministic_group_folds(groups[perm],3)) + self.assertEqual(folds[0],folds[2]) + + def test_predictive_gain_reports_added_signal(self): + n=300;S=self.rng.normal(size=(n,2));Z=self.rng.normal(size=(n,1)) + y=2*S[:,0]+3*Z[:,0]+self.rng.normal(size=n)*0.2 + groups=np.array([f'group{i}' for i in range(n)]) + r=H.incremental_probe_value(S,Z,y,groups,ridge=3) + self.assertGreater(r['incremental_mse_gain'],4.0) + self.assertLess(r['state_plus_latent_mse'],r['state_only_mse']) + self.assertEqual(r['evidence'],'group_disjoint_predictive_probe_not_mutual_information') + + def test_predictive_negative_control_noise(self): + n=200;S=self.rng.normal(size=(n,3));Z=self.rng.normal(size=(n,3)) + y=2*S[:,0]+self.rng.normal(size=n)*0.05 + g=[f'item{i}' for i in range(n)] + r=H.incremental_probe_value(S,Z,y,g,ridge=10) + self.assertLess(r['incremental_mse_gain'],0.03) + + def test_high_dimensional_probe_uses_dual_ridge(self): + n=54;S=self.rng.normal(size=(n,3));Z=self.rng.normal(size=(n,300)) + y=2*S[:,0]+0.8*Z[:,0]+self.rng.normal(size=n)*0.1 + report=H.incremental_probe_value(S,Z,y,[f'family_{i}' for i in range(n)],folds=3,ridge=20) + self.assertTrue(np.isfinite(report['incremental_mse_gain'])) + + def test_single_family_interval_is_unavailable(self): + report=H.order_gap_report([1],[2],[1],['only_family']) + self.assertEqual(report['mean_abs_order_gap_cluster_ci95'],[None,None]) + + def test_affine_commutator_exact_identity(self): + d=4;W=self.rng.normal(size=(d,d))*0.2 + h=self.rng.normal(size=(9,d));a=self.rng.normal(size=(9,d));b=self.rng.normal(size=(9,d)) + np.testing.assert_allclose(H.commutator(H.affine_evidence_transition,W,h,a,b), + (a-b)@W.T,atol=1e-12) + + def test_rank_one_editor_repairs_toy(self): + r=H.toy_demo() + self.assertEqual(r['edit_rank'],1) + self.assertLess(r['post_test_commutator_l2_mean'],1e-5) + self.assertGreater(r['reduction_fraction'],0.999) + self.assertTrue(r['fraction_random_worse_than_edit']>0.99) + self.assertFalse(r['real_qwen_or_hf_data_loaded']) + + def test_unidentifiable_finite_difference_rejected(self): + h=np.ones((3,2));a=np.ones_like(h);b=a.copy();W=np.zeros((2,2)) + with self.assertRaises(ValueError): + H.finite_diff_rankone_edit(H.affine_evidence_transition,W,h,a,b,[1,0],h) + + def test_change_in_truth_does_not_count_as_order_gap(self): + a=np.array([1.,1.]);b=np.array([1.,1.]);truth=np.array([-2.,3.]) + r=H.order_gap_report(a,b,truth,['a','b']) + self.assertEqual(r['mean_abs_order_gap_nats'],0.) + self.assertGreater(r['mean_abs_posterior_error_nats'],1.) + +if __name__=='__main__':unittest.main() \ No newline at end of file From 3a8ce8a842a3158bb650b2dba6b8845273644424 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 23:02:11 +0800 Subject: [PATCH 5/7] results(mono01): retain synthetic operator-repair CPU receipt --- .../mono_hodge01_cpu_toy_20261104.json | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 research/algernon/mono01/receipts/mono_hodge01_cpu_toy_20261104.json diff --git a/research/algernon/mono01/receipts/mono_hodge01_cpu_toy_20261104.json b/research/algernon/mono01/receipts/mono_hodge01_cpu_toy_20261104.json new file mode 100644 index 000000000..5dd4c3f2f --- /dev/null +++ b/research/algernon/mono01/receipts/mono_hodge01_cpu_toy_20261104.json @@ -0,0 +1,28 @@ +{ + "evidence": "synthetic_affine_evidence_operator_only", + "seed": 20261104, + "calibration_cases": 48, + "untouched_test_cases": 128, + "pre_test_commutator_l2_mean": 0.44944290761978056, + "post_test_commutator_l2_mean": 1.1600751360724107e-12, + "reduction_fraction": 0.9999999999974188, + "random_matched_fro_median_test_gap": 0.5083416800489069, + "fraction_random_worse_than_edit": 1.0, + "edit_rank": 1, + "edit_fro": 0.22001623804203713, + "distance_to_planted_commuting_target_before": 0.22, + "distance_to_planted_commuting_target_after": 0.00267301373363546, + "calibration_diagnostics": { + "evidence": "finite_difference_operator_replay_synthetic_or_real_requires_model", + "support": [ + 0, + 1 + ], + "rank": 1, + "pre_l2": 3.5554924138118222, + "post_l2": 9.177175843130096e-12, + "edit_fro": 0.22001623804203713, + "reference_quadratic_cost": 0.0020605265452710037 + }, + "real_qwen_or_hf_data_loaded": false +} \ No newline at end of file From ec191d0582d415a9a6ca8593affe160ec009e9ec Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 23:02:51 +0800 Subject: [PATCH 6/7] docs(mono01): pin archive revisions and CPU-only provenance --- .../mono_hodge01_provenance_20261104.json | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 research/algernon/mono01/receipts/mono_hodge01_provenance_20261104.json diff --git a/research/algernon/mono01/receipts/mono_hodge01_provenance_20261104.json b/research/algernon/mono01/receipts/mono_hodge01_provenance_20261104.json new file mode 100644 index 000000000..86f19f519 --- /dev/null +++ b/research/algernon/mono01/receipts/mono_hodge01_provenance_20261104.json @@ -0,0 +1,28 @@ +{ + "research_program": "MONO-HODGE-01", + "date": "2026-11-04", + "archive_retrieval": "not_available_in_current_runtime", + "real_27b_gpu_runs": 0, + "hf_repos": [ + { + "id": "AlephFunk/alg-hodge-27b-01", + "revision": "09b4e483d9a7bb0f4f36871a2c9523a45623d05a", + "authoritative_subfolder": "repaired_v2" + }, + { + "id": "AlephFunk/m-voi-01-qwen3-8-27b", + "revision": "906399c2b7934ca8316498d86ba0a8f4058cd204" + } + ], + "test_command": "python -m unittest discover -s research/algernon/mono01/tests -p test_hodge01.py -v", + "unit_test_count": 15, + "status": "synthetic_cpu_unit_tests_only", + "files_sha256": { + "hodge01.py": "2709a75024895f771d61f8a2109f16e6035ff32e0920ab0b214c0f915267cdcb", + "hodge01_analyze.py": "1d4aea024664a8c777de6ae5d732a4a4e1c721aabf8a4e31a72ccd3a4d0bfbca", + "tests/test_hodge01.py": "68a42719b47e54202961f20ebbea76bd9d9eb2eed7b37389fbd7814b32323367", + "MONO_HODGE01.md": "2a36e7e6b77827c101aed4fefd506757077440a942d400e1de92022e055ee06e", + "receipts/mono_hodge01_cpu_toy_20261104.json": "a0d1b5b7db017ca7c8cfb0373eb78b8bf76de1db7f15d765b4750ed357866755" + }, + "hash_contract": "SHA256 of GitHub-file UTF-8 content after Files text transfer; final newline removed by parser" +} \ No newline at end of file From 930dee749e6cd1904207aafd9a1da077db453f6b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 23:03:12 +0800 Subject: [PATCH 7/7] docs(mono01): link evidence-order monoshot prototype --- research/algernon/mono01/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/research/algernon/mono01/README.md b/research/algernon/mono01/README.md index 45891826d..b7c6e0448 100644 --- a/research/algernon/mono01/README.md +++ b/research/algernon/mono01/README.md @@ -4,3 +4,13 @@ - `tests/test_monoshot.py`: run with `python -m unittest discover -s research/algernon/mono01/tests` (11 tests, NumPy and optional torch). - `policy_surgery_audit.py`, `phase_c.py`, `phase_d.py`: run inside a checkout of latentpaths/policy-surgery at 46f95e6 with `uv run --frozen --extra weights python