GWAM_Data / scripts /validate_full_graph_loader_release.py
ChangChrisLiu's picture
Add paused GWAM research snapshot, large-model design, and verified temporal graph view
613b8aa verified
Raw
History Blame Contribute Delete
14.7 kB
#!/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())