# 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. Fine-tunes also get a cluster bootstrap over conditions (ci95_cluster), the number of conditions where G_function has the lower MSE (wins), and per-condition MSEs (D-049); these are sensitivity analyses. 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 /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__r_s 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__r_s 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) clus = [c for _, _, c in cases] groups = {} if all(c is not None for c in clus): # fine-tunes: seeds and ranks of one condition are not independent (D-049) for j, c in enumerate(clus): groups.setdefault(c, []).append(j) res["per_condition"] = {c: {"n": len(ix), **{m: float(per[m][ix].mean()) for m in per}} for c, ix in sorted(groups.items())} crng = np.random.default_rng(a.seed + 1) # separate stream: the case bootstrap above is unchanged 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()} if groups: g = [np.array(ix) for ix in groups.values()] cb = [np.concatenate([g[k] for k in crng.integers(0, len(g), len(g))]) for _ in range(2000)] res[f"delta_mse_Gf_minus_{m}"].update( ci95_cluster=np.percentile([d[s].mean() for s in cb], [2.5, 97.5]).tolist(), n_clusters=len(g), wins=int(sum(d[ix].mean() < 0 for ix in g))) 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()