copuladock / code /compact_v1 /smoke_test_compact_dataset.py
liofoil's picture
Add files using upload-large-folder tool
0cb481f verified
Raw
History Blame Contribute Delete
23.5 kB
#!/usr/bin/env python3
"""Compute-node smoke test for :class:`CompactGraphDataset`.
The test intentionally samples rather than scans the complete dataset. It
exercises:
* deterministic random graph reconstruction;
* at least one graph from every selected shard and cross-shard batches;
* the per-process mmap shard cache through repeated access;
* PyG DataLoader collation with zero and multiple worker processes; and
* model-facing tensor shapes, dtypes, index ranges, and finite values.
Timing, process RSS/high-water marks, page faults, and filesystem I/O counters
are written to an atomic JSON report. GNU ``time -v`` and Slurm accounting in
the companion sbatch file provide job-wide measurements including workers.
"""
from __future__ import annotations
import argparse
import gc
import json
import math
import os
import random
import resource
import socket
import statistics
import sys
import time
import traceback
from pathlib import Path
from typing import Any, Dict, List, Mapping, Sequence
import torch
import torch_geometric
from torch.utils.data import Subset
from torch_geometric.data import Batch, Data
from torch_geometric.loader import DataLoader
from compact_graph_dataset import CompactGraphDataset
MIB = 1024 * 1024
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Sample, batch, and profile a compact GNNCP dataset."
)
parser.add_argument("--compact", required=True, help="Compact dataset directory")
parser.add_argument("--report", help="Atomic JSON report path")
parser.add_argument("--num-random", type=int, default=16)
parser.add_argument(
"--max-shards",
type=int,
default=0,
help="Maximum shards to probe; 0 tests every shard",
)
parser.add_argument("--batch-size", type=int, default=4)
parser.add_argument("--num-workers", type=int, default=2)
parser.add_argument(
"--worker-timeout-s",
type=float,
default=180.0,
help="Multi-worker DataLoader timeout; zero disables it",
)
parser.add_argument("--max-batches", type=int, default=8)
parser.add_argument("--max-cached-shards", type=int, default=2)
parser.add_argument("--repeat-count", type=int, default=3)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument(
"--torch-threads",
type=int,
default=min(4, int(os.environ.get("SLURM_CPUS_PER_TASK", "4"))),
)
parser.add_argument(
"--no-strict",
action="store_true",
help="Disable loader invariant checks (not recommended for smoke tests)",
)
args = parser.parse_args()
positive = {
"num_random": args.num_random,
"batch_size": args.batch_size,
"max_batches": args.max_batches,
"max_cached_shards": args.max_cached_shards,
"repeat_count": args.repeat_count,
"torch_threads": args.torch_threads,
}
for name, value in positive.items():
if value < 1:
parser.error(f"--{name.replace('_', '-')} must be >= 1")
if args.num_workers < 0:
parser.error("--num-workers must be >= 0")
if args.worker_timeout_s < 0:
parser.error("--worker-timeout-s must be >= 0")
if args.max_shards < 0:
parser.error("--max-shards must be >= 0")
return args
def _proc_status_mib(field: str) -> float | None:
try:
with Path("/proc/self/status").open("r", encoding="utf-8") as handle:
for line in handle:
if line.startswith(f"{field}:"):
return float(line.split()[1]) / 1024.0
except OSError:
return None
return None
def _proc_io_bytes() -> Dict[str, int]:
result = {"read_bytes": 0, "write_bytes": 0}
try:
with Path("/proc/self/io").open("r", encoding="utf-8") as handle:
for line in handle:
key, raw_value = line.split(":", 1)
if key in result:
result[key] = int(raw_value.strip())
except OSError:
pass
return result
def resource_snapshot() -> Dict[str, float | int | None]:
usage = resource.getrusage(resource.RUSAGE_SELF)
children = resource.getrusage(resource.RUSAGE_CHILDREN)
io_bytes = _proc_io_bytes()
# ru_maxrss is KiB on Linux, which is the target Slurm platform.
return {
"monotonic_s": time.perf_counter(),
"rss_mib": _proc_status_mib("VmRSS"),
"hwm_mib": _proc_status_mib("VmHWM"),
"ru_maxrss_mib": float(usage.ru_maxrss) / 1024.0,
"minor_faults": int(usage.ru_minflt),
"major_faults": int(usage.ru_majflt),
"self_user_cpu_s": float(usage.ru_utime),
"self_system_cpu_s": float(usage.ru_stime),
"children_ru_maxrss_mib": float(children.ru_maxrss) / 1024.0,
"children_minor_faults": int(children.ru_minflt),
"children_major_faults": int(children.ru_majflt),
"children_user_cpu_s": float(children.ru_utime),
"children_system_cpu_s": float(children.ru_stime),
"read_bytes": io_bytes["read_bytes"],
"write_bytes": io_bytes["write_bytes"],
}
def resource_delta(
before: Mapping[str, float | int | None],
after: Mapping[str, float | int | None],
) -> Dict[str, float | int | None]:
def subtract(key: str) -> float | int | None:
left = after.get(key)
right = before.get(key)
if left is None or right is None:
return None
return left - right
return {
"elapsed_s": subtract("monotonic_s"),
"rss_mib_after": after.get("rss_mib"),
"rss_mib_delta": subtract("rss_mib"),
"hwm_mib_after": after.get("hwm_mib"),
"ru_maxrss_mib_after": after.get("ru_maxrss_mib"),
"minor_faults_delta": subtract("minor_faults"),
"major_faults_delta": subtract("major_faults"),
"self_user_cpu_s_delta": subtract("self_user_cpu_s"),
"self_system_cpu_s_delta": subtract("self_system_cpu_s"),
"children_ru_maxrss_mib_after": after.get("children_ru_maxrss_mib"),
"children_minor_faults_delta": subtract("children_minor_faults"),
"children_major_faults_delta": subtract("children_major_faults"),
"children_user_cpu_s_delta": subtract("children_user_cpu_s"),
"children_system_cpu_s_delta": subtract("children_system_cpu_s"),
"read_mib_delta": (
None
if subtract("read_bytes") is None
else float(subtract("read_bytes")) / MIB
),
"write_mib_delta": (
None
if subtract("write_bytes") is None
else float(subtract("write_bytes")) / MIB
),
}
def latency_summary(values: Sequence[float]) -> Dict[str, float | int]:
if not values:
return {"count": 0}
ordered = sorted(values)
p95_index = max(0, math.ceil(0.95 * len(ordered)) - 1)
return {
"count": len(ordered),
"total_s": float(sum(ordered)),
"mean_ms": float(statistics.fmean(ordered) * 1000.0),
"median_ms": float(statistics.median(ordered) * 1000.0),
"p95_ms": float(ordered[p95_index] * 1000.0),
"min_ms": float(ordered[0] * 1000.0),
"max_ms": float(ordered[-1] * 1000.0),
}
def ensure_finite(name: str, tensor: torch.Tensor) -> None:
if not bool(torch.isfinite(tensor).all().item()):
raise RuntimeError(f"{name} contains NaN or infinity")
def check_graph(data: Data, dataset_index: int) -> Dict[str, Any]:
required = (
"x",
"edge_index",
"edge_attr",
"pos",
"is_protein",
"y_true",
"y_pred",
"y_grt",
)
missing = [name for name in required if not hasattr(data, name)]
if missing:
raise RuntimeError(f"graph {dataset_index} is missing fields: {missing}")
num_nodes = int(data.num_nodes)
if data.x.shape != (num_nodes, 82) or data.x.dtype != torch.float32:
raise RuntimeError(
f"graph {dataset_index}: x={tuple(data.x.shape)} {data.x.dtype}"
)
if data.edge_index.ndim != 2 or data.edge_index.shape[0] != 2:
raise RuntimeError(
f"graph {dataset_index}: edge_index={tuple(data.edge_index.shape)}"
)
if data.edge_index.dtype != torch.int64:
raise RuntimeError(
f"graph {dataset_index}: edge_index dtype={data.edge_index.dtype}"
)
num_edges = int(data.edge_index.shape[1])
if data.edge_attr.shape != (num_edges, 4):
raise RuntimeError(
f"graph {dataset_index}: edge_attr={tuple(data.edge_attr.shape)}"
)
if data.edge_attr.dtype != torch.float32:
raise RuntimeError(
f"graph {dataset_index}: edge_attr dtype={data.edge_attr.dtype}"
)
node_shapes = {
"pos": (num_nodes, 3),
"is_protein": (num_nodes, 1),
"y_true": (num_nodes, 1),
"y_pred": (num_nodes, 3),
"y_grt": (num_nodes, 3),
}
for name, expected in node_shapes.items():
tensor = getattr(data, name)
if tuple(tensor.shape) != expected or tensor.dtype != torch.float32:
raise RuntimeError(
f"graph {dataset_index}: {name}={tuple(tensor.shape)} {tensor.dtype}"
)
ensure_finite(f"graph {dataset_index} {name}", tensor)
ensure_finite(f"graph {dataset_index} x", data.x)
ensure_finite(f"graph {dataset_index} edge_attr", data.edge_attr)
if not torch.equal(data.pos, data.y_pred):
raise RuntimeError(f"graph {dataset_index}: pos and y_pred differ")
if num_edges:
edge_min = int(data.edge_index.min().item())
edge_max = int(data.edge_index.max().item())
if edge_min < 0 or edge_max >= num_nodes:
raise RuntimeError(
f"graph {dataset_index}: edge endpoints [{edge_min},{edge_max}] "
f"outside [0,{num_nodes})"
)
protein_values = torch.unique(data.is_protein)
if not bool(torch.all((protein_values == 0) | (protein_values == 1)).item()):
raise RuntimeError(f"graph {dataset_index}: is_protein is not binary")
return {
"dataset_index": dataset_index,
"num_nodes": num_nodes,
"num_edges": num_edges,
"num_protein_nodes": int(data.is_protein.sum().item()),
"max_y_true": float(data.y_true.max().item()) if num_nodes else 0.0,
}
def check_batch(batch: Batch, expected_graphs: int) -> Dict[str, Any]:
actual_graphs = int(batch.num_graphs)
if actual_graphs != expected_graphs:
raise RuntimeError(
f"batch reports {actual_graphs} graphs, expected {expected_graphs}"
)
num_nodes = int(batch.x.shape[0])
if batch.x.ndim != 2 or batch.x.shape[1] != 82:
raise RuntimeError(f"batched x has shape {tuple(batch.x.shape)}")
if batch.edge_attr.ndim != 2 or batch.edge_attr.shape[1] != 4:
raise RuntimeError(
f"batched edge_attr has shape {tuple(batch.edge_attr.shape)}"
)
if batch.batch.numel() != num_nodes:
raise RuntimeError("PyG batch assignment length does not match node count")
if batch.ptr.numel() != actual_graphs + 1:
raise RuntimeError("PyG batch ptr length is invalid")
if not torch.equal(batch.pos, batch.y_pred):
raise RuntimeError("batched pos and y_pred differ")
ensure_finite("batch x", batch.x)
ensure_finite("batch edge_attr", batch.edge_attr)
ensure_finite("batch pos", batch.pos)
return {
"num_graphs": actual_graphs,
"num_nodes": num_nodes,
"num_edges": int(batch.edge_index.shape[1]),
}
def evenly_spaced(values: Sequence[int], limit: int) -> List[int]:
if limit <= 0 or len(values) <= limit:
return list(values)
if limit == 1:
return [values[0]]
positions = {
round(index * (len(values) - 1) / (limit - 1)) for index in range(limit)
}
return [values[position] for position in sorted(positions)]
def global_indices_by_shard(dataset: CompactGraphDataset) -> List[List[int]]:
result: List[List[int]] = [[] for _ in dataset.shards]
graph_map = dataset.manifest.get("graph_map")
if graph_map is not None:
for global_index, entry in enumerate(graph_map):
if isinstance(entry, Mapping):
shard_index = entry.get("shard", entry.get("shard_index"))
else:
shard_index = entry[0]
result[int(shard_index)].append(global_index)
else:
global_index = 0
for shard_index, count in enumerate(dataset._shard_counts):
result[shard_index].extend(range(global_index, global_index + count))
global_index += count
empty = [index for index, indices in enumerate(result) if not indices]
if empty:
raise RuntimeError(f"manifest contains empty shards: {empty}")
return result
def load_direct(
dataset: CompactGraphDataset,
indices: Sequence[int],
) -> Dict[str, Any]:
before = resource_snapshot()
latencies: List[float] = []
samples: List[Dict[str, Any]] = []
total_nodes = 0
total_edges = 0
for dataset_index in indices:
started = time.perf_counter()
graph = dataset[dataset_index]
latency = time.perf_counter() - started
metrics = check_graph(graph, dataset_index)
metadata = dataset.metadata(dataset_index)
metrics.update(
{
"shard_index": int(metadata["shard_index"]),
"source_graph_index": int(metadata["source_graph_index"]),
"latency_ms": latency * 1000.0,
}
)
if "system_id" in metadata:
metrics["system_id"] = metadata["system_id"]
samples.append(metrics)
latencies.append(latency)
total_nodes += metrics["num_nodes"]
total_edges += metrics["num_edges"]
del graph
gc.collect()
after = resource_snapshot()
resources = resource_delta(before, after)
elapsed = float(resources["elapsed_s"] or 0.0)
return {
"indices": list(indices),
"latency": latency_summary(latencies),
"total_nodes": total_nodes,
"total_edges": total_edges,
"graphs_per_s": len(indices) / elapsed if elapsed > 0 else None,
"nodes_per_s": total_nodes / elapsed if elapsed > 0 else None,
"samples": samples,
"resources": resources,
}
def run_loader(
dataset: CompactGraphDataset,
indices: Sequence[int],
*,
batch_size: int,
num_workers: int,
max_batches: int,
worker_timeout_s: float,
) -> Dict[str, Any]:
before = resource_snapshot()
subset = Subset(dataset, list(indices))
loader = DataLoader(
subset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
persistent_workers=False,
pin_memory=False,
timeout=worker_timeout_s if num_workers else 0,
)
latencies: List[float] = []
batch_metrics: List[Dict[str, Any]] = []
iterator = iter(loader)
prior = time.perf_counter()
try:
for batch_number, batch in enumerate(iterator):
now = time.perf_counter()
latency = now - prior
latencies.append(latency)
metrics = check_batch(batch, min(batch_size, len(indices) - batch_number * batch_size))
metrics["batch_number"] = batch_number
metrics["latency_ms"] = latency * 1000.0
batch_metrics.append(metrics)
del batch
if batch_number + 1 >= max_batches:
break
prior = time.perf_counter()
finally:
del iterator
del loader
del subset
gc.collect()
after = resource_snapshot()
resources = resource_delta(before, after)
elapsed = float(resources["elapsed_s"] or 0.0)
total_graphs = sum(item["num_graphs"] for item in batch_metrics)
total_nodes = sum(item["num_nodes"] for item in batch_metrics)
total_edges = sum(item["num_edges"] for item in batch_metrics)
return {
"num_workers": num_workers,
"worker_timeout_s": worker_timeout_s if num_workers else 0,
"batch_size": batch_size,
"input_indices": list(indices),
"batches_tested": len(batch_metrics),
"graphs_tested": total_graphs,
"total_nodes": total_nodes,
"total_edges": total_edges,
"graphs_per_s": total_graphs / elapsed if elapsed > 0 else None,
"nodes_per_s": total_nodes / elapsed if elapsed > 0 else None,
"latency": latency_summary(latencies),
"batches": batch_metrics,
"resources": resources,
}
def write_report(path: Path, report: Mapping[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}")
with temporary.open("w", encoding="utf-8") as handle:
json.dump(report, handle, indent=2, sort_keys=True, ensure_ascii=False)
handle.write("\n")
os.replace(temporary, path)
def run(args: argparse.Namespace) -> Dict[str, Any]:
compact = Path(args.compact).expanduser().resolve()
default_report = compact / (
f"smoke_report_{os.environ.get('SLURM_JOB_ID', str(os.getpid()))}.json"
)
report_path = (
Path(args.report).expanduser().resolve() if args.report else default_report
)
report: Dict[str, Any] = {
"status": "running",
"compact": str(compact),
"report": str(report_path),
"started_utc_epoch_s": time.time(),
"environment": {
"hostname": socket.gethostname(),
"pid": os.getpid(),
"python": sys.version,
"torch": torch.__version__,
"torch_geometric": torch_geometric.__version__,
"slurm_job_id": os.environ.get("SLURM_JOB_ID"),
"slurm_array_job_id": os.environ.get("SLURM_ARRAY_JOB_ID"),
"slurm_array_task_id": os.environ.get("SLURM_ARRAY_TASK_ID"),
"slurm_cpus_per_task": os.environ.get("SLURM_CPUS_PER_TASK"),
},
"config": vars(args),
"resources_at_start": resource_snapshot(),
}
try:
torch.set_num_threads(args.torch_threads)
initialization_before = resource_snapshot()
dataset = CompactGraphDataset(
compact,
max_cached_shards=args.max_cached_shards,
strict=not args.no_strict,
)
initialization_after = resource_snapshot()
if len(dataset) < 1:
raise RuntimeError("compact dataset is empty")
report["dataset"] = {
"num_graphs": len(dataset),
"num_shards": len(dataset.shards),
"n_systems": dataset.manifest.get("n_systems"),
"method": dataset.manifest.get("method"),
"size": dataset.manifest.get("size"),
"initialization": resource_delta(
initialization_before, initialization_after
),
}
shard_indices = global_indices_by_shard(dataset)
selected_shards = evenly_spaced(
list(range(len(shard_indices))), args.max_shards
)
boundary_indices: List[int] = []
first_per_shard: List[int] = []
for shard_index in selected_shards:
indices = shard_indices[shard_index]
first_per_shard.append(indices[0])
boundary_indices.append(indices[0])
if indices[-1] != indices[0]:
boundary_indices.append(indices[-1])
report["shard_probe"] = {
"selected_shards": selected_shards,
"boundary_indices": boundary_indices,
"all_shards_selected": len(selected_shards) == len(dataset.shards),
}
report["direct_cross_shard"] = load_direct(dataset, boundary_indices)
rng = random.Random(args.seed)
random_count = min(args.num_random, len(dataset))
random_indices = rng.sample(range(len(dataset)), random_count)
report["direct_random"] = load_direct(dataset, random_indices)
repeat_index = random_indices[0]
repeat_latencies: List[float] = []
repeat_before = resource_snapshot()
for _ in range(args.repeat_count):
started = time.perf_counter()
graph = dataset[repeat_index]
repeat_latencies.append(time.perf_counter() - started)
check_graph(graph, repeat_index)
del graph
gc.collect()
repeat_after = resource_snapshot()
report["repeated_access"] = {
"index": repeat_index,
"latency": latency_summary(repeat_latencies),
"resources": resource_delta(repeat_before, repeat_after),
}
cross_loader_indices = first_per_shard[
: args.batch_size * args.max_batches
]
report["cross_shard_dataloader"] = run_loader(
dataset,
cross_loader_indices,
batch_size=min(args.batch_size, len(cross_loader_indices)),
num_workers=0,
max_batches=args.max_batches,
worker_timeout_s=args.worker_timeout_s,
)
worker_indices = list(dict.fromkeys(random_indices + boundary_indices))
worker_indices = worker_indices[: args.batch_size * args.max_batches]
# Forked workers should start with an empty mmap cache. Constructing a
# fresh dataset here also catches errors in opening the same manifest
# independently from more than one process.
worker_dataset = CompactGraphDataset(
compact,
max_cached_shards=args.max_cached_shards,
strict=not args.no_strict,
)
report["multiworker_dataloader"] = run_loader(
worker_dataset,
worker_indices,
batch_size=min(args.batch_size, len(worker_indices)),
num_workers=args.num_workers,
max_batches=args.max_batches,
worker_timeout_s=args.worker_timeout_s,
)
del worker_dataset
report["resources_at_end"] = resource_snapshot()
report["completed_utc_epoch_s"] = time.time()
report["elapsed_s"] = (
report["completed_utc_epoch_s"] - report["started_utc_epoch_s"]
)
report["status"] = "passed"
except Exception as error:
report["status"] = "failed"
report["completed_utc_epoch_s"] = time.time()
report["elapsed_s"] = (
report["completed_utc_epoch_s"] - report["started_utc_epoch_s"]
)
report["error"] = f"{type(error).__name__}: {error}"
report["traceback"] = traceback.format_exc()
write_report(report_path, report)
raise
write_report(report_path, report)
print(
json.dumps(
{
"status": report["status"],
"report": str(report_path),
"num_graphs": report["dataset"]["num_graphs"],
"num_shards": report["dataset"]["num_shards"],
"elapsed_s": report["elapsed_s"],
"rss_mib": report["resources_at_end"]["rss_mib"],
"hwm_mib": report["resources_at_end"]["hwm_mib"],
},
indent=2,
sort_keys=True,
),
flush=True,
)
return report
def main() -> int:
args = parse_args()
report = run(args)
return 0 if report["status"] == "passed" else 1
if __name__ == "__main__":
raise SystemExit(main())