#!/usr/bin/env python3 """ Build GNNCP compact_v1 shards directly from docking pose files. Unlike ``build_graph_unified_enhanced.py``, this program never accumulates a dataset-wide ``list[Data]`` and never writes a monolithic legacy ``.pt`` file. It discovers poses deterministically; each worker builds one source system and immediately converts it to compact records. A single parent commits completed systems in source order, then packs bounded collections of records into tensor-only shards. The output directory is published atomically only after every selected system has been processed. Before publication, progress lives in a stable hidden ``..building`` directory. ``--resume`` reuses completed system checkpoints and any pose graphs already built for the current system. Examples -------- Single-system Slurm smoke test:: python build_compact_v1_direct.py \ --data-dir /path/to/docking_results \ --output-dir /path/to/compact_smoke \ --method protenix \ --system-id tnks2_lig_20 \ --max-poses-per-system 2 Full resumable build:: python build_compact_v1_direct.py \ --data-dir /path/to/docking_results \ --output-dir /path/to/compact_protenix \ --method protenix \ --num-workers 4 \ --resume Memory-bounded high-CPU build:: python build_compact_v1_direct.py \ --data-dir /path/to/docking_results \ --output-dir /path/to/compact_protenix \ --method protenix \ --system-workers 28 \ --num-workers 1 \ --memory-budget-gib 150 \ --resume """ from __future__ import annotations import argparse import concurrent.futures import fcntl import gc import hashlib import json import math import multiprocessing import os import re import shutil import sys import time import traceback from collections import Counter, OrderedDict from contextlib import contextmanager from dataclasses import dataclass, replace from datetime import datetime, timezone from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Sequence import torch from build_graph_unified_enhanced import build_graph_enhanced, find_docking_poses from convert_to_compact_v1 import ( DYNAMIC_COLUMNS, FORMAT_NAME, SCHEMA_VERSION, STATIC_COLUMNS, build_system_record, graph_content_hashes, pack_shard, ) DOCKING_METHODS = ("protenix", "diffdock", "autodock_vina", "medusagraph") PROGRESS_VERSION = 1 READY_CHECKPOINT_VERSION = 1 # ``build_graph_enhanced`` deliberately computes several dense SciPy distance # matrices. A single float64 N-by-N matrix occupies 8 * N**2 bytes; the # estimate below reserves room for roughly eight such matrices plus a fixed # parser/tensor overhead. It is intentionally an admission-control estimate, # not a statement about the serialized compact-record size. _WORKER_FIXED_MEMORY_MIB = 2048 _WORKER_DENSE_MEMORY_MULTIPLIER = 8 @dataclass(frozen=True) class PoseSpec: """One discovered pose and its stable pre-filter discovery index.""" source_graph_index: int system_id: str protein: Path ligand_native: Path ligand_pred: Path @dataclass(frozen=True) class SystemSpec: """All selected poses belonging to one source system.""" ordinal: int system_id: str protein: Path ligand_native: Path poses: tuple[PoseSpec, ...] @dataclass(frozen=True) class BuildConfig: data_dir: Path output_dir: Path method: str cutoff: float = 6.0 target_shard_mib: int = 512 num_workers: int = 1 system_workers: int = 1 memory_budget_gib: float | None = None strict: bool = True resume: bool = False on_error: str = "abort" max_systems: int | None = None max_poses_per_system: int | None = None include_systems: tuple[str, ...] = () GraphBuilder = Callable[..., Any] def _natural_key(value: str) -> tuple[Any, ...]: """Natural, case-insensitive ordering (pose2 before pose10).""" return tuple( int(part) if part.isdigit() else part.casefold() for part in re.split(r"(\d+)", value) ) def _atomic_json(path: Path, payload: Mapping[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") with temporary.open("w", encoding="utf-8") as handle: json.dump(payload, handle, indent=2, ensure_ascii=False) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) def _atomic_torch_save(payload: Any, path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") torch.save(payload, temporary) os.replace(temporary, path) @contextmanager def _exclusive_build_lock(output_dir: Path): """Hold a non-blocking advisory lock for the complete build/publication. The lock is a stable sidecar next to the output/staging directories rather than a file inside staging. Consequently, two ``--resume`` jobs cannot both enter the same staging directory. The zero-byte-ish sidecar is kept after exit so every future opener locks the same inode; a crashed process automatically releases its kernel lock. """ output_dir.parent.mkdir(parents=True, exist_ok=True) lock_path = output_dir.with_name(f".{output_dir.name}.build.lock") handle = lock_path.open("a+", encoding="utf-8") try: try: fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as exc: raise RuntimeError( f"another direct compact build is already using {output_dir}; " f"lock: {lock_path}" ) from exc handle.seek(0) handle.truncate() handle.write( json.dumps( { "pid": os.getpid(), "slurm_job_id": os.environ.get("SLURM_JOB_ID"), "output_dir": str(output_dir), "acquired_utc": datetime.now(timezone.utc).isoformat(), } ) + "\n" ) handle.flush() os.fsync(handle.fileno()) yield lock_path finally: try: fcntl.flock(handle.fileno(), fcntl.LOCK_UN) finally: handle.close() def _relative_or_absolute(path: Path, root: Path) -> str: try: return str(path.relative_to(root)) except ValueError: return str(path) def parse_args(argv: Sequence[str] | None = None) -> BuildConfig: parser = argparse.ArgumentParser( description=( "Build enhanced GNNCP graphs one system at a time and write " "compact_v1 shards directly." ) ) parser.add_argument("--data-dir", required=True, type=Path) parser.add_argument("--output-dir", required=True, type=Path) parser.add_argument("--method", required=True, choices=DOCKING_METHODS) parser.add_argument("--cutoff", type=float, default=6.0) parser.add_argument("--target-shard-mib", type=int, default=512) parser.add_argument( "--num-workers", type=int, default=1, help=( "Pose builders within one system. This must be 1 when " "--system-workers is greater than 1, so graph builders are never " "nested." ), ) parser.add_argument( "--system-workers", type=int, default=1, help=( "Independent source systems to build concurrently. The default 1 " "keeps the original sequential-system implementation." ), ) parser.add_argument( "--memory-budget-gib", type=float, default=None, help=( "Usable aggregate memory budget for --system-workers > 1. " "Workers are admitted by a conservative protein-size O(N^2) " "estimate; reserve node/parent memory outside this value." ), ) parser.add_argument( "--resume", action="store_true", help="Resume the stable hidden build directory after interruption.", ) parser.add_argument( "--on-error", choices=("abort", "skip-system"), default="abort", help="Never drops individual poses: skip-system drops the whole source system.", ) parser.add_argument( "--skip-strict-validation", action="store_true", help="Skip expensive redundant-field and edge-symmetry validation.", ) parser.add_argument("--max-systems", type=int, default=None) parser.add_argument("--max-poses-per-system", type=int, default=None) parser.add_argument( "--system-id", "--include-system", dest="include_systems", action="append", default=[], metavar="ID", help="Only build this source system ID; repeat to select multiple systems.", ) args = parser.parse_args(argv) return BuildConfig( data_dir=args.data_dir.expanduser().resolve(), output_dir=args.output_dir.expanduser().resolve(), method=args.method, cutoff=args.cutoff, target_shard_mib=args.target_shard_mib, num_workers=args.num_workers, system_workers=args.system_workers, memory_budget_gib=args.memory_budget_gib, strict=not args.skip_strict_validation, resume=args.resume, on_error=args.on_error, max_systems=args.max_systems, max_poses_per_system=args.max_poses_per_system, include_systems=tuple(args.include_systems), ) def _validate_config(config: BuildConfig) -> None: if not config.data_dir.is_dir(): raise FileNotFoundError(f"data directory not found: {config.data_dir}") if config.method not in DOCKING_METHODS: raise ValueError(f"unsupported docking method: {config.method}") if config.cutoff <= 0: raise ValueError("--cutoff must be positive") if config.target_shard_mib <= 0: raise ValueError("--target-shard-mib must be positive") if config.num_workers <= 0: raise ValueError("--num-workers must be positive") if config.system_workers <= 0: raise ValueError("--system-workers must be positive") if config.system_workers > 1 and config.num_workers != 1: raise ValueError( "--system-workers > 1 requires --num-workers=1; nested " "system/pose process pools are intentionally forbidden" ) if config.memory_budget_gib is not None and config.memory_budget_gib <= 0: raise ValueError("--memory-budget-gib must be positive") if config.system_workers > 1 and config.memory_budget_gib is None: raise ValueError( "--system-workers > 1 requires --memory-budget-gib so concurrent " "dense graph builders remain memory bounded" ) if config.max_systems is not None and config.max_systems <= 0: raise ValueError("--max-systems must be positive") if ( config.max_poses_per_system is not None and config.max_poses_per_system <= 0 ): raise ValueError("--max-poses-per-system must be positive") if config.output_dir == config.data_dir: raise ValueError("output directory must differ from the docking data directory") def discover_systems(config: BuildConfig) -> List[SystemSpec]: """Discover, filter, and deterministically order source systems and poses.""" raw_poses = find_docking_poses(str(config.data_dir), config.method) grouped: MutableMapping[str, List[Mapping[str, str]]] = OrderedDict() for pose in sorted( raw_poses, key=lambda item: ( _natural_key(str(item["pdb_id"])), _natural_key(str(Path(item["ligand_pred"]))), ), ): grouped.setdefault(str(pose["pdb_id"]), []).append(pose) requested = set(config.include_systems) if requested: missing = requested.difference(grouped) if missing: available = ", ".join(list(grouped)[:10]) raise ValueError( f"requested system IDs were not discovered: {sorted(missing)}; " f"first available IDs: {available}" ) grouped = OrderedDict((key, grouped[key]) for key in grouped if key in requested) selected_items = list(grouped.items()) if config.max_systems is not None: selected_items = selected_items[: config.max_systems] if not selected_items: raise ValueError("no docking systems matched the selection") systems: List[SystemSpec] = [] source_graph_index = 0 for ordinal, (system_id, raw_system_poses) in enumerate(selected_items): unique_by_path: Dict[Path, Mapping[str, str]] = {} for pose in raw_system_poses: unique_by_path[Path(pose["ligand_pred"]).resolve()] = pose ordered = [ unique_by_path[path] for path in sorted(unique_by_path, key=lambda value: _natural_key(str(value))) ] if config.max_poses_per_system is not None: ordered = ordered[: config.max_poses_per_system] if not ordered: continue proteins = {Path(pose["protein"]).resolve() for pose in ordered} natives = {Path(pose["ligand_native"]).resolve() for pose in ordered} if len(proteins) != 1 or len(natives) != 1: raise ValueError( f"{system_id}: discovered multiple protein/native files in one system" ) protein = next(iter(proteins)) ligand_native = next(iter(natives)) pose_specs: List[PoseSpec] = [] for pose in ordered: ligand_pred = Path(pose["ligand_pred"]).resolve() if ligand_pred.suffix.lower() != ".pdb": raise ValueError( f"{system_id}: unsupported pose format {ligand_pred.suffix!r}: " f"{ligand_pred}. build_graph_enhanced currently requires PDB poses." ) pose_specs.append( PoseSpec( source_graph_index=source_graph_index, system_id=system_id, protein=protein, ligand_native=ligand_native, ligand_pred=ligand_pred, ) ) source_graph_index += 1 systems.append( SystemSpec( ordinal=ordinal, system_id=system_id, protein=protein, ligand_native=ligand_native, poses=tuple(pose_specs), ) ) if not systems: raise ValueError("no PDB poses remained after filtering") return systems def _discovery_fingerprint(config: BuildConfig, systems: Sequence[SystemSpec]) -> str: """Hash data/format inputs while allowing safe scheduler changes on resume. ``num_workers``, ``system_workers`` and ``memory_budget_gib`` deliberately do not participate: they change only execution scheduling, not discovery, tensor content, ordering, or shard boundaries. This is what permits an existing sequential staging directory to resume with the adaptive cross-system scheduler. """ digest = hashlib.sha256() config_payload = { "format": FORMAT_NAME, "schema_version": SCHEMA_VERSION, "data_dir": str(config.data_dir), "method": config.method, "cutoff": config.cutoff, "target_shard_mib": config.target_shard_mib, "strict": config.strict, "on_error": config.on_error, "max_systems": config.max_systems, "max_poses_per_system": config.max_poses_per_system, "include_systems": sorted(config.include_systems), } digest.update(json.dumps(config_payload, sort_keys=True).encode("utf-8")) unique_paths = { path for system in systems for path in ( system.protein, system.ligand_native, *(pose.ligand_pred for pose in system.poses), ) } for path in sorted(unique_paths, key=str): stat = path.stat() digest.update(str(path).encode("utf-8")) digest.update(stat.st_size.to_bytes(8, "little", signed=False)) digest.update(stat.st_mtime_ns.to_bytes(8, "little", signed=False)) return digest.hexdigest() def _default_progress(fingerprint: str) -> Dict[str, Any]: return { "progress_version": PROGRESS_VERSION, "fingerprint": fingerprint, "next_system_index": 0, "next_shard_index": 0, "pending": [], "successful_source_systems": 0, "successful_graphs": 0, "compact_storage_groups": 0, "skipped_source_systems": 0, } def _pose_graph_path(work_dir: Path, local_pose_index: int) -> Path: return work_dir / f"pose_{local_pose_index:04d}.pt" def _count_nonhydrogen_pdb_atoms(path: Path) -> int: """Return a cheap, conservative node-count proxy without MDAnalysis. The graph builder selects ``not name H*``. PDB columns are sufficient for scheduling: over-counting an unusual hydrogen name only makes admission more conservative, whereas under-counting a large protein could cause an avoidable OOM. """ count = 0 with path.open("r", encoding="utf-8", errors="replace") as handle: for line in handle: if not line.startswith(("ATOM ", "HETATM")): continue atom_name = line[12:16].strip().upper() element = line[76:78].strip().upper() if atom_name.startswith("H") or element == "H": continue count += 1 return count def estimate_system_memory_mib(system: SystemSpec) -> int: """Estimate one system worker's peak working set for admission control. This follows the actual graph-builder scaling, which is dominated by dense float64 ``cdist`` matrices over protein plus predicted-ligand atoms. The native ligand is parsed too, so use the larger of the native and predicted ligand atom counts as a small conservative adjustment. The estimate is deliberately independent of pose count: cross-system mode builds poses sequentially in each worker and never nests a pose process pool. """ protein_atoms = _count_nonhydrogen_pdb_atoms(system.protein) ligand_atoms = max( _count_nonhydrogen_pdb_atoms(system.ligand_native), _count_nonhydrogen_pdb_atoms(system.poses[0].ligand_pred), ) n_nodes = max(1, protein_atoms + ligand_atoms) one_dense_matrix_mib = (8.0 * n_nodes * n_nodes) / (1024.0 * 1024.0) estimate = ( _WORKER_FIXED_MEMORY_MIB + _WORKER_DENSE_MEMORY_MULTIPLIER * one_dense_matrix_mib ) return max(1, int(math.ceil(estimate))) def _ready_checkpoint_path(stage_dir: Path, system_index: int) -> Path: return ( stage_dir / ".build_state" / "ready" / f"system_{system_index:08d}.pt" ) def _ready_error_path(stage_dir: Path, system_index: int) -> Path: return ( stage_dir / ".build_state" / "ready_errors" / f"system_{system_index:08d}.json" ) def _validate_ready_records( payload: Any, system_index: int, system: SystemSpec, ) -> List[Dict[str, Any]]: """Validate a worker-produced durable record before the single writer uses it.""" if not isinstance(payload, Mapping): raise ValueError("ready payload is not a mapping") if payload.get("ready_checkpoint_version") != READY_CHECKPOINT_VERSION: raise ValueError("incompatible ready checkpoint version") if int(payload.get("source_system_index", -1)) != system_index: raise ValueError("ready checkpoint system index does not match its filename") if str(payload.get("source_system_id", "")) != system.system_id: raise ValueError("ready checkpoint system ID does not match discovery") records = payload.get("records") if not isinstance(records, list) or not records: raise ValueError("ready checkpoint has no compact records") expected_indices = sorted(pose.source_graph_index for pose in system.poses) actual_indices: List[int] = [] for record in records: if not isinstance(record, Mapping): raise ValueError("ready checkpoint contains a non-mapping record") if str(record.get("_source_system_id", "")) != system.system_id: raise ValueError("ready checkpoint record has the wrong source system ID") source_graph_index = record.get("source_graph_index") if not isinstance(source_graph_index, torch.Tensor): raise ValueError("ready checkpoint record lacks source_graph_index") actual_indices.extend(int(value) for value in source_graph_index.tolist()) if sorted(actual_indices) != expected_indices: raise ValueError("ready checkpoint pose indices do not match discovery") return list(records) def _load_ready_records( stage_dir: Path, system_index: int, system: SystemSpec, *, discard_invalid: bool = True, ) -> List[Dict[str, Any]] | None: """Load a valid ready record, deleting only corrupt/stale local scratch.""" path = _ready_checkpoint_path(stage_dir, system_index) if not path.is_file(): return None try: payload = torch.load(path, map_location="cpu", weights_only=False) return _validate_ready_records(payload, system_index, system) except Exception as error: if discard_invalid: try: path.unlink() except FileNotFoundError: pass print( f"[ready-rebuild] {system.system_id}: discarded invalid ready " f"checkpoint ({type(error).__name__}: {error})", file=sys.stderr, flush=True, ) return None raise def _load_ready_error( stage_dir: Path, system_index: int, system: SystemSpec, ) -> Dict[str, Any] | None: """Load a durable skip-system outcome produced by a parallel worker.""" path = _ready_error_path(stage_dir, system_index) if not path.is_file(): return None try: with path.open("r", encoding="utf-8") as handle: payload = json.load(handle) if ( int(payload.get("system_index", -1)) != system_index or str(payload.get("system_id", "")) != system.system_id ): raise ValueError("ready error does not match discovered system") return payload except Exception as error: try: path.unlink() except FileNotFoundError: pass print( f"[ready-rebuild] {system.system_id}: discarded invalid ready error " f"({type(error).__name__}: {error})", file=sys.stderr, flush=True, ) return None def _build_pose_to_file( pose_payload: Mapping[str, Any], cutoff: float, output_path: str, ) -> tuple[bool, str]: """Process-pool worker. Each result is committed by atomic rename.""" try: graph = build_graph_enhanced( protein_pdb=str(pose_payload["protein"]), ligand_pred_pdb=str(pose_payload["ligand_pred"]), ligand_native_pdb=str(pose_payload["ligand_native"]), cutoff=cutoff, use_enhanced_features=True, ) _atomic_torch_save(graph, Path(output_path)) return True, output_path except Exception: return False, traceback.format_exc() def _validate_reusable_pose_file(path: Path) -> bool: try: graph = torch.load(path, map_location="cpu", weights_only=False) valid = ( hasattr(graph, "x") and isinstance(graph.x, torch.Tensor) and graph.x.ndim == 2 and graph.x.shape[1] == 82 ) del graph return bool(valid) except Exception: return False def build_pose_graphs( system: SystemSpec, work_dir: Path, config: BuildConfig, graph_builder: GraphBuilder = build_graph_enhanced, ) -> List[Any]: """Build/reuse every pose in one source system and return them in order.""" work_dir.mkdir(parents=True, exist_ok=True) missing: List[tuple[int, PoseSpec, Path]] = [] for local_index, pose in enumerate(system.poses): path = _pose_graph_path(work_dir, local_index) if path.is_file() and _validate_reusable_pose_file(path): continue if path.exists(): path.unlink() missing.append((local_index, pose, path)) if config.num_workers > 1 and graph_builder is not build_graph_enhanced: raise ValueError("a custom graph_builder is only supported with num_workers=1") errors: List[str] = [] if config.num_workers == 1: for local_index, pose, path in missing: try: graph = graph_builder( protein_pdb=str(pose.protein), ligand_pred_pdb=str(pose.ligand_pred), ligand_native_pdb=str(pose.ligand_native), cutoff=config.cutoff, use_enhanced_features=True, ) _atomic_torch_save(graph, path) del graph except Exception: errors.append( f"pose {local_index} ({pose.ligand_pred}):\n" f"{traceback.format_exc()}" ) break elif missing: payloads = [ ( { "protein": str(pose.protein), "ligand_pred": str(pose.ligand_pred), "ligand_native": str(pose.ligand_native), }, config.cutoff, str(path), ) for _, pose, path in missing ] with concurrent.futures.ProcessPoolExecutor( max_workers=config.num_workers ) as executor: futures = [executor.submit(_build_pose_to_file, *payload) for payload in payloads] for (local_index, pose, _), future in zip(missing, futures): ok, detail = future.result() if not ok: errors.append( f"pose {local_index} ({pose.ligand_pred}):\n{detail}" ) if errors: raise RuntimeError( f"{system.system_id}: {len(errors)} pose build(s) failed; " "the source system was not partially committed.\n" + "\n".join(errors[:3]) ) graphs: List[Any] = [] for local_index in range(len(system.poses)): path = _pose_graph_path(work_dir, local_index) graphs.append(torch.load(path, map_location="cpu", weights_only=False)) return graphs def compact_system_records( system: SystemSpec, graphs: Sequence[Any], strict: bool, data_root: Path, ) -> List[Dict[str, Any]]: """Convert one source system, splitting only when exact static content differs.""" if len(graphs) != len(system.poses): raise ValueError( f"{system.system_id}: graph count {len(graphs)} != pose count {len(system.poses)}" ) grouped: MutableMapping[str, List[int]] = OrderedDict() native_hashes: Dict[str, str] = {} for local_index, graph in enumerate(graphs): native_hash, shared_hash = graph_content_hashes(graph) grouped.setdefault(shared_hash, []).append(local_index) previous = native_hashes.setdefault(shared_hash, native_hash) if previous != native_hash: raise RuntimeError("shared-content SHA-256 collision detected") records: List[Dict[str, Any]] = [] multiple_groups = len(grouped) > 1 for shared_hash, local_indices in grouped.items(): storage_id = ( f"{system.system_id}__{shared_hash[:12]}" if multiple_groups else system.system_id ) descriptor = { "system_id": storage_id, "source_label": system.system_id, "source_label_counts": {system.system_id: len(local_indices)}, "native_hash": native_hashes[shared_hash], "shared_hash": shared_hash, "graph_indices": local_indices, } record = build_system_record(graphs, descriptor, strict=strict) global_indices = [ system.poses[local_index].source_graph_index for local_index in local_indices ] record["source_graph_index"] = torch.tensor(global_indices, dtype=torch.int64) record["_source_system_id"] = system.system_id record["_source_pose_paths"] = [ _relative_or_absolute( system.poses[local_index].ligand_pred, data_root, ) for local_index in local_indices ] records.append(record) return records def _build_system_to_ready_checkpoint( system_index: int, system: SystemSpec, stage_dir: str, config: BuildConfig, graph_builder: GraphBuilder = build_graph_enhanced, ) -> None: """Build one source system in a fresh process and atomically persist it. This worker never writes global progress, shard files, or the final output. Its only durable success artifact is a per-system ready checkpoint; the parent is the sole process allowed to consume it in source order. A fresh process per source system is intentional: dense NumPy/SciPy allocations from a large protein are returned to the OS when that process exits. """ stage = Path(stage_dir) ready_path = _ready_checkpoint_path(stage, system_index) if _load_ready_records(stage, system_index, system) is not None: return work_dir = stage / ".build_state" / "work" / f"system_{system_index:08d}" try: # Cross-system scheduling is validated to require one pose worker. A # replace makes that invariant explicit even if this helper is called # directly in a future test. worker_config = replace(config, num_workers=1, system_workers=1) graphs = build_pose_graphs( system, work_dir, worker_config, graph_builder=graph_builder, ) records = compact_system_records( system, graphs, strict=config.strict, data_root=config.data_dir, ) payload = { "ready_checkpoint_version": READY_CHECKPOINT_VERSION, "source_system_index": system_index, "source_system_id": system.system_id, "records": records, } _atomic_torch_save(payload, ready_path) del payload, records, graphs if work_dir.is_dir(): shutil.rmtree(work_dir) gc.collect() except Exception as error: if config.on_error != "skip-system": raise error_payload = { "system_index": system_index, "system_id": system.system_id, "num_poses": len(system.poses), "error_type": type(error).__name__, "error": str(error), "traceback": traceback.format_exc(), } _atomic_json(_ready_error_path(stage, system_index), error_payload) def _parallel_system_worker_main( system_index: int, system: SystemSpec, stage_dir: str, config: BuildConfig, graph_builder: GraphBuilder = build_graph_enhanced, ) -> None: """Top-level multiprocessing target; it must remain pickle/fork friendly.""" _build_system_to_ready_checkpoint( system_index, system, stage_dir, config, graph_builder=graph_builder, ) def _record_manifest_entry(record: Mapping[str, Any]) -> Dict[str, Any]: return { "system_id": record["_system_id"], "source_label": record["_source_label"], "source_system_id": record["_source_system_id"], "source_label_counts": record["_source_label_counts"], "native_hash": record["_native_hash"], "shared_hash": record["_shared_hash"], "num_graphs": record["_n_poses"], "num_nodes": record["_n_nodes"], "num_protein_nodes": record["_n_protein"], "num_ligand_nodes": record["_n_ligand"], "source_graph_indices": record["source_graph_index"].tolist(), "source_pose_paths": record["_source_pose_paths"], } def _flush_pending( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], ) -> None: pending = list(progress["pending"]) if not pending: return records: List[Dict[str, Any]] = [] checkpoint_paths: List[Path] = [] for entry in pending: checkpoint_path = stage_dir / entry["path"] checkpoint_paths.append(checkpoint_path) payload = torch.load(checkpoint_path, map_location="cpu", weights_only=False) if not isinstance(payload, list) or not payload: raise ValueError(f"invalid system checkpoint: {checkpoint_path}") records.extend(payload) shard_index = int(progress["next_shard_index"]) relative_path = f"shards/shard_{shard_index:05d}.pt" shard_path = stage_dir / relative_path packed = pack_shard(records) _atomic_torch_save(packed, shard_path) size_bytes = shard_path.stat().st_size metadata = { "path": relative_path, "num_graphs": int(packed["pose_system"].numel()), "num_systems": len(records), "num_source_systems": len( {str(record["_source_system_id"]) for record in records} ), "size_bytes": size_bytes, "systems": [_record_manifest_entry(record) for record in records], } meta_path = ( stage_dir / ".build_state" / "shard_metadata" / f"shard_{shard_index:05d}.json" ) _atomic_json(meta_path, metadata) progress["pending"] = [] progress["next_shard_index"] = shard_index + 1 _atomic_json(progress_path, progress) for checkpoint_path in checkpoint_paths: if checkpoint_path.is_file(): checkpoint_path.unlink() del packed, records gc.collect() print( f"[shard] {relative_path}: {metadata['num_source_systems']} source systems, " f"{metadata['num_systems']} storage groups, {metadata['num_graphs']} poses, " f"{size_bytes / 2**20:.1f} MiB", flush=True, ) def _commit_system_records( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], system_index: int, system: SystemSpec, records: Sequence[Mapping[str, Any]], target_bytes: int, total_systems: int, ) -> None: """Commit one fully-built source system in deterministic source order. Only the parent process calls this function. The ordering and state transitions intentionally match the original sequential loop so existing staging directories retain their resume and shard semantics. """ if int(progress["next_system_index"]) != system_index: raise RuntimeError( f"out-of-order system commit: expected {progress['next_system_index']}, " f"got {system_index}" ) if not records: raise ValueError(f"{system.system_id}: refusing to commit no records") record_bytes = sum(int(record["_tensor_bytes"]) for record in records) pending_bytes = sum(int(item["tensor_bytes"]) for item in progress["pending"]) if progress["pending"] and pending_bytes + record_bytes > target_bytes: _flush_pending(stage_dir, progress_path, progress) checkpoint_rel = f".build_state/checkpoints/system_{system_index:08d}.pt" checkpoint_path = stage_dir / checkpoint_rel _atomic_torch_save(list(records), checkpoint_path) progress["pending"].append( { "path": checkpoint_rel, "tensor_bytes": record_bytes, "source_system_index": system_index, "source_system_id": system.system_id, } ) progress["next_system_index"] = system_index + 1 progress["successful_source_systems"] += 1 progress["successful_graphs"] += len(system.poses) progress["compact_storage_groups"] += len(records) _atomic_json(progress_path, progress) print( f"[system] {system_index + 1}/{total_systems} " f"{system.system_id}: {len(system.poses)} poses, {len(records)} storage " f"group(s), {record_bytes / 2**20:.1f} MiB", flush=True, ) def _flush_pending_if_full( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], target_bytes: int, ) -> None: pending_bytes = sum(int(item["tensor_bytes"]) for item in progress["pending"]) if pending_bytes >= target_bytes: _flush_pending(stage_dir, progress_path, progress) def _commit_skipped_system( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], system_index: int, system: SystemSpec, error_payload: Mapping[str, Any], ) -> None: """Record a whole-system failure without disturbing deterministic order.""" if int(progress["next_system_index"]) != system_index: raise RuntimeError( f"out-of-order skipped-system commit: expected " f"{progress['next_system_index']}, got {system_index}" ) error_path = ( stage_dir / ".build_state" / "errors" / f"system_{system_index:08d}.json" ) _atomic_json(error_path, dict(error_payload)) progress["next_system_index"] = system_index + 1 progress["skipped_source_systems"] += 1 _atomic_json(progress_path, progress) print( f"[skip-system] {system.system_id}: " f"{error_payload.get('error_type', 'Error')}: {error_payload.get('error', '')}", file=sys.stderr, flush=True, ) def _load_shard_metadata(stage_dir: Path, count: int) -> List[Dict[str, Any]]: result = [] for shard_index in range(count): path = ( stage_dir / ".build_state" / "shard_metadata" / f"shard_{shard_index:05d}.json" ) with path.open("r", encoding="utf-8") as handle: result.append(json.load(handle)) return result def _load_errors(stage_dir: Path) -> List[Dict[str, Any]]: error_dir = stage_dir / ".build_state" / "errors" if not error_dir.is_dir(): return [] result = [] for path in sorted(error_dir.glob("system_*.json")): with path.open("r", encoding="utf-8") as handle: result.append(json.load(handle)) return result def _source_index_payload( config: BuildConfig, systems: Sequence[SystemSpec], successful_source_indices: set[int], errors: Sequence[Mapping[str, Any]], ) -> Dict[str, Any]: error_by_id = {str(item["system_id"]): item for item in errors} source_systems = [] for system in systems: successful = all( pose.source_graph_index in successful_source_indices for pose in system.poses ) source_systems.append( { "system_id": system.system_id, "status": "complete" if successful else "skipped", "protein": _relative_or_absolute(system.protein, config.data_dir), "ligand_native": _relative_or_absolute( system.ligand_native, config.data_dir ), "source_graph_indices": [ pose.source_graph_index for pose in system.poses ], "poses": [ _relative_or_absolute(pose.ligand_pred, config.data_dir) for pose in system.poses ], "error": error_by_id.get(system.system_id), } ) return { "data_dir": str(config.data_dir), "method": config.method, "systems": source_systems, } def _finish_dataset( config: BuildConfig, stage_dir: Path, progress: Mapping[str, Any], systems: Sequence[SystemSpec], ) -> Dict[str, Any]: shard_count = int(progress["next_shard_index"]) if shard_count == 0: raise RuntimeError("no systems were built successfully; refusing empty dataset") shards = _load_shard_metadata(stage_dir, shard_count) placements: List[tuple[int, int, int]] = [] compact_bytes = 0 for shard_index, shard_meta in enumerate(shards): shard_path = stage_dir / str(shard_meta["path"]) shard = torch.load( shard_path, map_location="cpu", mmap=True, weights_only=True, ) source_indices = shard["source_graph_index"].tolist() placements.extend( (int(source_index), shard_index, local_pose) for local_pose, source_index in enumerate(source_indices) ) compact_bytes += int(shard_meta["size_bytes"]) del shard placements.sort(key=lambda item: item[0]) successful_source_indices = [item[0] for item in placements] if len(successful_source_indices) != len(set(successful_source_indices)): raise RuntimeError("duplicate source_graph_index detected across shards") graph_map = [[item[1], item[2]] for item in placements] system_by_source_index = { pose.source_graph_index: system.system_id for system in systems for pose in system.poses } graph_to_system = [ system_by_source_index[source_index] for source_index in successful_source_indices ] counts = Counter(graph_to_system) system_index = { "graph_to_system": graph_to_system, "n_graphs": len(graph_to_system), "n_systems": len(counts), "systems": sorted(counts, key=_natural_key), "system_counts": dict(sorted(counts.items(), key=lambda item: _natural_key(item[0]))), "source_graph_indices": successful_source_indices, "note": ( "Labels are original source system IDs. Exact-content storage-group " "splits do not change graph_to_system." ), } _atomic_json(stage_dir / "system_index.json", system_index) errors = _load_errors(stage_dir) source_index = _source_index_payload( config, systems, set(successful_source_indices), errors, ) _atomic_json(stage_dir / "source_index.json", source_index) compact_systems = sum(int(shard["num_systems"]) for shard in shards) manifest: Dict[str, Any] = { "format": FORMAT_NAME, "schema_version": SCHEMA_VERSION, "status": "complete", "created_utc": datetime.now(timezone.utc).isoformat(), "method": config.method, "cutoff": config.cutoff, "source": { "data_dir": str(config.data_dir), "mode": "direct_from_docking_poses", "source_index": "source_index.json", "system_index": "system_index.json", "discovered_source_systems": len(systems), "discovered_poses": sum(len(system.poses) for system in systems), "skipped_source_systems": int(progress["skipped_source_systems"]), }, "grouping": { "split_label": "original_source_system_id", "storage_mode": "exact_shared_content_hash_within_source_system", "authoritative_storage_key": ( "sha256(exact float32 y_grt + node partition + " "x[:,0:34] + x[:,61:71])" ), "storage_splits_do_not_change_system_index": True, }, "features": { "full_dimension": 82, "dtype": "float32", "static_dimension": len(STATIC_COLUMNS), "static_columns": list(STATIC_COLUMNS), "dynamic_dimension": len(DYNAMIC_COLUMNS), "dynamic_columns": list(DYNAMIC_COLUMNS), }, "edges": { "index_dtype_on_disk": "int32", "stored_direction": "upper_triangle_src_lt_dst", "protein_protein_scope": "once_per_storage_group", "non_protein_protein_scope": "once_per_pose", "edge_attr": "derived_from_float32_coordinates_and_endpoint_types", }, "derived_fields": [ "pos", "is_protein", "y_true", "y_pred", "y_grt", "edge_index_reverse_direction", "edge_attr", "num_nodes", ], "n_graphs": len(graph_map), "n_systems": compact_systems, "n_source_systems": int(progress["successful_source_systems"]), "n_shards": len(shards), "graph_map": graph_map, "shards": shards, "size": {"compact_shard_bytes": compact_bytes}, "strict_validation": config.strict, "direct_builder": { "target_shard_mib": config.target_shard_mib, "resume_fingerprint": progress["fingerprint"], "on_error": config.on_error, }, } _atomic_json(stage_dir / "manifest.json", manifest) return manifest @dataclass class _RunningSystemWorker: process: Any estimated_memory_mib: int def _ready_outcome_kind( stage_dir: Path, system_index: int, system: SystemSpec, ) -> str | None: """Return a validated durable worker outcome without retaining tensors.""" records = _load_ready_records(stage_dir, system_index, system) if records is not None: del records return "success" error = _load_ready_error(stage_dir, system_index, system) if error is not None: return "skipped" return None def _unlink_if_exists(path: Path) -> None: try: path.unlink() except FileNotFoundError: pass def _commit_ready_systems_in_order( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], systems: Sequence[SystemSpec], target_bytes: int, submitted: set[int], ) -> int: """Consume only the next contiguous ready outcomes into the global writer.""" committed = 0 while int(progress["next_system_index"]) < len(systems): system_index = int(progress["next_system_index"]) system = systems[system_index] records = _load_ready_records(stage_dir, system_index, system) if records is not None: _commit_system_records( stage_dir, progress_path, progress, system_index, system, records, target_bytes, len(systems), ) _flush_pending_if_full(stage_dir, progress_path, progress, target_bytes) del records _unlink_if_exists(_ready_checkpoint_path(stage_dir, system_index)) # A prior interrupted retry can leave an obsolete skip artifact. _unlink_if_exists(_ready_error_path(stage_dir, system_index)) submitted.discard(system_index) committed += 1 continue error_payload = _load_ready_error(stage_dir, system_index, system) if error_payload is not None: _commit_skipped_system( stage_dir, progress_path, progress, system_index, system, error_payload, ) _unlink_if_exists(_ready_error_path(stage_dir, system_index)) submitted.discard(system_index) committed += 1 continue break if committed: gc.collect() return committed def _next_unscheduled_system_index( stage_dir: Path, progress: Mapping[str, Any], systems: Sequence[SystemSpec], submitted: set[int], ) -> int | None: """Find the earliest source system not already running or durably ready.""" start = int(progress["next_system_index"]) for system_index in range(start, len(systems)): if system_index in submitted: continue outcome = _ready_outcome_kind(stage_dir, system_index, systems[system_index]) if outcome is not None: submitted.add(system_index) continue return system_index return None def _terminate_running_workers(running: Mapping[int, _RunningSystemWorker]) -> None: """Best-effort cleanup when the parent aborts before workers finish.""" for worker in running.values(): if worker.process.is_alive(): worker.process.terminate() for worker in running.values(): worker.process.join() def _run_parallel_system_build( config: BuildConfig, stage_dir: Path, progress_path: Path, progress: Dict[str, Any], systems: Sequence[SystemSpec], *, graph_builder: GraphBuilder, ) -> None: """Build systems in memory-bounded fresh processes, then commit in order. Workers write only their own ready files. The parent alone updates progress/checkpoints/shards, so a completion-order race cannot change source_graph_index, graph_map, or shard membership. Fresh processes also prevent a large system's NumPy allocator high-water mark from becoming a hidden baseline for later small systems. """ if config.system_workers <= 1: raise ValueError("parallel system build requires --system-workers > 1") if config.num_workers != 1: raise ValueError("parallel system build requires --num-workers=1") if config.memory_budget_gib is None: raise ValueError("parallel system build requires --memory-budget-gib") ready_dir = stage_dir / ".build_state" / "ready" ready_error_dir = stage_dir / ".build_state" / "ready_errors" ready_dir.mkdir(parents=True, exist_ok=True) ready_error_dir.mkdir(parents=True, exist_ok=True) target_bytes = config.target_shard_mib * 1024 * 1024 budget_mib = int(math.floor(config.memory_budget_gib * 1024.0)) estimates = [estimate_system_memory_mib(system) for system in systems] too_large = [ (system.system_id, estimate) for system, estimate in zip(systems, estimates) if estimate > budget_mib ] if too_large: first_id, first_mib = too_large[0] raise ValueError( f"{len(too_large)} system(s) exceed the usable memory budget; first " f"{first_id} is estimated at {first_mib / 1024.0:.1f} GiB versus " f"{budget_mib / 1024.0:.1f} GiB. Increase --memory-budget-gib or " "build those systems in a larger-memory allocation." ) print( f"system workers: {config.system_workers} (one pose builder each)", flush=True, ) print( f"memory budget: {budget_mib / 1024.0:.1f} GiB usable; estimates " f"{min(estimates) / 1024.0:.1f}-{max(estimates) / 1024.0:.1f} GiB/system", flush=True, ) context = multiprocessing.get_context() running: Dict[int, _RunningSystemWorker] = {} submitted: set[int] = set() in_flight_mib = 0 try: while int(progress["next_system_index"]) < len(systems): _commit_ready_systems_in_order( stage_dir, progress_path, progress, systems, target_bytes, submitted, ) made_submission = False while len(running) < config.system_workers: system_index = _next_unscheduled_system_index( stage_dir, progress, systems, submitted, ) if system_index is None: break estimate_mib = estimates[system_index] if in_flight_mib + estimate_mib > budget_mib: break system = systems[system_index] process = context.Process( target=_parallel_system_worker_main, args=( system_index, system, str(stage_dir), config, graph_builder, ), name=f"compact-system-{system_index:05d}", ) process.start() running[system_index] = _RunningSystemWorker(process, estimate_mib) submitted.add(system_index) in_flight_mib += estimate_mib made_submission = True print( f"[schedule] {system_index + 1}/{len(systems)} " f"{system.system_id}: estimate {estimate_mib / 1024.0:.1f} GiB; " f"in flight {len(running)}/{config.system_workers}, " f"{in_flight_mib / 1024.0:.1f}/{budget_mib / 1024.0:.1f} GiB", flush=True, ) reaped = False for system_index, worker in list(running.items()): if worker.process.is_alive(): continue worker.process.join() exit_code = worker.process.exitcode del running[system_index] in_flight_mib -= worker.estimated_memory_mib reaped = True if system_index < int(progress["next_system_index"]): # The parent already consumed this worker's atomically # written ready artifact while it was doing final cleanup. # The artifact is intentionally gone by the time the child # exits, so do not require it a second time. continue outcome = _ready_outcome_kind( stage_dir, system_index, systems[system_index] ) if exit_code != 0: raise RuntimeError( f"parallel worker for {systems[system_index].system_id} " f"exited with status {exit_code}; no global progress was " "committed for that system" ) if outcome is None: raise RuntimeError( f"parallel worker for {systems[system_index].system_id} " "exited successfully without a ready checkpoint or error" ) if int(progress["next_system_index"]) >= len(systems): # A child may have written its ready file before completing # scratch cleanup. Join every such child before publishing or # removing .build_state so it cannot race the final rename. if not running: break if not reaped: time.sleep(0.1) continue if not made_submission and not reaped: # Never spin on a full memory budget while a worker is active. # A short polling interval also lets Slurm SIGTERM interrupt # promptly, leaving only atomically committed ready artifacts. time.sleep(0.1) except BaseException: _terminate_running_workers(running) raise def _run_locked( config: BuildConfig, *, graph_builder: GraphBuilder = build_graph_enhanced, ) -> Dict[str, Any]: """Implementation entered only while the output sidecar lock is held.""" _validate_config(config) if config.output_dir.exists(): raise FileExistsError( f"refusing to overwrite existing output directory: {config.output_dir}" ) stage_dir = config.output_dir.with_name(f".{config.output_dir.name}.building") if stage_dir.exists() and not config.resume: raise FileExistsError( f"incomplete build exists: {stage_dir}; pass --resume or move it aside" ) systems = discover_systems(config) fingerprint = _discovery_fingerprint(config, systems) progress_path = stage_dir / ".build_state" / "progress.json" if stage_dir.exists() and (stage_dir / "manifest.json").is_file(): os.replace(stage_dir, config.output_dir) print(f"published previously completed build: {config.output_dir}", flush=True) with (config.output_dir / "manifest.json").open("r", encoding="utf-8") as handle: return json.load(handle) if progress_path.is_file(): with progress_path.open("r", encoding="utf-8") as handle: progress = json.load(handle) if progress.get("progress_version") != PROGRESS_VERSION: raise ValueError("incompatible direct-builder progress version") if progress.get("fingerprint") != fingerprint: raise ValueError( "resume fingerprint changed: inputs or storage-affecting options differ" ) else: if stage_dir.exists() and any(stage_dir.iterdir()): raise ValueError( f"{stage_dir} exists without a valid progress file; move it aside" ) (stage_dir / "shards").mkdir(parents=True, exist_ok=True) (stage_dir / ".build_state" / "checkpoints").mkdir(parents=True, exist_ok=True) (stage_dir / ".build_state" / "work").mkdir(parents=True, exist_ok=True) progress = _default_progress(fingerprint) _atomic_json(progress_path, progress) print(f"data: {config.data_dir}", flush=True) print(f"output: {config.output_dir}", flush=True) print(f"staging: {stage_dir}", flush=True) print(f"systems: {len(systems)}", flush=True) print(f"poses: {sum(len(system.poses) for system in systems)}", flush=True) print(f"resume at: {progress['next_system_index']}", flush=True) print(f"pose workers/system: {config.num_workers}", flush=True) print(f"system workers: {config.system_workers}", flush=True) if config.memory_budget_gib is not None: print(f"memory budget: {config.memory_budget_gib:.1f} GiB usable", flush=True) print(f"strict: {config.strict}", flush=True) target_bytes = config.target_shard_mib * 1024 * 1024 if config.system_workers > 1: _run_parallel_system_build( config, stage_dir, progress_path, progress, systems, graph_builder=graph_builder, ) else: for system_index in range(int(progress["next_system_index"]), len(systems)): system = systems[system_index] work_dir = ( stage_dir / ".build_state" / "work" / f"system_{system_index:08d}" ) committed = False try: graphs = build_pose_graphs( system, work_dir, config, graph_builder=graph_builder, ) records = compact_system_records( system, graphs, strict=config.strict, data_root=config.data_dir, ) _commit_system_records( stage_dir, progress_path, progress, system_index, system, records, target_bytes, len(systems), ) committed = True _flush_pending_if_full( stage_dir, progress_path, progress, target_bytes ) del graphs, records if work_dir.is_dir(): shutil.rmtree(work_dir) gc.collect() except Exception as error: if committed: # The durable checkpoint/progress update succeeded. Do not # reinterpret a later scratch-cleanup failure as a skipped # source system. raise if config.on_error == "abort": raise error_payload = { "system_index": system_index, "system_id": system.system_id, "num_poses": len(system.poses), "error_type": type(error).__name__, "error": str(error), "traceback": traceback.format_exc(), } _commit_skipped_system( stage_dir, progress_path, progress, system_index, system, error_payload, ) _flush_pending(stage_dir, progress_path, progress) manifest = _finish_dataset(config, stage_dir, progress, systems) os.replace(stage_dir, config.output_dir) state_dir = config.output_dir / ".build_state" if state_dir.is_dir(): shutil.rmtree(state_dir) print( f"complete: {config.output_dir / 'manifest.json'} " f"({manifest['n_graphs']} graphs, {manifest['n_source_systems']} source " f"systems, {manifest['n_shards']} shards)", flush=True, ) return manifest def run( config: BuildConfig, *, graph_builder: GraphBuilder = build_graph_enhanced, ) -> Dict[str, Any]: """Run a direct compact build under an output-directory exclusive lock. The injectable graph builder is intentionally only for small CPU tests. Production CLI calls always use ``build_graph_enhanced``. """ with _exclusive_build_lock(config.output_dir): return _run_locked(config, graph_builder=graph_builder) def main(argv: Sequence[str] | None = None) -> int: config = parse_args(argv) run(config) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as error: print(f"ERROR: {error}", file=sys.stderr, flush=True) raise