#!/usr/bin/env python3 """Data Factory expansion — build merged training caches. Encodes every factory episode with the frozen ANCHOR (same path as df_verify.py) and composes two caches in the exact format of feature_cache_subset.pt: cache_df_r1.pt = D0 (subset cache) + factory D1 episodes cache_df_r2.pt = D0 + factory D1 + factory D2 episodes Factory episode records carry extra fields used by the grounding adapter (df_data.py): source, layout, scene_bench, target_id, cand_names, target_idx, has_sup. Aligned per-frame privileged arrays (obj_masks [F,6,128] bool) are stored at cache level; D0 frames are zero. Stats and the D0 text embeddings come from the subset cache; text embeddings for factory-only ds tasks are computed with the anchor text encoder from the canonical LIBERO instruction. Big tensors are staged through numpy memmaps so the build never holds the full feature tensor in RAM. """ import json import sys from pathlib import Path import numpy as np import torch sys.path.insert(0, str(Path(__file__).parent)) sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla")) from v2_dash import merge_item # noqa: E402 EXP = Path.home() / "sera_v4_experiments" DF = EXP / "data_factory" / "expand" STAGE = DF / "cache_stage" STAGE.mkdir(parents=True, exist_ok=True) K = 6 def encode_factory(policy): """Encode all factory episodes -> per-episode stage files.""" man = json.loads((DF / "manifest.json").read_text()) stage_meta = [] for e in man["episodes"]: sf = STAGE / f"{e['episode_id']}.pt" if sf.exists(): stage_meta.append((e, int(e["frames"]))) continue d = np.load(DF / e["file"]) av = torch.as_tensor(d["agentview"]).float() / 255.0 wr = torch.as_tensor(d["wrist"]).float() / 255.0 enc = [] for s in range(0, len(av), 64): imgs = torch.stack([av[s:s + 64], wr[s:s + 64]], dim=1).to("cuda") B = imgs.shape[0] pooled = policy.model.anchor.encode_patches( imgs.reshape(B * 2, 3, 256, 256)) enc.append(pooled.reshape(B, 2, 64, 768).cpu().half()) rec = {"features": torch.cat(enc), "states": torch.as_tensor(d["states"]), "actions": torch.as_tensor(d["actions"]), "obj_masks": torch.as_tensor(d["obj_masks"]).bool(), "obj_names": [str(x) for x in d["obj_names"]]} torch.save(rec, sf) stage_meta.append((e, int(rec["features"].shape[0]))) del rec, enc print("encoded", e["episode_id"], flush=True) return stage_meta def compose(stage_meta, include_sources, out_path, subset, text_emb): """Assemble the cache through on-disk memmaps (bounded RAM).""" tag = out_path.stem fac = [(e, n) for e, n in stage_meta if e["source"] in include_sources] total = int(subset["features"].shape[0]) + sum(n for _, n in fac) f_mm = np.memmap(STAGE / f"{tag}_features.dat", dtype=np.float16, mode="w+", shape=(total, 2, 64, 768)) s_mm = np.memmap(STAGE / f"{tag}_states.dat", dtype=np.float32, mode="w+", shape=(total, 8)) a_mm = np.memmap(STAGE / f"{tag}_actions.dat", dtype=np.float32, mode="w+", shape=(total, 7)) m_mm = np.memmap(STAGE / f"{tag}_masks.dat", dtype=np.bool_, mode="w+", shape=(total, K, 128)) eps_out = [] cursor = 0 def push(feats, states, actions, masks, ep_rec): nonlocal cursor L = int(feats.shape[0]) sl = slice(cursor, cursor + L) f_mm[sl] = feats.numpy() s_mm[sl] = states.numpy() a_mm[sl] = actions.numpy() m_mm[sl] = masks.numpy() ep_rec["start"] = cursor ep_rec["length"] = L cursor += L eps_out.append(ep_rec) for ep in subset["episodes"]: s, L = ep["start"], ep["length"] rec = dict(ep) rec.setdefault("source", "D0") rec["has_sup"] = False push(subset["features"][s:s + L], subset["states"][s:s + L], subset["actions"][s:s + L], torch.zeros(L, K, 128, dtype=torch.bool), rec) for e, _n in fac: rec = torch.load(STAGE / f"{e['episode_id']}.pt", weights_only=False) names = rec["obj_names"] masks = rec["obj_masks"] if masks.shape[1] < K: pad = torch.zeros(masks.shape[0], K - masks.shape[1], 128, dtype=torch.bool) masks = torch.cat([masks, pad], dim=1) ep_rec = {"task_index": int(e["target_ds"]), "split": "train", "source": e["source"], "layout": e["layout"], "scene_bench": e["scene_bench"], "target_id": e["target_id"], "cand_names": names, "target_idx": names.index(e["target_id"]), "has_sup": True, "episode_id": e["episode_id"]} push(rec["features"], rec["states"], rec["actions"], masks, ep_rec) for mm in (f_mm, s_mm, a_mm, m_mm): mm.flush() cache = {"features": torch.from_numpy(np.asarray(f_mm)), "states": torch.from_numpy(np.asarray(s_mm)), "actions": torch.from_numpy(np.asarray(a_mm)), "obj_masks": torch.from_numpy(np.asarray(m_mm)), "episodes": eps_out, "text_emb": text_emb, "stats": subset["stats"]} torch.save(cache, out_path) print(f"saved {out_path}: episodes={len(eps_out)} " f"(factory {len(fac)}) frames={cursor}", flush=True) return len(eps_out), len(fac), cursor def main(): merge_item("data_factory.cache", {"status": "running"}) from eval_trace_heldout import TracePolicy subset = torch.load(EXP / "trace_vla/feature_cache_subset.pt", weights_only=False) policy = TracePolicy( str(EXP / "trace_validation/runs/rawmem/ckpt_05000.pt"), "rawmem", subset) stage_meta = encode_factory(policy) # text embeddings for factory-only ds tasks inv = json.loads((EXP / "data_factory/scene_inventory.json") .read_text()) text_emb = dict(subset["text_emb"]) anchor = policy.model.anchor for bench_s, obj in inv["obj_of_task"].items(): ds = 20 + json.loads( (EXP / "fewshot/env_dataset_task_mapping.json").read_text() )[f"libero_object#{bench_s}"] if ds not in text_emb: instr = ("pick up the " + obj.replace("_1", "") .replace("_", " ") + " and place it in the basket") text_emb[ds] = anchor.encode_text([instr])[0].cpu().float() print("text_emb computed for ds", ds, instr, flush=True) n1 = compose(stage_meta, {"D1"}, EXP / "data_factory" / "cache_df_r1.pt", subset, text_emb) n2 = compose(stage_meta, {"D1", "D2"}, EXP / "data_factory" / "cache_df_r2.pt", subset, text_emb) merge_item("data_factory.cache", { "status": "done", "metrics": {"Cache R1 (D0+D1)": f"{n1[0]} ep / {n1[2]} frame", "Cache R2 (D0+D1+D2)": f"{n2[0]} ep / {n2[2]} frame"}}) print("CACHE DONE", n1, n2, flush=True) if __name__ == "__main__": main()