File size: 8,044 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
#!/usr/bin/env python3
"""TRACE-VLA v2 Data Factory — Task 5 integrity checks + Task 6.7
loader compatibility check, run against the SAVED pilot artifacts.

Part 1 (files only): pair identity, pose cross-checks, counterbalance,
held-out leakage, support!=query, array schema.
Part 2 (loader): build a TRACE feature cache from the factory
episodes with the frozen ANCHOR and pull real batches through
SupportQueryData — the exact class the training harness uses.
"""
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).parent))
from v2_dash import merge_item                   # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
OUT = EXP / "data_factory" / "pilot"
man = json.loads((OUT / "manifest.json").read_text())
attempts = json.loads((OUT / "attempts_log.json").read_text())
checks = {}


def ok(name, cond, detail=""):
    checks[name] = {"pass": bool(cond), "detail": detail}
    print(("PASS " if cond else "FAIL ") + name + " " + detail,
          flush=True)


# ---- Part 1: file-level integrity ------------------------------------
eps = {e["episode_id"]: e for e in man["episodes"]}
ok("pairs_8_of_8", len(man["pairs"]) == 8, f"pairs={len(man['pairs'])}")
ok("episodes_16", len(eps) == 16, f"episodes={len(eps)}")

hash_ok, drift_max = True, 0.0
for p in man["pairs"]:
    a, b = eps[p["episodes"]["A"]], eps[p["episodes"]["B"]]
    hash_ok &= (a["init_hash"] == b["init_hash"] == p["init_hash"])
    drift_max = max(drift_max, b.get("start_pose_drift_m", 0.0))
ok("pair_init_hash_match", hash_ok)
ok("pair_start_pose_drift_le_5mm", drift_max <= 0.005,
   f"max_drift={drift_max*1000:.1f}mm")

schema_ok, pose_ok, native_ok = True, True, True
min_frames = 10 ** 9
for e in eps.values():
    d = np.load(OUT / e["file"])
    av, wr, st, ac = d["agentview"], d["wrist"], d["states"], d["actions"]
    schema_ok &= (av.shape[1:] == (256, 256, 3)
                  and wr.shape[1:] == (256, 256, 3)
                  and st.shape[1] == 8 and ac.shape[1] == 7
                  and len({len(av), len(wr), len(st), len(ac)}) == 1
                  and av.dtype == np.uint8)
    min_frames = min(min_frames, len(av))
    basket = np.array(e["start_poses"]["basket_1"])
    end = np.array(e["obj_end"])
    pose_ok &= (abs(end[0] - basket[0]) <= 0.075
                and abs(end[1] - basket[1]) <= 0.075
                and 0.03 <= end[2] <= 0.16)
    if e["goal_id"] == "A":
        native_ok &= e.get("predicate_agrees_native", False)
ok("episode_array_schema", schema_ok, f"min_frames={min_frames}")
ok("obj_end_inside_basket_box_all", pose_ok)
ok("native_check_agrees_all_goalA", native_ok)

ok("no_heldout_goals",
   all(e["target_ds"] in (24, 26) for e in eps.values()),
   "targets=" + str(sorted({e['target_ds'] for e in eps.values()})))

from collections import Counter
goal_counts = Counter(e["goal_id"] for e in eps.values())
layout_counts = Counter(e["layout"] for e in eps.values())
ok("counterbalance_goals_layouts",
   goal_counts == {"A": 8, "B": 8}
   and layout_counts == {"orig": 8, "swap": 8},
   f"goals={dict(goal_counts)} layouts={dict(layout_counts)}")

# swap cross-check: in a swap pair, A's start xy must equal the orig
# pair's B start xy for the same init (positions truly exchanged)
by_key = {(e["layout"], e["init_index"], e["goal_id"]): e
          for e in eps.values()}
swap_ok = True
for i in range(4):
    for g1, g2 in (("A", "B"), ("B", "A")):
        p_swap = np.array(by_key[("swap", i, g1)]["start_poses"][
            by_key[("swap", i, g1)]["target_id"]][:2])
        p_orig = np.array(by_key[("orig", i, g2)]["start_poses"][
            by_key[("orig", i, g2)]["target_id"]][:2])
        swap_ok &= np.linalg.norm(p_swap - p_orig) < 0.01
ok("swap_positions_truly_exchanged", swap_ok)

sup_ok = all(e["support_demo_episode"] in (813, 816)
             and (e["support_demo_episode"] == 813)
             == (e["goal_id"] == "A") for e in eps.values())
ok("support_demo_task_matches_and_is_dataset_episode", sup_ok,
   "support eps are dataset episodes 813 (ds24) / 816 (ds26); query "
   "episodes are new simulator episodes, disjoint by construction")

succ = sum(1 for a in attempts if a["success"])
ok("attempts_logged", len(attempts) == man["n_attempts"],
   f"attempts={len(attempts)} success={succ}")

# ---- Part 2: TRACE loader --------------------------------------------
loader = {}
try:
    import torch
    sys.path.insert(0, str(EXP / "trace_vla"))
    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)
    feats, states, actions, ep_list = [], [], [], []
    cursor = 0
    for e in man["episodes"]:
        d = np.load(OUT / 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,2,3,256,256]
            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())
        f = torch.cat(enc)
        feats.append(f)
        states.append(torch.as_tensor(d["states"]))
        actions.append(torch.as_tensor(d["actions"]))
        ep_list.append({"start": cursor, "length": int(len(f)),
                        "task_index": int(e["target_ds"])})
        cursor += len(f)
    text_emb = dict(subset["text_emb"])
    if 26 not in text_emb:
        text_emb[26] = torch.zeros(768)
        loader["text_emb_ds26"] = "zeros placeholder (video-only path " \
                                  "ignores text; noted, not hidden)"
    cache = {"features": torch.cat(feats), "states": torch.cat(states),
             "actions": torch.cat(actions), "episodes": ep_list,
             "text_emb": text_emb, "stats": subset["stats"]}
    torch.save(cache, OUT / "loader_cache.pt")
    from trace_vla.data import SupportQueryData
    data = SupportQueryData(cache)
    gen = torch.Generator().manual_seed(0)
    idx = [0, len(data.samples) // 3, len(data.samples) // 2,
           len(data.samples) - 1]
    batch = data.get_batch(idx, "cpu", generator=gen)
    sup, qry = batch["support_episode"], batch["query_episode"]
    tasks_match = all(
        ep_list[int(s)]["task_index"] == ep_list[int(q)]["task_index"]
        for s, q in zip(sup.tolist(), qry.tolist()))
    loader.update({
        "ok": True, "n_samples": len(data.samples),
        "demo_pooled_shape": list(batch["demo_pooled"].shape),
        "action_target_shape": list(batch["action_target"].shape),
        "support_ne_query_all": bool((sup != qry).all()),
        "support_task_eq_query_task": bool(tasks_match)})
    ok("trace_loader_batch", True, json.dumps(loader))
except Exception as exc:  # noqa: BLE001
    loader = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
    ok("trace_loader_batch", False, loader["error"])

result = {"checks": checks, "loader": loader,
          "all_pass": all(c["pass"] for c in checks.values())}
(OUT / "verify_report.json").write_text(json.dumps(result, indent=1))
merge_item("data_factory.checks", {
    "status": "done" if result["all_pass"] else "fail",
    "verdict": ("Mọi kiểm tra toàn vẹn đạt; loader TRACE đọc dữ liệu "
                "không lỗi schema" if result["all_pass"]
                else "Có kiểm tra chưa đạt — xem verify_report.json"),
    "metrics": {
        "Kiểm tra đạt": f"{sum(c['pass'] for c in checks.values())}"
                        f"/{len(checks)}",
        "Drift pose trong cặp (max)": f"{drift_max*1000:.1f} mm",
        "Loader samples": str(loader.get("n_samples", "—"))}})
print("ALL_PASS" if result["all_pass"] else "SOME_FAILED")