cross-scenario-physics-code-transfer / code /_rev_q_posdis_scatter.py
physics-code-transfer-bench's picture
Initial anonymous release for NeurIPS 2026 E&D submission
189f45b verified
"""
EXP Q (reviewer_response): PosDis-vs-CROSS-SCENARIO SCATTER PLOT.
Sweep bottleneck hyperparameters to get a RANGE of (TopSim, PosDis,
CausalSpec) values, then plot each config's cross-scenario accuracy.
If correlations between metrics and transfer are near zero, the metrics
genuinely don't predict transfer (paper claim). If positive correlations
emerge, claim must narrow.
Configs:
Discrete: vary (n_heads, vocab_size) on V-JEPA collision restitution
L=2 V=5, L=2 V=10, L=3 V=5, L=3 V=10, L=4 V=5, L=4 V=10, L=5 V=5
Continuous: vary code_dim_per_agent
dim=2, 3, 5, 10, 20
For each config: train within collision (3 seeds, restitution 3-class),
measure TopSim/PosDis/CausalSpec on holdout, then run cross-scenario
collision->ramp at N=16 and N=192.
Result: scatter table (TopSim, PosDis, CausalSpec, CrossN16, CrossN192)
across configs + Spearman correlation of each metric with transfer.
"""
import json, time, sys, os, math
from pathlib import Path
from datetime import datetime, timezone
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.insert(0, os.path.dirname(__file__))
from _kinematics_train import (
DEVICE, ClassifierReceiver,
HIDDEN_DIM, N_AGENTS, BATCH_SIZE, SENDER_LR, RECEIVER_LR,
EARLY_STOP_PATIENCE,
)
from _killer_experiment import TemporalEncoder, DiscreteSender, DiscreteMultiSender
from _overnight_p1_transfer import (
train_receiver_frozen_sender as disc_train_recv,
eval_zero_shot as disc_eval_zs, make_splits,
)
from _overnight_p3_matrix import load_feat_subsampled, load_labels
from _rev_f_cnn_control import ci95
from _rev_m_continuous_bottleneck import (
train_continuous_base, train_recv_frozen_cont,
get_continuous_messages, topsim_continuous,
posdis_continuous_per_dim, causal_specificity,
)
OUT = Path("results/reviewer_response/exp_q")
OUT.mkdir(parents=True, exist_ok=True)
N_SEEDS = 3 # fewer seeds for sweep; we want coverage
N_LIST = [16, 192]
DISCRETE_CONFIGS = [
{"n_heads": 2, "vocab_size": 5},
{"n_heads": 2, "vocab_size": 10},
{"n_heads": 3, "vocab_size": 5},
{"n_heads": 3, "vocab_size": 10},
{"n_heads": 4, "vocab_size": 5},
{"n_heads": 4, "vocab_size": 10},
{"n_heads": 5, "vocab_size": 5},
]
CONTINUOUS_CONFIGS = [
{"code_dim": 2},
{"code_dim": 3},
{"code_dim": 5},
{"code_dim": 10},
{"code_dim": 20},
]
def log(msg):
ts = datetime.now(timezone.utc).strftime("%H:%M:%SZ")
print(f"[{ts}] EXP-Q: {msg}", flush=True)
# ─────────────────────────────────────────────────────────────────────────────
# Discrete sender with custom L (n_heads), V (vocab_size)
# ─────────────────────────────────────────────────────────────────────────────
def build_discrete_sender(feat_dim, n_heads, vocab_size, fpa=1):
senders = [DiscreteSender(TemporalEncoder(HIDDEN_DIM, feat_dim, fpa),
HIDDEN_DIM, vocab_size, n_heads)
for _ in range(N_AGENTS)]
return DiscreteMultiSender(senders).to(DEVICE)
def train_discrete_custom(feat, labels, seed, n_heads, vocab_size, n_epochs=150):
"""Train DiscreteSender with custom L=n_heads, V=vocab_size."""
N, nf, dim = feat.shape
fpa = 1
msg_dim = vocab_size * n_heads * N_AGENTS
agent_views = [feat[:, i:i+1, :] for i in range(N_AGENTS)]
torch.manual_seed(seed); np.random.seed(seed)
rng = np.random.RandomState(seed * 1000 + 42)
train_ids, holdout_ids = [], []
for c in np.unique(labels):
ids_c = np.where(labels == c)[0]
rng.shuffle(ids_c)
split = max(1, len(ids_c) // 5)
holdout_ids.extend(ids_c[:split]); train_ids.extend(ids_c[split:])
train_ids = np.array(train_ids); holdout_ids = np.array(holdout_ids)
n_classes = int(labels.max()) + 1
chance = 1.0 / n_classes
sender = build_discrete_sender(dim, n_heads, vocab_size, fpa)
receivers = [ClassifierReceiver(msg_dim, HIDDEN_DIM, n_classes).to(DEVICE)
for _ in range(3)]
so = torch.optim.Adam(sender.parameters(), lr=SENDER_LR)
ros = [torch.optim.Adam(r.parameters(), lr=RECEIVER_LR) for r in receivers]
labels_dev = torch.tensor(labels, dtype=torch.long).to(DEVICE)
me = math.log(vocab_size)
n_batches = max(1, len(train_ids) // BATCH_SIZE)
best_acc = 0.0; best_ep = 0
best_sender_state = None; best_receiver_states = None; best_recv_idx = 0
for ep in range(n_epochs):
if ep - best_ep > EARLY_STOP_PATIENCE and best_acc > chance + 0.05: break
if ep > 0 and ep % 40 == 0:
for i in range(len(receivers)):
receivers[i] = ClassifierReceiver(msg_dim, HIDDEN_DIM, n_classes).to(DEVICE)
ros[i] = torch.optim.Adam(receivers[i].parameters(), lr=RECEIVER_LR)
sender.train(); [r.train() for r in receivers]
tau = 3.0 + (1.0 - 3.0) * ep / max(1, n_epochs - 1)
hard = ep >= 30
rng_ep = np.random.RandomState(seed * 10000 + ep)
perm = rng_ep.permutation(train_ids)
for b in range(n_batches):
batch_ids = perm[b*BATCH_SIZE:(b+1)*BATCH_SIZE]
if len(batch_ids) < 4: continue
views = [v[batch_ids].to(DEVICE) for v in agent_views]
tgt = labels_dev[batch_ids]
msg, logits_list = sender(views, tau=tau, hard=hard)
loss = torch.tensor(0.0, device=DEVICE)
for r in receivers: loss = loss + F.cross_entropy(r(msg), tgt)
loss = loss / len(receivers)
for lg in logits_list:
lp = F.log_softmax(lg, -1); p = lp.exp().clamp(min=1e-8)
ent = -(p * lp).sum(-1).mean()
if ent / me < 0.1: loss = loss - 0.03 * ent
if torch.isnan(loss):
so.zero_grad(); [o.zero_grad() for o in ros]; continue
so.zero_grad(); [o.zero_grad() for o in ros]
loss.backward()
torch.nn.utils.clip_grad_norm_(sender.parameters(), 1.0)
so.step(); [o.step() for o in ros]
if ep % 50 == 0 and DEVICE.type == "mps": torch.mps.empty_cache()
if (ep + 1) % 10 == 0 or ep == 0:
sender.eval(); [r.eval() for r in receivers]
with torch.no_grad():
v_ho = [v[holdout_ids].to(DEVICE) for v in agent_views]
msg_ho, _ = sender(v_ho)
tgt_ho = labels_dev[holdout_ids]
best_per_recv = 0.0; best_idx = 0
for ri, r in enumerate(receivers):
preds = r(msg_ho).argmax(-1)
acc = (preds == tgt_ho).float().mean().item()
if acc > best_per_recv:
best_per_recv = acc; best_idx = ri
if best_per_recv > best_acc:
best_acc = best_per_recv; best_ep = ep
best_sender_state = {k: v.cpu().clone() for k, v in sender.state_dict().items()}
best_receiver_states = [
{k: v.cpu().clone() for k, v in r.state_dict().items()}
for r in receivers]
best_recv_idx = best_idx
return {
"sender_state": best_sender_state,
"receiver_states": best_receiver_states,
"best_recv_idx": best_recv_idx,
"train_ids": train_ids, "holdout_ids": holdout_ids,
"task_acc": best_acc, "chance": chance,
"n_classes": n_classes, "fpa": 1, "dim": dim,
"n_heads": n_heads, "vocab_size": vocab_size,
"msg_dim": msg_dim,
}
def disc_get_messages(base, feat):
"""Return discrete messages as one-hot concatenated (N, msg_dim)."""
sender = build_discrete_sender(feat.shape[2], base["n_heads"],
base["vocab_size"], base["fpa"])
sender.load_state_dict(base["sender_state"])
sender.eval().to(DEVICE)
agent_views = [feat[:, i:i+1, :] for i in range(N_AGENTS)]
with torch.no_grad():
views = [v.to(DEVICE) for v in agent_views]
msg, _ = sender(views)
return msg.cpu().float()
def disc_zero_shot(base, feat_tgt, labels_tgt, ho_ids):
sender = build_discrete_sender(feat_tgt.shape[2], base["n_heads"],
base["vocab_size"], base["fpa"])
sender.load_state_dict(base["sender_state"]); sender.eval().to(DEVICE)
receivers = [ClassifierReceiver(base["msg_dim"], HIDDEN_DIM, base["n_classes"]).to(DEVICE)
for _ in range(len(base["receiver_states"]))]
for r, s in zip(receivers, base["receiver_states"]): r.load_state_dict(s)
[r.eval() for r in receivers]
agent_views = [feat_tgt[:, i:i+1, :] for i in range(N_AGENTS)]
labels_dev = torch.tensor(labels_tgt, dtype=torch.long).to(DEVICE)
with torch.no_grad():
v_ho = [v[ho_ids].to(DEVICE) for v in agent_views]
msg_ho, _ = sender(v_ho)
tgt_ho = labels_dev[ho_ids]
best = 0.0
for r in receivers:
preds = r(msg_ho).argmax(-1)
best = max(best, (preds == tgt_ho).float().mean().item())
return best
def disc_train_recv_custom(base, feat_tgt, labels_tgt, train_ids, holdout_ids,
seed, n_target, n_epochs=80):
"""Mimics the canonical train_receiver_frozen_sender but using our custom
discrete sender architecture."""
if n_target == 0:
return disc_zero_shot(base, feat_tgt, labels_tgt, holdout_ids)
rng = np.random.RandomState(seed * 311 + 7 + n_target)
n_t_classes = int(np.max(labels_tgt)) + 1
per_class = max(1, n_target // n_t_classes)
picks = []
for c in range(n_t_classes):
ids_c = np.array([i for i in train_ids if labels_tgt[i] == c])
if len(ids_c) == 0: continue
rng.shuffle(ids_c)
picks.extend(ids_c[:per_class])
picks = np.array(picks)
if len(picks) > n_target: picks = picks[:n_target]
elif len(picks) < n_target and len(train_ids) > len(picks):
extras = np.array([i for i in train_ids if i not in set(picks)])
rng.shuffle(extras)
picks = np.concatenate([picks, extras[:n_target - len(picks)]])
if len(picks) < 2: return float("nan")
sender = build_discrete_sender(feat_tgt.shape[2], base["n_heads"],
base["vocab_size"], base["fpa"])
sender.load_state_dict(base["sender_state"]); sender.to(DEVICE).eval()
for p in sender.parameters(): p.requires_grad = False
receivers = [ClassifierReceiver(base["msg_dim"], HIDDEN_DIM, base["n_classes"]).to(DEVICE)
for _ in range(3)]
ros = [torch.optim.Adam(r.parameters(), lr=RECEIVER_LR) for r in receivers]
agent_views = [feat_tgt[:, i:i+1, :] for i in range(N_AGENTS)]
labels_dev = torch.tensor(labels_tgt, dtype=torch.long).to(DEVICE)
bs = min(BATCH_SIZE, len(picks))
best = 0.0
for ep in range(n_epochs):
[r.train() for r in receivers]
rng_ep = np.random.RandomState(seed * 10000 + ep)
perm = rng_ep.permutation(picks)
for b in range(max(1, len(picks) // bs)):
batch = perm[b*bs:(b+1)*bs]
if len(batch) < 2: continue
views = [v[batch].to(DEVICE) for v in agent_views]
with torch.no_grad():
msg, _ = sender(views)
for r, o in zip(receivers, ros):
logits = r(msg)
loss = F.cross_entropy(logits, labels_dev[batch])
if torch.isnan(loss): continue
o.zero_grad(); loss.backward(); o.step()
if (ep + 1) % 5 == 0:
[r.eval() for r in receivers]
with torch.no_grad():
v_ho = [v[holdout_ids].to(DEVICE) for v in agent_views]
msg_ho, _ = sender(v_ho)
tgt_ho = labels_dev[holdout_ids]
for r in receivers:
preds = r(msg_ho).argmax(-1)
acc = (preds == tgt_ho).float().mean().item()
if acc > best: best = acc
return best
# ─────────────────────────────────────────────────────────────────────────────
# Discrete TopSim/PosDis (token-based)
# ─────────────────────────────────────────────────────────────────────────────
def discrete_token_extract(base, feat):
"""Get argmax tokens from each head per agent. Returns (N, n_agents*n_heads) ints."""
sender = build_discrete_sender(feat.shape[2], base["n_heads"],
base["vocab_size"], base["fpa"])
sender.load_state_dict(base["sender_state"]); sender.eval().to(DEVICE)
agent_views = [feat[:, i:i+1, :] for i in range(N_AGENTS)]
all_tokens = []
with torch.no_grad():
views = [v.to(DEVICE) for v in agent_views]
for s, v in zip(sender.senders, views):
h = s.encoder(v)
for head in s.heads:
logits = head(h)
all_tokens.append(logits.argmax(-1).cpu().numpy())
return np.stack(all_tokens, axis=1) # (N, n_agents*n_heads)
def discrete_topsim(tokens, labels, n_pairs=5000):
from scipy.stats import spearmanr
rng = np.random.RandomState(42)
N = len(labels)
n_pairs = min(n_pairs, N * (N - 1) // 2)
tok_d = []; lbl_d = []
seen = set()
for _ in range(n_pairs):
i, j = rng.randint(0, N), rng.randint(0, N)
if i == j or (i, j) in seen or (j, i) in seen: continue
seen.add((i, j))
tok_d.append(int((tokens[i] != tokens[j]).sum()))
lbl_d.append(abs(int(labels[i]) - int(labels[j])))
if len(tok_d) < 10 or np.std(tok_d) < 1e-9 or np.std(lbl_d) < 1e-9:
return float("nan")
rho, _ = spearmanr(tok_d, lbl_d)
return float(rho) if not np.isnan(rho) else 0.0
def _mi_discrete(x, y):
n = len(x)
n_x = int(np.max(x)) + 1; n_y = int(np.max(y)) + 1
p_x = np.bincount(x, minlength=n_x) / n
p_y = np.bincount(y, minlength=n_y) / n
H_x = -np.sum([p * np.log(p) for p in p_x if p > 0])
H_y = -np.sum([p * np.log(p) for p in p_y if p > 0])
joint = np.zeros((n_x, n_y))
for xv, yv in zip(x, y): joint[int(xv), int(yv)] += 1
joint /= n
H_xy = 0.0
for v in joint.ravel():
if v > 0: H_xy -= v * np.log(v)
return max(H_x + H_y - H_xy, 0.0)
def discrete_posdis(tokens, labels):
"""Per-position MI with the single label, normalized to fraction of total MI
concentrated in the top position (single-prop variant)."""
P = tokens.shape[1]
mis = np.zeros(P)
for p in range(P):
mis[p] = _mi_discrete(tokens[:, p], labels)
if mis.sum() < 1e-9: return float("nan")
return float(mis.max() / mis.sum())
def discrete_causal_spec(base, feat, labels, holdout_ids):
"""Per-position mask -> measure receiver accuracy drop."""
sender = build_discrete_sender(feat.shape[2], base["n_heads"],
base["vocab_size"], base["fpa"])
sender.load_state_dict(base["sender_state"]); sender.eval().to(DEVICE)
receivers = [ClassifierReceiver(base["msg_dim"], HIDDEN_DIM, base["n_classes"]).to(DEVICE)
for _ in range(len(base["receiver_states"]))]
for r, s in zip(receivers, base["receiver_states"]): r.load_state_dict(s)
[r.eval() for r in receivers]
best_recv = receivers[base.get("best_recv_idx", 0)]
agent_views = [feat[:, i:i+1, :] for i in range(N_AGENTS)]
labels_dev = torch.tensor(labels, dtype=torch.long).to(DEVICE)
V = base["vocab_size"]; H = base["n_heads"]
with torch.no_grad():
v_ho = [v[holdout_ids].to(DEVICE) for v in agent_views]
msg_ho, _ = sender(v_ho)
tgt_ho = labels_dev[holdout_ids]
baseline = (best_recv(msg_ho).argmax(-1) == tgt_ho).float().mean().item()
# Mask each (agent, head) block
n_positions = N_AGENTS * H
drops = np.zeros(n_positions)
for pos in range(n_positions):
masked = msg_ho.clone()
start = pos * V
end = start + V
mean_block = msg_ho[:, start:end].mean(dim=0)
masked[:, start:end] = mean_block
acc = (best_recv(masked).argmax(-1) == tgt_ho).float().mean().item()
drops[pos] = baseline - acc
return baseline, drops
# ─────────────────────────────────────────────────────────────────────────────
# Main sweep
# ─────────────────────────────────────────────────────────────────────────────
def main():
t0 = time.time()
log("=" * 60)
log("EXP Q: PosDis-vs-cross-scenario sweep")
feat_c = load_feat_subsampled("collision", "vjepa2")
feat_r = load_feat_subsampled("ramp", "vjepa2")
lbl_c = load_labels("collision", "restitution")
lbl_r = load_labels("ramp", "restitution")
log(f" collision: {tuple(feat_c.shape)} dist={np.bincount(lbl_c).tolist()}")
log(f" ramp: {tuple(feat_r.shape)} dist={np.bincount(lbl_r).tolist()}")
rows = [] # each row: dict with config, metrics, transfer
# ── Discrete sweep ──
for cfg in DISCRETE_CONFIGS:
H, V = cfg["n_heads"], cfg["vocab_size"]
name = f"disc_L{H}_V{V}"
log(f"\n --- {name} (L={H}, V={V}) ---")
within_accs = []; bases = []
for seed in range(N_SEEDS):
t_s = time.time()
try:
base = train_discrete_custom(feat_c, lbl_c, seed, H, V)
bases.append(base); within_accs.append(float(base["task_acc"]))
log(f" {name} s{seed}: within={base['task_acc']:.3f} [{time.time()-t_s:.0f}s]")
except Exception as e:
log(f" {name} s{seed} FAILED: {e}")
bases.append(None); within_accs.append(float("nan"))
valid = [(i, a) for i, a in enumerate(within_accs) if not np.isnan(a)]
if not valid:
log(f" {name}: no successful base"); continue
best_idx = max(valid, key=lambda x: x[1])[0]
best_base = bases[best_idx]
ho_ids = best_base["holdout_ids"]
# Metrics on best base
try:
tokens = discrete_token_extract(best_base, feat_c)
tokens_ho = tokens[ho_ids]
ts = discrete_topsim(tokens_ho, lbl_c[ho_ids])
pd_ = discrete_posdis(tokens_ho, lbl_c[ho_ids])
base_acc, drops = discrete_causal_spec(best_base, feat_c, lbl_c, ho_ids)
cs = float(drops.max())
except Exception as e:
log(f" {name} metrics FAILED: {e}")
ts = pd_ = cs = float("nan")
# Cross-scenario at N=16, N=192
cross = {n: [] for n in N_LIST}
for seed, base in enumerate(bases):
if base is None:
for n in N_LIST: cross[n].append(float("nan"))
continue
tr_t, ho_t = make_splits(lbl_r, seed)
for n in N_LIST:
try:
if n == 0:
acc = disc_zero_shot(base, feat_r, lbl_r, ho_t)
else:
acc = disc_train_recv_custom(base, feat_r, lbl_r, tr_t, ho_t,
seed, n)
cross[n].append(float(acc))
except Exception as e:
log(f" {name} s{seed} N={n} FAILED: {e}")
cross[n].append(float("nan"))
wm = float(np.mean([a for a in within_accs if not np.isnan(a)]))
cross_means = {n: float(np.mean([x for x in cross[n] if not np.isnan(x)]))
if any(not np.isnan(x) for x in cross[n]) else float("nan")
for n in N_LIST}
log(f" {name}: within={wm:.3f} TopSim={ts:.3f} PosDis={pd_:.3f} "
f"CausalSpec={cs:.3f} cross16={cross_means[16]:.3f} cross192={cross_means[192]:.3f}")
rows.append({
"name": name, "type": "discrete",
"n_heads": H, "vocab_size": V,
"msg_dim": V * H * N_AGENTS,
"within": wm, "topsim": ts, "posdis": pd_, "causal_spec": cs,
"cross_n16": cross_means[16], "cross_n192": cross_means[192],
})
# ── Continuous sweep ──
for cfg in CONTINUOUS_CONFIGS:
D = cfg["code_dim"]
name = f"cont_dim{D}"
log(f"\n --- {name} ---")
within_accs = []; bases = []
for seed in range(N_SEEDS):
t_s = time.time()
try:
base = train_continuous_base(feat_c, lbl_c, seed,
code_dim_per_agent=D, n_epochs=150)
bases.append(base); within_accs.append(float(base["task_acc"]))
log(f" {name} s{seed}: within={base['task_acc']:.3f} [{time.time()-t_s:.0f}s]")
except Exception as e:
log(f" {name} s{seed} FAILED: {e}")
bases.append(None); within_accs.append(float("nan"))
valid = [(i, a) for i, a in enumerate(within_accs) if not np.isnan(a)]
if not valid:
log(f" {name}: no successful base"); continue
best_idx = max(valid, key=lambda x: x[1])[0]
best_base = bases[best_idx]
ho_ids = best_base["holdout_ids"]
try:
msgs = get_continuous_messages(best_base, feat_c)
msgs_ho = msgs[ho_ids]
ts = topsim_continuous(msgs_ho, lbl_c[ho_ids])
mi = posdis_continuous_per_dim(msgs_ho, lbl_c[ho_ids])
pd_ = float(mi.max() / (mi.sum() + 1e-9)) if mi.sum() > 0 else float("nan")
base_acc, drops = causal_specificity(best_base, feat_c, lbl_c, ho_ids)
cs = float(drops.max())
except Exception as e:
log(f" {name} metrics FAILED: {e}")
ts = pd_ = cs = float("nan")
cross = {n: [] for n in N_LIST}
for seed, base in enumerate(bases):
if base is None:
for n in N_LIST: cross[n].append(float("nan"))
continue
tr_t, ho_t = make_splits(lbl_r, seed)
for n in N_LIST:
try:
acc = train_recv_frozen_cont(base, feat_r, lbl_r, tr_t, ho_t,
seed, n)
cross[n].append(float(acc))
except Exception as e:
log(f" {name} s{seed} N={n} FAILED: {e}")
cross[n].append(float("nan"))
wm = float(np.mean([a for a in within_accs if not np.isnan(a)]))
cross_means = {n: float(np.mean([x for x in cross[n] if not np.isnan(x)]))
if any(not np.isnan(x) for x in cross[n]) else float("nan")
for n in N_LIST}
log(f" {name}: within={wm:.3f} TopSim={ts:.3f} PosDis={pd_:.3f} "
f"CausalSpec={cs:.3f} cross16={cross_means[16]:.3f} cross192={cross_means[192]:.3f}")
rows.append({
"name": name, "type": "continuous",
"code_dim": D, "msg_dim": D * N_AGENTS,
"within": wm, "topsim": ts, "posdis": pd_, "causal_spec": cs,
"cross_n16": cross_means[16], "cross_n192": cross_means[192],
})
# ── Spearman correlations ──
from scipy.stats import spearmanr
def safe_corr(metric, target):
x = []; y = []
for r in rows:
if not np.isnan(r[metric]) and not np.isnan(r[target]):
x.append(r[metric]); y.append(r[target])
if len(x) < 4 or np.std(x) < 1e-9 or np.std(y) < 1e-9:
return float("nan"), float("nan")
rho, p = spearmanr(x, y)
return float(rho), float(p)
corrs = {}
for met in ["topsim", "posdis", "causal_spec"]:
for tgt in ["cross_n16", "cross_n192"]:
corrs[(met, tgt)] = safe_corr(met, tgt)
# Build summary
lines = [
"EXPERIMENT Q -- PosDis vs CROSS-SCENARIO TRANSFER (V-JEPA 2, 3 seeds per config)",
"",
"Sweep across 7 discrete + 5 continuous bottleneck configs. Each row: best",
"within-collision metrics on holdout + cross-scenario coll->ramp accuracy",
"at N=16 and N=192 (mean across 3 seeds).",
"",
f"{'Config':<14s} | {'Within':<10s} | {'TopSim':<10s} | {'PosDis':<10s} | "
f"{'CausalSpec':<12s} | {'Cross N=16':<12s} | {'Cross N=192':<12s}",
"-" * 100,
]
for r in rows:
lines.append(
f"{r['name']:<14s} | "
f"{r['within']*100:5.1f}% | "
f"{r['topsim']:+.2f} | "
f"{r['posdis']:.2f} | "
f"{r['causal_spec']:.2f} | "
f"{r['cross_n16']*100:5.1f}% | "
f"{r['cross_n192']*100:5.1f}%")
lines.append("")
lines.append("SPEARMAN CORRELATIONS (across configs):")
for tgt in ["cross_n16", "cross_n192"]:
lines.append(f" vs {tgt}:")
for met in ["topsim", "posdis", "causal_spec"]:
rho, p = corrs[(met, tgt)]
lines.append(f" {met:<14s}: rho={rho:+.2f} p={p:.3f}")
# Verdict
lines.append("")
lines.append("VERDICT:")
abs_max_rho = 0
for k, (rho, p) in corrs.items():
if not np.isnan(rho): abs_max_rho = max(abs_max_rho, abs(rho))
if abs_max_rho < 0.30:
v = ("Compositionality metrics (TopSim, PosDis, CausalSpec) DO NOT predict "
"cross-scenario transfer. All Spearman |rho| < 0.30 across configs. "
"Strong support for the abstract claim.")
elif abs_max_rho < 0.55:
v = (f"Weak/moderate correlation (max |rho|={abs_max_rho:.2f}). Metrics "
"partially predict transfer but explain little variance. Honest, "
"nuanced finding.")
else:
v = (f"Strong correlation (max |rho|={abs_max_rho:.2f}). Some metrics DO "
"predict transfer. The abstract claim must be NARROWED.")
lines.append(f" {v}")
lines.append("")
lines.append(f"Total runtime: {(time.time()-t0)/60:.1f} min")
summary = "\n".join(lines)
(OUT / "exp_q_summary.txt").write_text(summary + "\n")
(OUT / "exp_q_summary.json").write_text(json.dumps({
"config": {"n_seeds": N_SEEDS, "N_list": N_LIST,
"discrete_configs": DISCRETE_CONFIGS,
"continuous_configs": CONTINUOUS_CONFIGS},
"rows": rows,
"spearman": {f"{m}__{t}": list(corrs[(m, t)]) for (m, t) in corrs},
"runtime_s": time.time() - t0,
}, indent=2, default=str))
print("\n" + summary, flush=True)
log(f"DONE in {(time.time()-t0)/60:.1f} min")
if __name__ == "__main__":
main()