File size: 3,422 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
#!/usr/bin/env python3
"""Extract ACT encoder features with each frame's position inside its episode.

Enables splitting an episode into phases. The interesting contrast for this task:
during REACHING the gripper has not touched anything, so any cable discrimination
must come from vision; during SORTING the cable is in hand, so tactile is
available too. If cable identity is decodable during reaching just as well as
during sorting, touch is not what carries it.

Frames are sampled uniformly across each episode (not randomly) so every phase is
covered evenly.
"""
import argparse
import numpy as np
import torch
import torch.nn.functional as F
from lerobot.datasets.lerobot_dataset import LeRobotDataset
from lerobot.policies.act.modeling_act import ACTPolicy


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("--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=40)
    ap.add_argument("--device", default="cuda")
    ap.add_argument("--out", default="outputs/pca/cache_cable_phase.npz")
    args = ap.parse_args()

    ds = LeRobotDataset(args.repo_id)
    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()))

    by = {}
    for ep in range(ds.meta.total_episodes):
        by.setdefault(episode_task(ds, ep), []).append(ep)

    rng = np.random.default_rng(0)
    feats, y, eps, tpos, tsec = [], [], [], [], []
    fps = ds.meta.fps
    for task, e in sorted(by.items()):
        chosen = rng.choice(e, size=min(args.eps_per_task, len(e)), 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])
            n = hi - lo
            # uniform coverage so each phase is represented
            idxs = np.linspace(0, n - 1, min(args.frames_per_ep, n)).astype(int)
            for k in idxs:
                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"]); y.append(task); eps.append(ep)
                tpos.append(k / max(n - 1, 1))     # 0 = episode start, 1 = end
                tsec.append(k / fps)                # seconds from episode start
    np.savez_compressed(args.out, feats=np.array(feats), y=np.array(y),
                        eps=np.array(eps), tpos=np.array(tpos), tsec=np.array(tsec))
    print(f"\nwrote {args.out}: {len(y)} frames, fps={fps}", flush=True)
    print(f"  episode length: {np.mean([int(ds.meta.episodes['dataset_to_index'][e]) - int(ds.meta.episodes['dataset_from_index'][e]) for e in range(ds.meta.total_episodes)]) / fps:.1f} s average", flush=True)


if __name__ == "__main__":
    main()