File size: 8,717 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
"""R6 200k run — build the raw image store + demo mid-feature store.

Phase 1 (30k->100k) unfreezes vision blocks 8-11 + final norm, so the
pooled-feature cache of the ladder cannot be used for frames the
policy consumes. This script builds, indexed EXACTLY like
cache_df_r2 frames (episode start/length):

  raw200k/raw_images.dat  uint8 [F, 2, 224, 224, 3]
      Every pool frame, both cameras. D0 frames come from the
      LeRobot dataset with the rot180 flip of build_subset_cache.py;
      factory frames come from the expand .npz files (no flip).
      Resize to 224 uses F.interpolate bilinear align_corners=False,
      the same op TipsAnchor.encode_patches applies internally.
      FACTORY FRAMES ARE STORED PRE-SCRAMBLED: the ladder's cache
      build (df_build_cache_expand.encode_factory) reshaped the
      NHWC stack [B,2,256,256,3] straight to (B*2,3,256,256) with
      no permute, so every factory feature in cache_df_r2 was
      encoded from a fixed pixel permutation of the true frame
      (verified 22/11: cos = 1.0 against the cache). The raw store
      applies that exact reinterpretation at 256 before resizing,
      so encoding a stored factory frame normally reproduces the
      distribution R6 was trained on. --factory-only rebuilds just
      the factory rows + demo mid store.
  raw200k/demo_mid.dat    fp16 [N, 258, 768]
      Tokens after the FROZEN block 7 of the original TIPSv2 encoder
      (fp32, no_grad) for the main-camera demo subsample frames
      (subsample_indices(length, 64)) of every cache episode.
  raw200k/raw200k_index.json
      Per-episode {start, length, source, episode_id, demo_offset,
      demo_n}.

Idempotent: skips work when raw200k/DONE exists.
"""
import json
import sys
import time
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))
from trace_vla.data import subsample_indices  # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
DF = EXP / "data_factory"
OUT = DF / "raw200k"
OUT.mkdir(parents=True, exist_ok=True)
DEVICE = "cuda"
BATCH = 256  # frames per GPU flush (x2 cameras)


def resize_u8(imgs_f: torch.Tensor) -> torch.Tensor:
    """imgs_f [N,3,H,W] float in [0,1] on GPU -> uint8 [N,224,224,3]."""
    if imgs_f.shape[-1] != 224 or imgs_f.shape[-2] != 224:
        imgs_f = F.interpolate(imgs_f, size=(224, 224), mode="bilinear",
                               align_corners=False)
    return (imgs_f.clamp(0, 1) * 255.0).round().to(torch.uint8) \
        .permute(0, 2, 3, 1).cpu().numpy()


def build_d0(raw, episodes, t0):
    """D0 rows: LeRobot frames, rot180 flip (build_subset_cache)."""
    d0_eps = [e for e in episodes if e.get("source", "D0") == "D0"]
    by_ds_id = {int(e["episode_id"]): e for e in d0_eps}
    print(f"D0 episodes: {len(d0_eps)}", flush=True)
    from lerobot.datasets.lerobot_dataset import LeRobotDataset
    ds = LeRobotDataset("lerobot/libero", revision="v3.0",
                        episodes=sorted(by_ds_id),
                        video_backend="pyav")
    buf, refs = [], []

    def flush():
        if not buf:
            return
        imgs = torch.stack(buf).to(DEVICE)          # [n,2,3,H,W]
        n = imgs.shape[0]
        out = resize_u8(imgs.flatten(0, 1).float())
        out = out.reshape(n, 2, 224, 224, 3)
        for i, pos in enumerate(refs):
            raw[pos] = out[i]
        buf.clear()
        refs.clear()

    seen = 0
    for i in range(len(ds)):
        item = ds[i]
        e = int(item["episode_index"])
        f = int(item["frame_index"])
        ep = by_ds_id[e]
        img = torch.flip(item["observation.images.image"],
                         dims=(-2, -1))
        img2 = torch.flip(item["observation.images.image2"],
                          dims=(-2, -1))
        if i == 0:
            print("dataset image shape/dtype:", tuple(img.shape),
                  img.dtype, "range", float(img.min()), float(img.max()),
                  flush=True)
        buf.append(torch.stack([img, img2]))
        refs.append(int(ep["start"]) + f)
        seen += 1
        if len(buf) >= BATCH:
            flush()
        if i % 5000 == 0:
            print(f"  D0 frame {i}/{len(ds)}", flush=True)
    flush()
    assert seen == sum(int(e["length"]) for e in d0_eps), \
        f"D0 frames {seen} != expected"
    print(f"D0 done ({seen} frames, {time.time() - t0:.0f}s)",
          flush=True)


def main():
    factory_only = "--factory-only" in sys.argv
    if (OUT / "DONE").exists() and not factory_only:
        print("raw200k already built, skipping", flush=True)
        return
    t0 = time.time()
    cache = torch.load(DF / "cache_df_r2.pt", weights_only=True,
                       mmap=True)
    episodes = cache["episodes"]
    n_frames = int(cache["features"].shape[0])
    assert sum(int(e["length"]) for e in episodes) == n_frames
    print(f"pool: {len(episodes)} episodes, {n_frames} frames",
          flush=True)
    raw = np.memmap(OUT / "raw_images.dat", dtype=np.uint8,
                    mode="r+" if factory_only else "w+",
                    shape=(n_frames, 2, 224, 224, 3))

    # ---------- D0 frames from the LeRobot dataset ----------
    if factory_only:
        print("factory-only: D0 rows kept from the previous build",
              flush=True)
    else:
        build_d0(raw, episodes, t0)

    # ---------- Factory frames from .npz (pre-scrambled) --------
    man = json.loads((DF / "expand" / "manifest.json").read_text())
    man_by_id = {e["episode_id"]: e for e in man["episodes"]}
    fac_eps = [e for e in episodes if e.get("source", "D0") != "D0"]
    print(f"factory episodes: {len(fac_eps)}", flush=True)
    for n_done, ep in enumerate(fac_eps):
        me = man_by_id[ep["episode_id"]]
        d = np.load(DF / "expand" / me["file"])
        av = torch.as_tensor(d["agentview"]).float() / 255.0
        wr = torch.as_tensor(d["wrist"]).float() / 255.0
        assert len(av) == int(ep["length"]), \
            f"{ep['episode_id']}: npz {len(av)} != cache {ep['length']}"
        for s in range(0, len(av), 128):
            imgs = torch.stack([av[s:s + 128], wr[s:s + 128]],
                               dim=1).to(DEVICE)     # [n,2,256,256,3]
            n = imgs.shape[0]
            # The ladder's exact reinterpretation (no permute):
            # NHWC buffer read as NCHW — a fixed pixel permutation.
            scr = imgs.reshape(n * 2, 3, 256, 256)
            out = resize_u8(scr)
            raw[int(ep["start"]) + s:
                int(ep["start"]) + s + n] = \
                out.reshape(n, 2, 224, 224, 3)
        if n_done % 100 == 0:
            print(f"  factory {n_done}/{len(fac_eps)}", flush=True)
    raw.flush()
    print(f"raw store done ({time.time() - t0:.0f}s)", flush=True)

    # ---------- Demo mid features (frozen bottom, fp32) ----------
    from trace_vla.anchor import TipsAnchor
    anchor = TipsAnchor("google/tipsv2-b14").to(DEVICE)
    ve = anchor.tips.vision_encoder
    total_demo = sum(len(subsample_indices(int(e["length"]), 64))
                     for e in episodes)
    mid = np.memmap(OUT / "demo_mid.dat", dtype=np.float16, mode="w+",
                    shape=(total_demo, 258, 768))
    index = {"F": n_frames, "episodes": []}
    offset = 0
    with torch.no_grad():
        for ei, ep in enumerate(episodes):
            idx = subsample_indices(int(ep["length"]), 64)
            pos = int(ep["start"]) + idx.numpy()
            feats = []
            for s in range(0, len(pos), 128):
                imgs = torch.as_tensor(
                    raw[pos[s:s + 128], 0]).to(DEVICE) \
                    .permute(0, 3, 1, 2).float() / 255.0
                tok = ve.prepare_tokens_with_masks(imgs)
                for blk in ve.blocks[:8]:
                    tok = blk(tok)
                feats.append(tok.cpu().half().numpy())
            arr = np.concatenate(feats, axis=0)
            mid[offset:offset + len(arr)] = arr
            index["episodes"].append({
                "start": int(ep["start"]), "length": int(ep["length"]),
                "source": ep.get("source", "D0"),
                "episode_id": ep["episode_id"],
                "demo_offset": int(offset), "demo_n": int(len(arr))})
            offset += len(arr)
            if ei % 100 == 0:
                print(f"  mid {ei}/{len(episodes)}", flush=True)
    mid.flush()
    (OUT / "raw200k_index.json").write_text(json.dumps(index))
    (OUT / "DONE").write_text("ok")
    print(f"ALL DONE: raw {n_frames} frames, demo mid {offset} images, "
          f"{time.time() - t0:.0f}s", flush=True)


if __name__ == "__main__":
    main()