File size: 14,749 Bytes
613b8aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python3
"""Resumable full-release gate for the strict GWAM temporal-window loader.

Every selected manifest episode is opened through ``GWAMFullGraphEpisode`` in
strict mode and exercised at the first, middle, and last legal L/H windows.
Results are append-only JSONL so interrupted runs can resume safely.
"""
from __future__ import annotations

import argparse
import concurrent.futures
import hashlib
import json
import os
import sys
import time
import traceback
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable

import numpy as np

PACKAGE_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PACKAGE_ROOT / "loaders"))

from gwam_full_graph_window import (  # noqa: E402
    CONTACT_EVENT,
    EXPECTED_SCHEMA,
    GWAMFullGraphEpisode,
    clear_full_graph_loader_caches,
)


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _window_starts(count: int) -> list[int]:
    if count <= 0:
        return []
    return sorted({0, (count - 1) // 2, count - 1})


def _validate_sample(sample: dict[str, Any]) -> dict[str, Any]:
    history = sample["history"]
    targets = sample["targets"]
    metadata = sample["metadata"]
    n = int(metadata["N_real"])
    l = int(metadata["history_length"])
    h = int(metadata["horizon"])
    if metadata["schema"] != EXPECTED_SCHEMA:
        raise AssertionError(f"unexpected schema {metadata['schema']!r}")
    expected_shapes = {
        "kinematic_state": (l, n, 15),
        "static_flags": (l, n, 2),
        "state_visibility": (l, n, 3),
        "sam2_visual": (l, n, 3, 256),
        "sam2_valid": (l, n, 3),
        "sam2_failed": (l, n, 3),
        "mask_valid": (l, n, 3),
    }
    for key, shape in expected_shapes.items():
        if history[key].shape != shape:
            raise AssertionError(f"history.{key} {history[key].shape} != {shape}")
    if targets["kinematic_state"].shape != (h, n, 15):
        raise AssertionError("future kinematic shape mismatch")
    if targets["contact_pair_event"].dtype != np.int64:
        raise AssertionError("contact_pair_event must be int64")
    expected_pairs = n * (n - 1) // 2
    if targets["contact_pair_index"].shape != (2, expected_pairs):
        raise AssertionError("contact pair domain is incomplete")
    if sample["future_action"].shape != (h, 12) or not sample["future_action_valid"].all():
        raise AssertionError("conditioning action contract failed")
    if not np.isfinite(history["kinematic_state"]).all():
        raise AssertionError("non-finite kinematic input")
    if not np.isfinite(history["sam2_visual"]).all():
        raise AssertionError("non-finite SAM2 input")
    if np.any(history["sam2_valid"] & history["sam2_failed"]):
        raise AssertionError("SAM2 valid/failed overlap")
    if not np.array_equal(
        history["sam2_valid"] | history["sam2_failed"], history["mask_valid"]
    ):
        raise AssertionError("SAM2 partition does not equal visible-mask pairs")
    if history["family_id"].min(initial=0) < 0 or history["family_id"].max(initial=0) > 9:
        raise AssertionError("dataset family id outside 0..9")
    for edge_index, edge_attr in zip(
        history["edge_index"], history["edge_attr"], strict=True
    ):
        if edge_index.shape[1] != edge_attr.shape[0]:
            raise AssertionError("edge row mismatch")
        contacts = edge_index[:, edge_attr[:, 2] == 1]
        contact_set = {tuple(pair) for pair in contacts.T.tolist()}
        if any((dst, src) not in contact_set for src, dst in contact_set):
            raise AssertionError("contact message edge lacks reverse direction")
    valid_events = targets["contact_pair_event"][targets["contact_pair_valid"]]
    event_counts = np.bincount(valid_events, minlength=4)
    return {
        "N_real": n,
        "history_mask_valid": int(history["mask_valid"].sum()),
        "history_sam2_valid": int(history["sam2_valid"].sum()),
        "history_sam2_failed": int(history["sam2_failed"].sum()),
        "event_off": int(event_counts[CONTACT_EVENT["off"]]),
        "event_make": int(event_counts[CONTACT_EVENT["make"]]),
        "event_hold": int(event_counts[CONTACT_EVENT["hold"]]),
        "event_break": int(event_counts[CONTACT_EVENT["break"]]),
        "history_edges": int(sum(edge.shape[1] for edge in history["edge_index"])),
        "future_dynamic_edges": int(
            sum(edge.shape[1] for edge in targets["dynamic_edge_index"])
        ),
    }


def _validate_episode(job: dict[str, Any]) -> dict[str, Any]:
    started = time.perf_counter()
    row = job["row"]
    stage_root = Path(job["stage_root"])
    zip_path = stage_root / row["zip_path"]
    result: dict[str, Any] = {
        "zip_path": row["zip_path"],
        "split": row.get("split"),
        "task": row.get("task"),
        "episode_id": row.get("episode_id"),
        "ok": False,
    }
    try:
        if not zip_path.is_file():
            raise FileNotFoundError(zip_path)
        actual_size = zip_path.stat().st_size
        expected_size = int(row.get("zip_size", actual_size))
        if actual_size != expected_size:
            raise ValueError(f"ZIP size {actual_size} != manifest {expected_size}")
        if job["verify_sha"]:
            actual_sha = _sha256(zip_path)
            if actual_sha != row.get("zip_sha256"):
                raise ValueError("ZIP SHA256 differs from manifest")
            result["zip_sha256"] = actual_sha

        with GWAMFullGraphEpisode(zip_path=zip_path, strict=True) as episode:
            legal_starts = episode.valid_start_times(
                history_length=job["history_length"], horizon=job["horizon"]
            )
            starts = _window_starts(len(legal_starts))
            if not starts:
                raise ValueError("episode has no legal temporal windows")
            window_stats = []
            for start_t in starts:
                sample = episode.load_window(
                    start_t=start_t,
                    history_length=job["history_length"],
                    horizon=job["horizon"],
                    mask_size=job["mask_size"],
                )
                stats = _validate_sample(sample)
                stats["start_t"] = start_t
                stats["anchor_t"] = int(sample["metadata"]["anchor_t"])
                window_stats.append(stats)
                del sample
            result.update(
                {
                    "ok": True,
                    "T": len(legal_starts) + job["history_length"] + job["horizon"] - 1,
                    "N_real": window_stats[0]["N_real"],
                    "legal_window_count": len(legal_starts),
                    "checked_starts": starts,
                    "window_stats": window_stats,
                }
            )
    except Exception as exc:
        result["error_type"] = type(exc).__name__
        result["error"] = str(exc)
        result["traceback"] = traceback.format_exc(limit=8)
    finally:
        clear_full_graph_loader_caches()
        result["elapsed_seconds"] = time.perf_counter() - started
    return result


def _read_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    if not path.exists():
        return rows
    with path.open() as f:
        for line in f:
            if line.strip():
                rows.append(json.loads(line))
    return rows


def _atomic_json(path: Path, value: Any) -> None:
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n")
    os.replace(tmp, path)


def _summarize(records: list[dict[str, Any]], expected: int) -> dict[str, Any]:
    unique: dict[str, dict[str, Any]] = {row["zip_path"]: row for row in records}
    rows = list(unique.values())
    passed = [row for row in rows if row.get("ok")]
    failed = [row for row in rows if not row.get("ok")]
    by_task: dict[str, Counter[str]] = defaultdict(Counter)
    for row in rows:
        key = f"{row.get('split')}/{row.get('task')}"
        by_task[key]["passed" if row.get("ok") else "failed"] += 1
    return {
        "expected_episode_count": expected,
        "unique_result_count": len(rows),
        "passed": len(passed),
        "failed": len(failed),
        "complete": len(rows) == expected,
        "all_passed": len(rows) == expected and not failed,
        "total_legal_windows": int(sum(row.get("legal_window_count", 0) for row in passed)),
        "min_T": min((row["T"] for row in passed), default=None),
        "max_T": max((row["T"] for row in passed), default=None),
        "min_N_real": min((row["N_real"] for row in passed), default=None),
        "max_N_real": max((row["N_real"] for row in passed), default=None),
        "elapsed_episode_seconds_sum": float(sum(row.get("elapsed_seconds", 0) for row in rows)),
        "failure_types": dict(Counter(row.get("error_type", "unknown") for row in failed)),
        "failed_zip_paths": [row["zip_path"] for row in failed],
        "by_split_task": {key: dict(value) for key, value in sorted(by_task.items())},
    }


def main(argv: Iterable[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--stage-root",
        type=Path,
        default=PACKAGE_ROOT / "staging" / "gwam_v12_sparse_v2_full",
    )
    parser.add_argument("--manifest", type=Path)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--history-length", type=int, default=8)
    parser.add_argument("--horizon", type=int, default=8)
    parser.add_argument("--mask-size", type=int, default=16)
    parser.add_argument("--split")
    parser.add_argument("--task")
    parser.add_argument("--limit", type=int)
    parser.add_argument("--resume", action="store_true")
    parser.add_argument("--retry-failures", action="store_true")
    parser.add_argument("--verify-sha", action="store_true")
    parser.add_argument("--progress-every", type=int, default=25)
    args = parser.parse_args(list(argv) if argv is not None else None)

    stage_root = args.stage_root.expanduser().resolve()
    manifest = (args.manifest or stage_root / "MANIFEST.jsonl").expanduser().resolve()
    rows = _read_jsonl(manifest)
    if args.split:
        rows = [row for row in rows if row.get("split") == args.split]
    if args.task:
        rows = [row for row in rows if row.get("task") == args.task]
    if args.limit is not None:
        rows = rows[: args.limit]
    if not rows:
        raise SystemExit("no manifest rows selected")

    output_dir = args.output_dir.expanduser().resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    result_path = output_dir / "episode_results.jsonl"
    summary_path = output_dir / "summary.json"
    prior = _read_jsonl(result_path) if args.resume else []
    done = {
        row["zip_path"]
        for row in prior
        if row.get("ok") or not args.retry_failures
    }
    pending = [row for row in rows if row["zip_path"] not in done]
    mode = "a" if args.resume and result_path.exists() else "w"
    if mode == "w":
        prior = []

    jobs = [
        {
            "row": row,
            "stage_root": str(stage_root),
            "history_length": args.history_length,
            "horizon": args.horizon,
            "mask_size": args.mask_size,
            "verify_sha": args.verify_sha,
        }
        for row in pending
    ]
    started = time.perf_counter()
    completed = 0
    with result_path.open(mode) as out:
        with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as pool:
            futures = [pool.submit(_validate_episode, job) for job in jobs]
            for future in concurrent.futures.as_completed(futures):
                record = future.result()
                out.write(json.dumps(record, sort_keys=True) + "\n")
                out.flush()
                completed += 1
                if completed % args.progress_every == 0 or not record.get("ok"):
                    elapsed = time.perf_counter() - started
                    rate = completed / elapsed if elapsed else 0.0
                    print(
                        f"completed={completed}/{len(jobs)} rate={rate:.2f}/s "
                        f"latest_ok={record.get('ok')} {record['zip_path']}",
                        flush=True,
                    )

    records = _read_jsonl(result_path)
    summary = _summarize(records, expected=len(rows))
    summary.update(
        {
            "stage_root": str(stage_root),
            "manifest": str(manifest),
            "history_length": args.history_length,
            "horizon": args.horizon,
            "mask_size": args.mask_size,
            "workers": args.workers,
            "verify_sha": bool(args.verify_sha),
            "wall_seconds_this_run": time.perf_counter() - started,
        }
    )
    latest = {record["zip_path"]: record for record in records}
    with (output_dir / "validated_manifest.jsonl").open("w") as out:
        for row in rows:
            validation = latest.get(row["zip_path"], {})
            if validation.get("ok"):
                merged = dict(row)
                merged["loader_validation"] = {
                    "history_length": args.history_length,
                    "horizon": args.horizon,
                    "mask_size": args.mask_size,
                    "checked_starts": validation.get("checked_starts", []),
                }
                out.write(json.dumps(merged, sort_keys=True) + "\n")
    with (output_dir / "quarantine_manifest.jsonl").open("w") as out:
        for row in rows:
            validation = latest.get(row["zip_path"], {})
            if validation and not validation.get("ok"):
                out.write(
                    json.dumps(
                        {
                            "zip_path": row["zip_path"],
                            "split": row.get("split"),
                            "task": row.get("task"),
                            "episode_id": row.get("episode_id"),
                            "error_type": validation.get("error_type"),
                            "error": validation.get("error"),
                        },
                        sort_keys=True,
                    )
                    + "\n"
                )
    _atomic_json(summary_path, summary)
    print(json.dumps(summary, indent=2, sort_keys=True))
    return 0 if summary["all_passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main())