File size: 3,846 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
#!/usr/bin/env python3
"""R6 200k run — rebuild the pooled-feature cache with the milestone
encoder (phase-2 input).

cache_df_r2_v100k.pt = cache_df_r2.pt with `features` recomputed from
the raw200k store by a TIPSv2 anchor whose blocks 8-11 + final norm
are the vision_top_ema of the phase-1 checkpoint (frozen for all of
phase 2). Every other key (episodes, states, actions, text_emb,
obj_masks, stats) is copied unchanged. Encoding runs fp32 through
TipsAnchor.encode_patches, the eval-path op.

With --pretrained (no --ckpt) the encoder is the original pretrained
anchor: the rebuilt features must then match cache_df_r2 within
cache-build tolerance (subset part was bf16) — pipeline self-test.
"""
import argparse
import sys
import time
from pathlib import Path

import numpy as np
import torch

sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))
from trace_vla.anchor import TipsAnchor                  # noqa: E402
from df_data_raw import apply_named_state                # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
DF = EXP / "data_factory"
RAW = DF / "raw200k"
DEVICE = "cuda"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt", default=None,
                    help="phase-1 checkpoint with vision_top_ema")
    ap.add_argument("--out", default=str(DF / "cache_df_r2_v100k.pt"))
    ap.add_argument("--limit", type=int, default=0,
                    help="only encode the first N frames (self-test)")
    args = ap.parse_args()
    t0 = time.time()
    cache = torch.load(DF / "cache_df_r2.pt", weights_only=True,
                       mmap=True)
    n_frames = int(cache["features"].shape[0])
    n = n_frames if not args.limit else min(args.limit, n_frames)
    import json
    idx = json.loads((RAW / "raw200k_index.json").read_text())
    assert idx["F"] == n_frames
    raw = np.memmap(RAW / "raw_images.dat", dtype=np.uint8, mode="r",
                    shape=(n_frames, 2, 224, 224, 3))
    anchor = TipsAnchor("google/tipsv2-b14").to(DEVICE)
    if args.ckpt:
        ck = torch.load(args.ckpt, weights_only=False)
        apply_named_state(anchor.tips.vision_encoder,
                          ck["vision_top_ema"])
        print(f"encoder: vision_top_ema from {args.ckpt} "
              f"(step {ck['step']})", flush=True)
    else:
        print("encoder: original pretrained anchor (self-test)",
              flush=True)
    anchor.eval()
    feats = np.memmap(DF / "cache_v100k_tmp.dat", dtype=np.float16,
                      mode="w+", shape=(n, 2, 64, 768))
    with torch.no_grad():
        for s in range(0, n, 128):
            imgs = torch.as_tensor(np.ascontiguousarray(
                raw[s:s + 128])).to(DEVICE) \
                .permute(0, 1, 4, 2, 3).float() / 255.0
            pooled = anchor.encode_patches(imgs.flatten(0, 1))
            feats[s:s + imgs.shape[0]] = pooled.reshape(
                -1, 2, 64, 768).half().cpu().numpy()
            if s % (128 * 100) == 0:
                print(f"  frame {s}/{n} ({time.time() - t0:.0f}s)",
                      flush=True)
    feats.flush()
    if args.limit:
        ref = cache["features"][:n].float()
        new = torch.from_numpy(np.array(feats)).float()
        d = (new - ref).abs()
        cos = torch.nn.functional.cosine_similarity(
            new.flatten(1), ref.flatten(1), dim=1).mean()
        print(f"SELF-TEST vs cache_df_r2: max diff {d.max():.5f}, "
              f"mean diff {d.mean():.6f}, cos {cos:.5f}",
              flush=True)
        return
    out = {k: (torch.from_numpy(feats) if k == "features" else cache[k])
           for k in cache.keys()}
    torch.save(out, args.out)
    (DF / "cache_v100k_tmp.dat").unlink()
    print(f"saved {args.out} ({n} frames, {time.time() - t0:.0f}s)",
          flush=True)


if __name__ == "__main__":
    main()