File size: 62,122 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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 | #!/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
``.<name>.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
|