File size: 13,595 Bytes
0cb481f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/env python3
"""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
    # Linux reports KiB; macOS reports bytes.
    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())