File size: 6,435 Bytes
3c41fb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Does the ACT encoder representation actually carry cable identity?

2-D PCA is unsupervised: if cable type is not among the top variance directions
it stays invisible even when the information is present. So measure it directly
with a linear probe, then visualise with LDA (a supervised projection).

Critical: the split is by EPISODE, not by frame. Frames inside one episode are
near-duplicates, so a frame-level split leaks the answer and any probe scores
~100% regardless of what the model learned. Held-out episodes are the only
honest test. LDA is likewise fit on train episodes and plotted on test episodes,
otherwise a supervised projection manufactures clusters that do not generalise.
"""
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

from lerobot.datasets.lerobot_dataset import LeRobotDataset
from lerobot.policies.act.modeling_act import ACTPolicy

COLORS = {"blue cable": "#2B6CB0", "cable 1.70 sq": "#C05621", "cable 3.30 sq": "#2F855A"}


def episode_task(ds, ep):
    t = ds.meta.episodes["tasks"][ep]
    return t[0] if isinstance(t, (list, np.ndarray)) else str(t)


def collect(ds, policy, device, eps_per_task, frames_per_ep, seed=0):
    captured = {}
    policy.model.encoder.register_forward_hook(
        lambda m, i, o: captured.__setitem__("enc", o.detach().mean(0).squeeze(0).float().cpu().numpy()))
    by_task = {}
    for ep in range(ds.meta.total_episodes):
        by_task.setdefault(episode_task(ds, ep), []).append(ep)
    rng = np.random.default_rng(seed)
    feats, pix, labels, epids = [], [], [], []
    for task, eps in sorted(by_task.items()):
        chosen = rng.choice(eps, size=min(eps_per_task, len(eps)), replace=False)
        print(f"  {task}: {len(chosen)} episodes", flush=True)
        for ep in chosen:
            lo = int(ds.meta.episodes["dataset_from_index"][ep])
            hi = int(ds.meta.episodes["dataset_to_index"][ep])
            for i in rng.choice(np.arange(lo, hi), size=min(frames_per_ep, hi - lo), replace=False):
                item = ds[int(i)]
                batch = {k: v.unsqueeze(0).to(device) for k, v in item.items()
                         if isinstance(v, torch.Tensor)}
                batch["task"] = [task]
                with torch.no_grad():
                    policy.select_action(batch)
                policy.reset()
                feats.append(captured["enc"])
                gs = item["observation.images.gelsight1"].unsqueeze(0).float()
                pix.append(F.adaptive_avg_pool2d(gs, 16).flatten().numpy())
                labels.append(task); epids.append(ep)
    return np.array(feats), np.array(pix), np.array(labels), np.array(epids)


def probe(X, y, ep, seed=0):
    """Logistic-regression accuracy on held-out EPISODES."""
    rng = np.random.default_rng(seed)
    tr = np.zeros(len(y), bool)
    for task in np.unique(y):
        eps = np.unique(ep[y == task])
        keep = rng.choice(eps, size=int(len(eps) * 0.7), replace=False)
        tr |= np.isin(ep, keep)
    clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000, C=1.0))
    clf.fit(X[tr], y[tr])
    return clf.score(X[~tr], y[~tr]), tr


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo-id", default="Kaz55/dg5f_ur5e_bluev2_cable170_330_270ep")
    ap.add_argument("--policy-path", required=True)
    ap.add_argument("--eps-per-task", type=int, default=30)
    ap.add_argument("--frames-per-ep", type=int, default=25)
    ap.add_argument("--device", default="cuda")
    ap.add_argument("--out", default="outputs/pca/cable_repr_analysis.png")
    args = ap.parse_args()

    ds = LeRobotDataset(args.repo_id)
    policy = ACTPolicy.from_pretrained(args.policy_path).to(args.device).eval()
    feats, pix, y, ep = collect(ds, policy, args.device, args.eps_per_task, args.frames_per_ep)
    print(f"collected {len(y)} frames; encoder dim {feats.shape[1]}\n", flush=True)

    chance = 1.0 / len(np.unique(y))
    results = {}
    for name, X in (("ACT encoder", feats), ("GelSight pixels", pix)):
        acc, tr = probe(X, y, ep)
        results[name] = (X, acc, tr)
        print(f"  {name:16s} held-out episode accuracy: {acc:.1%}  (chance {chance:.1%})", flush=True)

    fig, axes = plt.subplots(1, 3, figsize=(16.5, 5.2))
    # Panel 1+2: LDA fitted on train episodes, plotted on held-out episodes.
    for ax, name in zip(axes[:2], ("ACT encoder", "GelSight pixels")):
        X, acc, tr = results[name]
        lda = LDA(n_components=2).fit(X[tr], y[tr])
        xy = lda.transform(X[~tr])
        yt = y[~tr]
        for task in sorted(set(y)):
            m = yt == task
            ax.scatter(xy[m, 0], xy[m, 1], s=9, alpha=0.55, edgecolors="none",
                       c=COLORS.get(task, "#666"), label=task)
        ax.set_title(f"{name} — LDA (held-out episodes)\nprobe accuracy {acc:.1%} vs chance {chance:.1%}",
                     fontsize=10.5)
        ax.set_xlabel("LD1"); ax.set_ylabel("LD2")
        ax.spines[["top", "right"]].set_visible(False)
    axes[0].legend(frameon=False, fontsize=9)

    # Panel 3: which PCA component carries cable identity, if any.
    X = results["ACT encoder"][0]
    Xc = X - X.mean(0)
    p = PCA(n_components=30).fit(Xc)
    Z = p.transform(Xc)
    sep = []
    for k in range(30):
        groups = [Z[y == t, k] for t in sorted(set(y))]
        between = np.var([g.mean() for g in groups])
        within = np.mean([g.var() for g in groups])
        sep.append(between / (within + 1e-12))
    axes[2].bar(range(1, 31), sep, color="#2B6CB0")
    axes[2].set_title("ACT encoder — cable separability per PC\n(between-class / within-class variance)",
                      fontsize=10.5)
    axes[2].set_xlabel("principal component"); axes[2].set_ylabel("separability ratio")
    axes[2].spines[["top", "right"]].set_visible(False)

    fig.suptitle("Does the ACT internal representation encode cable identity?", fontsize=13)
    fig.tight_layout()
    fig.savefig(args.out, dpi=150)
    print(f"\nwrote {args.out}", flush=True)


if __name__ == "__main__":
    main()