File size: 5,743 Bytes
189f45b | 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 | """
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()
|