File size: 27,384 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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
"""
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()