File size: 7,683 Bytes
ae1ed83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build the frozen-feature cache for TRACE-VLA training (spec 13/17.2).

Reads the real lerobot/libero dataset (revision v3.0), restricted to
the 21 train tasks of the current program split
(~/sera_v4_experiments/fewshot/fs1_split.json). Computes state/action
MEAN_STD statistics over the full train split. Encodes a subset of
episodes (default: first 3 episodes of each train task) with the
frozen TIPSv2 anchor: rot180 orientation correction applied to the
dataset frames (spec 13.1), resize to 224, 2x2 pooling to 64 patches.

Output: a .pt file with fp16 features [F, 2, 64, 768], raw states and
actions, episode slices, per-task text embeddings, and the statistics.
"""
import argparse
import json
from pathlib import Path

import numpy as np
import torch

import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from trace_vla.anchor import TipsAnchor  # noqa: E402

EXP = Path.home() / "sera_v4_experiments"


def task_texts(meta, hf):
    """Resolve {task_index: instruction} robustly for this lerobot version."""
    # Preferred: tasks parquet in the dataset snapshot.
    try:
        import pandas as pd
        root = Path(meta.root) if getattr(meta, "root", None) else None
        cand = list(Path.home().glob(
            ".cache/huggingface/lerobot/lerobot/libero/meta/tasks.parquet"))
        if root is not None:
            cand = [root / "meta" / "tasks.parquet"] + cand
        for path in cand:
            if path.exists():
                df = pd.read_parquet(path)
                cols = {c.lower(): c for c in df.columns}
                ti = cols.get("task_index", df.columns[0])
                tx = cols.get("task", df.columns[-1])
                out = {int(r[ti]): str(r[tx]) for _, r in df.iterrows()}
                print(f"task texts from {path}: {len(out)} tasks")
                return out
    except Exception as e:  # noqa: BLE001
        print("tasks.parquet path failed:", e)
    t = meta.tasks
    print("meta.tasks type:", type(t).__name__)
    if isinstance(t, dict):
        return {int(k): str(v) for k, v in t.items()}
    raise RuntimeError("cannot resolve task texts")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--episodes-per-task", type=int, default=3)
    ap.add_argument("--out", default=str(EXP / "trace_vla" / "feature_cache.pt"))
    ap.add_argument("--encode-batch", type=int, default=32)
    args = ap.parse_args()

    from lerobot.datasets.lerobot_dataset import LeRobotDataset, LeRobotDatasetMetadata

    split = json.loads((EXP / "fewshot" / "fs1_split.json").read_text())
    train_tasks = split["train_tasks_ds"]
    train_eps = split["train_episodes"]
    print(f"train tasks: {train_tasks}")
    print(f"train episodes: {len(train_eps)}")

    meta = LeRobotDatasetMetadata("lerobot/libero", revision="v3.0")
    ep_len = np.array(meta.episodes["length"])
    full = LeRobotDataset("lerobot/libero", revision="v3.0",
                          video_backend="pyav")
    task_col = np.array(full.hf_dataset["task_index"])
    starts = np.zeros(len(ep_len) + 1, dtype=np.int64)
    np.cumsum(ep_len, out=starts[1:])
    ep_task = np.array([task_col[starts[e]] for e in range(len(ep_len))])

    # ---- statistics over the full train split (state/action columns) ----
    train_set = set(train_eps)
    ep_col = np.array(full.hf_dataset["episode_index"])
    rows = np.isin(ep_col, list(train_set))
    states = np.stack(full.hf_dataset["observation.state"])[rows].astype(np.float64)
    actions = np.stack(full.hf_dataset["action"])[rows].astype(np.float64)
    stats = {
        "state_mean": torch.tensor(states.mean(0), dtype=torch.float32),
        "state_std": torch.tensor(states.std(0), dtype=torch.float32),
        "action_mean": torch.tensor(actions.mean(0), dtype=torch.float32),
        "action_std": torch.tensor(actions.std(0), dtype=torch.float32),
    }
    print(f"stats over {rows.sum()} train frames")
    print("state_std:", stats["state_std"].tolist())
    print("action_std:", stats["action_std"].tolist())

    # ---- select episodes: first N per train task ----
    selected = []
    for t in train_tasks:
        eps = [e for e in train_eps if int(ep_task[e]) == t]
        selected.extend(sorted(eps)[: args.episodes_per_task])
    selected = sorted(selected)
    total_frames = int(sum(ep_len[e] for e in selected))
    print(f"selected {len(selected)} episodes, {total_frames} frames")

    texts = task_texts(meta, full.hf_dataset)

    device = "cuda" if torch.cuda.is_available() else "cpu"
    anchor = TipsAnchor("google/tipsv2-b14").to(device)
    text_emb = {}
    for t in train_tasks:
        text_emb[t] = anchor.encode_text([texts[t]])[0].cpu().float()
    print("text embeddings:", len(text_emb))

    ds = LeRobotDataset("lerobot/libero", revision="v3.0",
                        episodes=selected, video_backend="pyav")
    print("subset dataset length:", len(ds))

    per_ep = {e: {} for e in selected}   # ep -> {frame_index: feat[2,64,768]}
    buf_imgs, buf_refs = [], []

    def flush():
        if not buf_imgs:
            return
        imgs = torch.stack(buf_imgs).to(device)          # [N,2,3,256,256]
        n = imgs.shape[0]
        flat = imgs.flatten(0, 1).float()
        with torch.autocast("cuda", dtype=torch.bfloat16,
                            enabled=(device == "cuda")):
            pooled = anchor.encode_patches(flat)         # [2N,64,768]
        pooled = pooled.float().reshape(n, 2, 64, 768).half().cpu()
        for i, (e, f) in enumerate(buf_refs):
            per_ep[e][f] = pooled[i]
        buf_imgs.clear()
        buf_refs.clear()

    for i in range(len(ds)):
        item = ds[i]
        e = int(item["episode_index"])
        f = int(item["frame_index"])
        img = torch.flip(item["observation.images.image"], dims=(-2, -1))
        img2 = torch.flip(item["observation.images.image2"], dims=(-2, -1))
        buf_imgs.append(torch.stack([img, img2]))
        buf_refs.append((e, f))
        if len(buf_imgs) >= args.encode_batch:
            flush()
        if i % 2000 == 0:
            print(f"  frame {i}/{len(ds)}", flush=True)
    flush()

    feats, sts, acts, episodes = [], [], [], []
    offset = 0
    full_states = np.stack(full.hf_dataset["observation.state"])
    full_actions = np.stack(full.hf_dataset["action"])
    for e in selected:
        frames = per_ep[e]
        length = int(ep_len[e])
        assert len(frames) == length, f"ep {e}: {len(frames)} != {length}"
        for f in range(length):
            feats.append(frames[f])
        g0 = int(starts[e])
        sts.append(torch.tensor(full_states[g0:g0 + length], dtype=torch.float32))
        acts.append(torch.tensor(full_actions[g0:g0 + length], dtype=torch.float32))
        episodes.append({"start": offset, "length": length,
                         "episode_id": int(e), "task_index": int(ep_task[e])})
        offset += length
    cache = {
        "features": torch.stack(feats),
        "states": torch.cat(sts),
        "actions": torch.cat(acts),
        "episodes": episodes,
        "text_emb": text_emb,
        "stats": stats,
        "meta": {
            "dataset": "lerobot/libero", "revision": "v3.0",
            "orientation": "rot180 applied to dataset frames",
            "image_size": 224, "episodes_per_task": args.episodes_per_task,
            "selected_episodes": selected,
        },
    }
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    torch.save(cache, out)
    print(f"saved {out} ({out.stat().st_size / 1e9:.2f} GB), "
          f"features {tuple(cache['features'].shape)}")


if __name__ == "__main__":
    main()