File size: 5,526 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
#!/usr/bin/env python3
"""Extend the TRACE subset feature cache with ONE held-out task demo.

Built for Young's 19:32 21/11/2026 request: run TRACE C02 on a truly
held-out task. Object #7 (dataset index 25, "pick up the milk and
place it in the basket") is NOT in the 12-task subset C02 trained on.

This script loads feature_cache_subset.pt UNCHANGED (same stats, same
episodes - C02's training/eval conditions stay bit-identical), encodes
the FIRST episode of ds25 in dataset order with the identical contract
as build_subset_cache.py (frozen TIPSv2 google/tipsv2-b14, rot180 on
dataset frames, both cameras, 2x2 pooling to 64 patches, fp16), marks
it split="demo" (demo-only, never trained on), and saves the result
as a NEW file feature_cache_subset_plus25.pt. The original cache is
not modified.
"""
import json
from pathlib import Path

import numpy as np
import torch

import sys
sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))

from trace_vla.anchor import TipsAnchor  # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
TARGET_DS = 25


def task_texts(meta):
    import pandas as pd
    cand = [Path(meta.root) / "meta" / "tasks.parquet"] if \
        getattr(meta, "root", None) else []
    cand += list(Path.home().glob(
        ".cache/huggingface/lerobot/lerobot/libero/meta/tasks.parquet"))
    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])
            return {int(r[ti]): str(r[tx]) for _, r in df.iterrows()}
    raise RuntimeError("cannot resolve task texts")


def main():
    from lerobot.datasets.lerobot_dataset import LeRobotDataset, \
        LeRobotDatasetMetadata

    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"])
    ep_col = np.array(full.hf_dataset["episode_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))])

    eps = sorted(e for e in range(len(ep_len)) if ep_task[e] == TARGET_DS)
    demo_ep = eps[0]
    length = int(ep_len[demo_ep])
    print(f"ds{TARGET_DS}: {len(eps)} episodes, first = ep {demo_ep} "
          f"({length} frames)")

    texts = task_texts(meta)
    print(f"official task text: {texts[TARGET_DS]!r}")

    device = "cuda"
    anchor = TipsAnchor("google/tipsv2-b14").to(device)

    ds = LeRobotDataset("lerobot/libero", revision="v3.0",
                        episodes=[demo_ep], video_backend="pyav")
    per_frame = {}
    buf_imgs, buf_refs = [], []

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

    for i in range(len(ds)):
        item = ds[i]
        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(f)
        if len(buf_imgs) >= 32:
            flush()
    flush()
    assert len(per_frame) == length, f"{len(per_frame)} != {length}"
    new_feats = torch.stack([per_frame[f] for f in range(length)])
    print(f"encoded features {tuple(new_feats.shape)} {new_feats.dtype}")

    g0 = int(starts[demo_ep])
    full_states = np.stack(full.hf_dataset["observation.state"])
    full_actions = np.stack(full.hf_dataset["action"])
    new_states = torch.tensor(full_states[g0:g0 + length],
                              dtype=torch.float32)
    new_actions = torch.tensor(full_actions[g0:g0 + length],
                               dtype=torch.float32)

    cache = torch.load(EXP / "trace_vla" / "feature_cache_subset.pt",
                       weights_only=False)
    old_total = int(cache["features"].shape[0])
    cache["features"] = torch.cat([cache["features"], new_feats], dim=0)
    cache["states"] = torch.cat([cache["states"], new_states], dim=0)
    cache["actions"] = torch.cat([cache["actions"], new_actions], dim=0)
    cache["episodes"].append({"start": old_total, "length": length,
                              "episode_id": int(demo_ep),
                              "task_index": TARGET_DS, "split": "demo"})
    cache["text_emb"][TARGET_DS] = anchor.encode_text(
        [texts[TARGET_DS]])[0].cpu().float()
    cache["meta"]["plus25_extension"] = (
        f"appended demo-only episode {demo_ep} of ds{TARGET_DS} "
        f"({texts[TARGET_DS]!r}) for held-out eval; stats and all "
        "subset episodes unchanged")
    out = EXP / "trace_vla" / "feature_cache_subset_plus25.pt"
    torch.save(cache, out)
    print(f"saved {out} ({out.stat().st_size / 1e9:.2f} GB), "
          f"features {tuple(cache['features'].shape)}, "
          f"episodes {len(cache['episodes'])}")


if __name__ == "__main__":
    main()