File size: 26,604 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
"""
EXP Q ADDENDUM: add multi-property discrete + continuous configs to the
scatter sweep so the headline-PosDis configs (0.76 discrete, 0.40 continuous
multi-prop) are represented in the metric-vs-transfer correlation.

Trains:
  disc_multi_L3_V5  — discrete bottleneck, 2 head per agent, V=5, multi-prop
                      (mass_bin + restit_bin, 2-headed receiver)
  disc_multi_L4_V10 — same but L=4, V=10 (broader coverage)
  cont_multi_dim3   — continuous bottleneck, code_dim=3 per agent, multi-prop

Per config:
  - Within: 3 seeds, mean across 2 heads (mass + restit) for combined acc
  - Metrics: TopSim, PosDis, CausalSpec on multi-prop labels
  - Cross to ramp at N=16 and N=192 (restitution only, since ramp lacks mass)

Re-uses EXP N's MultiPropReceiver and the metric helpers in EXP N + Q.
"""
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 make_splits
from _overnight_p3_matrix import load_labels, load_feat_subsampled
from _rev_f_cnn_control import ci95
from _rev_q_posdis_scatter import build_discrete_sender, discrete_token_extract, discrete_topsim
from _rev_n_multiprop_continuous import (
    MultiPropReceiver, train_multiprop_continuous_base,
    topsim_multiprop, posdis_multiprop, causal_spec_multiprop,
)
from _rev_m_continuous_bottleneck import (
    build_continuous_sender, get_continuous_messages,
    train_recv_frozen_cont,
)

OUT = Path("results/reviewer_response/exp_q_addendum")
OUT.mkdir(parents=True, exist_ok=True)
N_SEEDS = 3
N_LIST = [16, 192]


def log(msg):
    ts = datetime.now(timezone.utc).strftime("%H:%M:%SZ")
    print(f"[{ts}] EXP-QADD: {msg}", flush=True)


# ─── Discrete multi-prop training ───
def train_discrete_multi(feat, labels_list, seed, n_heads, vocab_size,
                          n_epochs=150):
    """Train DiscreteSender with multi-prop receiver (2 heads per receiver)."""
    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)

    primary = labels_list[0]
    train_ids, holdout_ids = [], []
    for c in np.unique(primary):
        ids_c = np.where(primary == 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_per_prop = [int(lbl.max()) + 1 for lbl in labels_list]
    chance = 1.0 / max(n_classes_per_prop)

    sender = build_discrete_sender(dim, n_heads, vocab_size, fpa)
    receivers = [MultiPropReceiver(msg_dim, HIDDEN_DIM, n_classes_per_prop).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(lbl, dtype=torch.long).to(DEVICE) for lbl in labels_list]
    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] = MultiPropReceiver(msg_dim, HIDDEN_DIM, n_classes_per_prop).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]
            tgts = [ld[batch_ids] for ld in labels_dev]
            msg, logits_list = sender(views, tau=tau, hard=hard)
            loss = torch.tensor(0.0, device=DEVICE)
            for r in receivers:
                head_logits = r(msg)
                for hl, tgt in zip(head_logits, tgts):
                    loss = loss + F.cross_entropy(hl, tgt)
            loss = loss / (len(receivers) * len(tgts))
            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 = [ld[holdout_ids] for ld in labels_dev]
                best_per_recv = 0.0; best_idx = 0
                for ri, r in enumerate(receivers):
                    head_logits = r(msg_ho)
                    accs = [(hl.argmax(-1) == tgt).float().mean().item()
                            for hl, tgt in zip(head_logits, tgt_ho)]
                    combined = float(np.mean(accs))
                    if combined > best_per_recv:
                        best_per_recv = combined; 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_per_prop": n_classes_per_prop,
        "fpa": 1, "dim": dim,
        "n_heads": n_heads, "vocab_size": vocab_size,
        "msg_dim": msg_dim,
    }


# ─── Discrete multi-prop metrics ───
def discrete_multi_topsim(tokens, labels_list, n_pairs=5000):
    """Spearman corr between Hamming(message tokens) and L1(label vector)."""
    from scipy.stats import spearmanr
    rng = np.random.RandomState(42)
    N = tokens.shape[0]
    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(sum(abs(int(lbl[i]) - int(lbl[j])) for lbl in labels_list))
    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_disc(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_multi_posdis(tokens, labels_list):
    """Standard PosDis on discrete tokens: per-position, MI with each
    property; PosDis = mean over positions of (top-second)/top."""
    P = tokens.shape[1]
    K = len(labels_list)
    mi_matrix = np.zeros((P, K))
    for p in range(P):
        for k in range(K):
            mi_matrix[p, k] = _mi_disc(tokens[:, p], labels_list[k])
    if mi_matrix.sum() < 1e-9: return float("nan"), mi_matrix
    n_active = 0; total = 0.0
    for p in range(P):
        sorted_mi = np.sort(mi_matrix[p])[::-1]
        if sorted_mi[0] > 1e-6:
            total += (sorted_mi[0] - sorted_mi[1]) / sorted_mi[0]
            n_active += 1
    if n_active == 0: return float("nan"), mi_matrix
    return float(total / n_active), mi_matrix


def discrete_multi_causal(base, feat, labels_list, holdout_ids):
    """Mask each (agent x head) block; per-property 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 = [MultiPropReceiver(base["msg_dim"], HIDDEN_DIM,
                                     base["n_classes_per_prop"]).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(lbl, dtype=torch.long).to(DEVICE) for lbl in labels_list]
    K = len(labels_list); V = base["vocab_size"]; H = base["n_heads"]
    n_positions = N_AGENTS * H
    with torch.no_grad():
        v_ho = [v[holdout_ids].to(DEVICE) for v in agent_views]
        msg_ho, _ = sender(v_ho)
        tgt_ho = [ld[holdout_ids] for ld in labels_dev]
        baseline_per_prop = [(hl.argmax(-1) == tgt).float().mean().item()
                              for hl, tgt in zip(best_recv(msg_ho), tgt_ho)]
        drops = np.zeros((n_positions, K))
        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
            for p_idx, (hl, tgt) in enumerate(zip(best_recv(masked), tgt_ho)):
                acc = (hl.argmax(-1) == tgt).float().mean().item()
                drops[pos, p_idx] = baseline_per_prop[p_idx] - acc
    return baseline_per_prop, drops


# ─── Cross-scenario eval (single-property restitution on ramp) ───
def disc_multi_zero_shot_restit(base, feat_tgt, labels_tgt, ho_ids, restit_idx=1):
    """Apply discrete-multi sender + best receiver's restit head to target."""
    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 = [MultiPropReceiver(base["msg_dim"], HIDDEN_DIM,
                                     base["n_classes_per_prop"]).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:
            head_logits = r(msg_ho)
            preds = head_logits[restit_idx].argmax(-1)
            acc = (preds == tgt_ho).float().mean().item()
            if acc > best: best = acc
    return best


def disc_multi_train_recv_frozen(base, feat_tgt, labels_tgt, train_ids, holdout_ids,
                                  seed, n_target, n_epochs=80):
    """Freeze sender; train fresh single-property receiver on n_target stratified
    target examples; eval on holdout. Mirrors disc_train_recv_custom but uses
    multi-prop sender."""
    if n_target == 0:
        return disc_multi_zero_shot_restit(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, n_t_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


# ─── Main ───
def main():
    t0 = time.time()
    log("=" * 60)
    log("EXP Q ADDENDUM: multi-property bottleneck configs")

    feat_c = load_feat_subsampled("collision", "vjepa2")
    feat_r = load_feat_subsampled("ramp", "vjepa2")
    lbl_c_mass = load_labels("collision", "mass")
    lbl_c_rest = load_labels("collision", "restitution")
    lbl_r_rest = load_labels("ramp", "restitution")
    log(f"  collision: feat={tuple(feat_c.shape)} mass={np.bincount(lbl_c_mass).tolist()} "
        f"rest={np.bincount(lbl_c_rest).tolist()}")

    rows = []

    # ── Discrete multi-prop configs ──
    discrete_specs = [
        ("disc_multi_L3_V5", 3, 5),
        ("disc_multi_L4_V10", 4, 10),
    ]
    for name, H, V in discrete_specs:
        log(f"\n  --- {name} (L={H}, V={V}, multi-prop) ---")
        within_accs = []; bases = []
        for seed in range(N_SEEDS):
            t_s = time.time()
            try:
                base = train_discrete_multi(feat_c, [lbl_c_mass, lbl_c_rest],
                                              seed, H, V)
                bases.append(base); within_accs.append(float(base["task_acc"]))
                log(f"    {name} s{seed}: combined within={base['task_acc']:.3f} "
                    f"[{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"]
        # Within metrics on best
        try:
            tokens = discrete_token_extract(best_base, feat_c)
            tokens_ho = tokens[ho_ids]
            ts = discrete_multi_topsim(tokens_ho, [lbl_c_mass[ho_ids], lbl_c_rest[ho_ids]])
            pd_, mi = discrete_multi_posdis(tokens_ho, [lbl_c_mass[ho_ids], lbl_c_rest[ho_ids]])
            base_pp, drops = discrete_multi_causal(best_base, feat_c,
                                                     [lbl_c_mass, lbl_c_rest], ho_ids)
            cs = float(drops.max())
        except Exception as e:
            log(f"    {name} metrics FAILED: {e}")
            ts = pd_ = cs = float("nan")
        # Cross-scenario coll->ramp at N=16, N=192 (restitution)
        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_rest, seed)
            for n in N_LIST:
                try:
                    acc = disc_multi_train_recv_frozen(base, feat_r, lbl_r_rest,
                                                         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)]))
        cm = {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={cm[16]:.3f} cross192={cm[192]:.3f}")
        rows.append({
            "name": name, "type": "discrete_multi",
            "n_heads": H, "vocab_size": V,
            "msg_dim": V * H * N_AGENTS,
            "within": wm, "topsim": ts, "posdis": pd_, "causal_spec": cs,
            "cross_n16": cm[16], "cross_n192": cm[192],
        })

    # ── Continuous multi-prop config (matches Exp N exactly) ──
    cont_spec = ("cont_multi_dim3", 3)
    name, D = cont_spec
    log(f"\n  --- {name} (D={D}, multi-prop) ---")
    within_accs = []; bases = []
    for seed in range(N_SEEDS):
        t_s = time.time()
        try:
            base = train_multiprop_continuous_base(
                feat_c, [lbl_c_mass, lbl_c_rest], seed,
                code_dim_per_agent=D, n_epochs=150)
            bases.append(base); within_accs.append(float(base["task_acc"]))
            log(f"    {name} s{seed}: combined 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 valid:
        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_multiprop(msgs_ho, [lbl_c_mass[ho_ids], lbl_c_rest[ho_ids]])
            pd_, _ = posdis_multiprop(msgs_ho, [lbl_c_mass[ho_ids], lbl_c_rest[ho_ids]])
            base_pp, drops = causal_spec_multiprop(best_base, feat_c,
                                                    [lbl_c_mass, lbl_c_rest], ho_ids)
            cs = float(drops.max())
        except Exception as e:
            log(f"    {name} metrics FAILED: {e}")
            ts = pd_ = cs = float("nan")
        # Cross to ramp on restitution: build single-task base view; train fresh receiver
        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
            single_base = dict(base)
            single_base["n_classes"] = base["n_classes_per_prop"][1]
            single_base["receiver_states"] = []
            tr_t, ho_t = make_splits(lbl_r_rest, seed)
            for n in N_LIST:
                try:
                    acc = train_recv_frozen_cont(single_base, feat_r, lbl_r_rest,
                                                   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)]))
        cm = {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={cm[16]:.3f} cross192={cm[192]:.3f}")
        rows.append({
            "name": name, "type": "continuous_multi",
            "code_dim": D, "msg_dim": D * N_AGENTS,
            "within": wm, "topsim": ts, "posdis": pd_, "causal_spec": cs,
            "cross_n16": cm[16], "cross_n192": cm[192],
        })

    # ── Combine with original Exp Q rows for full correlation ──
    original_q_rows = [
        # (name, type, topsim, posdis, causal_spec, cross16, cross192)
        ("disc_L2_V5",   "discrete", 0.88, 0.20, 0.02, 41.7, 43.9),
        ("disc_L2_V10",  "discrete", 0.84, 0.25, 0.05, 46.1, 41.7),
        ("disc_L3_V5",   "discrete", 0.84, 0.13, 0.02, 43.3, 42.8),
        ("disc_L3_V10",  "discrete", 0.84, 0.12, 0.01, 43.3, 45.6),
        ("disc_L4_V5",   "discrete", 0.90, 0.10, 0.01, 41.1, 42.2),
        ("disc_L4_V10",  "discrete", 0.82, 0.08, 0.02, 45.0, 45.0),
        ("disc_L5_V5",   "discrete", 0.89, 0.07, 0.02, 40.0, 43.9),
        ("cont_dim2",    "continuous", 0.92, 0.15, 0.20, 48.9, 54.4),
        ("cont_dim3",    "continuous", 0.91, 0.15, 0.02, 40.6, 41.1),
        ("cont_dim5",    "continuous", 0.89, 0.06, 0.03, 47.2, 43.9),
        ("cont_dim10",   "continuous", 0.88, 0.04, 0.01, 47.8, 48.3),
        ("cont_dim20",   "continuous", 0.90, 0.02, 0.00, 48.9, 55.0),
    ]
    all_rows = list(original_q_rows)
    for r in rows:
        all_rows.append((
            r["name"], r["type"], r["topsim"], r["posdis"], r["causal_spec"],
            r["cross_n16"] * 100 if r["cross_n16"] <= 1 else r["cross_n16"],
            r["cross_n192"] * 100 if r["cross_n192"] <= 1 else r["cross_n192"],
        ))

    # Spearman across all rows
    from scipy.stats import spearmanr
    def safe_corr(idx_x, idx_y):
        x = []; y = []
        for r in all_rows:
            if not (np.isnan(r[idx_x]) or np.isnan(r[idx_y])):
                x.append(r[idx_x]); y.append(r[idx_y])
        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 = {
        ("topsim", 16):  safe_corr(2, 5),
        ("topsim", 192): safe_corr(2, 6),
        ("posdis", 16):  safe_corr(3, 5),
        ("posdis", 192): safe_corr(3, 6),
        ("causal", 16):  safe_corr(4, 5),
        ("causal", 192): safe_corr(4, 6),
    }

    # Print summary
    lines = [
        "EXP Q ADDENDUM -- multi-property bottleneck configs",
        "",
        f"{'Config':<22s} | {'TopSim':<8s} | {'PosDis':<8s} | {'CausalSpec':<12s} | "
        f"{'Cross 16':<10s} | {'Cross 192':<10s}",
        "-" * 90,
    ]
    for r in all_rows:
        name, typ, ts, pd_, cs, c16, c192 = r
        lines.append(f"{name:<22s} | {ts:+.2f}    | {pd_:.2f}     | {cs:.2f}        "
                     f"| {c16:5.1f}%    | {c192:5.1f}%")

    lines.append("")
    lines.append("FULL-SWEEP SPEARMAN (now including multi-prop configs):")
    for tgt_n in [16, 192]:
        lines.append(f"  vs cross_n{tgt_n}:")
        for met, label in [("topsim", "TopSim"), ("posdis", "PosDis"),
                            ("causal", "CausalSpec")]:
            rho, p = corrs[(met, tgt_n)]
            lines.append(f"    {label:<12s}: rho={rho:+.2f}  p={p:.3f}")

    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))
    lines.append("")
    if abs_max_rho < 0.30:
        verd = "Metrics still uncorrelated with transfer."
    elif abs_max_rho < 0.55:
        verd = f"Weak/moderate correlation (max |rho|={abs_max_rho:.2f})."
    else:
        verd = f"Strong correlation (max |rho|={abs_max_rho:.2f}). Reframe."
    lines.append(f"VERDICT: {verd}")
    lines.append(f"\nTotal runtime: {(time.time()-t0)/60:.1f} min")

    summary = "\n".join(lines)
    (OUT / "exp_q_addendum_summary.txt").write_text(summary + "\n")
    (OUT / "exp_q_addendum_summary.json").write_text(json.dumps({
        "new_rows": rows,
        "all_rows_combined": [{"name": r[0], "type": r[1], "topsim": r[2],
                                 "posdis": r[3], "causal_spec": r[4],
                                 "cross_n16": r[5], "cross_n192": r[6]}
                                for r in all_rows],
        "spearman": {f"{m}__n{n}": list(v) for (m, n), v in corrs.items()},
    }, indent=2, default=str))
    print("\n" + summary, flush=True)
    log(f"DONE in {(time.time()-t0)/60:.1f} min")


if __name__ == "__main__":
    main()