File size: 11,399 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
"""
PRIORITY 3: Transfer matrix across all available scenarios.

Property-scenario availability:
  restitution: collision, ramp, flat_drop, elasticity, ramp_3prop   (5)
  friction:    ramp, flat_drop, ramp_3prop                          (3)
  mass:        collision (elasticity has constant mass → skip)      (1)

For each property with >=2 scenarios: train on one, test on all.
Subsample all features to [N, 4, D] (fpa=1, 4 agents).

Modes:
  zero-shot       — apply source-trained receiver to target codes
  16-shot         — train new receiver on 16 stratified target examples

Backbones: vjepa2, dinov2, clip. Seeds: 2.
"""
import json, time, sys, os, math
from pathlib import Path
from datetime import datetime, timezone
import numpy as np
import torch
import torch.nn.functional as F

sys.path.insert(0, os.path.dirname(__file__))
from _kinematics_train import (
    ClassifierReceiver,
    HIDDEN_DIM, VOCAB_SIZE, N_HEADS, N_AGENTS, MSG_DIM, BATCH_SIZE,
    SENDER_LR, RECEIVER_LR, EARLY_STOP_PATIENCE, DEVICE,
)
from _killer_experiment import (
    TemporalEncoder, DiscreteSender, DiscreteMultiSender,
)
from _overnight_p1_transfer import (
    build_sender, train_base, eval_zero_shot, train_receiver_frozen_sender,
    make_splits, N_FRAMES_SUBSAMPLE,
)

OUT = Path("results/cross_scenario_transfer")
OUT.mkdir(parents=True, exist_ok=True)
LOG = Path("results/overnight_log.txt")
N_EPOCHS = 150
N_SEEDS = 2

# Feature file locations per (dataset, backbone)
FEATURE_FILES = {
    ("collision",  "vjepa2"): "results/vjepa2_collision_pooled.pt",
    ("collision",  "dinov2"): "results/collision_dinov2_features.pt",
    ("collision",  "clip"):   "results/kinematics_vs_mechanics/clip_collision_features.pt",
    ("ramp",       "vjepa2"): "results/vjepa2_ramp_temporal.pt",
    ("ramp",       "dinov2"): "results/phase54b_dino_features.pt",
    ("ramp",       "clip"):   "results/kinematics_vs_mechanics/clip_ramp_features.pt",
    ("flat_drop",  "vjepa2"): "results/kinematics_vs_mechanics/feat_vjepa2_flat_drop.pt",
    ("flat_drop",  "dinov2"): "results/kinematics_vs_mechanics/feat_dinov2_flat_drop.pt",
    ("flat_drop",  "clip"):   "results/kinematics_vs_mechanics/feat_clip_flat_drop.pt",
    ("elasticity", "vjepa2"): "results/kinematics_vs_mechanics/feat_vjepa2_elasticity.pt",
    ("elasticity", "dinov2"): "results/kinematics_vs_mechanics/feat_dinov2_elasticity.pt",
    ("elasticity", "clip"):   "results/kinematics_vs_mechanics/feat_clip_elasticity.pt",
    ("ramp_3prop", "vjepa2"): "results/kinematics_vs_mechanics/feat_vjepa2_ramp_3prop.pt",
    ("ramp_3prop", "dinov2"): "results/kinematics_vs_mechanics/feat_dinov2_ramp_3prop.pt",
    ("ramp_3prop", "clip"):   "results/kinematics_vs_mechanics/feat_clip_ramp_3prop.pt",
}

LABEL_FILES = {
    "collision":  "results/kinematics_vs_mechanics/labels_collision.npz",
    "ramp":       "results/kinematics_vs_mechanics/labels_ramp.npz",
    "flat_drop":  "results/kinematics_vs_mechanics/labels_flat_drop.npz",
    "elasticity": "results/kinematics_vs_mechanics/labels_elasticity.npz",
    "ramp_3prop": "results/kinematics_vs_mechanics/labels_ramp_3prop.npz",
}

# Property availability
PROPERTY_SCENARIOS = {
    "restitution": ["collision", "ramp", "flat_drop", "elasticity", "ramp_3prop"],
    "friction":    ["ramp", "flat_drop", "ramp_3prop"],
}


def log(msg):
    ts = datetime.now(timezone.utc).strftime("%H:%M:%SZ")
    line = f"[{ts}] P3-matrix: {msg}"
    print(line, flush=True)
    with open(LOG, "a") as f: f.write(line + "\n")


def load_feat_subsampled(dataset, backbone):
    """Return [N, 4, D]. Subsample evenly or duplicate-pad to 4 temporal positions."""
    path = FEATURE_FILES[(dataset, backbone)]
    d = torch.load(path, 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()
    else:
        # Duplicate-pad. Repeat each position ceil(4/T) times and slice first 4.
        reps = (N_FRAMES_SUBSAMPLE + T - 1) // T
        feat = feat.repeat(1, reps, 1)[:, :N_FRAMES_SUBSAMPLE, :].contiguous()
    return feat


def load_labels(dataset, target):
    z = np.load(LABEL_FILES[dataset])
    key = f"{target}_bin"
    if key not in z:
        return None
    return z[key].astype(np.int64)


def main():
    t0_all = time.time()
    log(f"=== PRIORITY 3: Transfer Matrix ===")

    # Load + cache all features
    feats = {}
    for key, path in FEATURE_FILES.items():
        if Path(path).exists():
            feats[key] = load_feat_subsampled(*key)
            log(f"  {key[0]}/{key[1]}: shape={tuple(feats[key].shape)}")
        else:
            log(f"  MISSING: {path}")

    # Load + validate labels
    labels_cache = {}
    for prop, scenarios in PROPERTY_SCENARIOS.items():
        for ds in scenarios:
            lbl = load_labels(ds, prop)
            if lbl is not None:
                labels_cache[(ds, prop)] = lbl
                log(f"  labels {ds}/{prop}: {np.bincount(lbl, minlength=3).tolist()}")
            else:
                log(f"  labels {ds}/{prop} MISSING")

    # Train all base senders (property, ds, bb, seed) once
    log("\n--- Training base senders ---")
    bases = {}
    for prop, scenarios in PROPERTY_SCENARIOS.items():
        for ds in scenarios:
            if (ds, prop) not in labels_cache: continue
            labels = labels_cache[(ds, prop)]
            for bb in ("vjepa2", "dinov2", "clip"):
                if (ds, bb) not in feats: continue
                for seed in range(N_SEEDS):
                    t0 = time.time()
                    b = train_base(feats[(ds, bb)], labels, seed, n_epochs=N_EPOCHS)
                    bases[(prop, ds, bb, seed)] = b
                    log(f"  {prop}/{ds}/{bb}/seed{seed}: within_acc={b['task_acc']:.3f} [{time.time()-t0:.0f}s]")

    # Build transfer matrix
    log("\n--- Transfer matrix evaluation ---")
    results = []
    for prop, scenarios in PROPERTY_SCENARIOS.items():
        for src in scenarios:
            if (src, prop) not in labels_cache: continue
            for tgt in scenarios:
                if (tgt, prop) not in labels_cache: continue
                for bb in ("vjepa2", "dinov2", "clip"):
                    if (src, bb) not in feats or (tgt, bb) not in feats: continue
                    for seed in range(N_SEEDS):
                        if (prop, src, bb, seed) not in bases: continue
                        base = bases[(prop, src, bb, seed)]
                        tgt_labels = labels_cache[(tgt, prop)]
                        train_ids_tgt, holdout_ids_tgt = make_splits(tgt_labels, seed)

                        # If src == tgt, report within-acc (no transfer)
                        if src == tgt:
                            acc_zs = base["task_acc"]
                            acc_16 = base["task_acc"]
                        else:
                            try:
                                acc_zs = eval_zero_shot(base, feats[(tgt, bb)],
                                                          tgt_labels, holdout_ids_tgt)
                            except Exception as e:
                                log(f"  ERROR zero-shot {prop}/{src}{tgt}/{bb}/seed{seed}: {e}")
                                acc_zs = float("nan")
                            try:
                                acc_16 = train_receiver_frozen_sender(
                                    base, feats[(tgt, bb)], tgt_labels,
                                    train_ids_tgt, holdout_ids_tgt, seed,
                                    max_examples=16, n_epochs=80)
                            except Exception as e:
                                log(f"  ERROR 16-shot {prop}/{src}{tgt}/{bb}/seed{seed}: {e}")
                                acc_16 = float("nan")

                        results.append({"property": prop, "src": src, "tgt": tgt,
                                         "backbone": bb, "seed": seed,
                                         "zero_shot_acc": float(acc_zs),
                                         "sixteen_shot_acc": float(acc_16)})

    # Aggregate matrices
    def matrix(prop, bb, mode_key):
        scens = PROPERTY_SCENARIOS[prop]
        M = np.full((len(scens), len(scens)), np.nan)
        for r in results:
            if r["property"] != prop or r["backbone"] != bb: continue
            i = scens.index(r["src"]); j = scens.index(r["tgt"])
            # Average across seeds
            # (gather all matching, avg)
        # Do it by seed-aggregation properly
        for i, src in enumerate(scens):
            for j, tgt in enumerate(scens):
                vals = [r[mode_key] for r in results
                        if r["property"] == prop and r["backbone"] == bb
                        and r["src"] == src and r["tgt"] == tgt]
                if vals:
                    M[i, j] = np.nanmean(vals)
        return M, scens

    lines = []
    lines.append(f"PRIORITY 3: PROPERTY TRANSFER MATRIX (2 seeds, 16-shot mode)")
    lines.append(f"Within-scenario cells (diagonal) show within-dataset training accuracy.")
    lines.append("")
    for prop in PROPERTY_SCENARIOS:
        lines.append(f"\n=== {prop.upper()} ({len(PROPERTY_SCENARIOS[prop])} scenarios) ===")
        for bb in ("vjepa2", "dinov2", "clip"):
            M, scens = matrix(prop, bb, "sixteen_shot_acc")
            if np.all(np.isnan(M)): continue
            lines.append(f"\n  {bb}:")
            head = "  " + "Train\\Test      | " + " | ".join(f"{s[:11]:>11s}" for s in scens)
            lines.append(head)
            lines.append("  " + "-" * (len(head) - 2))
            for i, src in enumerate(scens):
                row = f"  {src[:15]:<15s} | " + " | ".join(
                    f"{M[i,j]*100:>10.1f}%" if not np.isnan(M[i,j]) else f"{'—':>11s}"
                    for j in range(len(scens)))
                lines.append(row)

    # Also zero-shot matrix
    lines.append("\n\nZERO-SHOT MODE (no receiver retraining)")
    for prop in PROPERTY_SCENARIOS:
        lines.append(f"\n=== {prop.upper()} ===")
        for bb in ("vjepa2", "dinov2", "clip"):
            M, scens = matrix(prop, bb, "zero_shot_acc")
            if np.all(np.isnan(M)): continue
            lines.append(f"\n  {bb}:")
            head = "  " + "Train\\Test      | " + " | ".join(f"{s[:11]:>11s}" for s in scens)
            lines.append(head)
            lines.append("  " + "-" * (len(head) - 2))
            for i, src in enumerate(scens):
                row = f"  {src[:15]:<15s} | " + " | ".join(
                    f"{M[i,j]*100:>10.1f}%" if not np.isnan(M[i,j]) else f"{'—':>11s}"
                    for j in range(len(scens)))
                lines.append(row)

    total_s = time.time() - t0_all
    lines.append(f"\n\nTotal P3 runtime: {total_s/60:.1f} min ({total_s:.0f}s)")
    lines.append(f"N transfer evals: {len(results)}")
    lines.append(f"N base senders trained: {len(bases)}")

    summary = "\n".join(lines)
    (OUT / "p3_matrix_summary.txt").write_text(summary + "\n")
    with open(OUT / "p3_matrix_raw.json", "w") as f:
        json.dump({"runs": results, "total_runtime_s": total_s}, f, indent=2, default=str)
    log(f"\n{summary}")
    log(f"\nSaved: {OUT / 'p3_matrix_summary.txt'}")


if __name__ == "__main__":
    main()