#!/usr/bin/env python3 """R6 200k — verify the raw200k store against cache_df_r2. (a) Raw frames through the FULL original anchor (fp32) must match the cached pooled features (cos > 0.99) for one D0, one D1 and one D2 episode. (b) Demo mid tokens through the pretrained top (blocks 8-11 + norm) must match the cached demo features (cos > 0.99) — the split encode was measured bit-exact in fp32; the mid store is fp16, so a small tolerance applies. (c) With --final: phase-2 vision identity — vision_top_ema must be tensor-identical in ckpt_100000, ckpt_110000 and ckpt_200000 (vision frozen for all of phase 2), while the policy EMA moved. """ import json import sys from pathlib import Path import numpy as np import torch 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 TipsAnchor # noqa: E402 from trace_vla.data import subsample_indices # noqa: E402 from df_data_raw import VisionTop # noqa: E402 EXP = Path.home() / "sera_v4_experiments" DF = EXP / "data_factory" RAW = DF / "raw200k" DEVICE = "cuda" def cos(a, b): return float(F.cosine_similarity(a.flatten().float(), b.flatten().float(), dim=0)) def main(): if "--final" in sys.argv: def named(path): return torch.load(path, weights_only=False)[ "vision_top_ema"] base = named(DF / "runs" / "r6_200k" / "ckpt_100000.pt") for p in (DF / "runs" / "r6_200k_p2" / "ckpt_110000.pt", DF / "runs" / "r6_200k_p2" / "ckpt_200000.pt"): other = named(p) for mod in base: for k in base[mod]: d = (base[mod][k].float() - other[mod][k].float()).abs().max().item() assert d == 0.0, f"{p} {mod}.{k} diff {d}" print(f"VISION IDENTITY PASS: {p.name} vision_top_ema " f"== ckpt_100000", flush=True) e1 = torch.load(DF / "runs" / "r6_200k_p2" / "ckpt_110000.pt", weights_only=False)["ema"] e2 = torch.load(DF / "runs" / "r6_200k_p2" / "ckpt_200000.pt", weights_only=False)["ema"] k0 = sorted(e1.keys())[0] d = (e1[k0].float() - e2[k0].float()).abs().max().item() assert d > 0, "policy EMA did not move in phase 2" print(f"POLICY MOVED PASS: ema[{k0}] diff 110k vs 200k = {d}", flush=True) return cache = torch.load(DF / "cache_df_r2.pt", weights_only=True, mmap=True) idx = json.loads((RAW / "raw200k_index.json").read_text()) raw = np.memmap(RAW / "raw_images.dat", dtype=np.uint8, mode="r", shape=(idx["F"], 2, 224, 224, 3)) mid = np.memmap(RAW / "demo_mid.dat", dtype=np.float16, mode="r") mid = mid.reshape(mid.shape[0] // (258 * 768), 258, 768) anchor = TipsAnchor("google/tipsv2-b14").to(DEVICE).eval() top = VisionTop(anchor.tips.vision_encoder).to(DEVICE).eval() picked = {} for i, ep in enumerate(cache["episodes"]): src = ep.get("source", "D0") if src not in picked: picked[src] = (i, ep) with torch.no_grad(): for src, (ei, ep) in sorted(picked.items()): g = ep["start"] + 5 imgs = torch.as_tensor(np.ascontiguousarray(raw[g])) \ .to(DEVICE).permute(0, 3, 1, 2).float() / 255.0 pooled = anchor.encode_patches(imgs) ref = cache["features"][g].float().to(DEVICE) c = cos(pooled, ref) print(f"(a) {src} ep {ep['episode_id']} frame {g}: " f"cos = {c:.5f}, max diff " f"{(pooled - ref).abs().max():.5f}", flush=True) assert c > 0.99, f"raw store mismatch for {src}" # (b) demo path on the same episode rec = idx["episodes"][ei] rows = torch.as_tensor(np.ascontiguousarray( mid[rec["demo_offset"]: rec["demo_offset"] + rec["demo_n"]])) \ .to(DEVICE).float() with torch.autocast("cuda", dtype=torch.bfloat16): demo = top(rows).float() didx = subsample_indices(ep["length"], 64) refd = cache["features"][ep["start"] + didx, 0] \ .float().to(DEVICE) c2 = cos(demo, refd) print(f"(b) {src} ep {ep['episode_id']} demo: " f"cos = {c2:.5f}, max diff " f"{(demo - refd).abs().max():.5f}", flush=True) assert c2 > 0.99, f"demo mid mismatch for {src}" print("RAW200K VERIFY PASS", flush=True) if __name__ == "__main__": main()