""" EXP REV-P101-BN-N192: Test bottleneck on Phys101 cross-scenario at N=192. The original Phys101 experiment (P3) reported bottleneck cross-scenario at 16-shot (~45%). The new LP diagnostic shows LP at N=192 reaches 74-79% on Phys101. This script trains the bottleneck at N=192 to test whether the dissociation replicates at matched N (the natural comparison for the Kubric N=192 numbers). 5 seeds, both per-scenario and global tertile binning. """ import json, time, sys, os from pathlib import Path from datetime import datetime, timezone import numpy as np import torch PROMPT_RECEIVED_TIME = datetime.now(timezone.utc).isoformat() print(f"PROMPT_RECEIVED_TIME = {PROMPT_RECEIVED_TIME}", flush=True) T0 = time.time() sys.path.insert(0, os.path.dirname(__file__)) from _overnight_p1_transfer import ( train_base, train_receiver_frozen_sender, make_splits, N_FRAMES_SUBSAMPLE, ) OUT = Path("results/reviewer_response/exp_phys101_bn_n192") OUT.mkdir(parents=True, exist_ok=True) N_SEEDS = 5 N_TARGET = 192 DOMAINS = ("spring", "fall", "ramp") PHYS_FILES = {s: f"results/phase87_phys101_{s}_features.pt" for s in DOMAINS} def log(msg): ts = datetime.now(timezone.utc).strftime("%H:%M:%SZ") print(f"[{ts}] EXP-P101BN: {msg}", flush=True) def load_phys(s, mass_to_label): """Load features + apply provided mass->label function.""" d = torch.load(PHYS_FILES[s], weights_only=False, map_location="cpu") feat = d["features"].float() T = feat.shape[1] if T >= N_FRAMES_SUBSAMPLE: idx = np.linspace(0, T-1, N_FRAMES_SUBSAMPLE).astype(int) feat = feat[:, idx, :].contiguous() mass = np.asarray(d["mass_values"], dtype=np.float64) labels = mass_to_label(mass).astype(np.int64) return feat, labels, mass def main(): log("=" * 60) log(f"EXP P101 BN N={N_TARGET}: bottleneck on Phys101 at matched N") # First gather all masses for global tertile all_masses = [] for s in DOMAINS: d = torch.load(PHYS_FILES[s], weights_only=False, map_location="cpu") all_masses.append(np.asarray(d["mass_values"], dtype=np.float64)) all_mass = np.concatenate(all_masses) global_edges = np.quantile(all_mass, [1/3, 2/3]) log(f"Global tertile edges: {global_edges.tolist()}") pairs = [(src, tgt) for src in DOMAINS for tgt in DOMAINS if src != tgt] out = {"per_scenario": {}, "global": {}} for binning_name in ["per_scenario", "global"]: log(f"\n=== {binning_name.upper()} BINNING ===") # Build mass->label function for this binning if binning_name == "per_scenario": # Per-scenario: each scenario gets its own tertile data = {} for s in DOMAINS: d = torch.load(PHYS_FILES[s], weights_only=False, map_location="cpu") m = np.asarray(d["mass_values"], dtype=np.float64) edges = np.quantile(m, [1/3, 2/3]) f = lambda x, e=edges: np.searchsorted(e, x) data[s] = load_phys(s, f) else: # global f = lambda x: np.searchsorted(global_edges, x) data = {s: load_phys(s, f) for s in DOMAINS} for src in DOMAINS: log(f" --- {src} as source ---") for seed in range(N_SEEDS): feat_s, lbl_s, _ = data[src] t0 = time.time() try: base = train_base(feat_s, lbl_s, seed, n_epochs=150) log(f" {src} s{seed}: within={base['task_acc']:.3f} [{time.time()-t0:.0f}s]") except Exception as e: log(f" {src} s{seed} train FAILED: {e}") continue for tgt in DOMAINS: if tgt == src: continue feat_t, lbl_t, _ = data[tgt] tr, hoids = make_splits(lbl_t, seed) try: acc = train_receiver_frozen_sender( base, feat_t, lbl_t, tr, hoids, seed, max_examples=N_TARGET, n_epochs=80) except Exception as e: log(f" {src}->{tgt} s{seed} FAILED: {e}") acc = float("nan") key = f"{src}->{tgt}" out[binning_name].setdefault(key, []).append(float(acc)) log(f" {src}->{tgt} s{seed} N=192: {acc*100:.1f}%") # Aggregate SUMMARY = [f"Phys101 cross-scenario BOTTLENECK at N={N_TARGET} (5 seeds, mean across 6 directional pairs)", ""] for binning_name in ["per_scenario", "global"]: all_accs = [a for accs in out[binning_name].values() for a in accs if not np.isnan(a)] if all_accs: m = np.mean(all_accs); sd = np.std(all_accs, ddof=1) SUMMARY.append(f"--- {binning_name} ---") SUMMARY.append(f" Mean across pairs: {m*100:5.1f}% +/- {sd*100:.1f}%") for pair, accs in out[binning_name].items(): v = [a for a in accs if not np.isnan(a)] if v: SUMMARY.append(f" {pair}: {np.mean(v)*100:5.1f}% +/- {np.std(v, ddof=1) if len(v) > 1 else 0.0:.1f}%") SUMMARY.append("") print("\n".join(SUMMARY), flush=True) with open(OUT / "exp_phys101_bn_n192_summary.txt", "w") as fh: fh.write("\n".join(SUMMARY) + "\n") with open(OUT / "exp_phys101_bn_n192_summary.json", "w") as fh: json.dump(out, fh, indent=2) end_ts = datetime.now(timezone.utc).isoformat() runtime_min = (time.time() - T0) / 60.0 print(f"\nEND_TIME = {end_ts}\nTotal runtime: {runtime_min:.2f} min", flush=True) if __name__ == "__main__": main()