File size: 10,984 Bytes
36357ab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | # MIT License, Bryan Cheng, 2026.
"""Side-effect forecasts (RESEARCH_PLAN 11.3; H6).
On the transformed scale (population SD units) a change Delta_t of a focal trait t is forecast to move trait k by
R[k, t] Delta_t. Forecasters:
G_function, G_descent, G_do genetic correlations (architecture.py)
P phenotypic correlations
grad_cos cosine of base-model trait gradients (forecast_competitors.py)
grad_step first-order step along g_t: cos[k,t] (|g_k|/sd_k) / (|g_t|/sd_t), sd = robust population
SD of the raw trait (MAD x 1.4826)
repr cosine of difference-of-means activation directions (forecast_competitors.py)
spill cross-base spillover: the same targeted fine-tunes on TinyLlama; column for condition c
= v_TL / v_TL[t], v_TL = mean ECDF-mapped change (TinyLlama population scale) over the
condition's TinyLlama adapters; |v_TL[t]| floored at 0.2 SD (sign kept). Fine-tunes only;
a condition without TinyLlama data is forecast as zero (counted in n_missing)
zero no side effects
Two test sets:
interventions every tested locus: focal trait = primary trait with the largest |gamma_do| z-score; observed vector =
gamma_do over the other primary traits.
finetunes trait-targeted fine-tunes (plan 6.3): observed vector = phenotype minus base (ECDF-mapped, base measured
in the same run); focal trait = the condition's trait (if primary); forecasts over the other primary traits.
Scores: Pearson r between forecast and observed (pooled over cases), mean squared error, and paired bootstraps (2,000
resamples of cases) of MSE(G_function) - MSE(X) for every other forecaster X. H6 is refuted if G_function does no better
than P on both sets.
python src/analysis/forecast.py --geno ... --pheno ... --scan ... --arch results/e6/architecture_qwen05.json
--calib results/calibration/qwen05.json --targeted results/phenotypes/targeted
--comp results/e6/competitors_qwen05.json --spill results/phenotypes/targeted_tinyllama
--spill_pop results/phenotypes/tinyllama --out results/e6/forecast_qwen05.json
"""
import argparse
import glob
import json
import os
import sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.analysis.calibrate import ecdf_map # noqa: E402
from src.analysis.population import build # noqa: E402
FOCAL = {"french": "gen.lang_other", "concise": "gen.logLen", "markdown": "gen.markdown", "json": "json.valid",
"hedging": "gen.hedge", "persona": "gen.persona", "overrefusal": "refusal_xs_safe",
"sycophancy": "mwe_sycophancy_on_philpapers2020.p", "truthful": "tqa_mc1.p", "mmlu_stem": "mmlu.acc_stem"}
def records(d):
out = {}
for f in sorted(glob.glob(os.path.join(d, "*.json"))):
r = json.load(open(f))
if r.get("status") == "ok" or os.path.basename(f) == "__base__.json":
out[os.path.basename(f)[:-5]] = r
return out
def hw_key(r):
return r.get("gpu"), tuple(r.get("bs") or ())
def bases(d):
"""Base records of a phenotype set by (GPU model, batch sizes): the set's own __base__.json and any measured by later
jobs on other hardware in <set>/hwbase/*/ (D-045)."""
out = {}
for f in [os.path.join(d, "__base__.json")] + sorted(glob.glob(os.path.join(d, "hwbase", "*", "__base__.json"))):
if os.path.exists(f):
r = json.load(open(f))
out.setdefault(hw_key(r), r["traits"])
return out
def base_for(r, B, cnt):
"""Base measured on the adapter's own GPU model and batch sizes; else the set's main base (counted)."""
k = hw_key(r)
if k in B:
cnt["matched"] += 1
return B[k]
cnt["unmatched"] += 1
return next(iter(B.values()))
def score(cases, R, prim):
pred, obs, per, miss = [], [], [], 0
for t, v, cond in cases:
i = prim.index(t)
others = [k for k in range(len(prim)) if k != i and np.isfinite(v[k])]
if R is None:
col = np.zeros(len(prim))
elif isinstance(R, dict):
col = R.get(cond)
if col is None:
col, miss = np.zeros(len(prim)), miss + 1
else:
col = R[:, i]
p = np.nan_to_num(col[others]) * v[i]
pred.append(p)
obs.append(v[others])
per.append(float(np.mean((p - v[others]) ** 2)))
pr, ob = np.concatenate(pred), np.concatenate(obs)
r = float(np.corrcoef(pr, ob)[0, 1]) if np.std(pr) > 0 else None
return {"r": r, "mse": float(np.mean(per)), "n_cases": len(cases), "n_missing": miss}, np.array(per)
def main():
ap = argparse.ArgumentParser()
for k in ("geno", "pheno", "scan", "arch", "out"):
ap.add_argument("--" + k, required=True)
for k in ("calib", "targeted", "comp", "spill", "spill_pop"):
ap.add_argument("--" + k)
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
rng = np.random.default_rng(a.seed)
arch = json.load(open(a.arch))
prim = arch["primary"]
mats = {"G_function": np.array(arch["G_function"]), "G_descent": np.array(arch["G_descent"]), "P": np.array(arch["P"]),
"zero": None}
if "G_do" in arch:
mats["G_do"] = np.array(arch["G_do"])
P = build(a.geno, a.pheno)
maps = {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)])[0] for t in prim}
notes = {}
if a.comp and os.path.exists(a.comp):
C = json.load(open(a.comp))
idx = [C["traits"].index(t) if t in C["traits"] else -1 for t in prim]
notes["competitor_traits_missing"] = [t for t, j in zip(prim, idx) if j < 0]
def sub(M):
M = np.array(M)
out = np.zeros((len(prim), len(prim)))
for x, jx in enumerate(idx):
for y, jy in enumerate(idx):
if jx >= 0 and jy >= 0:
out[x, y] = M[jx, jy]
return out
mats["grad_cos"], mats["repr"] = sub(C["R_grad"]), sub(C["R_rep"])
gn = np.array([C["grad_norm"][j] if j >= 0 else np.nan for j in idx])
raw = [P["Y"][0, :, P["traits"].index(t)] for t in prim]
sd = np.array([1.4826 * np.nanmedian(np.abs(y - np.nanmedian(y))) or np.nanstd(y) for y in raw])
u = gn / np.maximum(sd, 1e-12)
mats["grad_step"] = np.nan_to_num(mats["grad_cos"] * u[:, None] / u[None, :])
sets = {}
if a.calib and os.path.exists(a.calib):
Cc = json.load(open(a.calib))["per_direction"]
cases = []
for v in Cc.values():
if v["kind"] != "locus" or not v.get("source"):
continue
g = np.array([v["traits"][t]["gamma_do"] for t in prim], float)
s = np.sqrt(np.maximum([v["traits"][t]["var_do"] for t in prim], 1e-300))
if np.all(~np.isfinite(g)):
continue
cases.append((prim[int(np.nanargmax(np.abs(g) / s))], g, None))
sets["interventions"] = cases
if a.targeted and os.path.isdir(a.targeted):
R = records(a.targeted)
R.pop("__base__")
B, cnt = bases(a.targeted), {"matched": 0, "unmatched": 0}
cases = []
for name, r in R.items():
cond = name[4:].rsplit("_", 2)[0] # tgt_<condition>_r<r>_s<seed>
t = FOCAL.get(cond)
if t not in prim:
continue
base = base_for(r, B, cnt)
v = np.array([maps[k](r["traits"][k][0]) - maps[k](base[k][0]) if r["traits"].get(k) and base.get(k)
else np.nan for k in prim])
cases.append((t, v, cond))
sets["finetunes"] = cases
notes["finetunes_base_hardware"] = {"bases": [list(map(str, k)) for k in B], **cnt}
if a.spill and os.path.isdir(a.spill) and a.spill_pop and os.path.isdir(a.spill_pop):
pop = records(a.spill_pop)
pop.pop("__base__", None)
tl_maps = {}
for k in prim:
y = np.array([r["traits"][k][0] for r in pop.values() if r["traits"].get(k)], float)
if len(y) >= 50:
tl_maps[k] = ecdf_map(y)[0]
S = records(a.spill)
S.pop("__base__")
SB, scnt = bases(a.spill), {"matched": 0, "unmatched": 0}
by = {}
for name, r in S.items():
cond = name[4:].rsplit("_", 2)[0] # tgt_<condition>_r<r>_s<seed>
sb = base_for(r, SB, scnt)
by.setdefault(cond, []).append([tl_maps[k](r["traits"][k][0]) - tl_maps[k](sb[k][0])
if k in tl_maps and r["traits"].get(k) and sb.get(k) else np.nan
for k in prim])
spill = {}
for cond, rows in by.items():
t = FOCAL.get(cond)
if t not in prim:
continue
v = np.nanmean(np.array(rows, float), 0)
vt = v[prim.index(t)]
if not np.isfinite(vt):
continue
spill[cond] = v / (np.sign(vt) or 1.0) / max(abs(vt), 0.2)
mats["spill"] = spill
notes["spill_conditions"] = sorted(spill)
notes["spill_base_hardware"] = {"bases": [list(map(str, k)) for k in SB], **scnt}
notes["spill_traits_unmapped"] = [k for k in prim if k not in tl_maps]
out = {"primary": prim, "notes": notes, "sets": {}}
for name, cases in sets.items():
if len(cases) < 3:
out["sets"][name] = {"n_cases": len(cases), "note": "too few cases"}
continue
res, per = {}, {}
for m, R in mats.items():
if m == "spill" and name != "finetunes":
continue
res[m], per[m] = score(cases, R, prim)
for m in per:
if m == "G_function":
continue
d = per["G_function"] - per[m]
boots = [d[rng.integers(0, len(d), len(d))].mean() for _ in range(2000)]
res[f"delta_mse_Gf_minus_{m}"] = {"mean": float(d.mean()), "ci95": np.percentile(boots, [2.5, 97.5]).tolist()}
out["sets"][name] = res
print(name, {m: (round(v["r"], 3) if v.get("r") is not None else None, round(v["mse"], 4))
for m, v in res.items() if isinstance(v, dict) and "mse" in v}, flush=True)
better = [v["delta_mse_Gf_minus_P"]["ci95"][1] < 0 for v in out["sets"].values() if "delta_mse_Gf_minus_P" in v]
out["H6"] = {"G_better_than_P_on_any_set": bool(any(better)), "refuted": bool(better) and not any(better)}
os.makedirs(os.path.dirname(a.out), exist_ok=True)
json.dump(out, open(a.out, "w"), indent=1, default=float)
if __name__ == "__main__":
main()
|