File size: 14,207 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env python3
"""R6 200k phase 1 — raw-image data path with a partially trainable
vision tower.

The ladder caches pooled ANCHOR features of a FROZEN encoder. Phase 1
unfreezes vision blocks 8-11 + final norm, so pooled features are
recomputed every step:

  live/history frames: raw store -> frozen bottom (prepare_tokens +
  blocks 0-7, no_grad) -> trainable top (blocks 8-11 + norm, grad)
  demo frames: precomputed mid tokens after block 7 (demo_mid.dat)
  -> trainable top (grad)

ECHO targets and text embeddings still come from the original cache
(frozen original feature space / frozen text encoder). All other
batch fields are identical to FactoryData/SupportQueryData: same
samples, same support pairing RNG consumption (one randint per
sample, in order), same masks and privileged grounding fields.
"""
import json
import sys
from pathlib import Path

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

sys.path.insert(0, str(Path(__file__).parent))
sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))
from trace_vla.anchor import pool_patches_2x2          # noqa: E402
from trace_vla.data import SupportQueryData, normalize, subsample_indices  # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
RAW = EXP / "data_factory" / "raw200k"
K = 6
TOP_CHUNK = 96


class VisionTop(nn.Module):
    """Trainable top of the TIPSv2 tower: blocks 8-11 + final norm.

    Holds REFERENCES to the anchor's own modules (shared parameters);
    the bottom (patch_embed, blocks 0-7) and the text encoder stay
    frozen and are only used under no_grad.
    """

    def __init__(self, vision_encoder):
        super().__init__()
        self.ve = vision_encoder
        self.blocks = nn.ModuleList(list(vision_encoder.blocks[8:12]))
        self.norm = vision_encoder.norm

    def forward(self, mid: torch.Tensor) -> torch.Tensor:
        """mid [N,258,768] -> pooled patch features [N,64,768]."""
        outs = []
        for chunk in mid.split(TOP_CHUNK):
            x = chunk
            for blk in self.blocks:
                x = torch.utils.checkpoint.checkpoint(
                    blk, x, use_reentrant=False)
            x = self.norm(x)
            outs.append(pool_patches_2x2(x[:, -256:]))
        return torch.cat(outs)

    def named_state(self):
        """Checkpoint-friendly dict keyed by tower block index."""
        out = {}
        for i, blk in enumerate(self.blocks):
            out[f"blocks.{8 + i}"] = blk.state_dict()
        out["norm"] = self.norm.state_dict()
        return out

    def load_named_state(self, named):
        for i, blk in enumerate(self.blocks):
            blk.load_state_dict(named[f"blocks.{8 + i}"])
        self.norm.load_state_dict(named["norm"])


def apply_named_state(vision_encoder, named):
    """Load a named_state dict into any TIPSv2 vision encoder."""
    for i in range(8, 12):
        vision_encoder.blocks[i].load_state_dict(named[f"blocks.{i}"])
    vision_encoder.norm.load_state_dict(named["norm"])


class VisionPipe:
    """Frozen bottom encodes + trainable top, bf16 autocast."""

    def __init__(self, anchor):
        self.anchor = anchor
        self.ve = anchor.tips.vision_encoder
        for p in anchor.parameters():
            p.requires_grad_(False)
        self.top = VisionTop(self.ve)
        for p in self.top.parameters():
            p.requires_grad_(True)
        anchor.eval()

    @torch.no_grad()
    def bottom(self, imgs: torch.Tensor) -> torch.Tensor:
        """imgs [N,3,224,224] float [0,1] -> mid tokens [N,258,768]."""
        outs = []
        for chunk in imgs.split(256):
            with torch.autocast("cuda", dtype=torch.bfloat16):
                tok = self.ve.prepare_tokens_with_masks(chunk)
                for blk in self.ve.blocks[:8]:
                    tok = blk(tok)
            outs.append(tok.float())
        return torch.cat(outs)

    def top_pooled(self, mid: torch.Tensor, grad: bool) -> torch.Tensor:
        with torch.autocast("cuda", dtype=torch.bfloat16):
            if grad:
                return self.top(mid).float()
            with torch.no_grad():
                return self.top(mid).float()


class RawData(SupportQueryData):
    """SupportQueryData + FactoryData fields, pooled features computed
    on the fly through the (partially trainable) vision tower."""

    def __init__(self, cache, config, pipe: VisionPipe,
                 want_grad: bool = True):
        super().__init__(cache, config)
        self.obj_masks = cache.get("obj_masks")
        self.pipe = pipe
        self.want_grad = want_grad
        self.cache_features = cache["features"]   # original frozen
        idx = json.loads((RAW / "raw200k_index.json").read_text())
        self.raw = np.memmap(RAW / "raw_images.dat", dtype=np.uint8,
                             mode="r",
                             shape=(idx["F"], 2, 224, 224, 3))
        self.mid = np.memmap(RAW / "demo_mid.dat", dtype=np.float16,
                             mode="r")
        n_mid = self.mid.shape[0] // (258 * 768)
        self.mid = self.mid.reshape(n_mid, 258, 768)
        self.demo_index = idx["episodes"]
        assert len(self.demo_index) == len(self.episodes)
        for rec, ep in zip(self.demo_index, self.episodes):
            assert rec["start"] == ep["start"] \
                and rec["length"] == ep["length"]

    # ---- feature computation -------------------------------------
    def _compute_features(self, rows_spec, demos_spec, device):
        """rows_spec: per sample (ei, t). demos_spec: per sample None
        or (sei, idx_tensor). Returns (live, past, demo) pooled
        tensors in cache layout (float32, on device)."""
        pipe = self.pipe
        live_pos, hist_pos, hist_ok = [], [], []
        for ei, t in rows_spec:
            ep = self.episodes[ei]
            g = ep["start"] + t
            live_pos.append(g)
            hp, ok = [], []
            for h in range(1, 4):
                th = t - h * 4
                if th >= 0:
                    hp.append(ep["start"] + th)
                    ok.append(True)
                else:
                    hp.append(g)
                    ok.append(False)
            hist_pos.append(hp)
            hist_ok.append(ok)
        all_pos = list(live_pos)
        for hp in hist_pos:
            all_pos.extend(hp)
        imgs = torch.as_tensor(
            np.ascontiguousarray(self.raw[all_pos])) \
            .to(device).permute(0, 1, 4, 2, 3).float() / 255.0
        imgs = imgs.flatten(0, 1)                     # [N*2,3,224,224]
        mid_live = pipe.bottom(imgs)
        mid_all = [mid_live]
        demo_slices = []
        cursor = mid_live.shape[0]
        for spec in demos_spec:
            if spec is None:
                demo_slices.append(None)
                continue
            sei, _idx = spec
            rec = self.demo_index[sei]
            rows = torch.as_tensor(
                np.ascontiguousarray(
                    self.mid[rec["demo_offset"]:
                             rec["demo_offset"] + rec["demo_n"]])) \
                .to(device).float()
            mid_all.append(rows)
            demo_slices.append((cursor, cursor + rows.shape[0]))
            cursor += rows.shape[0]
        mid = torch.cat(mid_all)
        pooled = pipe.top_pooled(mid, self.want_grad)  # [N,64,768]
        b = len(rows_spec)
        live = pooled[:b * 2].reshape(b, 2, 64, 768)
        past = pooled[b * 2:b * 8].reshape(b, 3, 2, 64, 768)
        ok_t = torch.tensor(hist_ok, device=device)
        past = past * ok_t[:, :, None, None, None].to(past.dtype)
        demos = []
        for sl in demo_slices:
            demos.append(None if sl is None else pooled[sl[0]:sl[1]])
        return live, past, demos

    def _query_scalars(self, ei, t):
        """Non-vision query fields (states/actions/echo from cache)."""
        feats, states, actions = self.cache_features, self.states, \
            self.actions
        ep = self.episodes[ei]
        g = ep["start"] + t
        ps, pa, pe, pm = [], [], [], []
        for h in range(1, 4):
            th = t - h * 4
            if th >= 0:
                gh = ep["start"] + th
                ps.append(normalize(states[gh], self.state_mean,
                                    self.state_std))
                pa.append(normalize(actions[gh], self.action_mean,
                                    self.action_std))
                pe.append(h * 4 / 10.0)
                pm.append(True)
            else:
                ps.append(torch.zeros(8))
                pa.append(torch.zeros(7))
                pe.append(0.0)
                pm.append(False)
        return {
            "state_norm": normalize(states[g], self.state_mean,
                                    self.state_std),
            "past_state": torch.stack(ps),
            "past_action": torch.stack(pa),
            "past_elapsed": torch.tensor(pe),
            "past_mask": torch.tensor(pm),
            "action_target": normalize(actions[g:g + 16],
                                       self.action_mean,
                                       self.action_std),
            "echo_target": (feats[g + 4, 0] - feats[g, 0]).detach(),
        }

    def get_batch(self, indices, device, generator=None, text=False):
        if generator is None:
            generator = torch.Generator().manual_seed(0)
        rows_spec, demos_spec = [], []
        for idx in indices:
            ei, t = self.samples[idx]
            rows_spec.append((ei, t))
            if text:
                demos_spec.append(None)
            else:
                task = self.episodes[ei]["task_index"]
                candidates = [e for e in self.by_task[task] if e != ei]
                pick = int(torch.randint(len(candidates), (1,),
                                         generator=generator))
                sei = candidates[pick]
                idx = subsample_indices(self.episodes[sei]["length"],
                                        self.demo_max_frames)
                demos_spec.append((sei, idx))
        live, past, demos = self._compute_features(rows_spec,
                                                   demos_spec, device)
        rows = [self._query_scalars(ei, t) for ei, t in rows_spec]
        b = len(rows_spec)
        batch = {
            "pooled_live": live.float().to(device),
            "text_emb": None,
            "state_norm": torch.stack([r["state_norm"] for r in rows])
                .float().to(device),
            "history": (
                past.float().to(device),
                torch.stack([r["past_state"] for r in rows])
                    .float().to(device),
                torch.stack([r["past_action"] for r in rows])
                    .float().to(device),
                torch.stack([r["past_elapsed"] for r in rows])
                    .float().to(device),
                torch.stack([r["past_mask"] for r in rows]).to(device),
            ),
            "action_target": torch.stack(
                [r["action_target"] for r in rows]).float().to(device),
            "action_mask": torch.ones(b, 16, dtype=torch.bool,
                                      device=device),
            "echo_target": torch.stack([r["echo_target"] for r in rows])
                .float().to(device),
            "echo_valid": torch.ones(b, dtype=torch.bool,
                                     device=device),
        }
        if text:
            batch["text_emb"] = torch.stack(
                [self.text_emb[self.episodes[ei]["task_index"]]
                 for ei, _t in rows_spec]).float().to(device)
            return batch
        # demo assembly identical to SupportQueryData (zero padding)
        t_max = max(d.shape[0] for d in demos)
        demo_pooled, frame_mask, frame_times = [], [], []
        for (sei, idx), frames in zip(demos_spec, demos):
            times = idx.float() / self.fps
            mask = torch.ones(len(idx), dtype=torch.bool)
            pad = t_max - frames.shape[0]
            if pad > 0:
                frames = torch.cat(
                    [frames, torch.zeros(pad, *frames.shape[1:],
                                         dtype=frames.dtype)], dim=0)
                mask = torch.cat(
                    [mask, torch.zeros(pad, dtype=torch.bool)], dim=0)
                times = torch.cat([times, torch.zeros(pad)], dim=0)
            demo_pooled.append(frames)
            frame_mask.append(mask)
            frame_times.append(times)
        batch["demo_pooled"] = torch.stack(demo_pooled) \
            .float().to(device)
        batch["frame_mask"] = torch.stack(frame_mask).to(device)
        batch["frame_times"] = torch.stack(frame_times) \
            .float().to(device)
        batch["support_episode"] = torch.tensor(
            [s[0] for s in demos_spec])
        batch["query_episode"] = torch.tensor(
            [ei for ei, _t in rows_spec])
        # FactoryData privileged fields + query progress (df_data.py)
        prog = torch.zeros(b)
        for bi, (ei, t) in enumerate(rows_spec):
            prog[bi] = t / max(1, self.episodes[ei]["length"] - 1)
        batch["query_progress"] = prog.to(device)
        cand = torch.zeros(b, K, 128)
        cvalid = torch.zeros(b, K, dtype=torch.bool)
        tmask = torch.zeros(b, 128)
        tidx = torch.full((b,), -1, dtype=torch.long)
        has = torch.zeros(b, dtype=torch.bool)
        if self.obj_masks is not None:
            for bi, (ei, t) in enumerate(rows_spec):
                ep = self.episodes[ei]
                if not ep.get("has_sup"):
                    continue
                m = self.obj_masks[ep["start"] + t].float()
                cand[bi] = m
                k = len(ep["cand_names"])
                cvalid[bi, :k] = True
                tidx[bi] = int(ep["target_idx"])
                tmask[bi] = m[int(ep["target_idx"])]
                has[bi] = True
        batch["cand_mask"] = cand.to(device)
        batch["cand_valid"] = cvalid.to(device)
        batch["target_idx"] = tidx.to(device)
        batch["target_mask"] = tmask.to(device)
        batch["has_sup"] = has.to(device)
        return batch