| |
| """Sample-level validation for a GNNCP compact graph dataset. |
| |
| This program never iterates the full legacy dataset. When ``--legacy`` is |
| provided it opens the old monolithic .pt with ``torch.load(..., mmap=True)`` |
| and touches only the requested sample tensors. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import random |
| import resource |
| import sys |
| from pathlib import Path |
| from typing import Any, Dict, Iterable, List, Optional, Sequence |
|
|
| import torch |
|
|
| from compact_graph_dataset import CompactGraphDataset |
|
|
|
|
| CORE_FIELDS = ( |
| "x", |
| "edge_index", |
| "edge_attr", |
| "pos", |
| "is_protein", |
| "y_true", |
| "y_pred", |
| "y_grt", |
| ) |
| FLOAT_FIELDS = { |
| "x", |
| "edge_attr", |
| "pos", |
| "is_protein", |
| "y_true", |
| "y_pred", |
| "y_grt", |
| } |
|
|
|
|
| def _rss_mib() -> float: |
| value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss |
| |
| if sys.platform == "darwin": |
| return value / (1024.0 * 1024.0) |
| return value / 1024.0 |
|
|
|
|
| def _parse_indices(text: Optional[str], length: int) -> Optional[List[int]]: |
| if text is None: |
| return None |
| values: List[int] = [] |
| for token in text.split(","): |
| token = token.strip() |
| if not token: |
| continue |
| if ":" in token: |
| parts = token.split(":") |
| if len(parts) not in (2, 3): |
| raise ValueError(f"bad index range: {token!r}") |
| start = int(parts[0]) if parts[0] else 0 |
| stop = int(parts[1]) if parts[1] else length |
| step = int(parts[2]) if len(parts) == 3 and parts[2] else 1 |
| values.extend(range(start, stop, step)) |
| else: |
| values.append(int(token)) |
| normalised = [] |
| for index in values: |
| if index < 0: |
| index += length |
| if not 0 <= index < length: |
| raise IndexError(f"sample index {index} outside [0,{length})") |
| normalised.append(index) |
| return list(dict.fromkeys(normalised)) |
|
|
|
|
| def _choose_indices(length: int, count: int, seed: int) -> List[int]: |
| if length <= 0: |
| return [] |
| count = min(max(int(count), 1), length) |
| selected = {0, length - 1} |
| rng = random.Random(seed) |
| while len(selected) < count: |
| selected.add(rng.randrange(length)) |
| return sorted(selected)[:count] |
|
|
|
|
| def _tensor_stats( |
| actual: torch.Tensor, |
| expected: torch.Tensor, |
| *, |
| atol: float, |
| rtol: float, |
| ) -> Dict[str, Any]: |
| result: Dict[str, Any] = { |
| "actual_shape": list(actual.shape), |
| "expected_shape": list(expected.shape), |
| "actual_dtype": str(actual.dtype), |
| "expected_dtype": str(expected.dtype), |
| } |
| if tuple(actual.shape) != tuple(expected.shape): |
| result.update({"passed": False, "reason": "shape_mismatch"}) |
| return result |
| if actual.dtype != expected.dtype: |
| result["dtype_match"] = False |
| else: |
| result["dtype_match"] = True |
|
|
| if actual.numel() == 0: |
| result.update( |
| { |
| "passed": bool(result["dtype_match"]), |
| "exact": True, |
| "max_abs": 0.0, |
| "mean_abs": 0.0, |
| } |
| ) |
| return result |
|
|
| if actual.is_floating_point() or expected.is_floating_point(): |
| actual_f64 = actual.to(torch.float64) |
| expected_f64 = expected.to(torch.float64) |
| finite_match = torch.equal(torch.isfinite(actual_f64), torch.isfinite(expected_f64)) |
| diff = torch.abs(actual_f64 - expected_f64) |
| finite_diff = diff[torch.isfinite(diff)] |
| max_abs = float(finite_diff.max().item()) if finite_diff.numel() else float("inf") |
| mean_abs = float(finite_diff.mean().item()) if finite_diff.numel() else float("inf") |
| close = bool( |
| torch.allclose(actual_f64, expected_f64, atol=atol, rtol=rtol, equal_nan=True) |
| ) |
| result.update( |
| { |
| "passed": bool(close and result["dtype_match"] and finite_match), |
| "exact": bool(torch.equal(actual, expected)), |
| "finite_pattern_match": finite_match, |
| "max_abs": max_abs, |
| "mean_abs": mean_abs, |
| } |
| ) |
| else: |
| exact = bool(torch.equal(actual, expected)) |
| result.update( |
| { |
| "passed": bool(exact and result["dtype_match"]), |
| "exact": exact, |
| } |
| ) |
| return result |
|
|
|
|
| def _invariants(graph: Any, cutoff: float, atol: float) -> Dict[str, Any]: |
| checks: Dict[str, bool] = {} |
| n = int(graph.num_nodes) |
| checks["x_Nx82"] = tuple(graph.x.shape) == (n, 82) |
| checks["edge_index_2xE"] = graph.edge_index.ndim == 2 and graph.edge_index.shape[0] == 2 |
| edge_count = int(graph.edge_index.shape[1]) if checks["edge_index_2xE"] else -1 |
| checks["edge_attr_Ex4"] = tuple(graph.edge_attr.shape) == (edge_count, 4) |
| checks["pos_Nx3"] = tuple(graph.pos.shape) == (n, 3) |
| checks["is_protein_Nx1"] = tuple(graph.is_protein.shape) == (n, 1) |
| checks["y_true_Nx1"] = tuple(graph.y_true.shape) == (n, 1) |
| checks["y_pred_Nx3"] = tuple(graph.y_pred.shape) == (n, 3) |
| checks["y_grt_Nx3"] = tuple(graph.y_grt.shape) == (n, 3) |
| checks["x_float32"] = graph.x.dtype == torch.float32 |
| checks["edge_index_int64"] = graph.edge_index.dtype == torch.int64 |
| checks["edge_attr_float32"] = graph.edge_attr.dtype == torch.float32 |
| checks["coordinates_float32"] = ( |
| graph.pos.dtype == graph.y_pred.dtype == graph.y_grt.dtype == torch.float32 |
| ) |
| checks["pos_equals_y_pred"] = bool(torch.equal(graph.pos, graph.y_pred)) |
|
|
| if edge_count >= 0 and graph.edge_index.numel(): |
| src, dst = graph.edge_index |
| checks["edge_bounds"] = bool( |
| (src.min() >= 0) |
| and (dst.min() >= 0) |
| and (src.max() < n) |
| and (dst.max() < n) |
| ) |
| checks["no_self_edges"] = bool(torch.all(src != dst).item()) |
| key = src * n + dst |
| checks["legacy_edge_order"] = bool(torch.all(key[1:] > key[:-1]).item()) |
| reversed_key = dst * n + src |
| checks["edges_are_bidirectional"] = bool( |
| torch.equal(torch.sort(key).values, torch.sort(reversed_key).values) |
| ) |
| distance = torch.sqrt( |
| torch.sum( |
| ( |
| graph.pos[src].to(torch.float64) |
| - graph.pos[dst].to(torch.float64) |
| ) |
| ** 2, |
| dim=1, |
| ) |
| ) |
| checks["edges_within_cutoff"] = bool( |
| torch.all(distance <= cutoff + atol).item() |
| ) |
| checks["edge_attr_distance"] = bool( |
| torch.allclose( |
| graph.edge_attr[:, 0].to(torch.float64), |
| distance / cutoff, |
| atol=atol, |
| rtol=0.0, |
| ) |
| ) |
| is_protein = graph.is_protein[:, 0] |
| checks["edge_attr_endpoint_types"] = bool( |
| torch.equal(graph.edge_attr[:, 2], is_protein[src]) |
| and torch.equal(graph.edge_attr[:, 3], is_protein[dst]) |
| ) |
| else: |
| checks["edge_bounds"] = True |
| checks["no_self_edges"] = True |
| checks["legacy_edge_order"] = True |
| checks["edges_are_bidirectional"] = True |
| checks["edges_within_cutoff"] = True |
| checks["edge_attr_distance"] = True |
| checks["edge_attr_endpoint_types"] = True |
|
|
| protein = graph.is_protein[:, 0] > 0.5 |
| checks["protein_first"] = bool( |
| not protein.numel() |
| or not bool((~protein).any().item()) |
| or not bool(protein[torch.nonzero(~protein, as_tuple=False)[0, 0] :].any().item()) |
| ) |
| checks["protein_y_true_zero"] = bool( |
| torch.all(graph.y_true[protein] == 0).item() |
| ) |
| ligand_error = torch.sqrt( |
| torch.sum((graph.y_pred[~protein] - graph.y_grt[~protein]) ** 2, dim=1) |
| ) |
| checks["ligand_y_true_matches_coordinates"] = bool( |
| torch.allclose( |
| graph.y_true[~protein, 0], |
| ligand_error, |
| atol=atol, |
| rtol=0.0, |
| ) |
| ) |
| return {"passed": all(checks.values()), "checks": checks} |
|
|
|
|
| def _load_legacy(path: Path, allow_eager: bool) -> Sequence[Any]: |
| try: |
| return torch.load( |
| path, |
| map_location="cpu", |
| mmap=True, |
| weights_only=False, |
| ) |
| except (TypeError, RuntimeError, ValueError) as exc: |
| if not allow_eager: |
| raise RuntimeError( |
| f"could not mmap legacy dataset {path}: {exc}. " |
| "Refusing an eager multi-GB load; pass --allow-eager-legacy " |
| "only inside a suitably sized Slurm job." |
| ) from exc |
| return torch.load(path, map_location="cpu", weights_only=False) |
|
|
|
|
| def validate(args: argparse.Namespace) -> Dict[str, Any]: |
| dataset = CompactGraphDataset( |
| args.compact, |
| max_cached_shards=args.max_cached_shards, |
| strict=True, |
| ) |
| indices = _parse_indices(args.indices, len(dataset)) |
| if indices is None: |
| indices = _choose_indices(len(dataset), args.num_samples, args.seed) |
|
|
| report: Dict[str, Any] = { |
| "compact": str(Path(args.compact).resolve()), |
| "num_graphs": len(dataset), |
| "indices": indices, |
| "atol": args.atol, |
| "rtol": args.rtol, |
| "rss_mib_before_samples": _rss_mib(), |
| "samples": [], |
| } |
|
|
| legacy: Optional[Sequence[Any]] = None |
| if args.legacy is not None: |
| legacy = _load_legacy(Path(args.legacy), args.allow_eager_legacy) |
| report["legacy"] = str(Path(args.legacy).resolve()) |
| report["legacy_num_graphs"] = len(legacy) |
| if len(legacy) != len(dataset): |
| report["length_match"] = False |
| else: |
| report["length_match"] = True |
|
|
| all_passed = report.get("length_match", True) |
| for index in indices: |
| graph = dataset[index] |
| sample_report: Dict[str, Any] = { |
| "index": index, |
| "metadata": dataset.metadata(index), |
| "invariants": _invariants(graph, dataset.cutoff, args.atol), |
| } |
| sample_passed = bool(sample_report["invariants"]["passed"]) |
|
|
| if legacy is not None and index < len(legacy): |
| reference = legacy[index] |
| parity: Dict[str, Any] = {} |
| for field in CORE_FIELDS: |
| if not hasattr(reference, field): |
| parity[field] = { |
| "passed": False, |
| "reason": "missing_in_legacy_graph", |
| } |
| continue |
| actual = getattr(graph, field) |
| expected = getattr(reference, field) |
| if not torch.is_tensor(actual) or not torch.is_tensor(expected): |
| parity[field] = { |
| "passed": False, |
| "reason": "field_is_not_tensor", |
| } |
| continue |
| parity[field] = _tensor_stats( |
| actual, |
| expected, |
| atol=args.atol if field in FLOAT_FIELDS else 0.0, |
| rtol=args.rtol if field in FLOAT_FIELDS else 0.0, |
| ) |
| sample_report["parity"] = parity |
| sample_passed = sample_passed and all( |
| bool(result["passed"]) for result in parity.values() |
| ) |
|
|
| sample_report["passed"] = sample_passed |
| all_passed = all_passed and sample_passed |
| report["samples"].append(sample_report) |
|
|
| report["rss_mib_after_samples"] = _rss_mib() |
| report["passed"] = bool(all_passed) |
| return report |
|
|
|
|
| def build_parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser( |
| description="Validate compact GNNCP graphs and optionally compare with legacy tensors." |
| ) |
| parser.add_argument( |
| "--compact", |
| required=True, |
| help="Compact dataset directory or manifest.json", |
| ) |
| parser.add_argument( |
| "--legacy", |
| help="Legacy list[torch_geometric.data.Data] .pt for mmap parity checks", |
| ) |
| parser.add_argument( |
| "--num-samples", |
| type=int, |
| default=8, |
| help="Number of deterministic samples when --indices is omitted (default: 8)", |
| ) |
| parser.add_argument( |
| "--indices", |
| help="Comma-separated indices/ranges, e.g. '0,10,20:24,-1'", |
| ) |
| parser.add_argument("--seed", type=int, default=0) |
| parser.add_argument( |
| "--atol", |
| type=float, |
| default=1e-6, |
| help="Absolute tolerance for reconstructed floating tensors", |
| ) |
| parser.add_argument("--rtol", type=float, default=1e-6) |
| parser.add_argument("--max-cached-shards", type=int, default=2) |
| parser.add_argument( |
| "--allow-eager-legacy", |
| action="store_true", |
| help="Allow fallback to an eager legacy torch.load if mmap is unavailable", |
| ) |
| parser.add_argument( |
| "--report", |
| help="Optional JSON report path (written atomically by the caller/job filesystem)", |
| ) |
| return parser |
|
|
|
|
| def main() -> int: |
| args = build_parser().parse_args() |
| report = validate(args) |
| rendered = json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) |
| print(rendered) |
| if args.report: |
| output = Path(args.report) |
| output.parent.mkdir(parents=True, exist_ok=True) |
| output.write_text(rendered + "\n", encoding="utf-8") |
| return 0 if report["passed"] else 1 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|