File size: 3,583 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
#!/usr/bin/env python3
"""Extract ACT encoder features for four cable sizes drawn from two datasets.

The 3.00 sq cable lives in a different dataset (cable3sizes_180ep) from the other
three (bluev2_cable170_330_270ep). Both were recorded with the same rig and the
same camera layout, and features come from one single policy, so they land in a
common space -- but the cross-dataset boundary is a real confound worth stating:
any session-level difference (lighting, gel state, day) rides along with the
3.00 sq label. The ordering test is what guards against reading too much into it:
a session artefact has no reason to place 3.00 sq *between* two other sizes.

Equal episode counts per size keep the t-SNE from being dominated by one class.
"""
import argparse
import numpy as np
import torch
from lerobot.datasets.lerobot_dataset import LeRobotDataset
from lerobot.policies.act.modeling_act import ACTPolicy

SOURCES = [
    ("Kaz55/dg5f_ur5e_bluev2_cable170_330_270ep",
     {"cable 1.70 sq": "1.70 sq", "blue cable": "blue (2.6 mm)", "cable 3.30 sq": "3.30 sq"}),
    ("Kaz55/dg5f_ur5e_cable3sizes_180ep",
     {"cable 3.00 sq": "3.00 sq"}),
]


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


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--policy-path", required=True)
    ap.add_argument("--eps-per-size", type=int, default=60)
    ap.add_argument("--frames-per-ep", type=int, default=15)
    ap.add_argument("--device", default="cuda")
    ap.add_argument("--out", default="outputs/pca/cache/cache_4sizes.npz")
    args = ap.parse_args()

    policy = ACTPolicy.from_pretrained(args.policy_path).to(args.device).eval()
    cap = {}
    policy.model.encoder.register_forward_hook(
        lambda m, i, o: cap.__setitem__("e", o.detach().mean(0).squeeze(0).float().cpu().numpy()))

    rng = np.random.default_rng(0)
    feats, label, eps, src = [], [], [], []
    for repo, wanted in SOURCES:
        ds = LeRobotDataset(repo)
        by = {}
        for ep in range(ds.meta.total_episodes):
            t = episode_task(ds, ep)
            if t in wanted:
                by.setdefault(t, []).append(ep)
        for task, e in sorted(by.items()):
            chosen = rng.choice(e, size=min(args.eps_per_size, len(e)), replace=False)
            print(f"  {repo.split('/')[-1]:34s} {wanted[task]:14s} {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])
                n = hi - lo
                for k in np.linspace(0, n - 1, min(args.frames_per_ep, n)).astype(int):
                    item = ds[int(lo + k)]
                    b = {kk: v.unsqueeze(0).to(args.device) for kk, v in item.items()
                         if isinstance(v, torch.Tensor)}
                    b["task"] = [task]
                    with torch.no_grad():
                        policy.select_action(b)
                    policy.reset()
                    feats.append(cap["e"]); label.append(wanted[task])
                    eps.append(f"{repo}#{ep}"); src.append(repo.split("/")[-1])
    np.savez_compressed(args.out, feats=np.array(feats), label=np.array(label),
                        eps=np.array(eps), src=np.array(src))
    lab = np.array(label)
    print(f"\nwrote {args.out}: {len(label)} frames")
    for u in sorted(set(label)):
        print(f"    {u:14s} {int((lab == u).sum())}")


if __name__ == "__main__":
    main()