Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- README.md +71 -0
- code/compact_v1/README.md +28 -0
- code/compact_v1/build_compact_v1_direct.py +1700 -0
- code/compact_v1/build_compact_v1_direct.sbatch +130 -0
- code/compact_v1/build_graph_unified_enhanced.py +864 -0
- code/compact_v1/build_system_index.py +295 -0
- code/compact_v1/compact_graph_dataset.py +543 -0
- code/compact_v1/convert_to_compact_v1.py +695 -0
- code/compact_v1/materialize_hiqbind_gnncp.py +240 -0
- code/compact_v1/requirements.txt +9 -0
- code/compact_v1/smoke_test_compact_dataset.py +636 -0
- code/compact_v1/test_build_compact_v1_direct.py +403 -0
- code/compact_v1/test_compact_graph_dataset.py +327 -0
- code/compact_v1/validate_compact_dataset.py +401 -0
- code/release/upload_copuladock.py +607 -0
- code/release/upload_copuladock.sbatch +44 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/manifest.json +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00015.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00016.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00023.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00024.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00025.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00026.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00027.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00038.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00042.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00043.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00050.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00052.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00053.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00056.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00059.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00063.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00067.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00074.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00075.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00082.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00083.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00086.pt +3 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/source_index.json +0 -0
- data/hiqbind_5k_v1/autodock_vina_full_v1/system_index.json +0 -0
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00008.pt +3 -0
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00029.pt +3 -0
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00036.pt +3 -0
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00048.pt +3 -0
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00049.pt +3 -0
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00065.pt +3 -0
- data/hiqbind_5k_v1/diffdock_full_v1/system_index.json +0 -0
- docs/DATASET_USAGE_ZH.md +198 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
data/hiqbind_5k_v1/autodock_vina_full_v1/manifest.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HiQBind 5K Compact Docking Graphs
|
| 2 |
+
|
| 3 |
+
本仓库发布 HiQBind 5K 蛋白–配体体系的两套已完成 docking baseline 图数据:DiffDock 和 AutoDock Vina。数据采用 `gnncp_compact_v1` 格式,可通过附带的 PyTorch Geometric loader 按需重建单个 pose 图,适用于 CQR-GNN 及其他 pose-level 图模型。
|
| 4 |
+
|
| 5 |
+
## 本次发布内容
|
| 6 |
+
|
| 7 |
+
| baseline | protein–ligand system | pose graph | shard | 数据目录约占空间 |
|
| 8 |
+
| --- | ---: | ---: | ---: | ---: |
|
| 9 |
+
| DiffDock | 4,979 | 97,988 | 98 | 49 GiB |
|
| 10 |
+
| AutoDock Vina | 4,887 | 85,824 | 88 | 44 GiB |
|
| 11 |
+
|
| 12 |
+
这里的 **system** 就是一个 protein–ligand pair;一个 system 最多包含 20 个 docking pose,因此一个 pose 对应一张 graph。部分 system 的有效 pose 少于 20 个,故 graph 总数不必等于 system 数乘以 20。
|
| 13 |
+
|
| 14 |
+
两个目录都已经完成严格校验(`status: complete`、`strict_validation: true`),构图 cutoff 为 6.0 Å。两方法共同覆盖 4,868 个 system;做直接方法对比时请使用该共同 system 集合,而不要假定两个目录的 system 完全相同。
|
| 15 |
+
|
| 16 |
+
仓库布局如下:
|
| 17 |
+
|
| 18 |
+
```text
|
| 19 |
+
data/hiqbind_5k_v1/
|
| 20 |
+
diffdock_full_v1/
|
| 21 |
+
autodock_vina_full_v1/
|
| 22 |
+
code/compact_v1/
|
| 23 |
+
docs/DATASET_USAGE_ZH.md
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
`data/` 中的 shard 是内部紧凑存储格式,不能把它直接当成 PyG `Data` 列表加载。请使用 `code/compact_v1/compact_graph_dataset.py` 提供的 `CompactGraphDataset`。
|
| 27 |
+
|
| 28 |
+
完整中文使用说明、system 级划分示例、图字段定义与重建流程见 [docs/DATASET_USAGE_ZH.md](docs/DATASET_USAGE_ZH.md)。
|
| 29 |
+
原始结构与模型的上游条款说明见 [NOTICE.md](NOTICE.md)。
|
| 30 |
+
|
| 31 |
+
## 快速开始
|
| 32 |
+
|
| 33 |
+
下载所需的一个方法及 reader:
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
from huggingface_hub import snapshot_download
|
| 37 |
+
|
| 38 |
+
snapshot_download(
|
| 39 |
+
repo_id="liofoil/copuladock",
|
| 40 |
+
repo_type="dataset",
|
| 41 |
+
local_dir="copuladock",
|
| 42 |
+
allow_patterns=[
|
| 43 |
+
"code/compact_v1/compact_graph_dataset.py",
|
| 44 |
+
"data/hiqbind_5k_v1/diffdock_full_v1/**",
|
| 45 |
+
],
|
| 46 |
+
)
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
然后:
|
| 50 |
+
|
| 51 |
+
```python
|
| 52 |
+
import sys
|
| 53 |
+
from pathlib import Path
|
| 54 |
+
|
| 55 |
+
root = Path("copuladock")
|
| 56 |
+
sys.path.insert(0, str(root / "code" / "compact_v1"))
|
| 57 |
+
from compact_graph_dataset import CompactGraphDataset
|
| 58 |
+
|
| 59 |
+
dataset = CompactGraphDataset(
|
| 60 |
+
root / "data" / "hiqbind_5k_v1" / "diffdock_full_v1"
|
| 61 |
+
)
|
| 62 |
+
graph = dataset[0]
|
| 63 |
+
print(len(dataset), graph.x.shape)
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## 重要使用约束
|
| 67 |
+
|
| 68 |
+
- 划分训练、验证和测试集时,必须以 `system` 为单位;同一个 protein–ligand pair 的所有 pose 不能跨 split,否则会发生 pose-level leakage。
|
| 69 |
+
- 该发布不包含原始 HiQBind PDB/SDF、原始 docking 输出或模型权重。它足以直接加载和训练 compact 图,但不能仅凭这些 shard 重建 docking 流程。
|
| 70 |
+
- 本批 5K 是一个 operational docking cohort,并非 PLINDER split。若用于 PLINDER 研究,请将它作为流程验证数据,另按 PLINDER 的规则建立最终划分。
|
| 71 |
+
- AutoDock Vina 和 DiffDock 的覆盖数低于初始 5,000,是因为少量个例未能产生可用 pose;这些 pair 没有被伪造或补齐。
|
code/compact_v1/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# compact_v1 construction and reader code
|
| 2 |
+
|
| 3 |
+
This directory contains the minimum code needed to read the released compact shards and to rebuild the same format from PDB docking poses.
|
| 4 |
+
|
| 5 |
+
## Read an existing release
|
| 6 |
+
|
| 7 |
+
Only `compact_graph_dataset.py` is required for normal training. It provides `CompactGraphDataset`, which opens tensor-only shard files lazily with `torch.load(..., mmap=True)` and reconstructs standard PyTorch Geometric `Data` objects.
|
| 8 |
+
|
| 9 |
+
## Build compact shards from PDB poses
|
| 10 |
+
|
| 11 |
+
Keep these three files in the same directory because the builder imports the other two by filename:
|
| 12 |
+
|
| 13 |
+
- `build_compact_v1_direct.py`
|
| 14 |
+
- `build_graph_unified_enhanced.py`
|
| 15 |
+
- `convert_to_compact_v1.py`
|
| 16 |
+
|
| 17 |
+
The direct builder expects a flat directory with one subdirectory per system containing `protein.pdb`, `ligand.pdb`, and predicted pose `.pdb` files. `materialize_hiqbind_gnncp.py` converts Docking Base common outputs to that layout through hard links.
|
| 18 |
+
|
| 19 |
+
`build_compact_v1_direct.sbatch` is an example Slurm wrapper only. Review and adapt account, partition, Python environment, paths, CPU count, and memory for your own cluster before use.
|
| 20 |
+
|
| 21 |
+
Run the bundled unit tests after changing the format code:
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
python -m unittest -v test_compact_graph_dataset.py test_build_compact_v1_direct.py
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
See `../../docs/DATASET_USAGE_ZH.md` for the Chinese user guide.
|
| 28 |
+
|
code/compact_v1/build_compact_v1_direct.py
ADDED
|
@@ -0,0 +1,1700 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Build GNNCP compact_v1 shards directly from docking pose files.
|
| 4 |
+
|
| 5 |
+
Unlike ``build_graph_unified_enhanced.py``, this program never accumulates a
|
| 6 |
+
dataset-wide ``list[Data]`` and never writes a monolithic legacy ``.pt`` file.
|
| 7 |
+
It discovers poses deterministically; each worker builds one source system and
|
| 8 |
+
immediately converts it to compact records. A single parent commits completed
|
| 9 |
+
systems in source order, then packs bounded collections of records into
|
| 10 |
+
tensor-only shards.
|
| 11 |
+
|
| 12 |
+
The output directory is published atomically only after every selected system
|
| 13 |
+
has been processed. Before publication, progress lives in a stable hidden
|
| 14 |
+
``.<name>.building`` directory. ``--resume`` reuses completed system
|
| 15 |
+
checkpoints and any pose graphs already built for the current system.
|
| 16 |
+
|
| 17 |
+
Examples
|
| 18 |
+
--------
|
| 19 |
+
Single-system Slurm smoke test::
|
| 20 |
+
|
| 21 |
+
python build_compact_v1_direct.py \
|
| 22 |
+
--data-dir /path/to/docking_results \
|
| 23 |
+
--output-dir /path/to/compact_smoke \
|
| 24 |
+
--method protenix \
|
| 25 |
+
--system-id tnks2_lig_20 \
|
| 26 |
+
--max-poses-per-system 2
|
| 27 |
+
|
| 28 |
+
Full resumable build::
|
| 29 |
+
|
| 30 |
+
python build_compact_v1_direct.py \
|
| 31 |
+
--data-dir /path/to/docking_results \
|
| 32 |
+
--output-dir /path/to/compact_protenix \
|
| 33 |
+
--method protenix \
|
| 34 |
+
--num-workers 4 \
|
| 35 |
+
--resume
|
| 36 |
+
|
| 37 |
+
Memory-bounded high-CPU build::
|
| 38 |
+
|
| 39 |
+
python build_compact_v1_direct.py \
|
| 40 |
+
--data-dir /path/to/docking_results \
|
| 41 |
+
--output-dir /path/to/compact_protenix \
|
| 42 |
+
--method protenix \
|
| 43 |
+
--system-workers 28 \
|
| 44 |
+
--num-workers 1 \
|
| 45 |
+
--memory-budget-gib 150 \
|
| 46 |
+
--resume
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
from __future__ import annotations
|
| 50 |
+
|
| 51 |
+
import argparse
|
| 52 |
+
import concurrent.futures
|
| 53 |
+
import fcntl
|
| 54 |
+
import gc
|
| 55 |
+
import hashlib
|
| 56 |
+
import json
|
| 57 |
+
import math
|
| 58 |
+
import multiprocessing
|
| 59 |
+
import os
|
| 60 |
+
import re
|
| 61 |
+
import shutil
|
| 62 |
+
import sys
|
| 63 |
+
import time
|
| 64 |
+
import traceback
|
| 65 |
+
from collections import Counter, OrderedDict
|
| 66 |
+
from contextlib import contextmanager
|
| 67 |
+
from dataclasses import dataclass, replace
|
| 68 |
+
from datetime import datetime, timezone
|
| 69 |
+
from pathlib import Path
|
| 70 |
+
from typing import Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Sequence
|
| 71 |
+
|
| 72 |
+
import torch
|
| 73 |
+
|
| 74 |
+
from build_graph_unified_enhanced import build_graph_enhanced, find_docking_poses
|
| 75 |
+
from convert_to_compact_v1 import (
|
| 76 |
+
DYNAMIC_COLUMNS,
|
| 77 |
+
FORMAT_NAME,
|
| 78 |
+
SCHEMA_VERSION,
|
| 79 |
+
STATIC_COLUMNS,
|
| 80 |
+
build_system_record,
|
| 81 |
+
graph_content_hashes,
|
| 82 |
+
pack_shard,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
DOCKING_METHODS = ("protenix", "diffdock", "autodock_vina", "medusagraph")
|
| 87 |
+
PROGRESS_VERSION = 1
|
| 88 |
+
READY_CHECKPOINT_VERSION = 1
|
| 89 |
+
|
| 90 |
+
# ``build_graph_enhanced`` deliberately computes several dense SciPy distance
|
| 91 |
+
# matrices. A single float64 N-by-N matrix occupies 8 * N**2 bytes; the
|
| 92 |
+
# estimate below reserves room for roughly eight such matrices plus a fixed
|
| 93 |
+
# parser/tensor overhead. It is intentionally an admission-control estimate,
|
| 94 |
+
# not a statement about the serialized compact-record size.
|
| 95 |
+
_WORKER_FIXED_MEMORY_MIB = 2048
|
| 96 |
+
_WORKER_DENSE_MEMORY_MULTIPLIER = 8
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@dataclass(frozen=True)
|
| 100 |
+
class PoseSpec:
|
| 101 |
+
"""One discovered pose and its stable pre-filter discovery index."""
|
| 102 |
+
|
| 103 |
+
source_graph_index: int
|
| 104 |
+
system_id: str
|
| 105 |
+
protein: Path
|
| 106 |
+
ligand_native: Path
|
| 107 |
+
ligand_pred: Path
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@dataclass(frozen=True)
|
| 111 |
+
class SystemSpec:
|
| 112 |
+
"""All selected poses belonging to one source system."""
|
| 113 |
+
|
| 114 |
+
ordinal: int
|
| 115 |
+
system_id: str
|
| 116 |
+
protein: Path
|
| 117 |
+
ligand_native: Path
|
| 118 |
+
poses: tuple[PoseSpec, ...]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@dataclass(frozen=True)
|
| 122 |
+
class BuildConfig:
|
| 123 |
+
data_dir: Path
|
| 124 |
+
output_dir: Path
|
| 125 |
+
method: str
|
| 126 |
+
cutoff: float = 6.0
|
| 127 |
+
target_shard_mib: int = 512
|
| 128 |
+
num_workers: int = 1
|
| 129 |
+
system_workers: int = 1
|
| 130 |
+
memory_budget_gib: float | None = None
|
| 131 |
+
strict: bool = True
|
| 132 |
+
resume: bool = False
|
| 133 |
+
on_error: str = "abort"
|
| 134 |
+
max_systems: int | None = None
|
| 135 |
+
max_poses_per_system: int | None = None
|
| 136 |
+
include_systems: tuple[str, ...] = ()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
GraphBuilder = Callable[..., Any]
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _natural_key(value: str) -> tuple[Any, ...]:
|
| 143 |
+
"""Natural, case-insensitive ordering (pose2 before pose10)."""
|
| 144 |
+
return tuple(
|
| 145 |
+
int(part) if part.isdigit() else part.casefold()
|
| 146 |
+
for part in re.split(r"(\d+)", value)
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _atomic_json(path: Path, payload: Mapping[str, Any]) -> None:
|
| 151 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
temporary = path.with_name(path.name + ".tmp")
|
| 153 |
+
with temporary.open("w", encoding="utf-8") as handle:
|
| 154 |
+
json.dump(payload, handle, indent=2, ensure_ascii=False)
|
| 155 |
+
handle.write("\n")
|
| 156 |
+
handle.flush()
|
| 157 |
+
os.fsync(handle.fileno())
|
| 158 |
+
os.replace(temporary, path)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _atomic_torch_save(payload: Any, path: Path) -> None:
|
| 162 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 163 |
+
temporary = path.with_name(path.name + ".tmp")
|
| 164 |
+
torch.save(payload, temporary)
|
| 165 |
+
os.replace(temporary, path)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@contextmanager
|
| 169 |
+
def _exclusive_build_lock(output_dir: Path):
|
| 170 |
+
"""Hold a non-blocking advisory lock for the complete build/publication.
|
| 171 |
+
|
| 172 |
+
The lock is a stable sidecar next to the output/staging directories rather
|
| 173 |
+
than a file inside staging. Consequently, two ``--resume`` jobs cannot
|
| 174 |
+
both enter the same staging directory. The zero-byte-ish sidecar is kept
|
| 175 |
+
after exit so every future opener locks the same inode; a crashed process
|
| 176 |
+
automatically releases its kernel lock.
|
| 177 |
+
"""
|
| 178 |
+
output_dir.parent.mkdir(parents=True, exist_ok=True)
|
| 179 |
+
lock_path = output_dir.with_name(f".{output_dir.name}.build.lock")
|
| 180 |
+
handle = lock_path.open("a+", encoding="utf-8")
|
| 181 |
+
try:
|
| 182 |
+
try:
|
| 183 |
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 184 |
+
except BlockingIOError as exc:
|
| 185 |
+
raise RuntimeError(
|
| 186 |
+
f"another direct compact build is already using {output_dir}; "
|
| 187 |
+
f"lock: {lock_path}"
|
| 188 |
+
) from exc
|
| 189 |
+
handle.seek(0)
|
| 190 |
+
handle.truncate()
|
| 191 |
+
handle.write(
|
| 192 |
+
json.dumps(
|
| 193 |
+
{
|
| 194 |
+
"pid": os.getpid(),
|
| 195 |
+
"slurm_job_id": os.environ.get("SLURM_JOB_ID"),
|
| 196 |
+
"output_dir": str(output_dir),
|
| 197 |
+
"acquired_utc": datetime.now(timezone.utc).isoformat(),
|
| 198 |
+
}
|
| 199 |
+
)
|
| 200 |
+
+ "\n"
|
| 201 |
+
)
|
| 202 |
+
handle.flush()
|
| 203 |
+
os.fsync(handle.fileno())
|
| 204 |
+
yield lock_path
|
| 205 |
+
finally:
|
| 206 |
+
try:
|
| 207 |
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
| 208 |
+
finally:
|
| 209 |
+
handle.close()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _relative_or_absolute(path: Path, root: Path) -> str:
|
| 213 |
+
try:
|
| 214 |
+
return str(path.relative_to(root))
|
| 215 |
+
except ValueError:
|
| 216 |
+
return str(path)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def parse_args(argv: Sequence[str] | None = None) -> BuildConfig:
|
| 220 |
+
parser = argparse.ArgumentParser(
|
| 221 |
+
description=(
|
| 222 |
+
"Build enhanced GNNCP graphs one system at a time and write "
|
| 223 |
+
"compact_v1 shards directly."
|
| 224 |
+
)
|
| 225 |
+
)
|
| 226 |
+
parser.add_argument("--data-dir", required=True, type=Path)
|
| 227 |
+
parser.add_argument("--output-dir", required=True, type=Path)
|
| 228 |
+
parser.add_argument("--method", required=True, choices=DOCKING_METHODS)
|
| 229 |
+
parser.add_argument("--cutoff", type=float, default=6.0)
|
| 230 |
+
parser.add_argument("--target-shard-mib", type=int, default=512)
|
| 231 |
+
parser.add_argument(
|
| 232 |
+
"--num-workers",
|
| 233 |
+
type=int,
|
| 234 |
+
default=1,
|
| 235 |
+
help=(
|
| 236 |
+
"Pose builders within one system. This must be 1 when "
|
| 237 |
+
"--system-workers is greater than 1, so graph builders are never "
|
| 238 |
+
"nested."
|
| 239 |
+
),
|
| 240 |
+
)
|
| 241 |
+
parser.add_argument(
|
| 242 |
+
"--system-workers",
|
| 243 |
+
type=int,
|
| 244 |
+
default=1,
|
| 245 |
+
help=(
|
| 246 |
+
"Independent source systems to build concurrently. The default 1 "
|
| 247 |
+
"keeps the original sequential-system implementation."
|
| 248 |
+
),
|
| 249 |
+
)
|
| 250 |
+
parser.add_argument(
|
| 251 |
+
"--memory-budget-gib",
|
| 252 |
+
type=float,
|
| 253 |
+
default=None,
|
| 254 |
+
help=(
|
| 255 |
+
"Usable aggregate memory budget for --system-workers > 1. "
|
| 256 |
+
"Workers are admitted by a conservative protein-size O(N^2) "
|
| 257 |
+
"estimate; reserve node/parent memory outside this value."
|
| 258 |
+
),
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument(
|
| 261 |
+
"--resume",
|
| 262 |
+
action="store_true",
|
| 263 |
+
help="Resume the stable hidden build directory after interruption.",
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"--on-error",
|
| 267 |
+
choices=("abort", "skip-system"),
|
| 268 |
+
default="abort",
|
| 269 |
+
help="Never drops individual poses: skip-system drops the whole source system.",
|
| 270 |
+
)
|
| 271 |
+
parser.add_argument(
|
| 272 |
+
"--skip-strict-validation",
|
| 273 |
+
action="store_true",
|
| 274 |
+
help="Skip expensive redundant-field and edge-symmetry validation.",
|
| 275 |
+
)
|
| 276 |
+
parser.add_argument("--max-systems", type=int, default=None)
|
| 277 |
+
parser.add_argument("--max-poses-per-system", type=int, default=None)
|
| 278 |
+
parser.add_argument(
|
| 279 |
+
"--system-id",
|
| 280 |
+
"--include-system",
|
| 281 |
+
dest="include_systems",
|
| 282 |
+
action="append",
|
| 283 |
+
default=[],
|
| 284 |
+
metavar="ID",
|
| 285 |
+
help="Only build this source system ID; repeat to select multiple systems.",
|
| 286 |
+
)
|
| 287 |
+
args = parser.parse_args(argv)
|
| 288 |
+
return BuildConfig(
|
| 289 |
+
data_dir=args.data_dir.expanduser().resolve(),
|
| 290 |
+
output_dir=args.output_dir.expanduser().resolve(),
|
| 291 |
+
method=args.method,
|
| 292 |
+
cutoff=args.cutoff,
|
| 293 |
+
target_shard_mib=args.target_shard_mib,
|
| 294 |
+
num_workers=args.num_workers,
|
| 295 |
+
system_workers=args.system_workers,
|
| 296 |
+
memory_budget_gib=args.memory_budget_gib,
|
| 297 |
+
strict=not args.skip_strict_validation,
|
| 298 |
+
resume=args.resume,
|
| 299 |
+
on_error=args.on_error,
|
| 300 |
+
max_systems=args.max_systems,
|
| 301 |
+
max_poses_per_system=args.max_poses_per_system,
|
| 302 |
+
include_systems=tuple(args.include_systems),
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _validate_config(config: BuildConfig) -> None:
|
| 307 |
+
if not config.data_dir.is_dir():
|
| 308 |
+
raise FileNotFoundError(f"data directory not found: {config.data_dir}")
|
| 309 |
+
if config.method not in DOCKING_METHODS:
|
| 310 |
+
raise ValueError(f"unsupported docking method: {config.method}")
|
| 311 |
+
if config.cutoff <= 0:
|
| 312 |
+
raise ValueError("--cutoff must be positive")
|
| 313 |
+
if config.target_shard_mib <= 0:
|
| 314 |
+
raise ValueError("--target-shard-mib must be positive")
|
| 315 |
+
if config.num_workers <= 0:
|
| 316 |
+
raise ValueError("--num-workers must be positive")
|
| 317 |
+
if config.system_workers <= 0:
|
| 318 |
+
raise ValueError("--system-workers must be positive")
|
| 319 |
+
if config.system_workers > 1 and config.num_workers != 1:
|
| 320 |
+
raise ValueError(
|
| 321 |
+
"--system-workers > 1 requires --num-workers=1; nested "
|
| 322 |
+
"system/pose process pools are intentionally forbidden"
|
| 323 |
+
)
|
| 324 |
+
if config.memory_budget_gib is not None and config.memory_budget_gib <= 0:
|
| 325 |
+
raise ValueError("--memory-budget-gib must be positive")
|
| 326 |
+
if config.system_workers > 1 and config.memory_budget_gib is None:
|
| 327 |
+
raise ValueError(
|
| 328 |
+
"--system-workers > 1 requires --memory-budget-gib so concurrent "
|
| 329 |
+
"dense graph builders remain memory bounded"
|
| 330 |
+
)
|
| 331 |
+
if config.max_systems is not None and config.max_systems <= 0:
|
| 332 |
+
raise ValueError("--max-systems must be positive")
|
| 333 |
+
if (
|
| 334 |
+
config.max_poses_per_system is not None
|
| 335 |
+
and config.max_poses_per_system <= 0
|
| 336 |
+
):
|
| 337 |
+
raise ValueError("--max-poses-per-system must be positive")
|
| 338 |
+
if config.output_dir == config.data_dir:
|
| 339 |
+
raise ValueError("output directory must differ from the docking data directory")
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def discover_systems(config: BuildConfig) -> List[SystemSpec]:
|
| 343 |
+
"""Discover, filter, and deterministically order source systems and poses."""
|
| 344 |
+
raw_poses = find_docking_poses(str(config.data_dir), config.method)
|
| 345 |
+
grouped: MutableMapping[str, List[Mapping[str, str]]] = OrderedDict()
|
| 346 |
+
for pose in sorted(
|
| 347 |
+
raw_poses,
|
| 348 |
+
key=lambda item: (
|
| 349 |
+
_natural_key(str(item["pdb_id"])),
|
| 350 |
+
_natural_key(str(Path(item["ligand_pred"]))),
|
| 351 |
+
),
|
| 352 |
+
):
|
| 353 |
+
grouped.setdefault(str(pose["pdb_id"]), []).append(pose)
|
| 354 |
+
|
| 355 |
+
requested = set(config.include_systems)
|
| 356 |
+
if requested:
|
| 357 |
+
missing = requested.difference(grouped)
|
| 358 |
+
if missing:
|
| 359 |
+
available = ", ".join(list(grouped)[:10])
|
| 360 |
+
raise ValueError(
|
| 361 |
+
f"requested system IDs were not discovered: {sorted(missing)}; "
|
| 362 |
+
f"first available IDs: {available}"
|
| 363 |
+
)
|
| 364 |
+
grouped = OrderedDict((key, grouped[key]) for key in grouped if key in requested)
|
| 365 |
+
|
| 366 |
+
selected_items = list(grouped.items())
|
| 367 |
+
if config.max_systems is not None:
|
| 368 |
+
selected_items = selected_items[: config.max_systems]
|
| 369 |
+
if not selected_items:
|
| 370 |
+
raise ValueError("no docking systems matched the selection")
|
| 371 |
+
|
| 372 |
+
systems: List[SystemSpec] = []
|
| 373 |
+
source_graph_index = 0
|
| 374 |
+
for ordinal, (system_id, raw_system_poses) in enumerate(selected_items):
|
| 375 |
+
unique_by_path: Dict[Path, Mapping[str, str]] = {}
|
| 376 |
+
for pose in raw_system_poses:
|
| 377 |
+
unique_by_path[Path(pose["ligand_pred"]).resolve()] = pose
|
| 378 |
+
ordered = [
|
| 379 |
+
unique_by_path[path]
|
| 380 |
+
for path in sorted(unique_by_path, key=lambda value: _natural_key(str(value)))
|
| 381 |
+
]
|
| 382 |
+
if config.max_poses_per_system is not None:
|
| 383 |
+
ordered = ordered[: config.max_poses_per_system]
|
| 384 |
+
if not ordered:
|
| 385 |
+
continue
|
| 386 |
+
|
| 387 |
+
proteins = {Path(pose["protein"]).resolve() for pose in ordered}
|
| 388 |
+
natives = {Path(pose["ligand_native"]).resolve() for pose in ordered}
|
| 389 |
+
if len(proteins) != 1 or len(natives) != 1:
|
| 390 |
+
raise ValueError(
|
| 391 |
+
f"{system_id}: discovered multiple protein/native files in one system"
|
| 392 |
+
)
|
| 393 |
+
protein = next(iter(proteins))
|
| 394 |
+
ligand_native = next(iter(natives))
|
| 395 |
+
pose_specs: List[PoseSpec] = []
|
| 396 |
+
for pose in ordered:
|
| 397 |
+
ligand_pred = Path(pose["ligand_pred"]).resolve()
|
| 398 |
+
if ligand_pred.suffix.lower() != ".pdb":
|
| 399 |
+
raise ValueError(
|
| 400 |
+
f"{system_id}: unsupported pose format {ligand_pred.suffix!r}: "
|
| 401 |
+
f"{ligand_pred}. build_graph_enhanced currently requires PDB poses."
|
| 402 |
+
)
|
| 403 |
+
pose_specs.append(
|
| 404 |
+
PoseSpec(
|
| 405 |
+
source_graph_index=source_graph_index,
|
| 406 |
+
system_id=system_id,
|
| 407 |
+
protein=protein,
|
| 408 |
+
ligand_native=ligand_native,
|
| 409 |
+
ligand_pred=ligand_pred,
|
| 410 |
+
)
|
| 411 |
+
)
|
| 412 |
+
source_graph_index += 1
|
| 413 |
+
systems.append(
|
| 414 |
+
SystemSpec(
|
| 415 |
+
ordinal=ordinal,
|
| 416 |
+
system_id=system_id,
|
| 417 |
+
protein=protein,
|
| 418 |
+
ligand_native=ligand_native,
|
| 419 |
+
poses=tuple(pose_specs),
|
| 420 |
+
)
|
| 421 |
+
)
|
| 422 |
+
if not systems:
|
| 423 |
+
raise ValueError("no PDB poses remained after filtering")
|
| 424 |
+
return systems
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def _discovery_fingerprint(config: BuildConfig, systems: Sequence[SystemSpec]) -> str:
|
| 428 |
+
"""Hash data/format inputs while allowing safe scheduler changes on resume.
|
| 429 |
+
|
| 430 |
+
``num_workers``, ``system_workers`` and ``memory_budget_gib`` deliberately
|
| 431 |
+
do not participate: they change only execution scheduling, not discovery,
|
| 432 |
+
tensor content, ordering, or shard boundaries. This is what permits an
|
| 433 |
+
existing sequential staging directory to resume with the adaptive
|
| 434 |
+
cross-system scheduler.
|
| 435 |
+
"""
|
| 436 |
+
digest = hashlib.sha256()
|
| 437 |
+
config_payload = {
|
| 438 |
+
"format": FORMAT_NAME,
|
| 439 |
+
"schema_version": SCHEMA_VERSION,
|
| 440 |
+
"data_dir": str(config.data_dir),
|
| 441 |
+
"method": config.method,
|
| 442 |
+
"cutoff": config.cutoff,
|
| 443 |
+
"target_shard_mib": config.target_shard_mib,
|
| 444 |
+
"strict": config.strict,
|
| 445 |
+
"on_error": config.on_error,
|
| 446 |
+
"max_systems": config.max_systems,
|
| 447 |
+
"max_poses_per_system": config.max_poses_per_system,
|
| 448 |
+
"include_systems": sorted(config.include_systems),
|
| 449 |
+
}
|
| 450 |
+
digest.update(json.dumps(config_payload, sort_keys=True).encode("utf-8"))
|
| 451 |
+
unique_paths = {
|
| 452 |
+
path
|
| 453 |
+
for system in systems
|
| 454 |
+
for path in (
|
| 455 |
+
system.protein,
|
| 456 |
+
system.ligand_native,
|
| 457 |
+
*(pose.ligand_pred for pose in system.poses),
|
| 458 |
+
)
|
| 459 |
+
}
|
| 460 |
+
for path in sorted(unique_paths, key=str):
|
| 461 |
+
stat = path.stat()
|
| 462 |
+
digest.update(str(path).encode("utf-8"))
|
| 463 |
+
digest.update(stat.st_size.to_bytes(8, "little", signed=False))
|
| 464 |
+
digest.update(stat.st_mtime_ns.to_bytes(8, "little", signed=False))
|
| 465 |
+
return digest.hexdigest()
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _default_progress(fingerprint: str) -> Dict[str, Any]:
|
| 469 |
+
return {
|
| 470 |
+
"progress_version": PROGRESS_VERSION,
|
| 471 |
+
"fingerprint": fingerprint,
|
| 472 |
+
"next_system_index": 0,
|
| 473 |
+
"next_shard_index": 0,
|
| 474 |
+
"pending": [],
|
| 475 |
+
"successful_source_systems": 0,
|
| 476 |
+
"successful_graphs": 0,
|
| 477 |
+
"compact_storage_groups": 0,
|
| 478 |
+
"skipped_source_systems": 0,
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def _pose_graph_path(work_dir: Path, local_pose_index: int) -> Path:
|
| 483 |
+
return work_dir / f"pose_{local_pose_index:04d}.pt"
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _count_nonhydrogen_pdb_atoms(path: Path) -> int:
|
| 487 |
+
"""Return a cheap, conservative node-count proxy without MDAnalysis.
|
| 488 |
+
|
| 489 |
+
The graph builder selects ``not name H*``. PDB columns are sufficient for
|
| 490 |
+
scheduling: over-counting an unusual hydrogen name only makes admission
|
| 491 |
+
more conservative, whereas under-counting a large protein could cause an
|
| 492 |
+
avoidable OOM.
|
| 493 |
+
"""
|
| 494 |
+
count = 0
|
| 495 |
+
with path.open("r", encoding="utf-8", errors="replace") as handle:
|
| 496 |
+
for line in handle:
|
| 497 |
+
if not line.startswith(("ATOM ", "HETATM")):
|
| 498 |
+
continue
|
| 499 |
+
atom_name = line[12:16].strip().upper()
|
| 500 |
+
element = line[76:78].strip().upper()
|
| 501 |
+
if atom_name.startswith("H") or element == "H":
|
| 502 |
+
continue
|
| 503 |
+
count += 1
|
| 504 |
+
return count
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def estimate_system_memory_mib(system: SystemSpec) -> int:
|
| 508 |
+
"""Estimate one system worker's peak working set for admission control.
|
| 509 |
+
|
| 510 |
+
This follows the actual graph-builder scaling, which is dominated by dense
|
| 511 |
+
float64 ``cdist`` matrices over protein plus predicted-ligand atoms. The
|
| 512 |
+
native ligand is parsed too, so use the larger of the native and predicted
|
| 513 |
+
ligand atom counts as a small conservative adjustment. The estimate is
|
| 514 |
+
deliberately independent of pose count: cross-system mode builds poses
|
| 515 |
+
sequentially in each worker and never nests a pose process pool.
|
| 516 |
+
"""
|
| 517 |
+
protein_atoms = _count_nonhydrogen_pdb_atoms(system.protein)
|
| 518 |
+
ligand_atoms = max(
|
| 519 |
+
_count_nonhydrogen_pdb_atoms(system.ligand_native),
|
| 520 |
+
_count_nonhydrogen_pdb_atoms(system.poses[0].ligand_pred),
|
| 521 |
+
)
|
| 522 |
+
n_nodes = max(1, protein_atoms + ligand_atoms)
|
| 523 |
+
one_dense_matrix_mib = (8.0 * n_nodes * n_nodes) / (1024.0 * 1024.0)
|
| 524 |
+
estimate = (
|
| 525 |
+
_WORKER_FIXED_MEMORY_MIB
|
| 526 |
+
+ _WORKER_DENSE_MEMORY_MULTIPLIER * one_dense_matrix_mib
|
| 527 |
+
)
|
| 528 |
+
return max(1, int(math.ceil(estimate)))
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def _ready_checkpoint_path(stage_dir: Path, system_index: int) -> Path:
|
| 532 |
+
return (
|
| 533 |
+
stage_dir
|
| 534 |
+
/ ".build_state"
|
| 535 |
+
/ "ready"
|
| 536 |
+
/ f"system_{system_index:08d}.pt"
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def _ready_error_path(stage_dir: Path, system_index: int) -> Path:
|
| 541 |
+
return (
|
| 542 |
+
stage_dir
|
| 543 |
+
/ ".build_state"
|
| 544 |
+
/ "ready_errors"
|
| 545 |
+
/ f"system_{system_index:08d}.json"
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def _validate_ready_records(
|
| 550 |
+
payload: Any,
|
| 551 |
+
system_index: int,
|
| 552 |
+
system: SystemSpec,
|
| 553 |
+
) -> List[Dict[str, Any]]:
|
| 554 |
+
"""Validate a worker-produced durable record before the single writer uses it."""
|
| 555 |
+
if not isinstance(payload, Mapping):
|
| 556 |
+
raise ValueError("ready payload is not a mapping")
|
| 557 |
+
if payload.get("ready_checkpoint_version") != READY_CHECKPOINT_VERSION:
|
| 558 |
+
raise ValueError("incompatible ready checkpoint version")
|
| 559 |
+
if int(payload.get("source_system_index", -1)) != system_index:
|
| 560 |
+
raise ValueError("ready checkpoint system index does not match its filename")
|
| 561 |
+
if str(payload.get("source_system_id", "")) != system.system_id:
|
| 562 |
+
raise ValueError("ready checkpoint system ID does not match discovery")
|
| 563 |
+
records = payload.get("records")
|
| 564 |
+
if not isinstance(records, list) or not records:
|
| 565 |
+
raise ValueError("ready checkpoint has no compact records")
|
| 566 |
+
|
| 567 |
+
expected_indices = sorted(pose.source_graph_index for pose in system.poses)
|
| 568 |
+
actual_indices: List[int] = []
|
| 569 |
+
for record in records:
|
| 570 |
+
if not isinstance(record, Mapping):
|
| 571 |
+
raise ValueError("ready checkpoint contains a non-mapping record")
|
| 572 |
+
if str(record.get("_source_system_id", "")) != system.system_id:
|
| 573 |
+
raise ValueError("ready checkpoint record has the wrong source system ID")
|
| 574 |
+
source_graph_index = record.get("source_graph_index")
|
| 575 |
+
if not isinstance(source_graph_index, torch.Tensor):
|
| 576 |
+
raise ValueError("ready checkpoint record lacks source_graph_index")
|
| 577 |
+
actual_indices.extend(int(value) for value in source_graph_index.tolist())
|
| 578 |
+
if sorted(actual_indices) != expected_indices:
|
| 579 |
+
raise ValueError("ready checkpoint pose indices do not match discovery")
|
| 580 |
+
return list(records)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _load_ready_records(
|
| 584 |
+
stage_dir: Path,
|
| 585 |
+
system_index: int,
|
| 586 |
+
system: SystemSpec,
|
| 587 |
+
*,
|
| 588 |
+
discard_invalid: bool = True,
|
| 589 |
+
) -> List[Dict[str, Any]] | None:
|
| 590 |
+
"""Load a valid ready record, deleting only corrupt/stale local scratch."""
|
| 591 |
+
path = _ready_checkpoint_path(stage_dir, system_index)
|
| 592 |
+
if not path.is_file():
|
| 593 |
+
return None
|
| 594 |
+
try:
|
| 595 |
+
payload = torch.load(path, map_location="cpu", weights_only=False)
|
| 596 |
+
return _validate_ready_records(payload, system_index, system)
|
| 597 |
+
except Exception as error:
|
| 598 |
+
if discard_invalid:
|
| 599 |
+
try:
|
| 600 |
+
path.unlink()
|
| 601 |
+
except FileNotFoundError:
|
| 602 |
+
pass
|
| 603 |
+
print(
|
| 604 |
+
f"[ready-rebuild] {system.system_id}: discarded invalid ready "
|
| 605 |
+
f"checkpoint ({type(error).__name__}: {error})",
|
| 606 |
+
file=sys.stderr,
|
| 607 |
+
flush=True,
|
| 608 |
+
)
|
| 609 |
+
return None
|
| 610 |
+
raise
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _load_ready_error(
|
| 614 |
+
stage_dir: Path,
|
| 615 |
+
system_index: int,
|
| 616 |
+
system: SystemSpec,
|
| 617 |
+
) -> Dict[str, Any] | None:
|
| 618 |
+
"""Load a durable skip-system outcome produced by a parallel worker."""
|
| 619 |
+
path = _ready_error_path(stage_dir, system_index)
|
| 620 |
+
if not path.is_file():
|
| 621 |
+
return None
|
| 622 |
+
try:
|
| 623 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 624 |
+
payload = json.load(handle)
|
| 625 |
+
if (
|
| 626 |
+
int(payload.get("system_index", -1)) != system_index
|
| 627 |
+
or str(payload.get("system_id", "")) != system.system_id
|
| 628 |
+
):
|
| 629 |
+
raise ValueError("ready error does not match discovered system")
|
| 630 |
+
return payload
|
| 631 |
+
except Exception as error:
|
| 632 |
+
try:
|
| 633 |
+
path.unlink()
|
| 634 |
+
except FileNotFoundError:
|
| 635 |
+
pass
|
| 636 |
+
print(
|
| 637 |
+
f"[ready-rebuild] {system.system_id}: discarded invalid ready error "
|
| 638 |
+
f"({type(error).__name__}: {error})",
|
| 639 |
+
file=sys.stderr,
|
| 640 |
+
flush=True,
|
| 641 |
+
)
|
| 642 |
+
return None
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def _build_pose_to_file(
|
| 646 |
+
pose_payload: Mapping[str, Any],
|
| 647 |
+
cutoff: float,
|
| 648 |
+
output_path: str,
|
| 649 |
+
) -> tuple[bool, str]:
|
| 650 |
+
"""Process-pool worker. Each result is committed by atomic rename."""
|
| 651 |
+
try:
|
| 652 |
+
graph = build_graph_enhanced(
|
| 653 |
+
protein_pdb=str(pose_payload["protein"]),
|
| 654 |
+
ligand_pred_pdb=str(pose_payload["ligand_pred"]),
|
| 655 |
+
ligand_native_pdb=str(pose_payload["ligand_native"]),
|
| 656 |
+
cutoff=cutoff,
|
| 657 |
+
use_enhanced_features=True,
|
| 658 |
+
)
|
| 659 |
+
_atomic_torch_save(graph, Path(output_path))
|
| 660 |
+
return True, output_path
|
| 661 |
+
except Exception:
|
| 662 |
+
return False, traceback.format_exc()
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def _validate_reusable_pose_file(path: Path) -> bool:
|
| 666 |
+
try:
|
| 667 |
+
graph = torch.load(path, map_location="cpu", weights_only=False)
|
| 668 |
+
valid = (
|
| 669 |
+
hasattr(graph, "x")
|
| 670 |
+
and isinstance(graph.x, torch.Tensor)
|
| 671 |
+
and graph.x.ndim == 2
|
| 672 |
+
and graph.x.shape[1] == 82
|
| 673 |
+
)
|
| 674 |
+
del graph
|
| 675 |
+
return bool(valid)
|
| 676 |
+
except Exception:
|
| 677 |
+
return False
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def build_pose_graphs(
|
| 681 |
+
system: SystemSpec,
|
| 682 |
+
work_dir: Path,
|
| 683 |
+
config: BuildConfig,
|
| 684 |
+
graph_builder: GraphBuilder = build_graph_enhanced,
|
| 685 |
+
) -> List[Any]:
|
| 686 |
+
"""Build/reuse every pose in one source system and return them in order."""
|
| 687 |
+
work_dir.mkdir(parents=True, exist_ok=True)
|
| 688 |
+
missing: List[tuple[int, PoseSpec, Path]] = []
|
| 689 |
+
for local_index, pose in enumerate(system.poses):
|
| 690 |
+
path = _pose_graph_path(work_dir, local_index)
|
| 691 |
+
if path.is_file() and _validate_reusable_pose_file(path):
|
| 692 |
+
continue
|
| 693 |
+
if path.exists():
|
| 694 |
+
path.unlink()
|
| 695 |
+
missing.append((local_index, pose, path))
|
| 696 |
+
|
| 697 |
+
if config.num_workers > 1 and graph_builder is not build_graph_enhanced:
|
| 698 |
+
raise ValueError("a custom graph_builder is only supported with num_workers=1")
|
| 699 |
+
|
| 700 |
+
errors: List[str] = []
|
| 701 |
+
if config.num_workers == 1:
|
| 702 |
+
for local_index, pose, path in missing:
|
| 703 |
+
try:
|
| 704 |
+
graph = graph_builder(
|
| 705 |
+
protein_pdb=str(pose.protein),
|
| 706 |
+
ligand_pred_pdb=str(pose.ligand_pred),
|
| 707 |
+
ligand_native_pdb=str(pose.ligand_native),
|
| 708 |
+
cutoff=config.cutoff,
|
| 709 |
+
use_enhanced_features=True,
|
| 710 |
+
)
|
| 711 |
+
_atomic_torch_save(graph, path)
|
| 712 |
+
del graph
|
| 713 |
+
except Exception:
|
| 714 |
+
errors.append(
|
| 715 |
+
f"pose {local_index} ({pose.ligand_pred}):\n"
|
| 716 |
+
f"{traceback.format_exc()}"
|
| 717 |
+
)
|
| 718 |
+
break
|
| 719 |
+
elif missing:
|
| 720 |
+
payloads = [
|
| 721 |
+
(
|
| 722 |
+
{
|
| 723 |
+
"protein": str(pose.protein),
|
| 724 |
+
"ligand_pred": str(pose.ligand_pred),
|
| 725 |
+
"ligand_native": str(pose.ligand_native),
|
| 726 |
+
},
|
| 727 |
+
config.cutoff,
|
| 728 |
+
str(path),
|
| 729 |
+
)
|
| 730 |
+
for _, pose, path in missing
|
| 731 |
+
]
|
| 732 |
+
with concurrent.futures.ProcessPoolExecutor(
|
| 733 |
+
max_workers=config.num_workers
|
| 734 |
+
) as executor:
|
| 735 |
+
futures = [executor.submit(_build_pose_to_file, *payload) for payload in payloads]
|
| 736 |
+
for (local_index, pose, _), future in zip(missing, futures):
|
| 737 |
+
ok, detail = future.result()
|
| 738 |
+
if not ok:
|
| 739 |
+
errors.append(
|
| 740 |
+
f"pose {local_index} ({pose.ligand_pred}):\n{detail}"
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
if errors:
|
| 744 |
+
raise RuntimeError(
|
| 745 |
+
f"{system.system_id}: {len(errors)} pose build(s) failed; "
|
| 746 |
+
"the source system was not partially committed.\n" + "\n".join(errors[:3])
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
graphs: List[Any] = []
|
| 750 |
+
for local_index in range(len(system.poses)):
|
| 751 |
+
path = _pose_graph_path(work_dir, local_index)
|
| 752 |
+
graphs.append(torch.load(path, map_location="cpu", weights_only=False))
|
| 753 |
+
return graphs
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def compact_system_records(
|
| 757 |
+
system: SystemSpec,
|
| 758 |
+
graphs: Sequence[Any],
|
| 759 |
+
strict: bool,
|
| 760 |
+
data_root: Path,
|
| 761 |
+
) -> List[Dict[str, Any]]:
|
| 762 |
+
"""Convert one source system, splitting only when exact static content differs."""
|
| 763 |
+
if len(graphs) != len(system.poses):
|
| 764 |
+
raise ValueError(
|
| 765 |
+
f"{system.system_id}: graph count {len(graphs)} != pose count {len(system.poses)}"
|
| 766 |
+
)
|
| 767 |
+
grouped: MutableMapping[str, List[int]] = OrderedDict()
|
| 768 |
+
native_hashes: Dict[str, str] = {}
|
| 769 |
+
for local_index, graph in enumerate(graphs):
|
| 770 |
+
native_hash, shared_hash = graph_content_hashes(graph)
|
| 771 |
+
grouped.setdefault(shared_hash, []).append(local_index)
|
| 772 |
+
previous = native_hashes.setdefault(shared_hash, native_hash)
|
| 773 |
+
if previous != native_hash:
|
| 774 |
+
raise RuntimeError("shared-content SHA-256 collision detected")
|
| 775 |
+
|
| 776 |
+
records: List[Dict[str, Any]] = []
|
| 777 |
+
multiple_groups = len(grouped) > 1
|
| 778 |
+
for shared_hash, local_indices in grouped.items():
|
| 779 |
+
storage_id = (
|
| 780 |
+
f"{system.system_id}__{shared_hash[:12]}"
|
| 781 |
+
if multiple_groups
|
| 782 |
+
else system.system_id
|
| 783 |
+
)
|
| 784 |
+
descriptor = {
|
| 785 |
+
"system_id": storage_id,
|
| 786 |
+
"source_label": system.system_id,
|
| 787 |
+
"source_label_counts": {system.system_id: len(local_indices)},
|
| 788 |
+
"native_hash": native_hashes[shared_hash],
|
| 789 |
+
"shared_hash": shared_hash,
|
| 790 |
+
"graph_indices": local_indices,
|
| 791 |
+
}
|
| 792 |
+
record = build_system_record(graphs, descriptor, strict=strict)
|
| 793 |
+
global_indices = [
|
| 794 |
+
system.poses[local_index].source_graph_index
|
| 795 |
+
for local_index in local_indices
|
| 796 |
+
]
|
| 797 |
+
record["source_graph_index"] = torch.tensor(global_indices, dtype=torch.int64)
|
| 798 |
+
record["_source_system_id"] = system.system_id
|
| 799 |
+
record["_source_pose_paths"] = [
|
| 800 |
+
_relative_or_absolute(
|
| 801 |
+
system.poses[local_index].ligand_pred,
|
| 802 |
+
data_root,
|
| 803 |
+
)
|
| 804 |
+
for local_index in local_indices
|
| 805 |
+
]
|
| 806 |
+
records.append(record)
|
| 807 |
+
return records
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
def _build_system_to_ready_checkpoint(
|
| 811 |
+
system_index: int,
|
| 812 |
+
system: SystemSpec,
|
| 813 |
+
stage_dir: str,
|
| 814 |
+
config: BuildConfig,
|
| 815 |
+
graph_builder: GraphBuilder = build_graph_enhanced,
|
| 816 |
+
) -> None:
|
| 817 |
+
"""Build one source system in a fresh process and atomically persist it.
|
| 818 |
+
|
| 819 |
+
This worker never writes global progress, shard files, or the final output.
|
| 820 |
+
Its only durable success artifact is a per-system ready checkpoint; the
|
| 821 |
+
parent is the sole process allowed to consume it in source order. A fresh
|
| 822 |
+
process per source system is intentional: dense NumPy/SciPy allocations
|
| 823 |
+
from a large protein are returned to the OS when that process exits.
|
| 824 |
+
"""
|
| 825 |
+
stage = Path(stage_dir)
|
| 826 |
+
ready_path = _ready_checkpoint_path(stage, system_index)
|
| 827 |
+
if _load_ready_records(stage, system_index, system) is not None:
|
| 828 |
+
return
|
| 829 |
+
|
| 830 |
+
work_dir = stage / ".build_state" / "work" / f"system_{system_index:08d}"
|
| 831 |
+
try:
|
| 832 |
+
# Cross-system scheduling is validated to require one pose worker. A
|
| 833 |
+
# replace makes that invariant explicit even if this helper is called
|
| 834 |
+
# directly in a future test.
|
| 835 |
+
worker_config = replace(config, num_workers=1, system_workers=1)
|
| 836 |
+
graphs = build_pose_graphs(
|
| 837 |
+
system,
|
| 838 |
+
work_dir,
|
| 839 |
+
worker_config,
|
| 840 |
+
graph_builder=graph_builder,
|
| 841 |
+
)
|
| 842 |
+
records = compact_system_records(
|
| 843 |
+
system,
|
| 844 |
+
graphs,
|
| 845 |
+
strict=config.strict,
|
| 846 |
+
data_root=config.data_dir,
|
| 847 |
+
)
|
| 848 |
+
payload = {
|
| 849 |
+
"ready_checkpoint_version": READY_CHECKPOINT_VERSION,
|
| 850 |
+
"source_system_index": system_index,
|
| 851 |
+
"source_system_id": system.system_id,
|
| 852 |
+
"records": records,
|
| 853 |
+
}
|
| 854 |
+
_atomic_torch_save(payload, ready_path)
|
| 855 |
+
del payload, records, graphs
|
| 856 |
+
if work_dir.is_dir():
|
| 857 |
+
shutil.rmtree(work_dir)
|
| 858 |
+
gc.collect()
|
| 859 |
+
except Exception as error:
|
| 860 |
+
if config.on_error != "skip-system":
|
| 861 |
+
raise
|
| 862 |
+
error_payload = {
|
| 863 |
+
"system_index": system_index,
|
| 864 |
+
"system_id": system.system_id,
|
| 865 |
+
"num_poses": len(system.poses),
|
| 866 |
+
"error_type": type(error).__name__,
|
| 867 |
+
"error": str(error),
|
| 868 |
+
"traceback": traceback.format_exc(),
|
| 869 |
+
}
|
| 870 |
+
_atomic_json(_ready_error_path(stage, system_index), error_payload)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def _parallel_system_worker_main(
|
| 874 |
+
system_index: int,
|
| 875 |
+
system: SystemSpec,
|
| 876 |
+
stage_dir: str,
|
| 877 |
+
config: BuildConfig,
|
| 878 |
+
graph_builder: GraphBuilder = build_graph_enhanced,
|
| 879 |
+
) -> None:
|
| 880 |
+
"""Top-level multiprocessing target; it must remain pickle/fork friendly."""
|
| 881 |
+
_build_system_to_ready_checkpoint(
|
| 882 |
+
system_index,
|
| 883 |
+
system,
|
| 884 |
+
stage_dir,
|
| 885 |
+
config,
|
| 886 |
+
graph_builder=graph_builder,
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def _record_manifest_entry(record: Mapping[str, Any]) -> Dict[str, Any]:
|
| 891 |
+
return {
|
| 892 |
+
"system_id": record["_system_id"],
|
| 893 |
+
"source_label": record["_source_label"],
|
| 894 |
+
"source_system_id": record["_source_system_id"],
|
| 895 |
+
"source_label_counts": record["_source_label_counts"],
|
| 896 |
+
"native_hash": record["_native_hash"],
|
| 897 |
+
"shared_hash": record["_shared_hash"],
|
| 898 |
+
"num_graphs": record["_n_poses"],
|
| 899 |
+
"num_nodes": record["_n_nodes"],
|
| 900 |
+
"num_protein_nodes": record["_n_protein"],
|
| 901 |
+
"num_ligand_nodes": record["_n_ligand"],
|
| 902 |
+
"source_graph_indices": record["source_graph_index"].tolist(),
|
| 903 |
+
"source_pose_paths": record["_source_pose_paths"],
|
| 904 |
+
}
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
def _flush_pending(
|
| 908 |
+
stage_dir: Path,
|
| 909 |
+
progress_path: Path,
|
| 910 |
+
progress: Dict[str, Any],
|
| 911 |
+
) -> None:
|
| 912 |
+
pending = list(progress["pending"])
|
| 913 |
+
if not pending:
|
| 914 |
+
return
|
| 915 |
+
records: List[Dict[str, Any]] = []
|
| 916 |
+
checkpoint_paths: List[Path] = []
|
| 917 |
+
for entry in pending:
|
| 918 |
+
checkpoint_path = stage_dir / entry["path"]
|
| 919 |
+
checkpoint_paths.append(checkpoint_path)
|
| 920 |
+
payload = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 921 |
+
if not isinstance(payload, list) or not payload:
|
| 922 |
+
raise ValueError(f"invalid system checkpoint: {checkpoint_path}")
|
| 923 |
+
records.extend(payload)
|
| 924 |
+
|
| 925 |
+
shard_index = int(progress["next_shard_index"])
|
| 926 |
+
relative_path = f"shards/shard_{shard_index:05d}.pt"
|
| 927 |
+
shard_path = stage_dir / relative_path
|
| 928 |
+
packed = pack_shard(records)
|
| 929 |
+
_atomic_torch_save(packed, shard_path)
|
| 930 |
+
size_bytes = shard_path.stat().st_size
|
| 931 |
+
metadata = {
|
| 932 |
+
"path": relative_path,
|
| 933 |
+
"num_graphs": int(packed["pose_system"].numel()),
|
| 934 |
+
"num_systems": len(records),
|
| 935 |
+
"num_source_systems": len(
|
| 936 |
+
{str(record["_source_system_id"]) for record in records}
|
| 937 |
+
),
|
| 938 |
+
"size_bytes": size_bytes,
|
| 939 |
+
"systems": [_record_manifest_entry(record) for record in records],
|
| 940 |
+
}
|
| 941 |
+
meta_path = (
|
| 942 |
+
stage_dir
|
| 943 |
+
/ ".build_state"
|
| 944 |
+
/ "shard_metadata"
|
| 945 |
+
/ f"shard_{shard_index:05d}.json"
|
| 946 |
+
)
|
| 947 |
+
_atomic_json(meta_path, metadata)
|
| 948 |
+
|
| 949 |
+
progress["pending"] = []
|
| 950 |
+
progress["next_shard_index"] = shard_index + 1
|
| 951 |
+
_atomic_json(progress_path, progress)
|
| 952 |
+
for checkpoint_path in checkpoint_paths:
|
| 953 |
+
if checkpoint_path.is_file():
|
| 954 |
+
checkpoint_path.unlink()
|
| 955 |
+
del packed, records
|
| 956 |
+
gc.collect()
|
| 957 |
+
print(
|
| 958 |
+
f"[shard] {relative_path}: {metadata['num_source_systems']} source systems, "
|
| 959 |
+
f"{metadata['num_systems']} storage groups, {metadata['num_graphs']} poses, "
|
| 960 |
+
f"{size_bytes / 2**20:.1f} MiB",
|
| 961 |
+
flush=True,
|
| 962 |
+
)
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def _commit_system_records(
|
| 966 |
+
stage_dir: Path,
|
| 967 |
+
progress_path: Path,
|
| 968 |
+
progress: Dict[str, Any],
|
| 969 |
+
system_index: int,
|
| 970 |
+
system: SystemSpec,
|
| 971 |
+
records: Sequence[Mapping[str, Any]],
|
| 972 |
+
target_bytes: int,
|
| 973 |
+
total_systems: int,
|
| 974 |
+
) -> None:
|
| 975 |
+
"""Commit one fully-built source system in deterministic source order.
|
| 976 |
+
|
| 977 |
+
Only the parent process calls this function. The ordering and state
|
| 978 |
+
transitions intentionally match the original sequential loop so existing
|
| 979 |
+
staging directories retain their resume and shard semantics.
|
| 980 |
+
"""
|
| 981 |
+
if int(progress["next_system_index"]) != system_index:
|
| 982 |
+
raise RuntimeError(
|
| 983 |
+
f"out-of-order system commit: expected {progress['next_system_index']}, "
|
| 984 |
+
f"got {system_index}"
|
| 985 |
+
)
|
| 986 |
+
if not records:
|
| 987 |
+
raise ValueError(f"{system.system_id}: refusing to commit no records")
|
| 988 |
+
record_bytes = sum(int(record["_tensor_bytes"]) for record in records)
|
| 989 |
+
pending_bytes = sum(int(item["tensor_bytes"]) for item in progress["pending"])
|
| 990 |
+
if progress["pending"] and pending_bytes + record_bytes > target_bytes:
|
| 991 |
+
_flush_pending(stage_dir, progress_path, progress)
|
| 992 |
+
|
| 993 |
+
checkpoint_rel = f".build_state/checkpoints/system_{system_index:08d}.pt"
|
| 994 |
+
checkpoint_path = stage_dir / checkpoint_rel
|
| 995 |
+
_atomic_torch_save(list(records), checkpoint_path)
|
| 996 |
+
progress["pending"].append(
|
| 997 |
+
{
|
| 998 |
+
"path": checkpoint_rel,
|
| 999 |
+
"tensor_bytes": record_bytes,
|
| 1000 |
+
"source_system_index": system_index,
|
| 1001 |
+
"source_system_id": system.system_id,
|
| 1002 |
+
}
|
| 1003 |
+
)
|
| 1004 |
+
progress["next_system_index"] = system_index + 1
|
| 1005 |
+
progress["successful_source_systems"] += 1
|
| 1006 |
+
progress["successful_graphs"] += len(system.poses)
|
| 1007 |
+
progress["compact_storage_groups"] += len(records)
|
| 1008 |
+
_atomic_json(progress_path, progress)
|
| 1009 |
+
print(
|
| 1010 |
+
f"[system] {system_index + 1}/{total_systems} "
|
| 1011 |
+
f"{system.system_id}: {len(system.poses)} poses, {len(records)} storage "
|
| 1012 |
+
f"group(s), {record_bytes / 2**20:.1f} MiB",
|
| 1013 |
+
flush=True,
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
def _flush_pending_if_full(
|
| 1018 |
+
stage_dir: Path,
|
| 1019 |
+
progress_path: Path,
|
| 1020 |
+
progress: Dict[str, Any],
|
| 1021 |
+
target_bytes: int,
|
| 1022 |
+
) -> None:
|
| 1023 |
+
pending_bytes = sum(int(item["tensor_bytes"]) for item in progress["pending"])
|
| 1024 |
+
if pending_bytes >= target_bytes:
|
| 1025 |
+
_flush_pending(stage_dir, progress_path, progress)
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
def _commit_skipped_system(
|
| 1029 |
+
stage_dir: Path,
|
| 1030 |
+
progress_path: Path,
|
| 1031 |
+
progress: Dict[str, Any],
|
| 1032 |
+
system_index: int,
|
| 1033 |
+
system: SystemSpec,
|
| 1034 |
+
error_payload: Mapping[str, Any],
|
| 1035 |
+
) -> None:
|
| 1036 |
+
"""Record a whole-system failure without disturbing deterministic order."""
|
| 1037 |
+
if int(progress["next_system_index"]) != system_index:
|
| 1038 |
+
raise RuntimeError(
|
| 1039 |
+
f"out-of-order skipped-system commit: expected "
|
| 1040 |
+
f"{progress['next_system_index']}, got {system_index}"
|
| 1041 |
+
)
|
| 1042 |
+
error_path = (
|
| 1043 |
+
stage_dir / ".build_state" / "errors" / f"system_{system_index:08d}.json"
|
| 1044 |
+
)
|
| 1045 |
+
_atomic_json(error_path, dict(error_payload))
|
| 1046 |
+
progress["next_system_index"] = system_index + 1
|
| 1047 |
+
progress["skipped_source_systems"] += 1
|
| 1048 |
+
_atomic_json(progress_path, progress)
|
| 1049 |
+
print(
|
| 1050 |
+
f"[skip-system] {system.system_id}: "
|
| 1051 |
+
f"{error_payload.get('error_type', 'Error')}: {error_payload.get('error', '')}",
|
| 1052 |
+
file=sys.stderr,
|
| 1053 |
+
flush=True,
|
| 1054 |
+
)
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def _load_shard_metadata(stage_dir: Path, count: int) -> List[Dict[str, Any]]:
|
| 1058 |
+
result = []
|
| 1059 |
+
for shard_index in range(count):
|
| 1060 |
+
path = (
|
| 1061 |
+
stage_dir
|
| 1062 |
+
/ ".build_state"
|
| 1063 |
+
/ "shard_metadata"
|
| 1064 |
+
/ f"shard_{shard_index:05d}.json"
|
| 1065 |
+
)
|
| 1066 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 1067 |
+
result.append(json.load(handle))
|
| 1068 |
+
return result
|
| 1069 |
+
|
| 1070 |
+
|
| 1071 |
+
def _load_errors(stage_dir: Path) -> List[Dict[str, Any]]:
|
| 1072 |
+
error_dir = stage_dir / ".build_state" / "errors"
|
| 1073 |
+
if not error_dir.is_dir():
|
| 1074 |
+
return []
|
| 1075 |
+
result = []
|
| 1076 |
+
for path in sorted(error_dir.glob("system_*.json")):
|
| 1077 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 1078 |
+
result.append(json.load(handle))
|
| 1079 |
+
return result
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
def _source_index_payload(
|
| 1083 |
+
config: BuildConfig,
|
| 1084 |
+
systems: Sequence[SystemSpec],
|
| 1085 |
+
successful_source_indices: set[int],
|
| 1086 |
+
errors: Sequence[Mapping[str, Any]],
|
| 1087 |
+
) -> Dict[str, Any]:
|
| 1088 |
+
error_by_id = {str(item["system_id"]): item for item in errors}
|
| 1089 |
+
source_systems = []
|
| 1090 |
+
for system in systems:
|
| 1091 |
+
successful = all(
|
| 1092 |
+
pose.source_graph_index in successful_source_indices
|
| 1093 |
+
for pose in system.poses
|
| 1094 |
+
)
|
| 1095 |
+
source_systems.append(
|
| 1096 |
+
{
|
| 1097 |
+
"system_id": system.system_id,
|
| 1098 |
+
"status": "complete" if successful else "skipped",
|
| 1099 |
+
"protein": _relative_or_absolute(system.protein, config.data_dir),
|
| 1100 |
+
"ligand_native": _relative_or_absolute(
|
| 1101 |
+
system.ligand_native, config.data_dir
|
| 1102 |
+
),
|
| 1103 |
+
"source_graph_indices": [
|
| 1104 |
+
pose.source_graph_index for pose in system.poses
|
| 1105 |
+
],
|
| 1106 |
+
"poses": [
|
| 1107 |
+
_relative_or_absolute(pose.ligand_pred, config.data_dir)
|
| 1108 |
+
for pose in system.poses
|
| 1109 |
+
],
|
| 1110 |
+
"error": error_by_id.get(system.system_id),
|
| 1111 |
+
}
|
| 1112 |
+
)
|
| 1113 |
+
return {
|
| 1114 |
+
"data_dir": str(config.data_dir),
|
| 1115 |
+
"method": config.method,
|
| 1116 |
+
"systems": source_systems,
|
| 1117 |
+
}
|
| 1118 |
+
|
| 1119 |
+
|
| 1120 |
+
def _finish_dataset(
|
| 1121 |
+
config: BuildConfig,
|
| 1122 |
+
stage_dir: Path,
|
| 1123 |
+
progress: Mapping[str, Any],
|
| 1124 |
+
systems: Sequence[SystemSpec],
|
| 1125 |
+
) -> Dict[str, Any]:
|
| 1126 |
+
shard_count = int(progress["next_shard_index"])
|
| 1127 |
+
if shard_count == 0:
|
| 1128 |
+
raise RuntimeError("no systems were built successfully; refusing empty dataset")
|
| 1129 |
+
shards = _load_shard_metadata(stage_dir, shard_count)
|
| 1130 |
+
|
| 1131 |
+
placements: List[tuple[int, int, int]] = []
|
| 1132 |
+
compact_bytes = 0
|
| 1133 |
+
for shard_index, shard_meta in enumerate(shards):
|
| 1134 |
+
shard_path = stage_dir / str(shard_meta["path"])
|
| 1135 |
+
shard = torch.load(
|
| 1136 |
+
shard_path,
|
| 1137 |
+
map_location="cpu",
|
| 1138 |
+
mmap=True,
|
| 1139 |
+
weights_only=True,
|
| 1140 |
+
)
|
| 1141 |
+
source_indices = shard["source_graph_index"].tolist()
|
| 1142 |
+
placements.extend(
|
| 1143 |
+
(int(source_index), shard_index, local_pose)
|
| 1144 |
+
for local_pose, source_index in enumerate(source_indices)
|
| 1145 |
+
)
|
| 1146 |
+
compact_bytes += int(shard_meta["size_bytes"])
|
| 1147 |
+
del shard
|
| 1148 |
+
placements.sort(key=lambda item: item[0])
|
| 1149 |
+
successful_source_indices = [item[0] for item in placements]
|
| 1150 |
+
if len(successful_source_indices) != len(set(successful_source_indices)):
|
| 1151 |
+
raise RuntimeError("duplicate source_graph_index detected across shards")
|
| 1152 |
+
graph_map = [[item[1], item[2]] for item in placements]
|
| 1153 |
+
|
| 1154 |
+
system_by_source_index = {
|
| 1155 |
+
pose.source_graph_index: system.system_id
|
| 1156 |
+
for system in systems
|
| 1157 |
+
for pose in system.poses
|
| 1158 |
+
}
|
| 1159 |
+
graph_to_system = [
|
| 1160 |
+
system_by_source_index[source_index]
|
| 1161 |
+
for source_index in successful_source_indices
|
| 1162 |
+
]
|
| 1163 |
+
counts = Counter(graph_to_system)
|
| 1164 |
+
system_index = {
|
| 1165 |
+
"graph_to_system": graph_to_system,
|
| 1166 |
+
"n_graphs": len(graph_to_system),
|
| 1167 |
+
"n_systems": len(counts),
|
| 1168 |
+
"systems": sorted(counts, key=_natural_key),
|
| 1169 |
+
"system_counts": dict(sorted(counts.items(), key=lambda item: _natural_key(item[0]))),
|
| 1170 |
+
"source_graph_indices": successful_source_indices,
|
| 1171 |
+
"note": (
|
| 1172 |
+
"Labels are original source system IDs. Exact-content storage-group "
|
| 1173 |
+
"splits do not change graph_to_system."
|
| 1174 |
+
),
|
| 1175 |
+
}
|
| 1176 |
+
_atomic_json(stage_dir / "system_index.json", system_index)
|
| 1177 |
+
|
| 1178 |
+
errors = _load_errors(stage_dir)
|
| 1179 |
+
source_index = _source_index_payload(
|
| 1180 |
+
config,
|
| 1181 |
+
systems,
|
| 1182 |
+
set(successful_source_indices),
|
| 1183 |
+
errors,
|
| 1184 |
+
)
|
| 1185 |
+
_atomic_json(stage_dir / "source_index.json", source_index)
|
| 1186 |
+
|
| 1187 |
+
compact_systems = sum(int(shard["num_systems"]) for shard in shards)
|
| 1188 |
+
manifest: Dict[str, Any] = {
|
| 1189 |
+
"format": FORMAT_NAME,
|
| 1190 |
+
"schema_version": SCHEMA_VERSION,
|
| 1191 |
+
"status": "complete",
|
| 1192 |
+
"created_utc": datetime.now(timezone.utc).isoformat(),
|
| 1193 |
+
"method": config.method,
|
| 1194 |
+
"cutoff": config.cutoff,
|
| 1195 |
+
"source": {
|
| 1196 |
+
"data_dir": str(config.data_dir),
|
| 1197 |
+
"mode": "direct_from_docking_poses",
|
| 1198 |
+
"source_index": "source_index.json",
|
| 1199 |
+
"system_index": "system_index.json",
|
| 1200 |
+
"discovered_source_systems": len(systems),
|
| 1201 |
+
"discovered_poses": sum(len(system.poses) for system in systems),
|
| 1202 |
+
"skipped_source_systems": int(progress["skipped_source_systems"]),
|
| 1203 |
+
},
|
| 1204 |
+
"grouping": {
|
| 1205 |
+
"split_label": "original_source_system_id",
|
| 1206 |
+
"storage_mode": "exact_shared_content_hash_within_source_system",
|
| 1207 |
+
"authoritative_storage_key": (
|
| 1208 |
+
"sha256(exact float32 y_grt + node partition + "
|
| 1209 |
+
"x[:,0:34] + x[:,61:71])"
|
| 1210 |
+
),
|
| 1211 |
+
"storage_splits_do_not_change_system_index": True,
|
| 1212 |
+
},
|
| 1213 |
+
"features": {
|
| 1214 |
+
"full_dimension": 82,
|
| 1215 |
+
"dtype": "float32",
|
| 1216 |
+
"static_dimension": len(STATIC_COLUMNS),
|
| 1217 |
+
"static_columns": list(STATIC_COLUMNS),
|
| 1218 |
+
"dynamic_dimension": len(DYNAMIC_COLUMNS),
|
| 1219 |
+
"dynamic_columns": list(DYNAMIC_COLUMNS),
|
| 1220 |
+
},
|
| 1221 |
+
"edges": {
|
| 1222 |
+
"index_dtype_on_disk": "int32",
|
| 1223 |
+
"stored_direction": "upper_triangle_src_lt_dst",
|
| 1224 |
+
"protein_protein_scope": "once_per_storage_group",
|
| 1225 |
+
"non_protein_protein_scope": "once_per_pose",
|
| 1226 |
+
"edge_attr": "derived_from_float32_coordinates_and_endpoint_types",
|
| 1227 |
+
},
|
| 1228 |
+
"derived_fields": [
|
| 1229 |
+
"pos",
|
| 1230 |
+
"is_protein",
|
| 1231 |
+
"y_true",
|
| 1232 |
+
"y_pred",
|
| 1233 |
+
"y_grt",
|
| 1234 |
+
"edge_index_reverse_direction",
|
| 1235 |
+
"edge_attr",
|
| 1236 |
+
"num_nodes",
|
| 1237 |
+
],
|
| 1238 |
+
"n_graphs": len(graph_map),
|
| 1239 |
+
"n_systems": compact_systems,
|
| 1240 |
+
"n_source_systems": int(progress["successful_source_systems"]),
|
| 1241 |
+
"n_shards": len(shards),
|
| 1242 |
+
"graph_map": graph_map,
|
| 1243 |
+
"shards": shards,
|
| 1244 |
+
"size": {"compact_shard_bytes": compact_bytes},
|
| 1245 |
+
"strict_validation": config.strict,
|
| 1246 |
+
"direct_builder": {
|
| 1247 |
+
"target_shard_mib": config.target_shard_mib,
|
| 1248 |
+
"resume_fingerprint": progress["fingerprint"],
|
| 1249 |
+
"on_error": config.on_error,
|
| 1250 |
+
},
|
| 1251 |
+
}
|
| 1252 |
+
_atomic_json(stage_dir / "manifest.json", manifest)
|
| 1253 |
+
return manifest
|
| 1254 |
+
|
| 1255 |
+
|
| 1256 |
+
@dataclass
|
| 1257 |
+
class _RunningSystemWorker:
|
| 1258 |
+
process: Any
|
| 1259 |
+
estimated_memory_mib: int
|
| 1260 |
+
|
| 1261 |
+
|
| 1262 |
+
def _ready_outcome_kind(
|
| 1263 |
+
stage_dir: Path,
|
| 1264 |
+
system_index: int,
|
| 1265 |
+
system: SystemSpec,
|
| 1266 |
+
) -> str | None:
|
| 1267 |
+
"""Return a validated durable worker outcome without retaining tensors."""
|
| 1268 |
+
records = _load_ready_records(stage_dir, system_index, system)
|
| 1269 |
+
if records is not None:
|
| 1270 |
+
del records
|
| 1271 |
+
return "success"
|
| 1272 |
+
error = _load_ready_error(stage_dir, system_index, system)
|
| 1273 |
+
if error is not None:
|
| 1274 |
+
return "skipped"
|
| 1275 |
+
return None
|
| 1276 |
+
|
| 1277 |
+
|
| 1278 |
+
def _unlink_if_exists(path: Path) -> None:
|
| 1279 |
+
try:
|
| 1280 |
+
path.unlink()
|
| 1281 |
+
except FileNotFoundError:
|
| 1282 |
+
pass
|
| 1283 |
+
|
| 1284 |
+
|
| 1285 |
+
def _commit_ready_systems_in_order(
|
| 1286 |
+
stage_dir: Path,
|
| 1287 |
+
progress_path: Path,
|
| 1288 |
+
progress: Dict[str, Any],
|
| 1289 |
+
systems: Sequence[SystemSpec],
|
| 1290 |
+
target_bytes: int,
|
| 1291 |
+
submitted: set[int],
|
| 1292 |
+
) -> int:
|
| 1293 |
+
"""Consume only the next contiguous ready outcomes into the global writer."""
|
| 1294 |
+
committed = 0
|
| 1295 |
+
while int(progress["next_system_index"]) < len(systems):
|
| 1296 |
+
system_index = int(progress["next_system_index"])
|
| 1297 |
+
system = systems[system_index]
|
| 1298 |
+
records = _load_ready_records(stage_dir, system_index, system)
|
| 1299 |
+
if records is not None:
|
| 1300 |
+
_commit_system_records(
|
| 1301 |
+
stage_dir,
|
| 1302 |
+
progress_path,
|
| 1303 |
+
progress,
|
| 1304 |
+
system_index,
|
| 1305 |
+
system,
|
| 1306 |
+
records,
|
| 1307 |
+
target_bytes,
|
| 1308 |
+
len(systems),
|
| 1309 |
+
)
|
| 1310 |
+
_flush_pending_if_full(stage_dir, progress_path, progress, target_bytes)
|
| 1311 |
+
del records
|
| 1312 |
+
_unlink_if_exists(_ready_checkpoint_path(stage_dir, system_index))
|
| 1313 |
+
# A prior interrupted retry can leave an obsolete skip artifact.
|
| 1314 |
+
_unlink_if_exists(_ready_error_path(stage_dir, system_index))
|
| 1315 |
+
submitted.discard(system_index)
|
| 1316 |
+
committed += 1
|
| 1317 |
+
continue
|
| 1318 |
+
|
| 1319 |
+
error_payload = _load_ready_error(stage_dir, system_index, system)
|
| 1320 |
+
if error_payload is not None:
|
| 1321 |
+
_commit_skipped_system(
|
| 1322 |
+
stage_dir,
|
| 1323 |
+
progress_path,
|
| 1324 |
+
progress,
|
| 1325 |
+
system_index,
|
| 1326 |
+
system,
|
| 1327 |
+
error_payload,
|
| 1328 |
+
)
|
| 1329 |
+
_unlink_if_exists(_ready_error_path(stage_dir, system_index))
|
| 1330 |
+
submitted.discard(system_index)
|
| 1331 |
+
committed += 1
|
| 1332 |
+
continue
|
| 1333 |
+
break
|
| 1334 |
+
if committed:
|
| 1335 |
+
gc.collect()
|
| 1336 |
+
return committed
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
def _next_unscheduled_system_index(
|
| 1340 |
+
stage_dir: Path,
|
| 1341 |
+
progress: Mapping[str, Any],
|
| 1342 |
+
systems: Sequence[SystemSpec],
|
| 1343 |
+
submitted: set[int],
|
| 1344 |
+
) -> int | None:
|
| 1345 |
+
"""Find the earliest source system not already running or durably ready."""
|
| 1346 |
+
start = int(progress["next_system_index"])
|
| 1347 |
+
for system_index in range(start, len(systems)):
|
| 1348 |
+
if system_index in submitted:
|
| 1349 |
+
continue
|
| 1350 |
+
outcome = _ready_outcome_kind(stage_dir, system_index, systems[system_index])
|
| 1351 |
+
if outcome is not None:
|
| 1352 |
+
submitted.add(system_index)
|
| 1353 |
+
continue
|
| 1354 |
+
return system_index
|
| 1355 |
+
return None
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def _terminate_running_workers(running: Mapping[int, _RunningSystemWorker]) -> None:
|
| 1359 |
+
"""Best-effort cleanup when the parent aborts before workers finish."""
|
| 1360 |
+
for worker in running.values():
|
| 1361 |
+
if worker.process.is_alive():
|
| 1362 |
+
worker.process.terminate()
|
| 1363 |
+
for worker in running.values():
|
| 1364 |
+
worker.process.join()
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
def _run_parallel_system_build(
|
| 1368 |
+
config: BuildConfig,
|
| 1369 |
+
stage_dir: Path,
|
| 1370 |
+
progress_path: Path,
|
| 1371 |
+
progress: Dict[str, Any],
|
| 1372 |
+
systems: Sequence[SystemSpec],
|
| 1373 |
+
*,
|
| 1374 |
+
graph_builder: GraphBuilder,
|
| 1375 |
+
) -> None:
|
| 1376 |
+
"""Build systems in memory-bounded fresh processes, then commit in order.
|
| 1377 |
+
|
| 1378 |
+
Workers write only their own ready files. The parent alone updates
|
| 1379 |
+
progress/checkpoints/shards, so a completion-order race cannot change
|
| 1380 |
+
source_graph_index, graph_map, or shard membership. Fresh processes also
|
| 1381 |
+
prevent a large system's NumPy allocator high-water mark from becoming a
|
| 1382 |
+
hidden baseline for later small systems.
|
| 1383 |
+
"""
|
| 1384 |
+
if config.system_workers <= 1:
|
| 1385 |
+
raise ValueError("parallel system build requires --system-workers > 1")
|
| 1386 |
+
if config.num_workers != 1:
|
| 1387 |
+
raise ValueError("parallel system build requires --num-workers=1")
|
| 1388 |
+
if config.memory_budget_gib is None:
|
| 1389 |
+
raise ValueError("parallel system build requires --memory-budget-gib")
|
| 1390 |
+
|
| 1391 |
+
ready_dir = stage_dir / ".build_state" / "ready"
|
| 1392 |
+
ready_error_dir = stage_dir / ".build_state" / "ready_errors"
|
| 1393 |
+
ready_dir.mkdir(parents=True, exist_ok=True)
|
| 1394 |
+
ready_error_dir.mkdir(parents=True, exist_ok=True)
|
| 1395 |
+
|
| 1396 |
+
target_bytes = config.target_shard_mib * 1024 * 1024
|
| 1397 |
+
budget_mib = int(math.floor(config.memory_budget_gib * 1024.0))
|
| 1398 |
+
estimates = [estimate_system_memory_mib(system) for system in systems]
|
| 1399 |
+
too_large = [
|
| 1400 |
+
(system.system_id, estimate)
|
| 1401 |
+
for system, estimate in zip(systems, estimates)
|
| 1402 |
+
if estimate > budget_mib
|
| 1403 |
+
]
|
| 1404 |
+
if too_large:
|
| 1405 |
+
first_id, first_mib = too_large[0]
|
| 1406 |
+
raise ValueError(
|
| 1407 |
+
f"{len(too_large)} system(s) exceed the usable memory budget; first "
|
| 1408 |
+
f"{first_id} is estimated at {first_mib / 1024.0:.1f} GiB versus "
|
| 1409 |
+
f"{budget_mib / 1024.0:.1f} GiB. Increase --memory-budget-gib or "
|
| 1410 |
+
"build those systems in a larger-memory allocation."
|
| 1411 |
+
)
|
| 1412 |
+
|
| 1413 |
+
print(
|
| 1414 |
+
f"system workers: {config.system_workers} (one pose builder each)",
|
| 1415 |
+
flush=True,
|
| 1416 |
+
)
|
| 1417 |
+
print(
|
| 1418 |
+
f"memory budget: {budget_mib / 1024.0:.1f} GiB usable; estimates "
|
| 1419 |
+
f"{min(estimates) / 1024.0:.1f}-{max(estimates) / 1024.0:.1f} GiB/system",
|
| 1420 |
+
flush=True,
|
| 1421 |
+
)
|
| 1422 |
+
|
| 1423 |
+
context = multiprocessing.get_context()
|
| 1424 |
+
running: Dict[int, _RunningSystemWorker] = {}
|
| 1425 |
+
submitted: set[int] = set()
|
| 1426 |
+
in_flight_mib = 0
|
| 1427 |
+
|
| 1428 |
+
try:
|
| 1429 |
+
while int(progress["next_system_index"]) < len(systems):
|
| 1430 |
+
_commit_ready_systems_in_order(
|
| 1431 |
+
stage_dir,
|
| 1432 |
+
progress_path,
|
| 1433 |
+
progress,
|
| 1434 |
+
systems,
|
| 1435 |
+
target_bytes,
|
| 1436 |
+
submitted,
|
| 1437 |
+
)
|
| 1438 |
+
|
| 1439 |
+
made_submission = False
|
| 1440 |
+
while len(running) < config.system_workers:
|
| 1441 |
+
system_index = _next_unscheduled_system_index(
|
| 1442 |
+
stage_dir,
|
| 1443 |
+
progress,
|
| 1444 |
+
systems,
|
| 1445 |
+
submitted,
|
| 1446 |
+
)
|
| 1447 |
+
if system_index is None:
|
| 1448 |
+
break
|
| 1449 |
+
estimate_mib = estimates[system_index]
|
| 1450 |
+
if in_flight_mib + estimate_mib > budget_mib:
|
| 1451 |
+
break
|
| 1452 |
+
system = systems[system_index]
|
| 1453 |
+
process = context.Process(
|
| 1454 |
+
target=_parallel_system_worker_main,
|
| 1455 |
+
args=(
|
| 1456 |
+
system_index,
|
| 1457 |
+
system,
|
| 1458 |
+
str(stage_dir),
|
| 1459 |
+
config,
|
| 1460 |
+
graph_builder,
|
| 1461 |
+
),
|
| 1462 |
+
name=f"compact-system-{system_index:05d}",
|
| 1463 |
+
)
|
| 1464 |
+
process.start()
|
| 1465 |
+
running[system_index] = _RunningSystemWorker(process, estimate_mib)
|
| 1466 |
+
submitted.add(system_index)
|
| 1467 |
+
in_flight_mib += estimate_mib
|
| 1468 |
+
made_submission = True
|
| 1469 |
+
print(
|
| 1470 |
+
f"[schedule] {system_index + 1}/{len(systems)} "
|
| 1471 |
+
f"{system.system_id}: estimate {estimate_mib / 1024.0:.1f} GiB; "
|
| 1472 |
+
f"in flight {len(running)}/{config.system_workers}, "
|
| 1473 |
+
f"{in_flight_mib / 1024.0:.1f}/{budget_mib / 1024.0:.1f} GiB",
|
| 1474 |
+
flush=True,
|
| 1475 |
+
)
|
| 1476 |
+
|
| 1477 |
+
reaped = False
|
| 1478 |
+
for system_index, worker in list(running.items()):
|
| 1479 |
+
if worker.process.is_alive():
|
| 1480 |
+
continue
|
| 1481 |
+
worker.process.join()
|
| 1482 |
+
exit_code = worker.process.exitcode
|
| 1483 |
+
del running[system_index]
|
| 1484 |
+
in_flight_mib -= worker.estimated_memory_mib
|
| 1485 |
+
reaped = True
|
| 1486 |
+
if system_index < int(progress["next_system_index"]):
|
| 1487 |
+
# The parent already consumed this worker's atomically
|
| 1488 |
+
# written ready artifact while it was doing final cleanup.
|
| 1489 |
+
# The artifact is intentionally gone by the time the child
|
| 1490 |
+
# exits, so do not require it a second time.
|
| 1491 |
+
continue
|
| 1492 |
+
outcome = _ready_outcome_kind(
|
| 1493 |
+
stage_dir, system_index, systems[system_index]
|
| 1494 |
+
)
|
| 1495 |
+
if exit_code != 0:
|
| 1496 |
+
raise RuntimeError(
|
| 1497 |
+
f"parallel worker for {systems[system_index].system_id} "
|
| 1498 |
+
f"exited with status {exit_code}; no global progress was "
|
| 1499 |
+
"committed for that system"
|
| 1500 |
+
)
|
| 1501 |
+
if outcome is None:
|
| 1502 |
+
raise RuntimeError(
|
| 1503 |
+
f"parallel worker for {systems[system_index].system_id} "
|
| 1504 |
+
"exited successfully without a ready checkpoint or error"
|
| 1505 |
+
)
|
| 1506 |
+
|
| 1507 |
+
if int(progress["next_system_index"]) >= len(systems):
|
| 1508 |
+
# A child may have written its ready file before completing
|
| 1509 |
+
# scratch cleanup. Join every such child before publishing or
|
| 1510 |
+
# removing .build_state so it cannot race the final rename.
|
| 1511 |
+
if not running:
|
| 1512 |
+
break
|
| 1513 |
+
if not reaped:
|
| 1514 |
+
time.sleep(0.1)
|
| 1515 |
+
continue
|
| 1516 |
+
if not made_submission and not reaped:
|
| 1517 |
+
# Never spin on a full memory budget while a worker is active.
|
| 1518 |
+
# A short polling interval also lets Slurm SIGTERM interrupt
|
| 1519 |
+
# promptly, leaving only atomically committed ready artifacts.
|
| 1520 |
+
time.sleep(0.1)
|
| 1521 |
+
except BaseException:
|
| 1522 |
+
_terminate_running_workers(running)
|
| 1523 |
+
raise
|
| 1524 |
+
|
| 1525 |
+
|
| 1526 |
+
def _run_locked(
|
| 1527 |
+
config: BuildConfig,
|
| 1528 |
+
*,
|
| 1529 |
+
graph_builder: GraphBuilder = build_graph_enhanced,
|
| 1530 |
+
) -> Dict[str, Any]:
|
| 1531 |
+
"""Implementation entered only while the output sidecar lock is held."""
|
| 1532 |
+
_validate_config(config)
|
| 1533 |
+
if config.output_dir.exists():
|
| 1534 |
+
raise FileExistsError(
|
| 1535 |
+
f"refusing to overwrite existing output directory: {config.output_dir}"
|
| 1536 |
+
)
|
| 1537 |
+
stage_dir = config.output_dir.with_name(f".{config.output_dir.name}.building")
|
| 1538 |
+
if stage_dir.exists() and not config.resume:
|
| 1539 |
+
raise FileExistsError(
|
| 1540 |
+
f"incomplete build exists: {stage_dir}; pass --resume or move it aside"
|
| 1541 |
+
)
|
| 1542 |
+
|
| 1543 |
+
systems = discover_systems(config)
|
| 1544 |
+
fingerprint = _discovery_fingerprint(config, systems)
|
| 1545 |
+
progress_path = stage_dir / ".build_state" / "progress.json"
|
| 1546 |
+
if stage_dir.exists() and (stage_dir / "manifest.json").is_file():
|
| 1547 |
+
os.replace(stage_dir, config.output_dir)
|
| 1548 |
+
print(f"published previously completed build: {config.output_dir}", flush=True)
|
| 1549 |
+
with (config.output_dir / "manifest.json").open("r", encoding="utf-8") as handle:
|
| 1550 |
+
return json.load(handle)
|
| 1551 |
+
|
| 1552 |
+
if progress_path.is_file():
|
| 1553 |
+
with progress_path.open("r", encoding="utf-8") as handle:
|
| 1554 |
+
progress = json.load(handle)
|
| 1555 |
+
if progress.get("progress_version") != PROGRESS_VERSION:
|
| 1556 |
+
raise ValueError("incompatible direct-builder progress version")
|
| 1557 |
+
if progress.get("fingerprint") != fingerprint:
|
| 1558 |
+
raise ValueError(
|
| 1559 |
+
"resume fingerprint changed: inputs or storage-affecting options differ"
|
| 1560 |
+
)
|
| 1561 |
+
else:
|
| 1562 |
+
if stage_dir.exists() and any(stage_dir.iterdir()):
|
| 1563 |
+
raise ValueError(
|
| 1564 |
+
f"{stage_dir} exists without a valid progress file; move it aside"
|
| 1565 |
+
)
|
| 1566 |
+
(stage_dir / "shards").mkdir(parents=True, exist_ok=True)
|
| 1567 |
+
(stage_dir / ".build_state" / "checkpoints").mkdir(parents=True, exist_ok=True)
|
| 1568 |
+
(stage_dir / ".build_state" / "work").mkdir(parents=True, exist_ok=True)
|
| 1569 |
+
progress = _default_progress(fingerprint)
|
| 1570 |
+
_atomic_json(progress_path, progress)
|
| 1571 |
+
|
| 1572 |
+
print(f"data: {config.data_dir}", flush=True)
|
| 1573 |
+
print(f"output: {config.output_dir}", flush=True)
|
| 1574 |
+
print(f"staging: {stage_dir}", flush=True)
|
| 1575 |
+
print(f"systems: {len(systems)}", flush=True)
|
| 1576 |
+
print(f"poses: {sum(len(system.poses) for system in systems)}", flush=True)
|
| 1577 |
+
print(f"resume at: {progress['next_system_index']}", flush=True)
|
| 1578 |
+
print(f"pose workers/system: {config.num_workers}", flush=True)
|
| 1579 |
+
print(f"system workers: {config.system_workers}", flush=True)
|
| 1580 |
+
if config.memory_budget_gib is not None:
|
| 1581 |
+
print(f"memory budget: {config.memory_budget_gib:.1f} GiB usable", flush=True)
|
| 1582 |
+
print(f"strict: {config.strict}", flush=True)
|
| 1583 |
+
|
| 1584 |
+
target_bytes = config.target_shard_mib * 1024 * 1024
|
| 1585 |
+
if config.system_workers > 1:
|
| 1586 |
+
_run_parallel_system_build(
|
| 1587 |
+
config,
|
| 1588 |
+
stage_dir,
|
| 1589 |
+
progress_path,
|
| 1590 |
+
progress,
|
| 1591 |
+
systems,
|
| 1592 |
+
graph_builder=graph_builder,
|
| 1593 |
+
)
|
| 1594 |
+
else:
|
| 1595 |
+
for system_index in range(int(progress["next_system_index"]), len(systems)):
|
| 1596 |
+
system = systems[system_index]
|
| 1597 |
+
work_dir = (
|
| 1598 |
+
stage_dir
|
| 1599 |
+
/ ".build_state"
|
| 1600 |
+
/ "work"
|
| 1601 |
+
/ f"system_{system_index:08d}"
|
| 1602 |
+
)
|
| 1603 |
+
committed = False
|
| 1604 |
+
try:
|
| 1605 |
+
graphs = build_pose_graphs(
|
| 1606 |
+
system,
|
| 1607 |
+
work_dir,
|
| 1608 |
+
config,
|
| 1609 |
+
graph_builder=graph_builder,
|
| 1610 |
+
)
|
| 1611 |
+
records = compact_system_records(
|
| 1612 |
+
system,
|
| 1613 |
+
graphs,
|
| 1614 |
+
strict=config.strict,
|
| 1615 |
+
data_root=config.data_dir,
|
| 1616 |
+
)
|
| 1617 |
+
_commit_system_records(
|
| 1618 |
+
stage_dir,
|
| 1619 |
+
progress_path,
|
| 1620 |
+
progress,
|
| 1621 |
+
system_index,
|
| 1622 |
+
system,
|
| 1623 |
+
records,
|
| 1624 |
+
target_bytes,
|
| 1625 |
+
len(systems),
|
| 1626 |
+
)
|
| 1627 |
+
committed = True
|
| 1628 |
+
_flush_pending_if_full(
|
| 1629 |
+
stage_dir, progress_path, progress, target_bytes
|
| 1630 |
+
)
|
| 1631 |
+
del graphs, records
|
| 1632 |
+
if work_dir.is_dir():
|
| 1633 |
+
shutil.rmtree(work_dir)
|
| 1634 |
+
gc.collect()
|
| 1635 |
+
except Exception as error:
|
| 1636 |
+
if committed:
|
| 1637 |
+
# The durable checkpoint/progress update succeeded. Do not
|
| 1638 |
+
# reinterpret a later scratch-cleanup failure as a skipped
|
| 1639 |
+
# source system.
|
| 1640 |
+
raise
|
| 1641 |
+
if config.on_error == "abort":
|
| 1642 |
+
raise
|
| 1643 |
+
error_payload = {
|
| 1644 |
+
"system_index": system_index,
|
| 1645 |
+
"system_id": system.system_id,
|
| 1646 |
+
"num_poses": len(system.poses),
|
| 1647 |
+
"error_type": type(error).__name__,
|
| 1648 |
+
"error": str(error),
|
| 1649 |
+
"traceback": traceback.format_exc(),
|
| 1650 |
+
}
|
| 1651 |
+
_commit_skipped_system(
|
| 1652 |
+
stage_dir,
|
| 1653 |
+
progress_path,
|
| 1654 |
+
progress,
|
| 1655 |
+
system_index,
|
| 1656 |
+
system,
|
| 1657 |
+
error_payload,
|
| 1658 |
+
)
|
| 1659 |
+
|
| 1660 |
+
_flush_pending(stage_dir, progress_path, progress)
|
| 1661 |
+
manifest = _finish_dataset(config, stage_dir, progress, systems)
|
| 1662 |
+
os.replace(stage_dir, config.output_dir)
|
| 1663 |
+
state_dir = config.output_dir / ".build_state"
|
| 1664 |
+
if state_dir.is_dir():
|
| 1665 |
+
shutil.rmtree(state_dir)
|
| 1666 |
+
print(
|
| 1667 |
+
f"complete: {config.output_dir / 'manifest.json'} "
|
| 1668 |
+
f"({manifest['n_graphs']} graphs, {manifest['n_source_systems']} source "
|
| 1669 |
+
f"systems, {manifest['n_shards']} shards)",
|
| 1670 |
+
flush=True,
|
| 1671 |
+
)
|
| 1672 |
+
return manifest
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
def run(
|
| 1676 |
+
config: BuildConfig,
|
| 1677 |
+
*,
|
| 1678 |
+
graph_builder: GraphBuilder = build_graph_enhanced,
|
| 1679 |
+
) -> Dict[str, Any]:
|
| 1680 |
+
"""Run a direct compact build under an output-directory exclusive lock.
|
| 1681 |
+
|
| 1682 |
+
The injectable graph builder is intentionally only for small CPU tests.
|
| 1683 |
+
Production CLI calls always use ``build_graph_enhanced``.
|
| 1684 |
+
"""
|
| 1685 |
+
with _exclusive_build_lock(config.output_dir):
|
| 1686 |
+
return _run_locked(config, graph_builder=graph_builder)
|
| 1687 |
+
|
| 1688 |
+
|
| 1689 |
+
def main(argv: Sequence[str] | None = None) -> int:
|
| 1690 |
+
config = parse_args(argv)
|
| 1691 |
+
run(config)
|
| 1692 |
+
return 0
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
if __name__ == "__main__":
|
| 1696 |
+
try:
|
| 1697 |
+
raise SystemExit(main())
|
| 1698 |
+
except Exception as error:
|
| 1699 |
+
print(f"ERROR: {error}", file=sys.stderr, flush=True)
|
| 1700 |
+
raise
|
code/compact_v1/build_compact_v1_direct.sbatch
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Build compact_v1 directly from docking PDB poses.
|
| 3 |
+
#
|
| 4 |
+
# Full build:
|
| 5 |
+
# sbatch --export=ALL,DATA_DIR=/path/to/poses,OUTPUT_DIR=/path/to/compact,METHOD=protenix \
|
| 6 |
+
# build_compact_v1_direct.sbatch
|
| 7 |
+
#
|
| 8 |
+
# High-CPU adaptive build (one fresh process per source system; no nested pose
|
| 9 |
+
# pools):
|
| 10 |
+
# sbatch --cpus-per-task=32 --mem=192G --time=24:00:00 \
|
| 11 |
+
# --export=ALL,DATA_DIR=/path/to/poses,OUTPUT_DIR=/path/to/compact,METHOD=protenix,SYSTEM_WORKERS=28,NUM_WORKERS=1,MEMORY_BUDGET_GIB=150 \
|
| 12 |
+
# build_compact_v1_direct.sbatch
|
| 13 |
+
#
|
| 14 |
+
# One-system smoke test:
|
| 15 |
+
# sbatch --export=ALL,DATA_DIR=/path/to/poses,OUTPUT_DIR=/path/to/smoke,METHOD=protenix,SYSTEM_ID=tnks2_lig_20,MAX_POSES=2 \
|
| 16 |
+
# build_compact_v1_direct.sbatch
|
| 17 |
+
|
| 18 |
+
#SBATCH --account=bghp-delta-cpu
|
| 19 |
+
#SBATCH --partition=cpu
|
| 20 |
+
#SBATCH --nodes=1
|
| 21 |
+
#SBATCH --ntasks-per-node=1
|
| 22 |
+
#SBATCH --cpus-per-task=8
|
| 23 |
+
#SBATCH --mem=96G
|
| 24 |
+
#SBATCH --time=24:00:00
|
| 25 |
+
#SBATCH --job-name=build_compact
|
| 26 |
+
#SBATCH --output=/work/nvme/bghp/hhao/gnncp/system_split_code/build_compact_%j.out
|
| 27 |
+
#SBATCH --error=/work/nvme/bghp/hhao/gnncp/system_split_code/build_compact_%j.err
|
| 28 |
+
#SBATCH --open-mode=append
|
| 29 |
+
#SBATCH --requeue
|
| 30 |
+
#SBATCH --mail-type=FAIL
|
| 31 |
+
|
| 32 |
+
set -Eeuo pipefail
|
| 33 |
+
umask 007
|
| 34 |
+
|
| 35 |
+
: "${DATA_DIR:?Export DATA_DIR=/path/to/docking_results}"
|
| 36 |
+
: "${OUTPUT_DIR:?Export OUTPUT_DIR=/path/to/new_compact_dataset}"
|
| 37 |
+
: "${METHOD:?Export METHOD=protenix|diffdock|autodock_vina|medusagraph}"
|
| 38 |
+
|
| 39 |
+
readonly PROJECT_ROOT=/work/nvme/bghp/hhao/gnncp
|
| 40 |
+
readonly BUILDER="${PROJECT_ROOT}/system_split_code/build_compact_v1_direct.py"
|
| 41 |
+
readonly PYTHON=/u/hhao/anaconda3/envs/gcp/bin/python
|
| 42 |
+
readonly SYSTEM_WORKERS="${SYSTEM_WORKERS:-1}"
|
| 43 |
+
if (( SYSTEM_WORKERS > 1 )); then
|
| 44 |
+
# Cross-system mode deliberately has one in-process pose builder per child.
|
| 45 |
+
# This avoids multiplying dense N-by-N distance matrices in nested pools.
|
| 46 |
+
readonly NUM_WORKERS="${NUM_WORKERS:-1}"
|
| 47 |
+
else
|
| 48 |
+
readonly NUM_WORKERS="${NUM_WORKERS:-4}"
|
| 49 |
+
fi
|
| 50 |
+
readonly MEMORY_BUDGET_GIB="${MEMORY_BUDGET_GIB:-}"
|
| 51 |
+
readonly TARGET_SHARD_MIB="${TARGET_SHARD_MIB:-512}"
|
| 52 |
+
readonly ON_ERROR="${ON_ERROR:-abort}"
|
| 53 |
+
|
| 54 |
+
finish()
|
| 55 |
+
{
|
| 56 |
+
local rc=$?
|
| 57 |
+
echo "[$(date --iso-8601=seconds)] job=${SLURM_JOB_ID} exit=${rc}"
|
| 58 |
+
}
|
| 59 |
+
trap finish EXIT
|
| 60 |
+
|
| 61 |
+
echo "[$(date --iso-8601=seconds)] host=$(hostname)"
|
| 62 |
+
echo "data=${DATA_DIR}"
|
| 63 |
+
echo "output=${OUTPUT_DIR}"
|
| 64 |
+
echo "method=${METHOD} pose_workers=${NUM_WORKERS} system_workers=${SYSTEM_WORKERS} memory_budget_gib=${MEMORY_BUDGET_GIB:-unset}"
|
| 65 |
+
|
| 66 |
+
test -x "${PYTHON}"
|
| 67 |
+
test -r "${BUILDER}"
|
| 68 |
+
test -d "${DATA_DIR}"
|
| 69 |
+
mkdir -p "$(dirname "${OUTPUT_DIR}")"
|
| 70 |
+
|
| 71 |
+
if [[ -s "${OUTPUT_DIR}/manifest.json" ]]; then
|
| 72 |
+
echo "Output already has a manifest; skipping completed build."
|
| 73 |
+
exit 0
|
| 74 |
+
fi
|
| 75 |
+
if [[ -e "${OUTPUT_DIR}" ]]; then
|
| 76 |
+
echo "Output exists without a manifest; refusing to overwrite: ${OUTPUT_DIR}" >&2
|
| 77 |
+
exit 3
|
| 78 |
+
fi
|
| 79 |
+
|
| 80 |
+
if (( SYSTEM_WORKERS > 1 )); then
|
| 81 |
+
if [[ "${NUM_WORKERS}" != "1" ]]; then
|
| 82 |
+
echo "SYSTEM_WORKERS>1 requires NUM_WORKERS=1; nested process pools are unsafe." >&2
|
| 83 |
+
exit 2
|
| 84 |
+
fi
|
| 85 |
+
: "${MEMORY_BUDGET_GIB:?Set MEMORY_BUDGET_GIB to a usable aggregate worker-memory budget for SYSTEM_WORKERS>1}"
|
| 86 |
+
fi
|
| 87 |
+
if [[ -n "${SLURM_CPUS_PER_TASK:-}" ]] && (( SYSTEM_WORKERS > SLURM_CPUS_PER_TASK )); then
|
| 88 |
+
echo "SYSTEM_WORKERS=${SYSTEM_WORKERS} exceeds SLURM_CPUS_PER_TASK=${SLURM_CPUS_PER_TASK}" >&2
|
| 89 |
+
exit 2
|
| 90 |
+
fi
|
| 91 |
+
|
| 92 |
+
# Each pose worker performs dense scipy distance calculations. Keep numerical
|
| 93 |
+
# libraries single-threaded and parallelise at the pose-process level.
|
| 94 |
+
export PYTHONUNBUFFERED=1
|
| 95 |
+
export OMP_NUM_THREADS=1
|
| 96 |
+
export MKL_NUM_THREADS=1
|
| 97 |
+
export OPENBLAS_NUM_THREADS=1
|
| 98 |
+
export NUMEXPR_NUM_THREADS=1
|
| 99 |
+
export MALLOC_ARENA_MAX=2
|
| 100 |
+
|
| 101 |
+
ARGS=(
|
| 102 |
+
--data-dir "${DATA_DIR}"
|
| 103 |
+
--output-dir "${OUTPUT_DIR}"
|
| 104 |
+
--method "${METHOD}"
|
| 105 |
+
--num-workers "${NUM_WORKERS}"
|
| 106 |
+
--system-workers "${SYSTEM_WORKERS}"
|
| 107 |
+
--target-shard-mib "${TARGET_SHARD_MIB}"
|
| 108 |
+
--on-error "${ON_ERROR}"
|
| 109 |
+
--resume
|
| 110 |
+
)
|
| 111 |
+
if [[ -n "${MEMORY_BUDGET_GIB}" ]]; then
|
| 112 |
+
ARGS+=(--memory-budget-gib "${MEMORY_BUDGET_GIB}")
|
| 113 |
+
fi
|
| 114 |
+
if [[ -n "${SYSTEM_ID:-}" ]]; then
|
| 115 |
+
ARGS+=(--system-id "${SYSTEM_ID}")
|
| 116 |
+
fi
|
| 117 |
+
if [[ -n "${MAX_SYSTEMS:-}" ]]; then
|
| 118 |
+
ARGS+=(--max-systems "${MAX_SYSTEMS}")
|
| 119 |
+
fi
|
| 120 |
+
if [[ -n "${MAX_POSES:-}" ]]; then
|
| 121 |
+
ARGS+=(--max-poses-per-system "${MAX_POSES}")
|
| 122 |
+
fi
|
| 123 |
+
|
| 124 |
+
df -h "$(dirname "${OUTPUT_DIR}")"
|
| 125 |
+
/usr/bin/time -v "${PYTHON}" "${BUILDER}" "${ARGS[@]}"
|
| 126 |
+
|
| 127 |
+
test -s "${OUTPUT_DIR}/manifest.json"
|
| 128 |
+
test -s "${OUTPUT_DIR}/system_index.json"
|
| 129 |
+
du -sh "${OUTPUT_DIR}"
|
| 130 |
+
echo "[$(date --iso-8601=seconds)] compact dataset committed successfully"
|
code/compact_v1/build_graph_unified_enhanced.py
ADDED
|
@@ -0,0 +1,864 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
Build Graph Unified Enhanced
|
| 5 |
+
=============================
|
| 6 |
+
|
| 7 |
+
整合版构图脚本,用于批量处理蛋白-配体数据并构建增强版图数据集
|
| 8 |
+
|
| 9 |
+
功能:
|
| 10 |
+
1. 批量处理多个 docking 结果
|
| 11 |
+
2. 构建增强版图特征 (82维节点特征 + 4维边特征)
|
| 12 |
+
3. 计算预测误差标签 (y_true, y_pred, y_grt)
|
| 13 |
+
4. 保存为 PyTorch Geometric 格式
|
| 14 |
+
|
| 15 |
+
使用方法:
|
| 16 |
+
python build_graph_unified_enhanced.py \\
|
| 17 |
+
--data_dir ./docking_results \\
|
| 18 |
+
--output ./datasets_x/protenix_enhanced_graphs.pt \\
|
| 19 |
+
--docking_type protenix
|
| 20 |
+
|
| 21 |
+
数据目录结构 (示例):
|
| 22 |
+
data_dir/
|
| 23 |
+
├── 1a30/
|
| 24 |
+
│ ├── protein.pdb # 蛋白结构
|
| 25 |
+
│ ├── ligand_native.pdb # 配体真实结构 (ground truth)
|
| 26 |
+
│ ├── 1a30_pose_01.pdb # Docking 预测 pose 1
|
| 27 |
+
│ ├── 1a30_pose_02.pdb # Docking 预测 pose 2
|
| 28 |
+
│ └── ...
|
| 29 |
+
├── 1b38/
|
| 30 |
+
│ └── ...
|
| 31 |
+
└── ...
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
import os
|
| 35 |
+
import glob
|
| 36 |
+
import argparse
|
| 37 |
+
from typing import Sequence, List, Dict, Tuple, Optional
|
| 38 |
+
from collections import defaultdict
|
| 39 |
+
|
| 40 |
+
import numpy as np
|
| 41 |
+
import torch
|
| 42 |
+
from torch_geometric.data import Data
|
| 43 |
+
import MDAnalysis as mda
|
| 44 |
+
from io import StringIO
|
| 45 |
+
from scipy.spatial.distance import cdist
|
| 46 |
+
from tqdm import tqdm
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# =============================================================================
|
| 50 |
+
# 基础字典
|
| 51 |
+
# =============================================================================
|
| 52 |
+
|
| 53 |
+
ELEMENTS = ["C", "N", "O", "S", "P", "F", "Cl", "Br", "I", "H", "Other"]
|
| 54 |
+
ELEMENT2IDX = {e: i for i, e in enumerate(ELEMENTS)}
|
| 55 |
+
|
| 56 |
+
AA3 = [
|
| 57 |
+
"ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE",
|
| 58 |
+
"LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL"
|
| 59 |
+
]
|
| 60 |
+
AA3_2IDX = {aa: i for i, aa in enumerate(AA3)}
|
| 61 |
+
AA_DIM = len(AA3) + 1
|
| 62 |
+
|
| 63 |
+
# 化学属性
|
| 64 |
+
ELECTRONEGATIVITY = {
|
| 65 |
+
"C": 2.55, "N": 3.04, "O": 3.44, "S": 2.58, "P": 2.19,
|
| 66 |
+
"F": 3.98, "Cl": 3.16, "Br": 2.96, "I": 2.66, "H": 2.20, "Other": 2.5
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
VDW_RADIUS = {
|
| 70 |
+
"C": 1.70, "N": 1.55, "O": 1.52, "S": 1.80, "P": 1.80,
|
| 71 |
+
"F": 1.47, "Cl": 1.75, "Br": 1.85, "I": 1.98, "H": 1.20, "Other": 1.70
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
ATOMIC_MASS = {
|
| 75 |
+
"C": 12.0, "N": 14.0, "O": 16.0, "S": 32.0, "P": 31.0,
|
| 76 |
+
"F": 19.0, "Cl": 35.5, "Br": 80.0, "I": 127.0, "H": 1.0, "Other": 12.0
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
HYDROPHOBICITY = {
|
| 80 |
+
"ALA": 0.70, "ARG": 0.00, "ASN": 0.11, "ASP": 0.11, "CYS": 0.78,
|
| 81 |
+
"GLN": 0.11, "GLU": 0.11, "GLY": 0.46, "HIS": 0.14, "ILE": 1.00,
|
| 82 |
+
"LEU": 0.92, "LYS": 0.07, "MET": 0.71, "PHE": 0.81, "PRO": 0.32,
|
| 83 |
+
"SER": 0.41, "THR": 0.42, "TRP": 0.40, "TYR": 0.36, "VAL": 0.97,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
AROMATIC_RESIDUES = {"PHE", "TYR", "TRP", "HIS"}
|
| 87 |
+
CHARGED_RESIDUES = {"ARG": 1, "LYS": 1, "ASP": -1, "GLU": -1, "HIS": 0.5}
|
| 88 |
+
POLAR_RESIDUES = {"SER", "THR", "ASN", "GLN", "TYR", "CYS"}
|
| 89 |
+
BACKBONE_ATOMS = {"N", "CA", "C", "O"}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# =============================================================================
|
| 93 |
+
# 工具函数
|
| 94 |
+
# =============================================================================
|
| 95 |
+
|
| 96 |
+
def _one_hot(idx: int, dim: int) -> np.ndarray:
|
| 97 |
+
v = np.zeros(dim, dtype=np.float32)
|
| 98 |
+
if 0 <= idx < dim:
|
| 99 |
+
v[idx] = 1.0
|
| 100 |
+
return v
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _get_element(atom) -> str:
|
| 104 |
+
elem = getattr(atom, "element", None)
|
| 105 |
+
if elem:
|
| 106 |
+
e = elem.strip().capitalize()
|
| 107 |
+
if e.upper() in ["CL", "BR"]:
|
| 108 |
+
return e.upper().title()
|
| 109 |
+
return e[0].upper()
|
| 110 |
+
name = atom.name.strip()
|
| 111 |
+
if not name:
|
| 112 |
+
return "Other"
|
| 113 |
+
if name[0].isdigit():
|
| 114 |
+
name = name[1:]
|
| 115 |
+
if name[:2].upper() in ["CL", "BR"]:
|
| 116 |
+
return name[:2].upper().title()
|
| 117 |
+
return name[0].upper()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def load_pdb_clean_models(pdb_path: str) -> mda.Universe:
|
| 121 |
+
"""读取 PDB,忽略 MODEL/ENDMDL"""
|
| 122 |
+
with open(pdb_path, "r") as f:
|
| 123 |
+
lines = f.readlines()
|
| 124 |
+
|
| 125 |
+
cleaned = []
|
| 126 |
+
for line in lines:
|
| 127 |
+
rec = line[:6].strip().upper()
|
| 128 |
+
if rec in ("MODEL", "ENDMDL"):
|
| 129 |
+
continue
|
| 130 |
+
cleaned.append(line)
|
| 131 |
+
|
| 132 |
+
text = "".join(cleaned)
|
| 133 |
+
return mda.Universe(StringIO(text), format="PDB")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# =============================================================================
|
| 137 |
+
# 增强版特征计算
|
| 138 |
+
# =============================================================================
|
| 139 |
+
|
| 140 |
+
def compute_local_geometry_features(
|
| 141 |
+
coords: np.ndarray,
|
| 142 |
+
radii: Sequence[float] = (3.0, 5.0, 8.0),
|
| 143 |
+
) -> np.ndarray:
|
| 144 |
+
"""局部几何特征: 邻居数量、各向异性、重心偏移"""
|
| 145 |
+
N = coords.shape[0]
|
| 146 |
+
dist_matrix = cdist(coords, coords)
|
| 147 |
+
|
| 148 |
+
features_list = []
|
| 149 |
+
|
| 150 |
+
for r in radii:
|
| 151 |
+
mask = (dist_matrix <= r) & (dist_matrix > 0)
|
| 152 |
+
n_neighbors = mask.sum(axis=1).astype(np.float32)
|
| 153 |
+
|
| 154 |
+
anisotropy = np.zeros(N, dtype=np.float32)
|
| 155 |
+
centroid_dist = np.zeros(N, dtype=np.float32)
|
| 156 |
+
|
| 157 |
+
for i in range(N):
|
| 158 |
+
neighbor_idx = np.where(mask[i])[0]
|
| 159 |
+
if len(neighbor_idx) < 3:
|
| 160 |
+
continue
|
| 161 |
+
|
| 162 |
+
neighbor_coords = coords[neighbor_idx] - coords[i]
|
| 163 |
+
centroid = neighbor_coords.mean(axis=0)
|
| 164 |
+
centroid_dist[i] = np.linalg.norm(centroid)
|
| 165 |
+
|
| 166 |
+
if len(neighbor_idx) >= 3:
|
| 167 |
+
cov = np.cov(neighbor_coords.T)
|
| 168 |
+
try:
|
| 169 |
+
eigenvalues = np.linalg.eigvalsh(cov)
|
| 170 |
+
eigenvalues = np.sort(eigenvalues)[::-1]
|
| 171 |
+
total = eigenvalues.sum() + 1e-8
|
| 172 |
+
anisotropy[i] = (eigenvalues[0] - eigenvalues[-1]) / total
|
| 173 |
+
except:
|
| 174 |
+
pass
|
| 175 |
+
|
| 176 |
+
features_list.extend([
|
| 177 |
+
n_neighbors.reshape(-1, 1),
|
| 178 |
+
anisotropy.reshape(-1, 1),
|
| 179 |
+
centroid_dist.reshape(-1, 1),
|
| 180 |
+
])
|
| 181 |
+
|
| 182 |
+
return np.concatenate(features_list, axis=1)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def compute_distance_statistics(
|
| 186 |
+
coords: np.ndarray,
|
| 187 |
+
coords_prot: np.ndarray,
|
| 188 |
+
coords_lig: np.ndarray,
|
| 189 |
+
) -> np.ndarray:
|
| 190 |
+
"""距离统计特征"""
|
| 191 |
+
N = coords.shape[0]
|
| 192 |
+
|
| 193 |
+
dist_to_prot = cdist(coords, coords_prot)
|
| 194 |
+
prot_min = dist_to_prot.min(axis=1, keepdims=True)
|
| 195 |
+
prot_mean = dist_to_prot.mean(axis=1, keepdims=True)
|
| 196 |
+
prot_std = dist_to_prot.std(axis=1, keepdims=True)
|
| 197 |
+
prot_q25 = np.percentile(dist_to_prot, 25, axis=1, keepdims=True)
|
| 198 |
+
prot_q75 = np.percentile(dist_to_prot, 75, axis=1, keepdims=True)
|
| 199 |
+
|
| 200 |
+
dist_to_lig = cdist(coords, coords_lig)
|
| 201 |
+
lig_min = dist_to_lig.min(axis=1, keepdims=True)
|
| 202 |
+
lig_mean = dist_to_lig.mean(axis=1, keepdims=True)
|
| 203 |
+
lig_std = dist_to_lig.std(axis=1, keepdims=True)
|
| 204 |
+
lig_q25 = np.percentile(dist_to_lig, 25, axis=1, keepdims=True)
|
| 205 |
+
lig_q75 = np.percentile(dist_to_lig, 75, axis=1, keepdims=True)
|
| 206 |
+
|
| 207 |
+
dist_all = cdist(coords, coords)
|
| 208 |
+
shells = [(0, 3), (3, 5), (5, 8), (8, 12)]
|
| 209 |
+
shell_counts = []
|
| 210 |
+
for r_min, r_max in shells:
|
| 211 |
+
mask = (dist_all > r_min) & (dist_all <= r_max)
|
| 212 |
+
count = mask.sum(axis=1, keepdims=True).astype(np.float32)
|
| 213 |
+
shell_counts.append(count)
|
| 214 |
+
|
| 215 |
+
return np.concatenate([
|
| 216 |
+
prot_min, prot_mean, prot_std, prot_q25, prot_q75,
|
| 217 |
+
lig_min, lig_mean, lig_std, lig_q25, lig_q75,
|
| 218 |
+
*shell_counts,
|
| 219 |
+
], axis=1)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def compute_chemical_features(atoms, elements: List[str]) -> np.ndarray:
|
| 223 |
+
"""化学特征"""
|
| 224 |
+
N = len(atoms)
|
| 225 |
+
|
| 226 |
+
electroneg = np.zeros((N, 1), dtype=np.float32)
|
| 227 |
+
vdw = np.zeros((N, 1), dtype=np.float32)
|
| 228 |
+
mass = np.zeros((N, 1), dtype=np.float32)
|
| 229 |
+
hbond_donor = np.zeros((N, 1), dtype=np.float32)
|
| 230 |
+
hbond_acceptor = np.zeros((N, 1), dtype=np.float32)
|
| 231 |
+
|
| 232 |
+
for i, (atom, elem) in enumerate(zip(atoms, elements)):
|
| 233 |
+
electroneg[i] = ELECTRONEGATIVITY.get(elem, 2.5)
|
| 234 |
+
vdw[i] = VDW_RADIUS.get(elem, 1.7)
|
| 235 |
+
mass[i] = ATOMIC_MASS.get(elem, 12.0)
|
| 236 |
+
|
| 237 |
+
if elem in ["N", "O"]:
|
| 238 |
+
hbond_donor[i] = 1.0
|
| 239 |
+
hbond_acceptor[i] = 1.0
|
| 240 |
+
elif elem == "S":
|
| 241 |
+
hbond_acceptor[i] = 0.5
|
| 242 |
+
|
| 243 |
+
electroneg = (electroneg - 2.0) / 2.0
|
| 244 |
+
vdw = (vdw - 1.2) / 0.8
|
| 245 |
+
mass = np.log1p(mass) / 5.0
|
| 246 |
+
|
| 247 |
+
return np.concatenate([electroneg, vdw, mass, hbond_donor, hbond_acceptor], axis=1)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def compute_protein_specific_features(atoms, is_protein: np.ndarray) -> np.ndarray:
|
| 251 |
+
"""蛋白质特定特征"""
|
| 252 |
+
N = len(atoms)
|
| 253 |
+
|
| 254 |
+
is_backbone = np.zeros((N, 1), dtype=np.float32)
|
| 255 |
+
hydrophobicity = np.zeros((N, 1), dtype=np.float32)
|
| 256 |
+
aromaticity = np.zeros((N, 1), dtype=np.float32)
|
| 257 |
+
charge = np.zeros((N, 1), dtype=np.float32)
|
| 258 |
+
polarity = np.zeros((N, 1), dtype=np.float32)
|
| 259 |
+
|
| 260 |
+
for i, atom in enumerate(atoms):
|
| 261 |
+
if is_protein[i, 0] < 0.5:
|
| 262 |
+
hydrophobicity[i] = 0.5
|
| 263 |
+
continue
|
| 264 |
+
|
| 265 |
+
resname = atom.resname.strip().upper()
|
| 266 |
+
atomname = atom.name.strip().upper()
|
| 267 |
+
|
| 268 |
+
if atomname in BACKBONE_ATOMS:
|
| 269 |
+
is_backbone[i] = 1.0
|
| 270 |
+
|
| 271 |
+
hydrophobicity[i] = HYDROPHOBICITY.get(resname, 0.5)
|
| 272 |
+
aromaticity[i] = 1.0 if resname in AROMATIC_RESIDUES else 0.0
|
| 273 |
+
charge[i] = CHARGED_RESIDUES.get(resname, 0.0)
|
| 274 |
+
polarity[i] = 1.0 if resname in POLAR_RESIDUES else 0.0
|
| 275 |
+
|
| 276 |
+
return np.concatenate([is_backbone, hydrophobicity, aromaticity, charge, polarity], axis=1)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def compute_topology_features(dist_matrix: np.ndarray, cutoff: float = 6.0) -> np.ndarray:
|
| 280 |
+
"""拓扑特征"""
|
| 281 |
+
N = dist_matrix.shape[0]
|
| 282 |
+
adj = (dist_matrix <= cutoff) & (dist_matrix > 0)
|
| 283 |
+
|
| 284 |
+
degree = adj.sum(axis=1).astype(np.float32)
|
| 285 |
+
|
| 286 |
+
clustering = np.zeros(N, dtype=np.float32)
|
| 287 |
+
for i in range(N):
|
| 288 |
+
neighbors = np.where(adj[i])[0]
|
| 289 |
+
k = len(neighbors)
|
| 290 |
+
if k < 2:
|
| 291 |
+
continue
|
| 292 |
+
subgraph = adj[np.ix_(neighbors, neighbors)]
|
| 293 |
+
edges = subgraph.sum() / 2
|
| 294 |
+
max_edges = k * (k - 1) / 2
|
| 295 |
+
clustering[i] = edges / max_edges if max_edges > 0 else 0
|
| 296 |
+
|
| 297 |
+
adj2 = adj @ adj
|
| 298 |
+
np.fill_diagonal(adj2, 0)
|
| 299 |
+
second_degree = (adj2 > 0).sum(axis=1).astype(np.float32)
|
| 300 |
+
|
| 301 |
+
degree_norm = degree / (degree.max() + 1e-8)
|
| 302 |
+
second_degree_norm = second_degree / (second_degree.max() + 1e-8)
|
| 303 |
+
|
| 304 |
+
return np.stack([degree_norm, clustering, second_degree_norm], axis=1)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def compute_interface_features(coords: np.ndarray, is_protein: np.ndarray, cutoff: float = 5.0) -> np.ndarray:
|
| 308 |
+
"""界面特征"""
|
| 309 |
+
N = coords.shape[0]
|
| 310 |
+
prot_mask = is_protein.flatten() > 0.5
|
| 311 |
+
|
| 312 |
+
coords_prot = coords[prot_mask]
|
| 313 |
+
coords_lig = coords[~prot_mask]
|
| 314 |
+
|
| 315 |
+
dist_prot_to_lig = cdist(coords_prot, coords_lig)
|
| 316 |
+
prot_min_dist = dist_prot_to_lig.min(axis=1)
|
| 317 |
+
|
| 318 |
+
dist_lig_to_prot = cdist(coords_lig, coords_prot)
|
| 319 |
+
lig_min_dist = dist_lig_to_prot.min(axis=1)
|
| 320 |
+
|
| 321 |
+
is_interface = np.zeros((N, 1), dtype=np.float32)
|
| 322 |
+
interface_distance = np.zeros((N, 1), dtype=np.float32)
|
| 323 |
+
|
| 324 |
+
prot_idx = np.where(prot_mask)[0]
|
| 325 |
+
lig_idx = np.where(~prot_mask)[0]
|
| 326 |
+
|
| 327 |
+
for i, idx in enumerate(prot_idx):
|
| 328 |
+
is_interface[idx] = 1.0 if prot_min_dist[i] <= cutoff else 0.0
|
| 329 |
+
interface_distance[idx] = prot_min_dist[i]
|
| 330 |
+
|
| 331 |
+
for i, idx in enumerate(lig_idx):
|
| 332 |
+
is_interface[idx] = 1.0 if lig_min_dist[i] <= cutoff else 0.0
|
| 333 |
+
interface_distance[idx] = lig_min_dist[i]
|
| 334 |
+
|
| 335 |
+
interface_distance = np.clip(interface_distance / 10.0, 0, 1)
|
| 336 |
+
|
| 337 |
+
return np.concatenate([is_interface, interface_distance], axis=1)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def compute_local_environment_features(coords: np.ndarray, elements: List[str], cutoff: float = 5.0) -> np.ndarray:
|
| 341 |
+
"""局部环境特征"""
|
| 342 |
+
N = coords.shape[0]
|
| 343 |
+
dist_matrix = cdist(coords, coords)
|
| 344 |
+
mask = (dist_matrix <= cutoff) & (dist_matrix > 0)
|
| 345 |
+
|
| 346 |
+
elem_to_idx = {"C": 0, "N": 1, "O": 2, "S": 3}
|
| 347 |
+
|
| 348 |
+
neighbor_composition = np.zeros((N, 4), dtype=np.float32)
|
| 349 |
+
neighbor_electroneg = np.zeros((N, 1), dtype=np.float32)
|
| 350 |
+
neighbor_mass = np.zeros((N, 1), dtype=np.float32)
|
| 351 |
+
|
| 352 |
+
for i in range(N):
|
| 353 |
+
neighbor_idx = np.where(mask[i])[0]
|
| 354 |
+
if len(neighbor_idx) == 0:
|
| 355 |
+
continue
|
| 356 |
+
|
| 357 |
+
for j in neighbor_idx:
|
| 358 |
+
elem = elements[j]
|
| 359 |
+
if elem in elem_to_idx:
|
| 360 |
+
neighbor_composition[i, elem_to_idx[elem]] += 1
|
| 361 |
+
neighbor_electroneg[i] += ELECTRONEGATIVITY.get(elem, 2.5)
|
| 362 |
+
neighbor_mass[i] += ATOMIC_MASS.get(elem, 12.0)
|
| 363 |
+
|
| 364 |
+
n = len(neighbor_idx)
|
| 365 |
+
neighbor_composition[i] /= n
|
| 366 |
+
neighbor_electroneg[i] /= n
|
| 367 |
+
neighbor_mass[i] /= n
|
| 368 |
+
|
| 369 |
+
neighbor_electroneg = (neighbor_electroneg - 2.5) / 1.5
|
| 370 |
+
neighbor_mass = np.log1p(neighbor_mass) / 5.0
|
| 371 |
+
|
| 372 |
+
return np.concatenate([neighbor_composition, neighbor_electroneg, neighbor_mass], axis=1)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# =============================================================================
|
| 376 |
+
# 核心构图函数
|
| 377 |
+
# =============================================================================
|
| 378 |
+
|
| 379 |
+
def build_graph_enhanced(
|
| 380 |
+
protein_pdb: str,
|
| 381 |
+
ligand_pred_pdb: str,
|
| 382 |
+
ligand_native_pdb: str,
|
| 383 |
+
cutoff: float = 6.0,
|
| 384 |
+
neighbor_radii: Sequence[float] = (3.0, 5.0, 8.0),
|
| 385 |
+
use_enhanced_features: bool = True,
|
| 386 |
+
) -> Data:
|
| 387 |
+
"""
|
| 388 |
+
构建增强版蛋白-配体图
|
| 389 |
+
|
| 390 |
+
Args:
|
| 391 |
+
protein_pdb: 蛋白结构文件
|
| 392 |
+
ligand_pred_pdb: 配体预测结构 (docking pose)
|
| 393 |
+
ligand_native_pdb: 配体真实结构 (ground truth)
|
| 394 |
+
cutoff: 构图距离阈值
|
| 395 |
+
neighbor_radii: 邻居统计的距离半径
|
| 396 |
+
use_enhanced_features: 是否使用增强特征 (82维),否则使用基础特征 (~40维)
|
| 397 |
+
|
| 398 |
+
Returns:
|
| 399 |
+
Data: 包含节点特征、边、标签的图数据
|
| 400 |
+
"""
|
| 401 |
+
# ---- 1. 读取文件 ----
|
| 402 |
+
u_p = load_pdb_clean_models(protein_pdb)
|
| 403 |
+
u_l_pred = load_pdb_clean_models(ligand_pred_pdb)
|
| 404 |
+
u_l_native = load_pdb_clean_models(ligand_native_pdb)
|
| 405 |
+
|
| 406 |
+
prot_atoms = u_p.select_atoms("not name H*")
|
| 407 |
+
lig_pred_atoms = u_l_pred.select_atoms("not name H*")
|
| 408 |
+
lig_native_atoms = u_l_native.select_atoms("not name H*")
|
| 409 |
+
|
| 410 |
+
coords_prot = prot_atoms.positions.astype(np.float32)
|
| 411 |
+
coords_lig_pred = lig_pred_atoms.positions.astype(np.float32)
|
| 412 |
+
coords_lig_native = lig_native_atoms.positions.astype(np.float32)
|
| 413 |
+
|
| 414 |
+
Np = coords_prot.shape[0]
|
| 415 |
+
Nl = coords_lig_pred.shape[0]
|
| 416 |
+
N = Np + Nl
|
| 417 |
+
|
| 418 |
+
# 检查配体原子数是否匹配
|
| 419 |
+
if coords_lig_pred.shape[0] != coords_lig_native.shape[0]:
|
| 420 |
+
raise ValueError(f"配体原子数不匹配: pred={coords_lig_pred.shape[0]}, native={coords_lig_native.shape[0]}")
|
| 421 |
+
|
| 422 |
+
# ---- 2. 计算误差标签 ----
|
| 423 |
+
# 蛋白原子误差 = 0 (蛋白位置固定)
|
| 424 |
+
errors_prot = np.zeros(Np, dtype=np.float32)
|
| 425 |
+
|
| 426 |
+
# 配体原子误差 = |pred - native|
|
| 427 |
+
errors_lig = np.linalg.norm(coords_lig_pred - coords_lig_native, axis=1).astype(np.float32)
|
| 428 |
+
|
| 429 |
+
y_true = np.concatenate([errors_prot, errors_lig]) # [N]
|
| 430 |
+
|
| 431 |
+
# 预测坐标和真实坐标 (用于评估时计算区间)
|
| 432 |
+
coords_all_pred = np.vstack([coords_prot, coords_lig_pred]) # [N, 3]
|
| 433 |
+
coords_all_native = np.vstack([coords_prot, coords_lig_native]) # [N, 3]
|
| 434 |
+
|
| 435 |
+
# y_pred 和 y_grt 存储完整的三维坐标
|
| 436 |
+
# 评估时用 |y_pred - y_grt| 计算实际误差,检查是否 <= radius
|
| 437 |
+
y_pred = coords_all_pred # [N, 3]
|
| 438 |
+
y_grt = coords_all_native # [N, 3]
|
| 439 |
+
|
| 440 |
+
# ---- 3. 合并原子列表 ----
|
| 441 |
+
all_atoms = list(prot_atoms) + list(lig_pred_atoms)
|
| 442 |
+
elements = [_get_element(atom) for atom in all_atoms]
|
| 443 |
+
|
| 444 |
+
# ---- 4. 基础特征 ----
|
| 445 |
+
# 元素 one-hot
|
| 446 |
+
atom_type_oh = np.stack([
|
| 447 |
+
_one_hot(ELEMENT2IDX.get(elem, ELEMENT2IDX["Other"]), len(ELEMENTS))
|
| 448 |
+
for elem in elements
|
| 449 |
+
])
|
| 450 |
+
|
| 451 |
+
# 残基类型 one-hot
|
| 452 |
+
res_type_oh = []
|
| 453 |
+
for i, atom in enumerate(all_atoms):
|
| 454 |
+
if i < Np:
|
| 455 |
+
resname = atom.resname.strip().upper()
|
| 456 |
+
idx = AA3_2IDX.get(resname, len(AA3))
|
| 457 |
+
else:
|
| 458 |
+
idx = len(AA3)
|
| 459 |
+
res_type_oh.append(_one_hot(idx, AA_DIM))
|
| 460 |
+
res_type_oh = np.stack(res_type_oh)
|
| 461 |
+
|
| 462 |
+
# is_protein / is_ligand
|
| 463 |
+
is_protein = np.zeros((N, 1), dtype=np.float32)
|
| 464 |
+
is_protein[:Np] = 1.0
|
| 465 |
+
is_ligand = 1.0 - is_protein
|
| 466 |
+
|
| 467 |
+
# ---- 5. 距离特征 ----
|
| 468 |
+
prot_center = coords_prot.mean(axis=0, keepdims=True)
|
| 469 |
+
lig_center = coords_lig_pred.mean(axis=0, keepdims=True)
|
| 470 |
+
|
| 471 |
+
d_prot_center = np.linalg.norm(coords_all_pred - prot_center, axis=1, keepdims=True)
|
| 472 |
+
d_lig_center = np.linalg.norm(coords_all_pred - lig_center, axis=1, keepdims=True)
|
| 473 |
+
|
| 474 |
+
dist_all = cdist(coords_all_pred, coords_all_pred)
|
| 475 |
+
d_min_prot = cdist(coords_all_pred, coords_prot).min(axis=1, keepdims=True)
|
| 476 |
+
d_min_lig = cdist(coords_all_pred, coords_lig_pred).min(axis=1, keepdims=True)
|
| 477 |
+
|
| 478 |
+
# 归一化
|
| 479 |
+
d_prot_center_norm = d_prot_center / 50.0
|
| 480 |
+
d_lig_center_norm = d_lig_center / 30.0
|
| 481 |
+
d_min_prot_norm = d_min_prot / 20.0
|
| 482 |
+
d_min_lig_norm = d_min_lig / 20.0
|
| 483 |
+
|
| 484 |
+
# ---- 6. 构建特征 ----
|
| 485 |
+
if use_enhanced_features:
|
| 486 |
+
# 增强特征 (82维)
|
| 487 |
+
local_geom_feat = compute_local_geometry_features(coords_all_pred, radii=neighbor_radii)
|
| 488 |
+
dist_stat_feat = compute_distance_statistics(coords_all_pred, coords_prot, coords_lig_pred) / 20.0
|
| 489 |
+
chem_feat = compute_chemical_features(all_atoms, elements)
|
| 490 |
+
prot_specific_feat = compute_protein_specific_features(all_atoms, is_protein)
|
| 491 |
+
topo_feat = compute_topology_features(dist_all, cutoff=cutoff)
|
| 492 |
+
interface_feat = compute_interface_features(coords_all_pred, is_protein)
|
| 493 |
+
local_env_feat = compute_local_environment_features(coords_all_pred, elements, cutoff=5.0)
|
| 494 |
+
|
| 495 |
+
data_x = np.concatenate([
|
| 496 |
+
atom_type_oh, # 11
|
| 497 |
+
res_type_oh, # 21
|
| 498 |
+
is_protein, # 1
|
| 499 |
+
is_ligand, # 1
|
| 500 |
+
d_prot_center_norm, # 1
|
| 501 |
+
d_lig_center_norm, # 1
|
| 502 |
+
d_min_prot_norm, # 1
|
| 503 |
+
d_min_lig_norm, # 1
|
| 504 |
+
local_geom_feat, # 9
|
| 505 |
+
dist_stat_feat, # 14
|
| 506 |
+
chem_feat, # 5
|
| 507 |
+
prot_specific_feat, # 5
|
| 508 |
+
topo_feat, # 3
|
| 509 |
+
interface_feat, # 2
|
| 510 |
+
local_env_feat, # 6
|
| 511 |
+
], axis=1).astype(np.float32)
|
| 512 |
+
else:
|
| 513 |
+
# 基础特征 (~40维)
|
| 514 |
+
neighbor_feats = []
|
| 515 |
+
for r in neighbor_radii[:2]: # 只用前两个半径
|
| 516 |
+
mask = (dist_all <= r) & (~np.eye(N, dtype=bool))
|
| 517 |
+
n_nb = mask.sum(axis=1, keepdims=True)
|
| 518 |
+
neighbor_feats.append(n_nb.astype(np.float32))
|
| 519 |
+
neighbor_feats = np.concatenate(neighbor_feats, axis=1)
|
| 520 |
+
|
| 521 |
+
data_x = np.concatenate([
|
| 522 |
+
atom_type_oh,
|
| 523 |
+
res_type_oh,
|
| 524 |
+
is_protein,
|
| 525 |
+
is_ligand,
|
| 526 |
+
d_prot_center_norm,
|
| 527 |
+
d_lig_center_norm,
|
| 528 |
+
d_min_prot_norm,
|
| 529 |
+
d_min_lig_norm,
|
| 530 |
+
neighbor_feats,
|
| 531 |
+
], axis=1).astype(np.float32)
|
| 532 |
+
|
| 533 |
+
# ---- 7. 构建边 ----
|
| 534 |
+
mask = (dist_all <= cutoff) & (~np.eye(N, dtype=bool))
|
| 535 |
+
src, dst = np.where(mask)
|
| 536 |
+
edge_index = np.vstack([src, dst]).astype(np.int64)
|
| 537 |
+
|
| 538 |
+
# ---- 8. 边特征 ----
|
| 539 |
+
if use_enhanced_features:
|
| 540 |
+
edge_dist = dist_all[src, dst]
|
| 541 |
+
edge_attr = np.stack([
|
| 542 |
+
edge_dist / cutoff,
|
| 543 |
+
np.exp(-edge_dist / 3.0),
|
| 544 |
+
(src < Np).astype(np.float32),
|
| 545 |
+
(dst < Np).astype(np.float32),
|
| 546 |
+
], axis=1).astype(np.float32)
|
| 547 |
+
else:
|
| 548 |
+
edge_attr = None
|
| 549 |
+
|
| 550 |
+
# ---- 9. 构建 Data ----
|
| 551 |
+
data = Data(
|
| 552 |
+
x=torch.from_numpy(data_x),
|
| 553 |
+
edge_index=torch.from_numpy(edge_index),
|
| 554 |
+
pos=torch.from_numpy(coords_all_pred),
|
| 555 |
+
is_protein=torch.from_numpy(is_protein),
|
| 556 |
+
y_true=torch.from_numpy(y_true).unsqueeze(-1), # [N, 1] 误差
|
| 557 |
+
y_pred=torch.from_numpy(y_pred), # [N, 3] 预测坐标
|
| 558 |
+
y_grt=torch.from_numpy(y_grt), # [N, 3] 真实坐标
|
| 559 |
+
num_nodes=N,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if edge_attr is not None:
|
| 563 |
+
data.edge_attr = torch.from_numpy(edge_attr)
|
| 564 |
+
|
| 565 |
+
return data
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
# =============================================================================
|
| 569 |
+
# 批量处理函数
|
| 570 |
+
# =============================================================================
|
| 571 |
+
|
| 572 |
+
def find_docking_poses(
|
| 573 |
+
pdb_dir: str,
|
| 574 |
+
docking_type: str = "protenix",
|
| 575 |
+
) -> List[Dict[str, str]]:
|
| 576 |
+
"""
|
| 577 |
+
自动发现目录中的 docking poses
|
| 578 |
+
|
| 579 |
+
支持的目录结构:
|
| 580 |
+
- protenix: {target}_{lig_id}/lig_{id}_pose*.pdb 或 {pdb_id}_pose_*.pdb
|
| 581 |
+
- diffdock: {pdb_id}/rank*_confidence*.sdf 或 *pose*.pdb
|
| 582 |
+
- autodock_vina: {pdb_id}/vina_pose_*.pdb 或 *pose*.pdb
|
| 583 |
+
- medusagraph: {pdb_id}/medusa_pose_*.pdb 或 *pose*.pdb
|
| 584 |
+
|
| 585 |
+
Returns:
|
| 586 |
+
List of dicts with keys: pdb_id, protein, ligand_pred, ligand_native
|
| 587 |
+
"""
|
| 588 |
+
poses = []
|
| 589 |
+
|
| 590 |
+
for pdb_id in os.listdir(pdb_dir):
|
| 591 |
+
subdir = os.path.join(pdb_dir, pdb_id)
|
| 592 |
+
if not os.path.isdir(subdir):
|
| 593 |
+
continue
|
| 594 |
+
|
| 595 |
+
# 找蛋白文件
|
| 596 |
+
protein_file = None
|
| 597 |
+
for name in ["protein.pdb", f"{pdb_id}_protein.pdb", "receptor.pdb"]:
|
| 598 |
+
path = os.path.join(subdir, name)
|
| 599 |
+
if os.path.exists(path):
|
| 600 |
+
protein_file = path
|
| 601 |
+
break
|
| 602 |
+
|
| 603 |
+
if protein_file is None:
|
| 604 |
+
continue
|
| 605 |
+
|
| 606 |
+
# 找原生配体 (增加 ligands.pdb)
|
| 607 |
+
native_file = None
|
| 608 |
+
for name in ["ligands.pdb", "ligand.pdb", "ligand_native.pdb", f"{pdb_id}_ligand.pdb", "native.pdb"]:
|
| 609 |
+
path = os.path.join(subdir, name)
|
| 610 |
+
if os.path.exists(path):
|
| 611 |
+
native_file = path
|
| 612 |
+
break
|
| 613 |
+
|
| 614 |
+
if native_file is None:
|
| 615 |
+
continue
|
| 616 |
+
|
| 617 |
+
# 找 docking poses (更灵活的匹配)
|
| 618 |
+
pose_files = []
|
| 619 |
+
|
| 620 |
+
if docking_type == "protenix":
|
| 621 |
+
# 尝试多种模式
|
| 622 |
+
patterns = [
|
| 623 |
+
os.path.join(subdir, f"*_pose*.pdb"), # lig_1_pose1.pdb, xxx_pose_01.pdb
|
| 624 |
+
os.path.join(subdir, f"{pdb_id}_pose_*.pdb"), # cdk2_lig_1_pose_01.pdb
|
| 625 |
+
]
|
| 626 |
+
elif docking_type == "diffdock":
|
| 627 |
+
patterns = [
|
| 628 |
+
os.path.join(subdir, f"*_pose*.pdb"),
|
| 629 |
+
os.path.join(subdir, f"rank*.pdb"),
|
| 630 |
+
os.path.join(subdir, f"rank*_confidence*.sdf"),
|
| 631 |
+
]
|
| 632 |
+
elif docking_type == "autodock_vina":
|
| 633 |
+
patterns = [
|
| 634 |
+
os.path.join(subdir, f"*_pose*.pdb"),
|
| 635 |
+
os.path.join(subdir, "vina_pose_*.pdb"),
|
| 636 |
+
os.path.join(subdir, "vina_out*.pdb"),
|
| 637 |
+
]
|
| 638 |
+
elif docking_type == "medusagraph":
|
| 639 |
+
patterns = [
|
| 640 |
+
os.path.join(subdir, f"*_pose*.pdb"),
|
| 641 |
+
os.path.join(subdir, "medusa_pose_*.pdb"),
|
| 642 |
+
]
|
| 643 |
+
else:
|
| 644 |
+
patterns = [os.path.join(subdir, f"*pose*.pdb")]
|
| 645 |
+
|
| 646 |
+
for pattern in patterns:
|
| 647 |
+
pose_files.extend(glob.glob(pattern))
|
| 648 |
+
|
| 649 |
+
# 去重并排除原生配体文件
|
| 650 |
+
pose_files = list(set(pose_files))
|
| 651 |
+
pose_files = [f for f in pose_files if os.path.basename(f) not in ["ligands.pdb", "ligand.pdb", "native.pdb"]]
|
| 652 |
+
|
| 653 |
+
for pose_file in pose_files:
|
| 654 |
+
poses.append({
|
| 655 |
+
'pdb_id': pdb_id,
|
| 656 |
+
'protein': protein_file,
|
| 657 |
+
'ligand_pred': pose_file,
|
| 658 |
+
'ligand_native': native_file,
|
| 659 |
+
})
|
| 660 |
+
|
| 661 |
+
return poses
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def _build_single_graph(args):
|
| 665 |
+
"""单个图构建函数 (用于多进程)"""
|
| 666 |
+
pose, cutoff, use_enhanced_features, temp_dir = args
|
| 667 |
+
try:
|
| 668 |
+
data = build_graph_enhanced(
|
| 669 |
+
protein_pdb=pose['protein'],
|
| 670 |
+
ligand_pred_pdb=pose['ligand_pred'],
|
| 671 |
+
ligand_native_pdb=pose['ligand_native'],
|
| 672 |
+
cutoff=cutoff,
|
| 673 |
+
use_enhanced_features=use_enhanced_features,
|
| 674 |
+
)
|
| 675 |
+
# 保存到临时文件,避免跨进程传输 PyTorch tensor
|
| 676 |
+
temp_file = os.path.join(temp_dir, f"{pose['pdb_id']}_{os.path.basename(pose['ligand_pred'])}.pt")
|
| 677 |
+
torch.save(data, temp_file)
|
| 678 |
+
return ('success', temp_file)
|
| 679 |
+
except Exception as e:
|
| 680 |
+
return ('error', (pose['pdb_id'], str(e)))
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def build_dataset(
|
| 684 |
+
data_dir: str,
|
| 685 |
+
output_path: str,
|
| 686 |
+
docking_type: str = "protenix",
|
| 687 |
+
cutoff: float = 6.0,
|
| 688 |
+
use_enhanced_features: bool = True,
|
| 689 |
+
max_samples: int = None,
|
| 690 |
+
num_workers: int = 1,
|
| 691 |
+
) -> None:
|
| 692 |
+
"""
|
| 693 |
+
批量构建数据集
|
| 694 |
+
|
| 695 |
+
Args:
|
| 696 |
+
data_dir: 数据目录
|
| 697 |
+
output_path: 输出文件路径
|
| 698 |
+
docking_type: docking 类型
|
| 699 |
+
cutoff: 构图阈值
|
| 700 |
+
use_enhanced_features: 是否使用增强特征
|
| 701 |
+
max_samples: 最大样本数 (用于测试)
|
| 702 |
+
num_workers: 并行进程数 (默认 1,设为 -1 使用所有 CPU)
|
| 703 |
+
"""
|
| 704 |
+
import multiprocessing as mp
|
| 705 |
+
import tempfile
|
| 706 |
+
import shutil
|
| 707 |
+
|
| 708 |
+
print(f"扫描目录: {data_dir}")
|
| 709 |
+
poses = find_docking_poses(data_dir, docking_type)
|
| 710 |
+
print(f"发现 {len(poses)} 个 docking poses")
|
| 711 |
+
|
| 712 |
+
if max_samples is not None:
|
| 713 |
+
poses = poses[:max_samples]
|
| 714 |
+
print(f"限制为 {max_samples} 个样本")
|
| 715 |
+
|
| 716 |
+
# 确定进程数
|
| 717 |
+
if num_workers == -1:
|
| 718 |
+
num_workers = mp.cpu_count()
|
| 719 |
+
elif num_workers <= 0:
|
| 720 |
+
num_workers = 1
|
| 721 |
+
|
| 722 |
+
graphs = []
|
| 723 |
+
errors = []
|
| 724 |
+
|
| 725 |
+
if num_workers == 1:
|
| 726 |
+
# 单进程模式
|
| 727 |
+
for pose in tqdm(poses, desc="构建图"):
|
| 728 |
+
try:
|
| 729 |
+
data = build_graph_enhanced(
|
| 730 |
+
protein_pdb=pose['protein'],
|
| 731 |
+
ligand_pred_pdb=pose['ligand_pred'],
|
| 732 |
+
ligand_native_pdb=pose['ligand_native'],
|
| 733 |
+
cutoff=cutoff,
|
| 734 |
+
use_enhanced_features=use_enhanced_features,
|
| 735 |
+
)
|
| 736 |
+
graphs.append(data)
|
| 737 |
+
except Exception as e:
|
| 738 |
+
errors.append((pose['pdb_id'], str(e)))
|
| 739 |
+
else:
|
| 740 |
+
# 多进程模式 - 使用临时目录存储中间结果
|
| 741 |
+
print(f"使用 {num_workers} 个进程并行构建")
|
| 742 |
+
|
| 743 |
+
# 创建临时目录
|
| 744 |
+
temp_dir = tempfile.mkdtemp(prefix="graph_build_")
|
| 745 |
+
print(f"临时目录: {temp_dir}")
|
| 746 |
+
|
| 747 |
+
try:
|
| 748 |
+
# 准备参数
|
| 749 |
+
args_list = [(pose, cutoff, use_enhanced_features, temp_dir) for pose in poses]
|
| 750 |
+
|
| 751 |
+
# 使用进程池
|
| 752 |
+
with mp.Pool(processes=num_workers) as pool:
|
| 753 |
+
results = list(tqdm(
|
| 754 |
+
pool.imap(_build_single_graph, args_list),
|
| 755 |
+
total=len(args_list),
|
| 756 |
+
desc=f"构建图 ({num_workers} workers)"
|
| 757 |
+
))
|
| 758 |
+
|
| 759 |
+
# 收集结果
|
| 760 |
+
print("正在收集结果...")
|
| 761 |
+
temp_files = []
|
| 762 |
+
for result in results:
|
| 763 |
+
if result[0] == 'success':
|
| 764 |
+
temp_files.append(result[1])
|
| 765 |
+
else:
|
| 766 |
+
errors.append(result[1])
|
| 767 |
+
|
| 768 |
+
# 从临时文件加载数据
|
| 769 |
+
for temp_file in tqdm(temp_files, desc="加载图数据"):
|
| 770 |
+
try:
|
| 771 |
+
data = torch.load(temp_file, weights_only=False)
|
| 772 |
+
graphs.append(data)
|
| 773 |
+
except Exception as e:
|
| 774 |
+
errors.append(("load_error", str(e)))
|
| 775 |
+
|
| 776 |
+
finally:
|
| 777 |
+
# 清理临时目录
|
| 778 |
+
print(f"清理临时目录...")
|
| 779 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 780 |
+
|
| 781 |
+
print(f"\n成功: {len(graphs)} | 失败: {len(errors)}")
|
| 782 |
+
|
| 783 |
+
if errors and len(errors) <= 10:
|
| 784 |
+
print("失败样本:")
|
| 785 |
+
for pdb_id, err in errors:
|
| 786 |
+
print(f" {pdb_id}: {err}")
|
| 787 |
+
|
| 788 |
+
# 保存
|
| 789 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 790 |
+
torch.save(graphs, output_path)
|
| 791 |
+
print(f"\n数据集已保存到: {output_path}")
|
| 792 |
+
|
| 793 |
+
# 统计
|
| 794 |
+
if graphs:
|
| 795 |
+
n_nodes = sum(g.num_nodes for g in graphs)
|
| 796 |
+
n_edges = sum(g.edge_index.shape[1] for g in graphs)
|
| 797 |
+
feature_dim = graphs[0].x.shape[1]
|
| 798 |
+
has_edge_attr = hasattr(graphs[0], 'edge_attr') and graphs[0].edge_attr is not None
|
| 799 |
+
|
| 800 |
+
print(f"\n数据集统计:")
|
| 801 |
+
print(f" 图数量: {len(graphs)}")
|
| 802 |
+
print(f" 总节点数: {n_nodes}")
|
| 803 |
+
print(f" 总边数: {n_edges}")
|
| 804 |
+
print(f" 节点特征维度: {feature_dim}")
|
| 805 |
+
print(f" 边特征: {'有' if has_edge_attr else '无'}")
|
| 806 |
+
|
| 807 |
+
# 误差统计
|
| 808 |
+
all_errors = []
|
| 809 |
+
for g in graphs:
|
| 810 |
+
is_prot = g.is_protein.squeeze(-1)
|
| 811 |
+
y_true = g.y_true.squeeze(-1)
|
| 812 |
+
lig_mask = (is_prot == 0)
|
| 813 |
+
all_errors.append(y_true[lig_mask])
|
| 814 |
+
|
| 815 |
+
all_errors = torch.cat(all_errors)
|
| 816 |
+
print(f"\n误差统计 (配体原子):")
|
| 817 |
+
print(f" 样本数: {len(all_errors)}")
|
| 818 |
+
print(f" 均值: {all_errors.mean():.4f} Å")
|
| 819 |
+
print(f" 中位数: {all_errors.median():.4f} Å")
|
| 820 |
+
print(f" 标准差: {all_errors.std():.4f} Å")
|
| 821 |
+
print(f" 范围: [{all_errors.min():.4f}, {all_errors.max():.4f}] Å")
|
| 822 |
+
print(f" 90% 分位: {torch.quantile(all_errors, 0.9):.4f} Å")
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
# =============================================================================
|
| 826 |
+
# 命令行接口
|
| 827 |
+
# =============================================================================
|
| 828 |
+
|
| 829 |
+
def main():
|
| 830 |
+
parser = argparse.ArgumentParser(description="构建增强版蛋白-配体图数据集")
|
| 831 |
+
|
| 832 |
+
parser.add_argument("--data_dir", type=str, required=True, help="数据目录")
|
| 833 |
+
parser.add_argument("--output", type=str, required=True, help="输出文件路径")
|
| 834 |
+
parser.add_argument("--docking_type", type=str, default="protenix",
|
| 835 |
+
choices=["protenix", "diffdock", "autodock_vina", "medusagraph"],
|
| 836 |
+
help="Docking 类型")
|
| 837 |
+
parser.add_argument("--cutoff", type=float, default=6.0, help="构图距离阈值")
|
| 838 |
+
parser.add_argument("--no_enhanced", action="store_true", help="不使用增强特征")
|
| 839 |
+
parser.add_argument("--max_samples", type=int, default=None, help="最大样本数")
|
| 840 |
+
parser.add_argument("--num_workers", type=int, default=1,
|
| 841 |
+
help="并行进程数 (默认 1,设为 -1 使用所有 CPU)")
|
| 842 |
+
|
| 843 |
+
args = parser.parse_args()
|
| 844 |
+
|
| 845 |
+
build_dataset(
|
| 846 |
+
data_dir=args.data_dir,
|
| 847 |
+
output_path=args.output,
|
| 848 |
+
docking_type=args.docking_type,
|
| 849 |
+
cutoff=args.cutoff,
|
| 850 |
+
use_enhanced_features=not args.no_enhanced,
|
| 851 |
+
max_samples=args.max_samples,
|
| 852 |
+
num_workers=args.num_workers,
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
if __name__ == "__main__":
|
| 857 |
+
main()
|
| 858 |
+
|
| 859 |
+
# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/protenix --output /work/nvme/bghp/hhao/gnncp/datasets_all/protenix_enhanced_graphs.pt --docking_type protenix --num_workers -1
|
| 860 |
+
# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/diffdock --output /work/nvme/bghp/hhao/gnncp/datasets_all/diffdock_enhanced_graphs.pt --docking_type diffdock --num_workers -1
|
| 861 |
+
# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/medusagraph --output /work/nvme/bghp/hhao/gnncp/datasets_all/medusagraph_enhanced_graphs.pt --docking_type medusagraph --num_workers -1
|
| 862 |
+
# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/autodock_vina --output /work/nvme/bghp/hhao/gnncp/datasets_all/autodock_vina_enhanced_graphs.pt --docking_type autodock_vina --num_workers -1
|
| 863 |
+
# salloc -t 06:00:00 --mem=128g --account=beyd-delta-cpu --partition=cpu --nodes=1 --tasks=1 --tasks-per-node=1 --cpus-per-task=24
|
| 864 |
+
# salloc -t 03:00:00 --mem=64g --account=beyd-delta-cpu --partition=cpu --nodes=1 --tasks=1 --tasks-per-node=1 --cpus-per-task=16
|
code/compact_v1/build_system_index.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Build graph→system index for each enhanced dataset + global split assignment.
|
| 4 |
+
|
| 5 |
+
Two outputs:
|
| 6 |
+
|
| 7 |
+
1. Per-method graph→system mapping (needed to know which graph belongs to which system):
|
| 8 |
+
datasets_all/{method}_system_index.json
|
| 9 |
+
{ "graph_to_system": ["cdk2_lig_1", ...], "systems": [...], ... }
|
| 10 |
+
|
| 11 |
+
2. Global split assignment (shared across ALL methods, generated once):
|
| 12 |
+
datasets_all/system_split_assignment.json
|
| 13 |
+
{ "train": ["cdk2_lig_1", ...],
|
| 14 |
+
"val": ["mcl1_lig_5", ...],
|
| 15 |
+
"calib": ["syk_lig_10", ...],
|
| 16 |
+
"test": ["cdk8_lig_3", ...],
|
| 17 |
+
"seed": 42,
|
| 18 |
+
"ratios": {"train": 0.70, "val": 0.10, "calib": 0.10, "test": 0.10} }
|
| 19 |
+
|
| 20 |
+
The split assignment uses the FULL system list from autodock_vina (as reference)
|
| 21 |
+
to ensure all 4 methods use the exact same split.
|
| 22 |
+
|
| 23 |
+
Usage:
|
| 24 |
+
python build_system_index.py
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import os
|
| 28 |
+
import json
|
| 29 |
+
import time
|
| 30 |
+
from collections import defaultdict
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
import torch
|
| 34 |
+
from torch_geometric.data import Data
|
| 35 |
+
|
| 36 |
+
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 37 |
+
|
| 38 |
+
from build_graph_unified_enhanced import load_pdb_clean_models
|
| 39 |
+
|
| 40 |
+
torch.serialization.add_safe_globals([Data])
|
| 41 |
+
|
| 42 |
+
# Data directories: siblings of system_split/
|
| 43 |
+
# Structure: parent_dir/system_split/ (this), parent_dir/filtered_output/, parent_dir/datasets_all/
|
| 44 |
+
PARENT_DIR = os.path.dirname(SCRIPT_DIR)
|
| 45 |
+
DATA_DIR = os.path.join(PARENT_DIR, "filtered_output")
|
| 46 |
+
DATASETS_DIR = os.path.join(PARENT_DIR, "datasets_all")
|
| 47 |
+
|
| 48 |
+
METHODS = {
|
| 49 |
+
"autodock_vina": "autodock_vina_enhanced_graphs.pt",
|
| 50 |
+
"diffdock": "diffdock_enhanced_graphs.pt",
|
| 51 |
+
"medusagraph": "medusagraph_enhanced_graphs.pt",
|
| 52 |
+
"protenix": "protenix_enhanced_graphs.pt",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def compute_fingerprint(graph):
|
| 57 |
+
"""(n_lig_atoms, (cx, cy, cz)) from ligand ground truth centroid."""
|
| 58 |
+
is_prot = graph.is_protein.squeeze(-1)
|
| 59 |
+
lig_mask = is_prot == 0
|
| 60 |
+
n_lig = int(lig_mask.sum().item())
|
| 61 |
+
if n_lig == 0:
|
| 62 |
+
return (0, (0.0, 0.0, 0.0))
|
| 63 |
+
lig_grt = graph.y_grt[lig_mask]
|
| 64 |
+
centroid = lig_grt.mean(dim=0)
|
| 65 |
+
return (n_lig, (round(centroid[0].item(), 2),
|
| 66 |
+
round(centroid[1].item(), 2),
|
| 67 |
+
round(centroid[2].item(), 2)))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def read_native_centroid(pdb_path):
|
| 71 |
+
"""Read native ligand PDB → (n_heavy_atoms, (cx, cy, cz))."""
|
| 72 |
+
u = load_pdb_clean_models(pdb_path)
|
| 73 |
+
atoms = u.select_atoms("not name H*")
|
| 74 |
+
coords = atoms.positions.astype(np.float32)
|
| 75 |
+
n = coords.shape[0]
|
| 76 |
+
c = coords.mean(axis=0)
|
| 77 |
+
return (n, (round(float(c[0]), 2), round(float(c[1]), 2), round(float(c[2]), 2)))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def build_fp_to_system(method_subdir):
|
| 81 |
+
"""Build fingerprint → system name mapping from PDB files."""
|
| 82 |
+
method_dir = os.path.join(DATA_DIR, method_subdir)
|
| 83 |
+
systems = sorted([d for d in os.listdir(method_dir)
|
| 84 |
+
if os.path.isdir(os.path.join(method_dir, d))])
|
| 85 |
+
|
| 86 |
+
fp_to_system = {}
|
| 87 |
+
for system in systems:
|
| 88 |
+
native_path = os.path.join(method_dir, system, "ligands.pdb")
|
| 89 |
+
if not os.path.exists(native_path):
|
| 90 |
+
continue
|
| 91 |
+
try:
|
| 92 |
+
fp = read_native_centroid(native_path)
|
| 93 |
+
fp_to_system[fp] = system
|
| 94 |
+
except Exception:
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
return fp_to_system
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def match_graph_to_system(graph_fp, fp_to_system):
|
| 101 |
+
"""Exact match, then fuzzy match (same n_atoms, closest centroid < 0.5 Å)."""
|
| 102 |
+
if graph_fp in fp_to_system:
|
| 103 |
+
return fp_to_system[graph_fp]
|
| 104 |
+
|
| 105 |
+
n_lig, (cx, cy, cz) = graph_fp
|
| 106 |
+
best_dist = 999.0
|
| 107 |
+
best_sys = None
|
| 108 |
+
for fp, sys_name in fp_to_system.items():
|
| 109 |
+
fn, (fx, fy, fz) = fp
|
| 110 |
+
if fn != n_lig:
|
| 111 |
+
continue
|
| 112 |
+
dist = ((cx - fx)**2 + (cy - fy)**2 + (cz - fz)**2) ** 0.5
|
| 113 |
+
if dist < best_dist:
|
| 114 |
+
best_dist = dist
|
| 115 |
+
best_sys = sys_name
|
| 116 |
+
if best_dist < 0.5:
|
| 117 |
+
return best_sys
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def process_method(method_name, dataset_filename):
|
| 122 |
+
"""Build system index for one method."""
|
| 123 |
+
dataset_path = os.path.join(DATASETS_DIR, dataset_filename)
|
| 124 |
+
if not os.path.exists(dataset_path):
|
| 125 |
+
print(f" [SKIP] {dataset_path} not found")
|
| 126 |
+
return
|
| 127 |
+
|
| 128 |
+
print(f"\n{'='*60}")
|
| 129 |
+
print(f" {method_name}")
|
| 130 |
+
print(f"{'='*60}")
|
| 131 |
+
|
| 132 |
+
# Load dataset
|
| 133 |
+
print(f" Loading {dataset_path} ...")
|
| 134 |
+
t0 = time.time()
|
| 135 |
+
graphs = torch.load(dataset_path, weights_only=False)
|
| 136 |
+
n = len(graphs)
|
| 137 |
+
print(f" Loaded {n} graphs in {time.time()-t0:.1f}s")
|
| 138 |
+
|
| 139 |
+
# Build fingerprint → system mapping
|
| 140 |
+
print(f" Building fingerprint map from PDB files...")
|
| 141 |
+
fp_to_system = build_fp_to_system(method_name)
|
| 142 |
+
print(f" {len(fp_to_system)} systems from PDB files")
|
| 143 |
+
|
| 144 |
+
# Match each graph
|
| 145 |
+
print(f" Matching graphs to systems...")
|
| 146 |
+
graph_to_system = []
|
| 147 |
+
matched = 0
|
| 148 |
+
unmatched = 0
|
| 149 |
+
|
| 150 |
+
for i, g in enumerate(graphs):
|
| 151 |
+
fp = compute_fingerprint(g)
|
| 152 |
+
system = match_graph_to_system(fp, fp_to_system)
|
| 153 |
+
if system:
|
| 154 |
+
graph_to_system.append(system)
|
| 155 |
+
matched += 1
|
| 156 |
+
else:
|
| 157 |
+
graph_to_system.append("UNKNOWN")
|
| 158 |
+
unmatched += 1
|
| 159 |
+
|
| 160 |
+
print(f" Matched: {matched}/{n}, Unmatched: {unmatched}")
|
| 161 |
+
|
| 162 |
+
# Verify: count per system
|
| 163 |
+
system_counts = defaultdict(int)
|
| 164 |
+
for s in graph_to_system:
|
| 165 |
+
system_counts[s] += 1
|
| 166 |
+
|
| 167 |
+
systems = sorted([s for s in system_counts.keys() if s != "UNKNOWN"])
|
| 168 |
+
print(f" Unique systems: {len(systems)}")
|
| 169 |
+
|
| 170 |
+
counts = [system_counts[s] for s in systems]
|
| 171 |
+
print(f" Poses per system: min={min(counts)}, max={max(counts)}, "
|
| 172 |
+
f"median={sorted(counts)[len(counts)//2]}")
|
| 173 |
+
|
| 174 |
+
# Save
|
| 175 |
+
index_filename = dataset_filename.replace("_enhanced_graphs.pt", "_system_index.json")
|
| 176 |
+
index_path = os.path.join(DATASETS_DIR, index_filename)
|
| 177 |
+
|
| 178 |
+
index_data = {
|
| 179 |
+
"graph_to_system": graph_to_system,
|
| 180 |
+
"systems": systems,
|
| 181 |
+
"n_graphs": n,
|
| 182 |
+
"n_systems": len(systems),
|
| 183 |
+
"system_counts": dict(sorted(system_counts.items())),
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
with open(index_path, 'w') as f:
|
| 187 |
+
json.dump(index_data, f, indent=2)
|
| 188 |
+
print(f" Saved: {index_path}")
|
| 189 |
+
|
| 190 |
+
del graphs
|
| 191 |
+
return index_data
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
SPLIT_SEED = 42
|
| 195 |
+
TRAIN_RATIO = 0.70
|
| 196 |
+
VAL_RATIO = 0.10
|
| 197 |
+
CALIB_RATIO = 0.10
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def generate_split_assignment(all_systems, seed=SPLIT_SEED):
|
| 201 |
+
"""
|
| 202 |
+
Generate a global system-level split assignment.
|
| 203 |
+
Uses a canonical sorted list of all systems, shuffles with fixed seed,
|
| 204 |
+
then splits 70/10/10/10.
|
| 205 |
+
|
| 206 |
+
Returns dict with train/val/calib/test system lists.
|
| 207 |
+
"""
|
| 208 |
+
import random as _random
|
| 209 |
+
|
| 210 |
+
systems = sorted(all_systems)
|
| 211 |
+
n = len(systems)
|
| 212 |
+
|
| 213 |
+
rng = _random.Random(seed)
|
| 214 |
+
rng.shuffle(systems)
|
| 215 |
+
|
| 216 |
+
train_end = int(n * TRAIN_RATIO)
|
| 217 |
+
val_end = train_end + int(n * VAL_RATIO)
|
| 218 |
+
calib_end = val_end + int(n * CALIB_RATIO)
|
| 219 |
+
|
| 220 |
+
assignment = {
|
| 221 |
+
"train": sorted(systems[:train_end]),
|
| 222 |
+
"val": sorted(systems[train_end:val_end]),
|
| 223 |
+
"calib": sorted(systems[val_end:calib_end]),
|
| 224 |
+
"test": sorted(systems[calib_end:]),
|
| 225 |
+
"seed": seed,
|
| 226 |
+
"ratios": {
|
| 227 |
+
"train": TRAIN_RATIO,
|
| 228 |
+
"val": VAL_RATIO,
|
| 229 |
+
"calib": CALIB_RATIO,
|
| 230 |
+
"test": round(1.0 - TRAIN_RATIO - VAL_RATIO - CALIB_RATIO, 2),
|
| 231 |
+
},
|
| 232 |
+
"n_systems": n,
|
| 233 |
+
"n_train": train_end,
|
| 234 |
+
"n_val": val_end - train_end,
|
| 235 |
+
"n_calib": calib_end - val_end,
|
| 236 |
+
"n_test": n - calib_end,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
return assignment
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def main():
|
| 243 |
+
print("Building system indices for all datasets")
|
| 244 |
+
print(f"Data dir: {DATA_DIR}")
|
| 245 |
+
print(f"Datasets dir: {DATASETS_DIR}")
|
| 246 |
+
|
| 247 |
+
all_method_systems = {}
|
| 248 |
+
for method_name, dataset_filename in METHODS.items():
|
| 249 |
+
result = process_method(method_name, dataset_filename)
|
| 250 |
+
if result:
|
| 251 |
+
all_method_systems[method_name] = result["systems"]
|
| 252 |
+
|
| 253 |
+
# ---- Generate global split assignment ----
|
| 254 |
+
# Use the full system list (intersection of all methods to be safe)
|
| 255 |
+
if all_method_systems:
|
| 256 |
+
common_systems = set(all_method_systems[list(all_method_systems.keys())[0]])
|
| 257 |
+
for systems in all_method_systems.values():
|
| 258 |
+
common_systems &= set(systems)
|
| 259 |
+
common_systems = sorted(common_systems)
|
| 260 |
+
|
| 261 |
+
print(f"\n{'='*60}")
|
| 262 |
+
print(f" Global Split Assignment")
|
| 263 |
+
print(f"{'='*60}")
|
| 264 |
+
print(f" Common systems across all methods: {len(common_systems)}")
|
| 265 |
+
|
| 266 |
+
# Check if all methods have the same systems
|
| 267 |
+
for method, systems in all_method_systems.items():
|
| 268 |
+
diff = set(systems) - set(common_systems)
|
| 269 |
+
if diff:
|
| 270 |
+
print(f" [WARN] {method} has extra systems: {diff}")
|
| 271 |
+
|
| 272 |
+
assignment = generate_split_assignment(common_systems)
|
| 273 |
+
|
| 274 |
+
print(f" Train: {assignment['n_train']} systems")
|
| 275 |
+
print(f" Val: {assignment['n_val']} systems")
|
| 276 |
+
print(f" Calib: {assignment['n_calib']} systems")
|
| 277 |
+
print(f" Test: {assignment['n_test']} systems")
|
| 278 |
+
|
| 279 |
+
# Show per-target distribution in test set
|
| 280 |
+
target_counts = defaultdict(int)
|
| 281 |
+
for s in assignment["test"]:
|
| 282 |
+
target = s.rsplit("_lig_", 1)[0]
|
| 283 |
+
target_counts[target] += 1
|
| 284 |
+
print(f"\n Test set targets: {dict(sorted(target_counts.items()))}")
|
| 285 |
+
|
| 286 |
+
assignment_path = os.path.join(DATASETS_DIR, "system_split_assignment.json")
|
| 287 |
+
with open(assignment_path, 'w') as f:
|
| 288 |
+
json.dump(assignment, f, indent=2)
|
| 289 |
+
print(f" Saved: {assignment_path}")
|
| 290 |
+
|
| 291 |
+
print("\nDone!")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
main()
|
code/compact_v1/compact_graph_dataset.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
The compact format stores data that are shared by all poses of a system only
|
| 5 |
+
once. A sample is reconstructed on demand with the same public PyG schema as
|
| 6 |
+
``build_graph_unified_enhanced.py``:
|
| 7 |
+
|
| 8 |
+
``x, edge_index, edge_attr, pos, is_protein, y_true, y_pred, y_grt``.
|
| 9 |
+
|
| 10 |
+
Nothing in this module changes the model-facing feature dimensions. Node
|
| 11 |
+
features are reconstructed as float32 [N, 82] and edge features as float32
|
| 12 |
+
[E, 4].
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import bisect
|
| 18 |
+
import json
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch.utils.data import Dataset
|
| 25 |
+
from torch_geometric.data import Data
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
FORMAT_NAME = "gnncp_compact_v1"
|
| 29 |
+
SCHEMA_VERSION = 1
|
| 30 |
+
STATIC_WIDTH = 44
|
| 31 |
+
DYNAMIC_WIDTH = 38
|
| 32 |
+
NODE_WIDTH = 82
|
| 33 |
+
EDGE_WIDTH = 4
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CompactFormatError(RuntimeError):
|
| 37 |
+
"""Raised when a compact dataset does not satisfy the v1 contract."""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _as_edge_matrix(value: torch.Tensor, name: str) -> torch.Tensor:
|
| 41 |
+
"""Return an edge tensor as [2, E] without materialising when possible."""
|
| 42 |
+
if value.ndim != 2:
|
| 43 |
+
raise CompactFormatError(f"{name} must be rank 2, got shape={tuple(value.shape)}")
|
| 44 |
+
if value.shape[0] == 2:
|
| 45 |
+
return value
|
| 46 |
+
if value.shape[1] == 2:
|
| 47 |
+
return value.t()
|
| 48 |
+
raise CompactFormatError(f"{name} must have shape [2,E] or [E,2], got {tuple(value.shape)}")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _get_shard_path(entry: Mapping[str, Any]) -> str:
|
| 52 |
+
for key in ("path", "file", "filename"):
|
| 53 |
+
if key in entry:
|
| 54 |
+
return str(entry[key])
|
| 55 |
+
raise CompactFormatError("each manifest shard needs one of: path, file, filename")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _get_shard_graph_count(entry: Mapping[str, Any]) -> int:
|
| 59 |
+
for key in ("num_graphs", "n_graphs"):
|
| 60 |
+
if key in entry:
|
| 61 |
+
return int(entry[key])
|
| 62 |
+
raise CompactFormatError("each manifest shard needs num_graphs (or n_graphs)")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CompactGraphDataset(Dataset):
|
| 66 |
+
"""Map-style, mmap-backed dataset for compact GNNCP graphs.
|
| 67 |
+
|
| 68 |
+
Parameters
|
| 69 |
+
----------
|
| 70 |
+
root:
|
| 71 |
+
Compact dataset directory or its ``manifest.json`` path.
|
| 72 |
+
max_cached_shards:
|
| 73 |
+
Per-process LRU size. Each shard is loaded with ``mmap=True``; keeping
|
| 74 |
+
a shard in this cache does not eagerly read all tensor storage.
|
| 75 |
+
DataLoader workers each maintain their own cache.
|
| 76 |
+
strict:
|
| 77 |
+
Check inexpensive shape/range invariants while reconstructing samples.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
root: Union[str, Path],
|
| 83 |
+
*,
|
| 84 |
+
max_cached_shards: int = 2,
|
| 85 |
+
strict: bool = True,
|
| 86 |
+
) -> None:
|
| 87 |
+
super().__init__()
|
| 88 |
+
root = Path(root).expanduser()
|
| 89 |
+
if root.is_dir():
|
| 90 |
+
self.root = root.resolve()
|
| 91 |
+
self.manifest_path = self.root / "manifest.json"
|
| 92 |
+
else:
|
| 93 |
+
self.manifest_path = root.resolve()
|
| 94 |
+
self.root = self.manifest_path.parent
|
| 95 |
+
|
| 96 |
+
if max_cached_shards < 1:
|
| 97 |
+
raise ValueError("max_cached_shards must be >= 1")
|
| 98 |
+
self.max_cached_shards = int(max_cached_shards)
|
| 99 |
+
self.strict = bool(strict)
|
| 100 |
+
self.manifest = self._read_manifest(self.manifest_path)
|
| 101 |
+
self.cutoff = float(self.manifest.get("cutoff", 6.0))
|
| 102 |
+
if self.cutoff <= 0:
|
| 103 |
+
raise CompactFormatError(f"cutoff must be positive, got {self.cutoff}")
|
| 104 |
+
|
| 105 |
+
raw_shards = self.manifest.get("shards")
|
| 106 |
+
if not isinstance(raw_shards, list) or not raw_shards:
|
| 107 |
+
raise CompactFormatError("manifest.shards must be a non-empty list")
|
| 108 |
+
self.shards: List[Mapping[str, Any]] = raw_shards
|
| 109 |
+
self._shard_counts = [_get_shard_graph_count(s) for s in self.shards]
|
| 110 |
+
self._shard_ends: List[int] = []
|
| 111 |
+
running = 0
|
| 112 |
+
for count in self._shard_counts:
|
| 113 |
+
if count < 0:
|
| 114 |
+
raise CompactFormatError(f"negative shard graph count: {count}")
|
| 115 |
+
running += count
|
| 116 |
+
self._shard_ends.append(running)
|
| 117 |
+
|
| 118 |
+
graph_map = self.manifest.get("graph_map")
|
| 119 |
+
if graph_map is None:
|
| 120 |
+
self._graph_map: Optional[Sequence[Any]] = None
|
| 121 |
+
self._length = running
|
| 122 |
+
else:
|
| 123 |
+
if not isinstance(graph_map, list):
|
| 124 |
+
raise CompactFormatError("manifest.graph_map must be a list")
|
| 125 |
+
self._graph_map = graph_map
|
| 126 |
+
self._length = len(graph_map)
|
| 127 |
+
|
| 128 |
+
declared = self.manifest.get("num_graphs", self.manifest.get("n_graphs"))
|
| 129 |
+
if declared is not None and int(declared) != self._length:
|
| 130 |
+
raise CompactFormatError(
|
| 131 |
+
f"manifest graph count mismatch: declared={declared}, mapped={self._length}"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# This cache must never be serialised into DataLoader workers. Each
|
| 135 |
+
# process reopens mmap-backed shards independently.
|
| 136 |
+
self._cache: MutableMapping[int, Mapping[str, Any]] = OrderedDict()
|
| 137 |
+
|
| 138 |
+
@staticmethod
|
| 139 |
+
def _read_manifest(path: Path) -> Dict[str, Any]:
|
| 140 |
+
if not path.is_file():
|
| 141 |
+
raise FileNotFoundError(f"compact manifest not found: {path}")
|
| 142 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 143 |
+
manifest = json.load(handle)
|
| 144 |
+
if not isinstance(manifest, dict):
|
| 145 |
+
raise CompactFormatError("manifest root must be a JSON object")
|
| 146 |
+
|
| 147 |
+
format_name = manifest.get("format", manifest.get("format_name"))
|
| 148 |
+
if format_name != FORMAT_NAME:
|
| 149 |
+
raise CompactFormatError(
|
| 150 |
+
f"unsupported compact format {format_name!r}; expected {FORMAT_NAME!r}"
|
| 151 |
+
)
|
| 152 |
+
version = int(manifest.get("schema_version", manifest.get("version", -1)))
|
| 153 |
+
if version != SCHEMA_VERSION:
|
| 154 |
+
raise CompactFormatError(
|
| 155 |
+
f"unsupported schema version {version}; expected {SCHEMA_VERSION}"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
static_columns = manifest.get("static_columns")
|
| 159 |
+
dynamic_columns = manifest.get("dynamic_columns")
|
| 160 |
+
expected_static = [[0, 34], [61, 71]]
|
| 161 |
+
expected_dynamic = [[34, 61], [71, 82]]
|
| 162 |
+
if static_columns is not None and static_columns != expected_static:
|
| 163 |
+
raise CompactFormatError(
|
| 164 |
+
f"unexpected static_columns={static_columns}; expected {expected_static}"
|
| 165 |
+
)
|
| 166 |
+
if dynamic_columns is not None and dynamic_columns != expected_dynamic:
|
| 167 |
+
raise CompactFormatError(
|
| 168 |
+
f"unexpected dynamic_columns={dynamic_columns}; expected {expected_dynamic}"
|
| 169 |
+
)
|
| 170 |
+
return manifest
|
| 171 |
+
|
| 172 |
+
def __len__(self) -> int:
|
| 173 |
+
return self._length
|
| 174 |
+
|
| 175 |
+
def __getstate__(self) -> Dict[str, Any]:
|
| 176 |
+
state = dict(self.__dict__)
|
| 177 |
+
state["_cache"] = OrderedDict()
|
| 178 |
+
return state
|
| 179 |
+
|
| 180 |
+
def _resolve_index(self, index: int) -> Tuple[int, int]:
|
| 181 |
+
if not isinstance(index, int):
|
| 182 |
+
try:
|
| 183 |
+
index = int(index)
|
| 184 |
+
except (TypeError, ValueError) as exc:
|
| 185 |
+
raise TypeError(f"graph index must be an integer, got {type(index)!r}") from exc
|
| 186 |
+
if index < 0:
|
| 187 |
+
index += self._length
|
| 188 |
+
if index < 0 or index >= self._length:
|
| 189 |
+
raise IndexError(f"graph index {index} outside [0, {self._length})")
|
| 190 |
+
|
| 191 |
+
if self._graph_map is None:
|
| 192 |
+
shard_index = bisect.bisect_right(self._shard_ends, index)
|
| 193 |
+
start = 0 if shard_index == 0 else self._shard_ends[shard_index - 1]
|
| 194 |
+
return shard_index, index - start
|
| 195 |
+
|
| 196 |
+
entry = self._graph_map[index]
|
| 197 |
+
if isinstance(entry, Mapping):
|
| 198 |
+
shard_index = entry.get("shard", entry.get("shard_index"))
|
| 199 |
+
local_index = entry.get(
|
| 200 |
+
"local_pose", entry.get("local_index", entry.get("graph_index"))
|
| 201 |
+
)
|
| 202 |
+
elif isinstance(entry, (list, tuple)) and len(entry) == 2:
|
| 203 |
+
shard_index, local_index = entry
|
| 204 |
+
else:
|
| 205 |
+
raise CompactFormatError(
|
| 206 |
+
f"graph_map[{index}] must be [shard,local_pose] or an object"
|
| 207 |
+
)
|
| 208 |
+
if shard_index is None or local_index is None:
|
| 209 |
+
raise CompactFormatError(f"incomplete graph_map entry at index {index}: {entry}")
|
| 210 |
+
shard_index = int(shard_index)
|
| 211 |
+
local_index = int(local_index)
|
| 212 |
+
if not 0 <= shard_index < len(self.shards):
|
| 213 |
+
raise CompactFormatError(
|
| 214 |
+
f"graph_map[{index}] has invalid shard index {shard_index}"
|
| 215 |
+
)
|
| 216 |
+
if not 0 <= local_index < self._shard_counts[shard_index]:
|
| 217 |
+
raise CompactFormatError(
|
| 218 |
+
f"graph_map[{index}] has invalid local pose {local_index} "
|
| 219 |
+
f"for shard {shard_index}"
|
| 220 |
+
)
|
| 221 |
+
return shard_index, local_index
|
| 222 |
+
|
| 223 |
+
def _load_shard(self, shard_index: int) -> Mapping[str, Any]:
|
| 224 |
+
if shard_index in self._cache:
|
| 225 |
+
shard = self._cache.pop(shard_index)
|
| 226 |
+
self._cache[shard_index] = shard
|
| 227 |
+
return shard
|
| 228 |
+
|
| 229 |
+
relative = Path(_get_shard_path(self.shards[shard_index]))
|
| 230 |
+
path = relative if relative.is_absolute() else self.root / relative
|
| 231 |
+
if not path.is_file():
|
| 232 |
+
raise FileNotFoundError(f"compact shard not found: {path}")
|
| 233 |
+
try:
|
| 234 |
+
shard = torch.load(
|
| 235 |
+
path,
|
| 236 |
+
map_location="cpu",
|
| 237 |
+
mmap=True,
|
| 238 |
+
weights_only=True,
|
| 239 |
+
)
|
| 240 |
+
except TypeError as exc:
|
| 241 |
+
raise RuntimeError(
|
| 242 |
+
"CompactGraphDataset requires a PyTorch version supporting "
|
| 243 |
+
"torch.load(..., mmap=True, weights_only=True)"
|
| 244 |
+
) from exc
|
| 245 |
+
if not isinstance(shard, Mapping):
|
| 246 |
+
raise CompactFormatError(f"shard {path} is not a tensor dictionary")
|
| 247 |
+
self._check_shard_header(shard, path, shard_index)
|
| 248 |
+
|
| 249 |
+
self._cache[shard_index] = shard
|
| 250 |
+
while len(self._cache) > self.max_cached_shards:
|
| 251 |
+
self._cache.popitem(last=False)
|
| 252 |
+
return shard
|
| 253 |
+
|
| 254 |
+
def _check_shard_header(
|
| 255 |
+
self,
|
| 256 |
+
shard: Mapping[str, Any],
|
| 257 |
+
path: Path,
|
| 258 |
+
shard_index: int,
|
| 259 |
+
) -> None:
|
| 260 |
+
required = {
|
| 261 |
+
"schema_version",
|
| 262 |
+
"system_graph_ptr",
|
| 263 |
+
"pose_system",
|
| 264 |
+
"source_graph_index",
|
| 265 |
+
"system_node_ptr",
|
| 266 |
+
"n_protein",
|
| 267 |
+
"x_static",
|
| 268 |
+
"protein_ptr",
|
| 269 |
+
"protein_pos",
|
| 270 |
+
"native_ligand_ptr",
|
| 271 |
+
"native_ligand_pos",
|
| 272 |
+
"pose_node_ptr",
|
| 273 |
+
"x_dynamic",
|
| 274 |
+
"pose_ligand_ptr",
|
| 275 |
+
"ligand_pos",
|
| 276 |
+
"pp_edge_ptr",
|
| 277 |
+
"pp_edge_upper",
|
| 278 |
+
"nonpp_edge_ptr",
|
| 279 |
+
"nonpp_edge_upper",
|
| 280 |
+
}
|
| 281 |
+
missing = sorted(required.difference(shard))
|
| 282 |
+
if missing:
|
| 283 |
+
raise CompactFormatError(f"shard {path} is missing keys: {missing}")
|
| 284 |
+
|
| 285 |
+
raw_version = shard["schema_version"]
|
| 286 |
+
if torch.is_tensor(raw_version):
|
| 287 |
+
if raw_version.numel() != 1:
|
| 288 |
+
raise CompactFormatError(f"{path}: schema_version must contain one value")
|
| 289 |
+
version = int(raw_version.reshape(-1)[0].item())
|
| 290 |
+
else:
|
| 291 |
+
version = int(raw_version)
|
| 292 |
+
if version != SCHEMA_VERSION:
|
| 293 |
+
raise CompactFormatError(f"{path}: schema_version={version}, expected 1")
|
| 294 |
+
|
| 295 |
+
expected_graphs = self._shard_counts[shard_index]
|
| 296 |
+
actual_graphs = int(shard["pose_system"].numel())
|
| 297 |
+
if expected_graphs != actual_graphs:
|
| 298 |
+
raise CompactFormatError(
|
| 299 |
+
f"{path}: pose count={actual_graphs}, manifest says {expected_graphs}"
|
| 300 |
+
)
|
| 301 |
+
if int(shard["source_graph_index"].numel()) != actual_graphs:
|
| 302 |
+
raise CompactFormatError(f"{path}: source_graph_index length mismatch")
|
| 303 |
+
|
| 304 |
+
num_systems = int(shard["n_protein"].numel())
|
| 305 |
+
pointer_lengths = {
|
| 306 |
+
"system_graph_ptr": num_systems + 1,
|
| 307 |
+
"system_node_ptr": num_systems + 1,
|
| 308 |
+
"protein_ptr": num_systems + 1,
|
| 309 |
+
"native_ligand_ptr": num_systems + 1,
|
| 310 |
+
"pp_edge_ptr": num_systems + 1,
|
| 311 |
+
"pose_node_ptr": actual_graphs + 1,
|
| 312 |
+
"pose_ligand_ptr": actual_graphs + 1,
|
| 313 |
+
"nonpp_edge_ptr": actual_graphs + 1,
|
| 314 |
+
}
|
| 315 |
+
for name, expected_length in pointer_lengths.items():
|
| 316 |
+
if int(shard[name].numel()) != expected_length:
|
| 317 |
+
raise CompactFormatError(
|
| 318 |
+
f"{path}: {name} length={shard[name].numel()}, "
|
| 319 |
+
f"expected {expected_length}"
|
| 320 |
+
)
|
| 321 |
+
if shard["x_static"].ndim != 2 or shard["x_static"].shape[1] != STATIC_WIDTH:
|
| 322 |
+
raise CompactFormatError(
|
| 323 |
+
f"{path}: x_static must be [sum_system_nodes,{STATIC_WIDTH}]"
|
| 324 |
+
)
|
| 325 |
+
if shard["x_dynamic"].ndim != 2 or shard["x_dynamic"].shape[1] != DYNAMIC_WIDTH:
|
| 326 |
+
raise CompactFormatError(
|
| 327 |
+
f"{path}: x_dynamic must be [sum_pose_nodes,{DYNAMIC_WIDTH}]"
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
@staticmethod
|
| 331 |
+
def _bounds(pointer: torch.Tensor, index: int, name: str) -> Tuple[int, int]:
|
| 332 |
+
start = int(pointer[index].item())
|
| 333 |
+
end = int(pointer[index + 1].item())
|
| 334 |
+
if start < 0 or end < start:
|
| 335 |
+
raise CompactFormatError(f"invalid {name} interval [{start}, {end})")
|
| 336 |
+
return start, end
|
| 337 |
+
|
| 338 |
+
def _reconstruct_edges(
|
| 339 |
+
self,
|
| 340 |
+
shard: Mapping[str, Any],
|
| 341 |
+
system_index: int,
|
| 342 |
+
pose_index: int,
|
| 343 |
+
pos: torch.Tensor,
|
| 344 |
+
n_protein: int,
|
| 345 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 346 |
+
pp_start, pp_end = self._bounds(shard["pp_edge_ptr"], system_index, "pp_edge_ptr")
|
| 347 |
+
np_start, np_end = self._bounds(
|
| 348 |
+
shard["nonpp_edge_ptr"], pose_index, "nonpp_edge_ptr"
|
| 349 |
+
)
|
| 350 |
+
pp_all = _as_edge_matrix(shard["pp_edge_upper"], "pp_edge_upper")
|
| 351 |
+
nonpp_all = _as_edge_matrix(shard["nonpp_edge_upper"], "nonpp_edge_upper")
|
| 352 |
+
pp = pp_all[:, pp_start:pp_end].to(torch.int64)
|
| 353 |
+
nonpp = nonpp_all[:, np_start:np_end].to(torch.int64)
|
| 354 |
+
upper = torch.cat((pp, nonpp), dim=1)
|
| 355 |
+
|
| 356 |
+
num_nodes = int(pos.shape[0])
|
| 357 |
+
if self.strict and upper.numel():
|
| 358 |
+
if int(upper.min().item()) < 0 or int(upper.max().item()) >= num_nodes:
|
| 359 |
+
raise CompactFormatError("edge endpoint outside graph node range")
|
| 360 |
+
if not bool(torch.all(upper[0] < upper[1]).item()):
|
| 361 |
+
raise CompactFormatError("compact edges must be upper triangular (src < dst)")
|
| 362 |
+
if pp.numel() and int(pp.max().item()) >= n_protein:
|
| 363 |
+
raise CompactFormatError("pp_edge_upper contains a ligand endpoint")
|
| 364 |
+
if nonpp.numel() and not bool(
|
| 365 |
+
torch.all(nonpp[1] >= n_protein).item()
|
| 366 |
+
):
|
| 367 |
+
raise CompactFormatError(
|
| 368 |
+
"nonpp_edge_upper must contain at least one ligand endpoint"
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
if upper.shape[1] == 0:
|
| 372 |
+
return (
|
| 373 |
+
torch.empty((2, 0), dtype=torch.int64),
|
| 374 |
+
torch.empty((0, EDGE_WIDTH), dtype=torch.float32),
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
# Compute the two geometric attributes once per undirected edge in
|
| 378 |
+
# float64. The legacy builder's scipy.cdist also computes distances
|
| 379 |
+
# from float32 coordinates in float64 before casting edge_attr to f32.
|
| 380 |
+
delta = pos[upper[0]].to(torch.float64) - pos[upper[1]].to(torch.float64)
|
| 381 |
+
distance = torch.sqrt(torch.sum(delta * delta, dim=1))
|
| 382 |
+
attr0 = (distance / self.cutoff).to(torch.float32)
|
| 383 |
+
attr1 = torch.exp(-distance / 3.0).to(torch.float32)
|
| 384 |
+
|
| 385 |
+
src = torch.cat((upper[0], upper[1]), dim=0)
|
| 386 |
+
dst = torch.cat((upper[1], upper[0]), dim=0)
|
| 387 |
+
attr0 = torch.cat((attr0, attr0), dim=0)
|
| 388 |
+
attr1 = torch.cat((attr1, attr1), dim=0)
|
| 389 |
+
|
| 390 |
+
# np.where in the legacy builder emits row-major (src,dst) order.
|
| 391 |
+
# Restoring this order makes edge_index parity deterministic.
|
| 392 |
+
order = torch.argsort(src * num_nodes + dst)
|
| 393 |
+
src = src[order]
|
| 394 |
+
dst = dst[order]
|
| 395 |
+
edge_index = torch.stack((src, dst), dim=0)
|
| 396 |
+
edge_attr = torch.stack(
|
| 397 |
+
(
|
| 398 |
+
attr0[order],
|
| 399 |
+
attr1[order],
|
| 400 |
+
(src < n_protein).to(torch.float32),
|
| 401 |
+
(dst < n_protein).to(torch.float32),
|
| 402 |
+
),
|
| 403 |
+
dim=1,
|
| 404 |
+
)
|
| 405 |
+
return edge_index, edge_attr
|
| 406 |
+
|
| 407 |
+
def __getitem__(self, index: int) -> Data:
|
| 408 |
+
shard_index, pose_index = self._resolve_index(index)
|
| 409 |
+
shard = self._load_shard(shard_index)
|
| 410 |
+
|
| 411 |
+
system_index = int(shard["pose_system"][pose_index].item())
|
| 412 |
+
num_systems = int(shard["n_protein"].numel())
|
| 413 |
+
if not 0 <= system_index < num_systems:
|
| 414 |
+
raise CompactFormatError(
|
| 415 |
+
f"pose {pose_index} references invalid system {system_index}"
|
| 416 |
+
)
|
| 417 |
+
n_protein = int(shard["n_protein"][system_index].item())
|
| 418 |
+
|
| 419 |
+
static_start, static_end = self._bounds(
|
| 420 |
+
shard["system_node_ptr"], system_index, "system_node_ptr"
|
| 421 |
+
)
|
| 422 |
+
dynamic_start, dynamic_end = self._bounds(
|
| 423 |
+
shard["pose_node_ptr"], pose_index, "pose_node_ptr"
|
| 424 |
+
)
|
| 425 |
+
static = shard["x_static"][static_start:static_end].to(torch.float32)
|
| 426 |
+
dynamic = shard["x_dynamic"][dynamic_start:dynamic_end].to(torch.float32)
|
| 427 |
+
num_nodes = static_end - static_start
|
| 428 |
+
if dynamic_end - dynamic_start != num_nodes:
|
| 429 |
+
raise CompactFormatError(
|
| 430 |
+
f"pose {pose_index}: static nodes={num_nodes}, "
|
| 431 |
+
f"dynamic nodes={dynamic_end - dynamic_start}"
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
protein_start, protein_end = self._bounds(
|
| 435 |
+
shard["protein_ptr"], system_index, "protein_ptr"
|
| 436 |
+
)
|
| 437 |
+
native_start, native_end = self._bounds(
|
| 438 |
+
shard["native_ligand_ptr"], system_index, "native_ligand_ptr"
|
| 439 |
+
)
|
| 440 |
+
ligand_start, ligand_end = self._bounds(
|
| 441 |
+
shard["pose_ligand_ptr"], pose_index, "pose_ligand_ptr"
|
| 442 |
+
)
|
| 443 |
+
protein_pos = shard["protein_pos"][protein_start:protein_end].to(torch.float32)
|
| 444 |
+
native_ligand_pos = shard["native_ligand_pos"][native_start:native_end].to(
|
| 445 |
+
torch.float32
|
| 446 |
+
)
|
| 447 |
+
ligand_pos = shard["ligand_pos"][ligand_start:ligand_end].to(torch.float32)
|
| 448 |
+
|
| 449 |
+
n_ligand = num_nodes - n_protein
|
| 450 |
+
if self.strict:
|
| 451 |
+
coordinate_counts = {
|
| 452 |
+
"protein": int(protein_pos.shape[0]),
|
| 453 |
+
"native_ligand": int(native_ligand_pos.shape[0]),
|
| 454 |
+
"pose_ligand": int(ligand_pos.shape[0]),
|
| 455 |
+
}
|
| 456 |
+
expected_counts = {
|
| 457 |
+
"protein": n_protein,
|
| 458 |
+
"native_ligand": n_ligand,
|
| 459 |
+
"pose_ligand": n_ligand,
|
| 460 |
+
}
|
| 461 |
+
if coordinate_counts != expected_counts:
|
| 462 |
+
raise CompactFormatError(
|
| 463 |
+
f"pose {pose_index}: coordinate counts {coordinate_counts}, "
|
| 464 |
+
f"expected {expected_counts}"
|
| 465 |
+
)
|
| 466 |
+
if protein_pos.ndim != 2 or protein_pos.shape[1] != 3:
|
| 467 |
+
raise CompactFormatError("protein_pos must have shape [Np,3]")
|
| 468 |
+
if ligand_pos.ndim != 2 or ligand_pos.shape[1] != 3:
|
| 469 |
+
raise CompactFormatError("ligand_pos must have shape [Nl,3]")
|
| 470 |
+
if native_ligand_pos.ndim != 2 or native_ligand_pos.shape[1] != 3:
|
| 471 |
+
raise CompactFormatError("native_ligand_pos must have shape [Nl,3]")
|
| 472 |
+
|
| 473 |
+
x = torch.empty((num_nodes, NODE_WIDTH), dtype=torch.float32)
|
| 474 |
+
x[:, :34] = static[:, :34]
|
| 475 |
+
x[:, 34:61] = dynamic[:, :27]
|
| 476 |
+
x[:, 61:71] = static[:, 34:44]
|
| 477 |
+
x[:, 71:82] = dynamic[:, 27:38]
|
| 478 |
+
|
| 479 |
+
pos = torch.cat((protein_pos, ligand_pos), dim=0)
|
| 480 |
+
y_grt = torch.cat((protein_pos, native_ligand_pos), dim=0)
|
| 481 |
+
is_protein = torch.zeros((num_nodes, 1), dtype=torch.float32)
|
| 482 |
+
is_protein[:n_protein] = 1.0
|
| 483 |
+
y_true = torch.zeros((num_nodes, 1), dtype=torch.float32)
|
| 484 |
+
ligand_error = ligand_pos - native_ligand_pos
|
| 485 |
+
y_true[n_protein:, 0] = torch.sqrt(
|
| 486 |
+
torch.sum(ligand_error * ligand_error, dim=1)
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
edge_index, edge_attr = self._reconstruct_edges(
|
| 490 |
+
shard, system_index, pose_index, pos, n_protein
|
| 491 |
+
)
|
| 492 |
+
return Data(
|
| 493 |
+
x=x,
|
| 494 |
+
edge_index=edge_index,
|
| 495 |
+
edge_attr=edge_attr,
|
| 496 |
+
pos=pos,
|
| 497 |
+
is_protein=is_protein,
|
| 498 |
+
y_true=y_true,
|
| 499 |
+
# y_pred intentionally aliases pos. It has the same value contract
|
| 500 |
+
# as the legacy data and avoids an unnecessary graph-local copy.
|
| 501 |
+
y_pred=pos,
|
| 502 |
+
y_grt=y_grt,
|
| 503 |
+
num_nodes=num_nodes,
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
def metadata(self, index: int) -> Dict[str, Any]:
|
| 507 |
+
"""Return stable source/system metadata without reconstructing a graph."""
|
| 508 |
+
shard_index, pose_index = self._resolve_index(index)
|
| 509 |
+
shard = self._load_shard(shard_index)
|
| 510 |
+
system_index = int(shard["pose_system"][pose_index].item())
|
| 511 |
+
source_index = int(shard["source_graph_index"][pose_index].item())
|
| 512 |
+
result: Dict[str, Any] = {
|
| 513 |
+
"dataset_index": int(index),
|
| 514 |
+
"source_graph_index": source_index,
|
| 515 |
+
"shard_index": shard_index,
|
| 516 |
+
"local_pose_index": pose_index,
|
| 517 |
+
"local_system_index": system_index,
|
| 518 |
+
}
|
| 519 |
+
shard_manifest = self.shards[shard_index]
|
| 520 |
+
system_ids = shard_manifest.get("system_ids")
|
| 521 |
+
if isinstance(system_ids, list) and 0 <= system_index < len(system_ids):
|
| 522 |
+
result["system_id"] = system_ids[system_index]
|
| 523 |
+
else:
|
| 524 |
+
systems = shard_manifest.get("systems")
|
| 525 |
+
if (
|
| 526 |
+
isinstance(systems, list)
|
| 527 |
+
and 0 <= system_index < len(systems)
|
| 528 |
+
and isinstance(systems[system_index], Mapping)
|
| 529 |
+
):
|
| 530 |
+
system_metadata = systems[system_index]
|
| 531 |
+
if "system_id" in system_metadata:
|
| 532 |
+
result["system_id"] = system_metadata["system_id"]
|
| 533 |
+
if "source_label" in system_metadata:
|
| 534 |
+
result["source_label"] = system_metadata["source_label"]
|
| 535 |
+
return result
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
__all__ = [
|
| 539 |
+
"CompactFormatError",
|
| 540 |
+
"CompactGraphDataset",
|
| 541 |
+
"FORMAT_NAME",
|
| 542 |
+
"SCHEMA_V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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Convert a legacy ``torch.save(list[torch_geometric.data.Data])`` dataset to
|
| 4 |
+
GNNCP compact_v1 shards.
|
| 5 |
+
|
| 6 |
+
This program is intentionally meant to run in a Slurm compute job. The legacy
|
| 7 |
+
file is a single pickle, so it must be opened as a whole; ``mmap=True`` keeps
|
| 8 |
+
its tensor storages file-backed while the converter processes one system at a
|
| 9 |
+
time.
|
| 10 |
+
|
| 11 |
+
The compact format is lossless for the stored float32 node features and
|
| 12 |
+
coordinates. It does not reduce the 82-dimensional model input:
|
| 13 |
+
|
| 14 |
+
* 44 pose-invariant x columns are stored once per system.
|
| 15 |
+
* 38 pose-dependent x columns are stored once per pose.
|
| 16 |
+
* protein-protein undirected edges are stored once per system.
|
| 17 |
+
* all other undirected edges are stored once per pose.
|
| 18 |
+
* pos, is_protein, y_true, y_pred, y_grt, edge_attr and reverse edges are
|
| 19 |
+
derived by the loader.
|
| 20 |
+
|
| 21 |
+
All systems remain wholly within one shard. ``manifest.json`` maps every
|
| 22 |
+
legacy graph index to ``[shard_index, local_pose_index]``.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import gc
|
| 29 |
+
import hashlib
|
| 30 |
+
import json
|
| 31 |
+
import os
|
| 32 |
+
import sys
|
| 33 |
+
from collections import Counter, defaultdict
|
| 34 |
+
from datetime import datetime, timezone
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Sequence, Tuple
|
| 37 |
+
|
| 38 |
+
import torch
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
FORMAT_NAME = "gnncp_compact_v1"
|
| 42 |
+
SCHEMA_VERSION = 1
|
| 43 |
+
|
| 44 |
+
# build_graph_unified_enhanced.py column layout:
|
| 45 |
+
# static: atom OH (11), residue OH (21), protein/ligand flags (2),
|
| 46 |
+
# chemistry (5), protein-specific (5)
|
| 47 |
+
# dynamic: all geometry/topology/interface/environment columns.
|
| 48 |
+
STATIC_COLUMNS: Tuple[int, ...] = tuple(range(0, 34)) + tuple(range(61, 71))
|
| 49 |
+
DYNAMIC_COLUMNS: Tuple[int, ...] = tuple(range(34, 61)) + tuple(range(71, 82))
|
| 50 |
+
|
| 51 |
+
UNKNOWN_LABELS = {"", "UNKNOWN", "NONE", "NULL", "N/A"}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def parse_args() -> argparse.Namespace:
|
| 55 |
+
parser = argparse.ArgumentParser(
|
| 56 |
+
description="Convert a legacy GNNCP PyG list to compact_v1 tensor shards."
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument("--input", required=True, type=Path, help="Legacy *_enhanced_graphs.pt")
|
| 59 |
+
parser.add_argument("--output-dir", required=True, type=Path, help="New method output directory")
|
| 60 |
+
parser.add_argument("--method", required=True, help="Docking method name stored in manifest")
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--system-index",
|
| 63 |
+
type=Path,
|
| 64 |
+
default=None,
|
| 65 |
+
help=(
|
| 66 |
+
"Optional JSON containing graph_to_system labels. Exact tensor "
|
| 67 |
+
"content remains the authoritative grouping key."
|
| 68 |
+
),
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"--target-shard-mib",
|
| 72 |
+
type=int,
|
| 73 |
+
default=512,
|
| 74 |
+
help="Approximate uncompressed tensor bytes per shard; systems never cross shards.",
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--cutoff",
|
| 78 |
+
type=float,
|
| 79 |
+
default=6.0,
|
| 80 |
+
help="Original graph cutoff, needed to reconstruct edge_attr (default: 6.0 A).",
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--no-mmap",
|
| 84 |
+
action="store_true",
|
| 85 |
+
help="Eagerly load tensor storage. Only use in a sufficiently large-memory compute job.",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--skip-strict-validation",
|
| 89 |
+
action="store_true",
|
| 90 |
+
help="Skip expensive edge symmetry and redundant-field consistency checks.",
|
| 91 |
+
)
|
| 92 |
+
return parser.parse_args()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def tensor_bytes(tensor: torch.Tensor) -> int:
|
| 96 |
+
return tensor.numel() * tensor.element_size()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def require_tensor(graph: Any, name: str) -> torch.Tensor:
|
| 100 |
+
value = getattr(graph, name, None)
|
| 101 |
+
if not isinstance(value, torch.Tensor):
|
| 102 |
+
raise ValueError(f"graph is missing tensor field {name!r}")
|
| 103 |
+
if value.device.type != "cpu":
|
| 104 |
+
value = value.cpu()
|
| 105 |
+
return value
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def infer_partition(graph: Any) -> Tuple[int, int, int]:
|
| 109 |
+
x = require_tensor(graph, "x")
|
| 110 |
+
if x.ndim != 2 or x.shape[1] != 82:
|
| 111 |
+
raise ValueError(f"expected x=[N,82], got {tuple(x.shape)}")
|
| 112 |
+
if x.dtype != torch.float32:
|
| 113 |
+
raise ValueError(f"expected float32 x, got {x.dtype}")
|
| 114 |
+
|
| 115 |
+
mask = require_tensor(graph, "is_protein").reshape(-1)
|
| 116 |
+
n_nodes = x.shape[0]
|
| 117 |
+
if mask.numel() != n_nodes:
|
| 118 |
+
raise ValueError("is_protein length does not match x")
|
| 119 |
+
is_protein = mask > 0.5
|
| 120 |
+
n_protein = int(is_protein.sum().item())
|
| 121 |
+
if n_protein <= 0 or n_protein >= n_nodes:
|
| 122 |
+
raise ValueError(f"invalid protein/ligand partition: N={n_nodes}, Np={n_protein}")
|
| 123 |
+
expected = torch.arange(n_nodes) < n_protein
|
| 124 |
+
if not torch.equal(is_protein, expected):
|
| 125 |
+
raise ValueError("compact_v1 requires protein nodes first and ligand nodes last")
|
| 126 |
+
return n_nodes, n_protein, n_nodes - n_protein
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def graph_content_hashes(graph: Any) -> Tuple[str, str]:
|
| 130 |
+
"""Return exact native-structure and pose-shared-content hashes.
|
| 131 |
+
|
| 132 |
+
The legacy per-method indices are useful labels, but some of them are not
|
| 133 |
+
aligned perfectly with the graph list. The shared-content hash is
|
| 134 |
+
therefore the authoritative grouping key. It also includes all 44
|
| 135 |
+
nominally static x columns: a few legacy poses use different ligand atom
|
| 136 |
+
annotations despite sharing the same native coordinates, and those poses
|
| 137 |
+
must not silently share an incompatible x_static tensor.
|
| 138 |
+
"""
|
| 139 |
+
n_nodes, n_protein, n_ligand = infer_partition(graph)
|
| 140 |
+
y_grt = require_tensor(graph, "y_grt")
|
| 141 |
+
if y_grt.dtype != torch.float32 or tuple(y_grt.shape) != (n_nodes, 3):
|
| 142 |
+
raise ValueError(f"expected y_grt float32 [{n_nodes},3], got {y_grt.dtype} {tuple(y_grt.shape)}")
|
| 143 |
+
x = require_tensor(graph, "x")
|
| 144 |
+
static_index = torch.tensor(STATIC_COLUMNS, dtype=torch.int64)
|
| 145 |
+
x_static = x.index_select(1, static_index).contiguous()
|
| 146 |
+
|
| 147 |
+
prefix = bytearray(b"gnncp-native-v1\0")
|
| 148 |
+
prefix.extend(n_nodes.to_bytes(8, "little", signed=False))
|
| 149 |
+
prefix.extend(n_protein.to_bytes(8, "little", signed=False))
|
| 150 |
+
prefix.extend(n_ligand.to_bytes(8, "little", signed=False))
|
| 151 |
+
|
| 152 |
+
native_digest = hashlib.sha256()
|
| 153 |
+
native_digest.update(prefix)
|
| 154 |
+
native_digest.update(memoryview(y_grt.detach().contiguous().numpy()))
|
| 155 |
+
native_hash = native_digest.hexdigest()
|
| 156 |
+
|
| 157 |
+
shared_digest = hashlib.sha256()
|
| 158 |
+
shared_digest.update(b"gnncp-shared-v1\0")
|
| 159 |
+
shared_digest.update(bytes.fromhex(native_hash))
|
| 160 |
+
shared_digest.update(memoryview(x_static.detach().numpy()))
|
| 161 |
+
return native_hash, shared_digest.hexdigest()
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def read_system_labels(path: Path | None, n_graphs: int) -> Tuple[List[str | None], str]:
|
| 165 |
+
if path is None:
|
| 166 |
+
return [None] * n_graphs, "y_grt_sha256"
|
| 167 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 168 |
+
payload = json.load(handle)
|
| 169 |
+
labels = payload.get("graph_to_system")
|
| 170 |
+
if not isinstance(labels, list):
|
| 171 |
+
raise ValueError(f"{path}: graph_to_system is not a list")
|
| 172 |
+
if len(labels) != n_graphs:
|
| 173 |
+
raise ValueError(
|
| 174 |
+
f"{path}: graph_to_system has {len(labels)} entries, legacy dataset has {n_graphs}"
|
| 175 |
+
)
|
| 176 |
+
normalized: List[str | None] = []
|
| 177 |
+
for value in labels:
|
| 178 |
+
label = str(value).strip() if value is not None else ""
|
| 179 |
+
normalized.append(None if label.upper() in UNKNOWN_LABELS else label)
|
| 180 |
+
return normalized, "graph_to_system_plus_y_grt_sha256"
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def group_graphs(
|
| 184 |
+
graphs: Sequence[Any], labels: Sequence[str | None]
|
| 185 |
+
) -> List[Dict[str, Any]]:
|
| 186 |
+
"""
|
| 187 |
+
Group solely by exact pose-shared tensor content.
|
| 188 |
+
|
| 189 |
+
External system labels are deliberately not part of the grouping key.
|
| 190 |
+
They are attached only when every labelled member agrees. This prevents a
|
| 191 |
+
stale/misaligned index from either merging unrelated graphs or splitting
|
| 192 |
+
poses that have identical shared tensors.
|
| 193 |
+
"""
|
| 194 |
+
grouped: MutableMapping[str, List[int]] = defaultdict(list)
|
| 195 |
+
native_hash_by_shared: Dict[str, str] = {}
|
| 196 |
+
n_graphs = len(graphs)
|
| 197 |
+
for graph_index, graph in enumerate(graphs):
|
| 198 |
+
native_hash, shared_hash = graph_content_hashes(graph)
|
| 199 |
+
grouped[shared_hash].append(graph_index)
|
| 200 |
+
previous_native_hash = native_hash_by_shared.setdefault(shared_hash, native_hash)
|
| 201 |
+
if previous_native_hash != native_hash:
|
| 202 |
+
raise RuntimeError("shared-content SHA-256 collision detected")
|
| 203 |
+
if (graph_index + 1) % 500 == 0 or graph_index + 1 == n_graphs:
|
| 204 |
+
print(f"[group] hashed {graph_index + 1}/{n_graphs} graphs", flush=True)
|
| 205 |
+
|
| 206 |
+
systems: List[Dict[str, Any]] = []
|
| 207 |
+
for shared_hash, graph_indices in grouped.items():
|
| 208 |
+
label_counts = Counter(
|
| 209 |
+
labels[index] for index in graph_indices if labels[index] is not None
|
| 210 |
+
)
|
| 211 |
+
agreed_label = next(iter(label_counts)) if len(label_counts) == 1 else None
|
| 212 |
+
systems.append(
|
| 213 |
+
{
|
| 214 |
+
"system_id": agreed_label or f"hash_{shared_hash[:20]}",
|
| 215 |
+
"source_label": agreed_label,
|
| 216 |
+
"source_label_counts": dict(sorted(label_counts.items())),
|
| 217 |
+
"native_hash": native_hash_by_shared[shared_hash],
|
| 218 |
+
"shared_hash": shared_hash,
|
| 219 |
+
"graph_indices": sorted(graph_indices),
|
| 220 |
+
}
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# A legacy label can legitimately cover more than one exact shared tensor
|
| 224 |
+
# signature. Keep those records distinct and make their IDs unambiguous.
|
| 225 |
+
label_occurrences = Counter(
|
| 226 |
+
item["source_label"] for item in systems if item["source_label"] is not None
|
| 227 |
+
)
|
| 228 |
+
for item in systems:
|
| 229 |
+
label = item["source_label"]
|
| 230 |
+
if label is not None and label_occurrences[label] > 1:
|
| 231 |
+
item["system_id"] = f"{label}__{item['shared_hash'][:12]}"
|
| 232 |
+
|
| 233 |
+
# Deterministic output independent of dict insertion details.
|
| 234 |
+
systems.sort(key=lambda item: (item["system_id"], item["graph_indices"][0]))
|
| 235 |
+
return systems
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def canonical_upper_edges(
|
| 239 |
+
edge_index: torch.Tensor, n_nodes: int, strict: bool
|
| 240 |
+
) -> torch.Tensor:
|
| 241 |
+
"""Return each symmetric directed edge pair once, with local src < dst."""
|
| 242 |
+
if edge_index.ndim != 2 or edge_index.shape[0] != 2:
|
| 243 |
+
raise ValueError(f"expected edge_index=[2,E], got {tuple(edge_index.shape)}")
|
| 244 |
+
edge = edge_index.to(dtype=torch.int64)
|
| 245 |
+
src, dst = edge[0], edge[1]
|
| 246 |
+
if edge.numel() and (
|
| 247 |
+
int(edge.min().item()) < 0 or int(edge.max().item()) >= n_nodes
|
| 248 |
+
):
|
| 249 |
+
raise ValueError("edge_index contains an out-of-range node index")
|
| 250 |
+
if torch.any(src == dst):
|
| 251 |
+
raise ValueError("legacy graph unexpectedly contains self edges")
|
| 252 |
+
|
| 253 |
+
upper_mask = src < dst
|
| 254 |
+
upper = edge[:, upper_mask]
|
| 255 |
+
if strict:
|
| 256 |
+
lower_mask = src > dst
|
| 257 |
+
if int(upper_mask.sum()) != int(lower_mask.sum()):
|
| 258 |
+
raise ValueError("edge_index is not a symmetric directed edge list")
|
| 259 |
+
upper_key = upper[0] * n_nodes + upper[1]
|
| 260 |
+
reverse_lower_key = dst[lower_mask] * n_nodes + src[lower_mask]
|
| 261 |
+
upper_key = torch.sort(upper_key).values
|
| 262 |
+
reverse_lower_key = torch.sort(reverse_lower_key).values
|
| 263 |
+
if not torch.equal(upper_key, reverse_lower_key):
|
| 264 |
+
raise ValueError("edge_index is missing one or more reverse edges")
|
| 265 |
+
if upper_key.numel() > 1 and torch.any(upper_key[1:] == upper_key[:-1]):
|
| 266 |
+
raise ValueError("edge_index contains duplicate edges")
|
| 267 |
+
return upper.to(dtype=torch.int32).contiguous()
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def assert_equal(name: str, actual: torch.Tensor, expected: torch.Tensor) -> None:
|
| 271 |
+
if actual.dtype != expected.dtype or actual.shape != expected.shape:
|
| 272 |
+
raise ValueError(
|
| 273 |
+
f"{name} differs: {actual.dtype}{tuple(actual.shape)} vs "
|
| 274 |
+
f"{expected.dtype}{tuple(expected.shape)}"
|
| 275 |
+
)
|
| 276 |
+
if not torch.equal(actual, expected):
|
| 277 |
+
raise ValueError(f"{name} is not identical within a system")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def build_system_record(
|
| 281 |
+
graphs: Sequence[Any],
|
| 282 |
+
system: Mapping[str, Any],
|
| 283 |
+
strict: bool,
|
| 284 |
+
) -> Dict[str, Any]:
|
| 285 |
+
graph_indices: List[int] = list(system["graph_indices"])
|
| 286 |
+
reference = graphs[graph_indices[0]]
|
| 287 |
+
n_nodes, n_protein, n_ligand = infer_partition(reference)
|
| 288 |
+
n_poses = len(graph_indices)
|
| 289 |
+
|
| 290 |
+
static_index = torch.tensor(STATIC_COLUMNS, dtype=torch.int64)
|
| 291 |
+
dynamic_index = torch.tensor(DYNAMIC_COLUMNS, dtype=torch.int64)
|
| 292 |
+
|
| 293 |
+
ref_x = require_tensor(reference, "x")
|
| 294 |
+
x_static = ref_x.index_select(1, static_index).contiguous().clone()
|
| 295 |
+
ref_pos = require_tensor(reference, "pos")
|
| 296 |
+
ref_y_pred = require_tensor(reference, "y_pred")
|
| 297 |
+
ref_y_grt = require_tensor(reference, "y_grt")
|
| 298 |
+
for field_name, value in (
|
| 299 |
+
("pos", ref_pos),
|
| 300 |
+
("y_pred", ref_y_pred),
|
| 301 |
+
("y_grt", ref_y_grt),
|
| 302 |
+
):
|
| 303 |
+
if value.dtype != torch.float32 or tuple(value.shape) != (n_nodes, 3):
|
| 304 |
+
raise ValueError(
|
| 305 |
+
f"{system['system_id']}: expected {field_name} float32 [{n_nodes},3]"
|
| 306 |
+
)
|
| 307 |
+
if strict:
|
| 308 |
+
assert_equal("reference pos/y_pred", ref_pos, ref_y_pred)
|
| 309 |
+
|
| 310 |
+
protein_pos = ref_pos[:n_protein].contiguous().clone()
|
| 311 |
+
native_ligand_pos = ref_y_grt[n_protein:].contiguous().clone()
|
| 312 |
+
x_dynamic = torch.empty((n_poses * n_nodes, len(DYNAMIC_COLUMNS)), dtype=torch.float32)
|
| 313 |
+
ligand_pos = torch.empty((n_poses * n_ligand, 3), dtype=torch.float32)
|
| 314 |
+
|
| 315 |
+
ref_upper = canonical_upper_edges(
|
| 316 |
+
require_tensor(reference, "edge_index"), n_nodes, strict
|
| 317 |
+
)
|
| 318 |
+
ref_pp_mask = (ref_upper[0] < n_protein) & (ref_upper[1] < n_protein)
|
| 319 |
+
pp_edge_upper = ref_upper[:, ref_pp_mask].contiguous().clone()
|
| 320 |
+
|
| 321 |
+
nonpp_edges: List[torch.Tensor] = []
|
| 322 |
+
nonpp_counts: List[int] = []
|
| 323 |
+
|
| 324 |
+
for pose_index, graph_index in enumerate(graph_indices):
|
| 325 |
+
graph = graphs[graph_index]
|
| 326 |
+
shape = infer_partition(graph)
|
| 327 |
+
if shape != (n_nodes, n_protein, n_ligand):
|
| 328 |
+
raise ValueError(
|
| 329 |
+
f"{system['system_id']}: graph {graph_index} changed node partition "
|
| 330 |
+
f"from {(n_nodes, n_protein, n_ligand)} to {shape}"
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
x = require_tensor(graph, "x")
|
| 334 |
+
current_static = x.index_select(1, static_index)
|
| 335 |
+
assert_equal("x static columns", current_static, x_static)
|
| 336 |
+
dynamic_start = pose_index * n_nodes
|
| 337 |
+
x_dynamic[dynamic_start : dynamic_start + n_nodes].copy_(
|
| 338 |
+
x.index_select(1, dynamic_index)
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
pos = require_tensor(graph, "pos")
|
| 342 |
+
y_pred = require_tensor(graph, "y_pred")
|
| 343 |
+
y_grt = require_tensor(graph, "y_grt")
|
| 344 |
+
for field_name, value in (("pos", pos), ("y_pred", y_pred), ("y_grt", y_grt)):
|
| 345 |
+
if value.dtype != torch.float32 or tuple(value.shape) != (n_nodes, 3):
|
| 346 |
+
raise ValueError(
|
| 347 |
+
f"{system['system_id']}: graph {graph_index} has invalid {field_name}"
|
| 348 |
+
)
|
| 349 |
+
assert_equal("protein coordinates", pos[:n_protein], protein_pos)
|
| 350 |
+
assert_equal("native ligand coordinates", y_grt[n_protein:], native_ligand_pos)
|
| 351 |
+
if strict:
|
| 352 |
+
assert_equal("pos/y_pred", pos, y_pred)
|
| 353 |
+
assert_equal("ground-truth protein coordinates", y_grt[:n_protein], protein_pos)
|
| 354 |
+
y_true = require_tensor(graph, "y_true").reshape(-1)
|
| 355 |
+
if y_true.dtype != torch.float32 or y_true.numel() != n_nodes:
|
| 356 |
+
raise ValueError("invalid y_true")
|
| 357 |
+
expected_error = torch.linalg.vector_norm(pos - y_grt, dim=1)
|
| 358 |
+
if not torch.allclose(y_true, expected_error, rtol=1e-5, atol=1e-5):
|
| 359 |
+
raise ValueError("y_true cannot be reconstructed from pos and y_grt")
|
| 360 |
+
|
| 361 |
+
ligand_start = pose_index * n_ligand
|
| 362 |
+
ligand_pos[ligand_start : ligand_start + n_ligand].copy_(pos[n_protein:])
|
| 363 |
+
|
| 364 |
+
upper = canonical_upper_edges(require_tensor(graph, "edge_index"), n_nodes, strict)
|
| 365 |
+
pp_mask = (upper[0] < n_protein) & (upper[1] < n_protein)
|
| 366 |
+
assert_equal("protein-protein edges", upper[:, pp_mask], pp_edge_upper)
|
| 367 |
+
nonpp = upper[:, ~pp_mask].contiguous().clone()
|
| 368 |
+
nonpp_edges.append(nonpp)
|
| 369 |
+
nonpp_counts.append(nonpp.shape[1])
|
| 370 |
+
|
| 371 |
+
if strict:
|
| 372 |
+
edge_attr = require_tensor(graph, "edge_attr")
|
| 373 |
+
if edge_attr.dtype != torch.float32 or tuple(edge_attr.shape) != (
|
| 374 |
+
require_tensor(graph, "edge_index").shape[1],
|
| 375 |
+
4,
|
| 376 |
+
):
|
| 377 |
+
raise ValueError("invalid edge_attr")
|
| 378 |
+
|
| 379 |
+
if nonpp_edges:
|
| 380 |
+
nonpp_edge_upper = torch.cat(nonpp_edges, dim=1)
|
| 381 |
+
else:
|
| 382 |
+
nonpp_edge_upper = torch.empty((2, 0), dtype=torch.int32)
|
| 383 |
+
|
| 384 |
+
record: Dict[str, Any] = {
|
| 385 |
+
# Metadata used for packing/manifest; not serialized into the tensor shard.
|
| 386 |
+
"_system_id": system["system_id"],
|
| 387 |
+
"_source_label": system["source_label"],
|
| 388 |
+
"_source_label_counts": system["source_label_counts"],
|
| 389 |
+
"_native_hash": system["native_hash"],
|
| 390 |
+
"_shared_hash": system["shared_hash"],
|
| 391 |
+
"_n_nodes": n_nodes,
|
| 392 |
+
"_n_protein": n_protein,
|
| 393 |
+
"_n_ligand": n_ligand,
|
| 394 |
+
"_n_poses": n_poses,
|
| 395 |
+
# Serialized tensors.
|
| 396 |
+
"x_static": x_static,
|
| 397 |
+
"protein_pos": protein_pos,
|
| 398 |
+
"native_ligand_pos": native_ligand_pos,
|
| 399 |
+
"x_dynamic": x_dynamic,
|
| 400 |
+
"ligand_pos": ligand_pos,
|
| 401 |
+
"pp_edge_upper": pp_edge_upper,
|
| 402 |
+
"nonpp_edge_upper": nonpp_edge_upper,
|
| 403 |
+
"nonpp_edge_counts": torch.tensor(nonpp_counts, dtype=torch.int64),
|
| 404 |
+
"source_graph_index": torch.tensor(graph_indices, dtype=torch.int64),
|
| 405 |
+
}
|
| 406 |
+
record["_tensor_bytes"] = sum(
|
| 407 |
+
tensor_bytes(value) for value in record.values() if isinstance(value, torch.Tensor)
|
| 408 |
+
)
|
| 409 |
+
return record
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def cumulative_ptr(lengths: Iterable[int]) -> torch.Tensor:
|
| 413 |
+
values = [0]
|
| 414 |
+
for length in lengths:
|
| 415 |
+
values.append(values[-1] + int(length))
|
| 416 |
+
return torch.tensor(values, dtype=torch.int64)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def concatenate(records: Sequence[Mapping[str, Any]], key: str, dim: int = 0) -> torch.Tensor:
|
| 420 |
+
tensors = [record[key] for record in records]
|
| 421 |
+
return torch.cat(tensors, dim=dim)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def pack_shard(records: Sequence[Mapping[str, Any]]) -> Dict[str, torch.Tensor]:
|
| 425 |
+
n_poses = [record["_n_poses"] for record in records]
|
| 426 |
+
n_nodes = [record["_n_nodes"] for record in records]
|
| 427 |
+
n_protein = [record["_n_protein"] for record in records]
|
| 428 |
+
n_ligand = [record["_n_ligand"] for record in records]
|
| 429 |
+
|
| 430 |
+
pose_system = torch.repeat_interleave(
|
| 431 |
+
torch.arange(len(records), dtype=torch.int32),
|
| 432 |
+
torch.tensor(n_poses, dtype=torch.int64),
|
| 433 |
+
)
|
| 434 |
+
pose_node_lengths: List[int] = []
|
| 435 |
+
pose_ligand_lengths: List[int] = []
|
| 436 |
+
for p, n, nl in zip(n_poses, n_nodes, n_ligand):
|
| 437 |
+
pose_node_lengths.extend([n] * p)
|
| 438 |
+
pose_ligand_lengths.extend([nl] * p)
|
| 439 |
+
|
| 440 |
+
return {
|
| 441 |
+
"schema_version": torch.tensor([SCHEMA_VERSION], dtype=torch.int32),
|
| 442 |
+
"system_graph_ptr": cumulative_ptr(n_poses),
|
| 443 |
+
"pose_system": pose_system,
|
| 444 |
+
"source_graph_index": concatenate(records, "source_graph_index"),
|
| 445 |
+
"system_node_ptr": cumulative_ptr(n_nodes),
|
| 446 |
+
"n_protein": torch.tensor(n_protein, dtype=torch.int32),
|
| 447 |
+
"x_static": concatenate(records, "x_static"),
|
| 448 |
+
"protein_ptr": cumulative_ptr(n_protein),
|
| 449 |
+
"protein_pos": concatenate(records, "protein_pos"),
|
| 450 |
+
"native_ligand_ptr": cumulative_ptr(n_ligand),
|
| 451 |
+
"native_ligand_pos": concatenate(records, "native_ligand_pos"),
|
| 452 |
+
"pose_node_ptr": cumulative_ptr(pose_node_lengths),
|
| 453 |
+
"x_dynamic": concatenate(records, "x_dynamic"),
|
| 454 |
+
"pose_ligand_ptr": cumulative_ptr(pose_ligand_lengths),
|
| 455 |
+
"ligand_pos": concatenate(records, "ligand_pos"),
|
| 456 |
+
"pp_edge_ptr": cumulative_ptr(
|
| 457 |
+
record["pp_edge_upper"].shape[1] for record in records
|
| 458 |
+
),
|
| 459 |
+
"pp_edge_upper": concatenate(records, "pp_edge_upper", dim=1),
|
| 460 |
+
"nonpp_edge_ptr": cumulative_ptr(
|
| 461 |
+
int(count)
|
| 462 |
+
for record in records
|
| 463 |
+
for count in record["nonpp_edge_counts"].tolist()
|
| 464 |
+
),
|
| 465 |
+
"nonpp_edge_upper": concatenate(records, "nonpp_edge_upper", dim=1),
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def main() -> int:
|
| 470 |
+
args = parse_args()
|
| 471 |
+
input_path = args.input.resolve()
|
| 472 |
+
output_dir = args.output_dir.resolve()
|
| 473 |
+
system_index = args.system_index.resolve() if args.system_index else None
|
| 474 |
+
|
| 475 |
+
if not input_path.is_file():
|
| 476 |
+
raise FileNotFoundError(input_path)
|
| 477 |
+
if system_index is not None and not system_index.is_file():
|
| 478 |
+
raise FileNotFoundError(system_index)
|
| 479 |
+
if output_dir.exists():
|
| 480 |
+
raise FileExistsError(
|
| 481 |
+
f"refusing to overwrite existing output directory: {output_dir}"
|
| 482 |
+
)
|
| 483 |
+
if args.target_shard_mib <= 0:
|
| 484 |
+
raise ValueError("--target-shard-mib must be positive")
|
| 485 |
+
|
| 486 |
+
output_dir.parent.mkdir(parents=True, exist_ok=True)
|
| 487 |
+
run_id = os.environ.get("SLURM_JOB_ID") or str(os.getpid())
|
| 488 |
+
staging_dir = output_dir.with_name(f".{output_dir.name}.building.{run_id}")
|
| 489 |
+
if staging_dir.exists():
|
| 490 |
+
raise FileExistsError(f"staging directory already exists: {staging_dir}")
|
| 491 |
+
shard_dir = staging_dir / "shards"
|
| 492 |
+
shard_dir.mkdir(parents=True)
|
| 493 |
+
|
| 494 |
+
print(f"input: {input_path}", flush=True)
|
| 495 |
+
print(f"output: {output_dir}", flush=True)
|
| 496 |
+
print(f"staging: {staging_dir}", flush=True)
|
| 497 |
+
print(f"method: {args.method}", flush=True)
|
| 498 |
+
print(f"mmap: {not args.no_mmap}", flush=True)
|
| 499 |
+
print(f"strict: {not args.skip_strict_validation}", flush=True)
|
| 500 |
+
|
| 501 |
+
try:
|
| 502 |
+
graphs = torch.load(
|
| 503 |
+
input_path,
|
| 504 |
+
map_location="cpu",
|
| 505 |
+
weights_only=False,
|
| 506 |
+
mmap=not args.no_mmap,
|
| 507 |
+
)
|
| 508 |
+
except RuntimeError as exc:
|
| 509 |
+
if not args.no_mmap:
|
| 510 |
+
raise RuntimeError(
|
| 511 |
+
"mmap loading failed. Re-submit a sufficiently large-memory Slurm job "
|
| 512 |
+
"with --no-mmap if this file uses legacy torch serialization."
|
| 513 |
+
) from exc
|
| 514 |
+
raise
|
| 515 |
+
if not isinstance(graphs, (list, tuple)):
|
| 516 |
+
raise TypeError(f"expected legacy list/tuple, got {type(graphs).__name__}")
|
| 517 |
+
n_graphs = len(graphs)
|
| 518 |
+
if n_graphs == 0:
|
| 519 |
+
raise ValueError("legacy dataset is empty")
|
| 520 |
+
print(f"opened {n_graphs} legacy graphs", flush=True)
|
| 521 |
+
|
| 522 |
+
labels, grouping_mode = read_system_labels(system_index, n_graphs)
|
| 523 |
+
systems = group_graphs(graphs, labels)
|
| 524 |
+
print(
|
| 525 |
+
f"grouped into {len(systems)} systems via exact shared-content hash "
|
| 526 |
+
f"(labels: {grouping_mode})",
|
| 527 |
+
flush=True,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
target_bytes = args.target_shard_mib * 1024 * 1024
|
| 531 |
+
strict = not args.skip_strict_validation
|
| 532 |
+
graph_map: List[List[int] | None] = [None] * n_graphs
|
| 533 |
+
shard_manifest: List[Dict[str, Any]] = []
|
| 534 |
+
pending: List[Dict[str, Any]] = []
|
| 535 |
+
pending_bytes = 0
|
| 536 |
+
compact_bytes = 0
|
| 537 |
+
|
| 538 |
+
def flush_pending() -> None:
|
| 539 |
+
nonlocal pending, pending_bytes, compact_bytes
|
| 540 |
+
if not pending:
|
| 541 |
+
return
|
| 542 |
+
shard_index = len(shard_manifest)
|
| 543 |
+
relative_path = f"shards/shard_{shard_index:05d}.pt"
|
| 544 |
+
final_path = staging_dir / relative_path
|
| 545 |
+
temp_path = final_path.with_suffix(".pt.tmp")
|
| 546 |
+
packed = pack_shard(pending)
|
| 547 |
+
torch.save(packed, temp_path)
|
| 548 |
+
os.replace(temp_path, final_path)
|
| 549 |
+
size_bytes = final_path.stat().st_size
|
| 550 |
+
compact_bytes += size_bytes
|
| 551 |
+
|
| 552 |
+
local_pose = 0
|
| 553 |
+
system_entries: List[Dict[str, Any]] = []
|
| 554 |
+
for record in pending:
|
| 555 |
+
source_indices = record["source_graph_index"].tolist()
|
| 556 |
+
for offset, source_index in enumerate(source_indices):
|
| 557 |
+
graph_map[source_index] = [shard_index, local_pose + offset]
|
| 558 |
+
system_entries.append(
|
| 559 |
+
{
|
| 560 |
+
"system_id": record["_system_id"],
|
| 561 |
+
"source_label": record["_source_label"],
|
| 562 |
+
"source_label_counts": record["_source_label_counts"],
|
| 563 |
+
"native_hash": record["_native_hash"],
|
| 564 |
+
"shared_hash": record["_shared_hash"],
|
| 565 |
+
"num_graphs": record["_n_poses"],
|
| 566 |
+
"num_nodes": record["_n_nodes"],
|
| 567 |
+
"num_protein_nodes": record["_n_protein"],
|
| 568 |
+
"num_ligand_nodes": record["_n_ligand"],
|
| 569 |
+
}
|
| 570 |
+
)
|
| 571 |
+
local_pose += record["_n_poses"]
|
| 572 |
+
|
| 573 |
+
shard_manifest.append(
|
| 574 |
+
{
|
| 575 |
+
"path": relative_path,
|
| 576 |
+
"num_graphs": local_pose,
|
| 577 |
+
"num_systems": len(pending),
|
| 578 |
+
"size_bytes": size_bytes,
|
| 579 |
+
"systems": system_entries,
|
| 580 |
+
}
|
| 581 |
+
)
|
| 582 |
+
print(
|
| 583 |
+
f"[write] {relative_path}: {len(pending)} systems, {local_pose} graphs, "
|
| 584 |
+
f"{size_bytes / 2**20:.1f} MiB",
|
| 585 |
+
flush=True,
|
| 586 |
+
)
|
| 587 |
+
del packed
|
| 588 |
+
pending = []
|
| 589 |
+
pending_bytes = 0
|
| 590 |
+
gc.collect()
|
| 591 |
+
|
| 592 |
+
for system_number, system in enumerate(systems, start=1):
|
| 593 |
+
record = build_system_record(graphs, system, strict=strict)
|
| 594 |
+
record_bytes = int(record["_tensor_bytes"])
|
| 595 |
+
if pending and pending_bytes + record_bytes > target_bytes:
|
| 596 |
+
flush_pending()
|
| 597 |
+
pending.append(record)
|
| 598 |
+
pending_bytes += record_bytes
|
| 599 |
+
print(
|
| 600 |
+
f"[system] {system_number}/{len(systems)} {system['system_id']}: "
|
| 601 |
+
f"{record['_n_poses']} poses, {record_bytes / 2**20:.1f} MiB raw compact",
|
| 602 |
+
flush=True,
|
| 603 |
+
)
|
| 604 |
+
flush_pending()
|
| 605 |
+
|
| 606 |
+
if any(item is None for item in graph_map):
|
| 607 |
+
raise RuntimeError("internal error: graph_map is incomplete")
|
| 608 |
+
|
| 609 |
+
source_stat = input_path.stat()
|
| 610 |
+
manifest: Dict[str, Any] = {
|
| 611 |
+
"format": FORMAT_NAME,
|
| 612 |
+
"schema_version": SCHEMA_VERSION,
|
| 613 |
+
"status": "complete",
|
| 614 |
+
"created_utc": datetime.now(timezone.utc).isoformat(),
|
| 615 |
+
"method": args.method,
|
| 616 |
+
"cutoff": args.cutoff,
|
| 617 |
+
"source": {
|
| 618 |
+
"path": str(input_path),
|
| 619 |
+
"size_bytes": source_stat.st_size,
|
| 620 |
+
"mtime_ns": source_stat.st_mtime_ns,
|
| 621 |
+
"system_index": str(system_index) if system_index else None,
|
| 622 |
+
},
|
| 623 |
+
"grouping": {
|
| 624 |
+
"mode": "exact_shared_content_hash",
|
| 625 |
+
"label_source": grouping_mode,
|
| 626 |
+
"authoritative_key": (
|
| 627 |
+
"sha256(exact float32 y_grt + node partition + "
|
| 628 |
+
"x[:,0:34] + x[:,61:71])"
|
| 629 |
+
),
|
| 630 |
+
"external_labels_are_metadata_only": True,
|
| 631 |
+
},
|
| 632 |
+
"features": {
|
| 633 |
+
"full_dimension": 82,
|
| 634 |
+
"dtype": "float32",
|
| 635 |
+
"static_dimension": len(STATIC_COLUMNS),
|
| 636 |
+
"static_columns": list(STATIC_COLUMNS),
|
| 637 |
+
"dynamic_dimension": len(DYNAMIC_COLUMNS),
|
| 638 |
+
"dynamic_columns": list(DYNAMIC_COLUMNS),
|
| 639 |
+
},
|
| 640 |
+
"edges": {
|
| 641 |
+
"index_dtype_on_disk": "int32",
|
| 642 |
+
"stored_direction": "upper_triangle_src_lt_dst",
|
| 643 |
+
"protein_protein_scope": "once_per_system",
|
| 644 |
+
"non_protein_protein_scope": "once_per_pose",
|
| 645 |
+
"edge_attr": "derived_from_float32_coordinates_and_endpoint_types",
|
| 646 |
+
},
|
| 647 |
+
"derived_fields": [
|
| 648 |
+
"pos",
|
| 649 |
+
"is_protein",
|
| 650 |
+
"y_true",
|
| 651 |
+
"y_pred",
|
| 652 |
+
"y_grt",
|
| 653 |
+
"edge_index_reverse_direction",
|
| 654 |
+
"edge_attr",
|
| 655 |
+
"num_nodes",
|
| 656 |
+
],
|
| 657 |
+
"n_graphs": n_graphs,
|
| 658 |
+
"n_systems": len(systems),
|
| 659 |
+
"n_shards": len(shard_manifest),
|
| 660 |
+
"graph_map": graph_map,
|
| 661 |
+
"shards": shard_manifest,
|
| 662 |
+
"size": {
|
| 663 |
+
"legacy_bytes": source_stat.st_size,
|
| 664 |
+
"compact_shard_bytes": compact_bytes,
|
| 665 |
+
"legacy_to_compact_ratio": (
|
| 666 |
+
source_stat.st_size / compact_bytes if compact_bytes else None
|
| 667 |
+
),
|
| 668 |
+
},
|
| 669 |
+
"strict_validation": strict,
|
| 670 |
+
}
|
| 671 |
+
manifest_path = staging_dir / "manifest.json"
|
| 672 |
+
temp_manifest = staging_dir / "manifest.json.tmp"
|
| 673 |
+
with temp_manifest.open("w", encoding="utf-8") as handle:
|
| 674 |
+
json.dump(manifest, handle, indent=2, ensure_ascii=False)
|
| 675 |
+
handle.write("\n")
|
| 676 |
+
os.replace(temp_manifest, manifest_path)
|
| 677 |
+
|
| 678 |
+
# Atomic publication: manifest.json is the stable completion marker.
|
| 679 |
+
os.replace(staging_dir, output_dir)
|
| 680 |
+
print(f"complete: {output_dir / 'manifest.json'}", flush=True)
|
| 681 |
+
print(
|
| 682 |
+
f"legacy={source_stat.st_size / 2**30:.2f} GiB, "
|
| 683 |
+
f"compact_shards={compact_bytes / 2**30:.2f} GiB, "
|
| 684 |
+
f"ratio={source_stat.st_size / compact_bytes:.2f}x",
|
| 685 |
+
flush=True,
|
| 686 |
+
)
|
| 687 |
+
return 0
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
if __name__ == "__main__":
|
| 691 |
+
try:
|
| 692 |
+
raise SystemExit(main())
|
| 693 |
+
except Exception as error:
|
| 694 |
+
print(f"ERROR: {error}", file=sys.stderr, flush=True)
|
| 695 |
+
raise
|
code/compact_v1/materialize_hiqbind_gnncp.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Materialize Docking Base PDB outputs into GNNCP's flat pose layout.
|
| 3 |
+
|
| 4 |
+
The operation is intentionally non-destructive: it reads canonical common
|
| 5 |
+
outputs and creates hard links in a new directory. It neither rewrites nor
|
| 6 |
+
moves a docking result. The resulting layout is accepted by
|
| 7 |
+
``gnncp/system_split_code/build_compact_v1_direct.py``.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import csv
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import re
|
| 17 |
+
import shutil
|
| 18 |
+
import tempfile
|
| 19 |
+
from datetime import datetime, timezone
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, Iterable
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
METHODS = ("diffdock", "autodock_vina", "medusagraph", "protenix")
|
| 25 |
+
TARGET_RE = re.compile(r"[A-Za-z0-9_.-]+\Z")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class MaterializeError(RuntimeError):
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _utc_now() -> str:
|
| 33 |
+
return datetime.now(timezone.utc).isoformat()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _write_json(path: Path, value: dict[str, Any]) -> None:
|
| 37 |
+
path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _read_manifest(path: Path) -> dict[str, Any]:
|
| 41 |
+
try:
|
| 42 |
+
value = json.loads(path.read_text(encoding="utf-8"))
|
| 43 |
+
except (OSError, json.JSONDecodeError) as exc:
|
| 44 |
+
raise MaterializeError(f"cannot read manifest {path}: {exc}") from exc
|
| 45 |
+
if not isinstance(value, dict):
|
| 46 |
+
raise MaterializeError(f"manifest is not an object: {path}")
|
| 47 |
+
return value
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _inside(path: Path, root: Path) -> Path:
|
| 51 |
+
resolved = path.resolve()
|
| 52 |
+
try:
|
| 53 |
+
resolved.relative_to(root.resolve())
|
| 54 |
+
except ValueError as exc:
|
| 55 |
+
raise MaterializeError(f"path escapes native output directory: {path}") from exc
|
| 56 |
+
return resolved
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _pose_paths(native: Path) -> list[Path]:
|
| 60 |
+
csv_path = native / "poses.csv"
|
| 61 |
+
try:
|
| 62 |
+
with csv_path.open("r", newline="", encoding="utf-8") as handle:
|
| 63 |
+
rows = list(csv.DictReader(handle))
|
| 64 |
+
except OSError as exc:
|
| 65 |
+
raise MaterializeError(f"cannot read {csv_path}: {exc}") from exc
|
| 66 |
+
if not rows:
|
| 67 |
+
raise MaterializeError(f"no emitted poses in {csv_path}")
|
| 68 |
+
poses: list[tuple[int, str, Path]] = []
|
| 69 |
+
for ordinal, row in enumerate(rows, start=1):
|
| 70 |
+
raw_path = row.get("pose_file")
|
| 71 |
+
if not raw_path:
|
| 72 |
+
raise MaterializeError(f"{csv_path}: pose row {ordinal} has no pose_file")
|
| 73 |
+
candidate = Path(raw_path)
|
| 74 |
+
source = candidate if candidate.is_absolute() else native / candidate
|
| 75 |
+
source = _inside(source, native)
|
| 76 |
+
if source.suffix.lower() != ".pdb" or not source.is_file():
|
| 77 |
+
raise MaterializeError(f"{csv_path}: unsupported or missing PDB pose {source}")
|
| 78 |
+
rank_text = row.get("rank", "")
|
| 79 |
+
try:
|
| 80 |
+
rank = int(rank_text)
|
| 81 |
+
except ValueError:
|
| 82 |
+
rank = ordinal
|
| 83 |
+
poses.append((rank, source.name, source))
|
| 84 |
+
poses.sort(key=lambda item: (item[0], item[1]))
|
| 85 |
+
return [item[2] for item in poses]
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _discover(source_roots: Iterable[Path], method: str) -> dict[str, dict[str, Any]]:
|
| 89 |
+
"""Discover eligible outputs; later source roots deliberately take precedence."""
|
| 90 |
+
selected: dict[str, dict[str, Any]] = {}
|
| 91 |
+
for source_root in source_roots:
|
| 92 |
+
if not source_root.is_dir():
|
| 93 |
+
raise MaterializeError(f"source root is not a directory: {source_root}")
|
| 94 |
+
# Do not use a recursive glob here: a bulk run's work tree includes
|
| 95 |
+
# multi-gigabyte raw model artifacts. These are the only published
|
| 96 |
+
# Docking Base layouts produced by the normal/sharded/bulk launchers.
|
| 97 |
+
patterns = (
|
| 98 |
+
f"output/{method}/*/native/manifest.json",
|
| 99 |
+
f"shards/*/{method}/output/{method}/*/native/manifest.json",
|
| 100 |
+
f"workers/*/units/*/{method}/output/{method}/*/native/manifest.json",
|
| 101 |
+
f"*/{method}/output/{method}/*/native/manifest.json",
|
| 102 |
+
)
|
| 103 |
+
manifest_paths = {
|
| 104 |
+
path
|
| 105 |
+
for pattern in patterns
|
| 106 |
+
for path in source_root.glob(pattern)
|
| 107 |
+
}
|
| 108 |
+
for manifest_path in sorted(manifest_paths, key=lambda value: str(value)):
|
| 109 |
+
native = manifest_path.parent
|
| 110 |
+
target = native.parent.name
|
| 111 |
+
if not TARGET_RE.fullmatch(target):
|
| 112 |
+
raise MaterializeError(f"unsafe target name {target!r} in {native}")
|
| 113 |
+
manifest = _read_manifest(manifest_path)
|
| 114 |
+
if manifest.get("status") not in {"success", "partial"}:
|
| 115 |
+
continue
|
| 116 |
+
selected[target] = {
|
| 117 |
+
"native": native.resolve(),
|
| 118 |
+
"manifest": manifest_path.resolve(),
|
| 119 |
+
"source_root": source_root.resolve(),
|
| 120 |
+
}
|
| 121 |
+
return selected
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _link(source: Path, destination: Path) -> None:
|
| 125 |
+
if destination.exists() or destination.is_symlink():
|
| 126 |
+
raise MaterializeError(f"unexpected existing materialized file: {destination}")
|
| 127 |
+
try:
|
| 128 |
+
os.link(source, destination)
|
| 129 |
+
except OSError as exc:
|
| 130 |
+
raise MaterializeError(
|
| 131 |
+
f"hard-link failed ({source} -> {destination}); source and output must share a filesystem: {exc}"
|
| 132 |
+
) from exc
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 136 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 137 |
+
parser.add_argument("--method", choices=METHODS, required=True)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--source-root",
|
| 140 |
+
action="append",
|
| 141 |
+
type=Path,
|
| 142 |
+
required=True,
|
| 143 |
+
help="run root to scan; repeatable, later roots take target precedence",
|
| 144 |
+
)
|
| 145 |
+
parser.add_argument("--output-root", type=Path, required=True)
|
| 146 |
+
parser.add_argument("--max-systems", type=int, help="materialize this many ordered systems")
|
| 147 |
+
parser.add_argument("--max-poses-per-system", type=int, default=20)
|
| 148 |
+
return parser
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main() -> int:
|
| 152 |
+
args = build_parser().parse_args()
|
| 153 |
+
if args.max_systems is not None and args.max_systems <= 0:
|
| 154 |
+
raise MaterializeError("--max-systems must be positive")
|
| 155 |
+
if args.max_poses_per_system <= 0:
|
| 156 |
+
raise MaterializeError("--max-poses-per-system must be positive")
|
| 157 |
+
output_root = args.output_root.expanduser().resolve()
|
| 158 |
+
if output_root.exists():
|
| 159 |
+
raise MaterializeError(f"output root already exists; refusing to replace it: {output_root}")
|
| 160 |
+
source_roots = [path.expanduser().resolve() for path in args.source_root]
|
| 161 |
+
selected = _discover(source_roots, args.method)
|
| 162 |
+
ordered_targets = sorted(selected, key=str.casefold)
|
| 163 |
+
if args.max_systems is not None:
|
| 164 |
+
ordered_targets = ordered_targets[: args.max_systems]
|
| 165 |
+
if not ordered_targets:
|
| 166 |
+
raise MaterializeError("no success/partial common outputs discovered")
|
| 167 |
+
|
| 168 |
+
output_root.parent.mkdir(parents=True, exist_ok=True)
|
| 169 |
+
staging = Path(tempfile.mkdtemp(prefix=f".{output_root.name}.building-", dir=output_root.parent))
|
| 170 |
+
records: dict[str, Any] = {}
|
| 171 |
+
skipped: dict[str, str] = {}
|
| 172 |
+
try:
|
| 173 |
+
for target in ordered_targets:
|
| 174 |
+
source = selected[target]
|
| 175 |
+
native = Path(source["native"])
|
| 176 |
+
try:
|
| 177 |
+
protein = _inside(native / "protein.pdb", native)
|
| 178 |
+
ligand = _inside(native / "ligand.pdb", native)
|
| 179 |
+
if not protein.is_file() or not ligand.is_file():
|
| 180 |
+
raise MaterializeError("missing protein.pdb or ligand.pdb")
|
| 181 |
+
poses = _pose_paths(native)[: args.max_poses_per_system]
|
| 182 |
+
if not poses:
|
| 183 |
+
raise MaterializeError("no usable PDB poses")
|
| 184 |
+
destination = staging / target
|
| 185 |
+
destination.mkdir()
|
| 186 |
+
_link(protein, destination / "protein.pdb")
|
| 187 |
+
_link(ligand, destination / "ligand.pdb")
|
| 188 |
+
names: list[str] = []
|
| 189 |
+
for ordinal, pose in enumerate(poses, start=1):
|
| 190 |
+
name = f"{target}_pose_{ordinal:03d}.pdb"
|
| 191 |
+
_link(pose, destination / name)
|
| 192 |
+
names.append(name)
|
| 193 |
+
records[target] = {
|
| 194 |
+
"source_root": str(source["source_root"]),
|
| 195 |
+
"source_native": str(native),
|
| 196 |
+
"source_manifest": str(source["manifest"]),
|
| 197 |
+
"pose_count": len(names),
|
| 198 |
+
"materialized_poses": names,
|
| 199 |
+
}
|
| 200 |
+
except MaterializeError as exc:
|
| 201 |
+
shutil.rmtree(staging / target, ignore_errors=True)
|
| 202 |
+
skipped[target] = str(exc)
|
| 203 |
+
if not records:
|
| 204 |
+
raise MaterializeError("all selected systems were unusable")
|
| 205 |
+
source_index = {
|
| 206 |
+
"kind": "docking_base_common_output_to_gnncp_flat_index",
|
| 207 |
+
"method": args.method,
|
| 208 |
+
"records": records,
|
| 209 |
+
"skipped": skipped,
|
| 210 |
+
}
|
| 211 |
+
_write_json(staging / "source_index.json", source_index)
|
| 212 |
+
_write_json(
|
| 213 |
+
staging / "materialization_manifest.json",
|
| 214 |
+
{
|
| 215 |
+
"kind": "docking_base_gnncp_materialization",
|
| 216 |
+
"created_utc": _utc_now(),
|
| 217 |
+
"method": args.method,
|
| 218 |
+
"link_mode": "hardlink",
|
| 219 |
+
"source_roots": [str(path) for path in source_roots],
|
| 220 |
+
"requested_system_count": len(ordered_targets),
|
| 221 |
+
"materialized_system_count": len(records),
|
| 222 |
+
"materialized_pose_count": sum(item["pose_count"] for item in records.values()),
|
| 223 |
+
"skipped_system_count": len(skipped),
|
| 224 |
+
"max_poses_per_system": args.max_poses_per_system,
|
| 225 |
+
},
|
| 226 |
+
)
|
| 227 |
+
os.replace(staging, output_root)
|
| 228 |
+
except Exception:
|
| 229 |
+
shutil.rmtree(staging, ignore_errors=True)
|
| 230 |
+
raise
|
| 231 |
+
print(json.dumps({"output_root": str(output_root), **json.loads((output_root / "materialization_manifest.json").read_text())}, sort_keys=True))
|
| 232 |
+
return 0
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
if __name__ == "__main__":
|
| 236 |
+
try:
|
| 237 |
+
raise SystemExit(main())
|
| 238 |
+
except MaterializeError as exc:
|
| 239 |
+
print(f"error: {exc}")
|
| 240 |
+
raise SystemExit(2)
|
code/compact_v1/requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reader dependencies
|
| 2 |
+
torch>=2.3
|
| 3 |
+
torch-geometric>=2.4
|
| 4 |
+
|
| 5 |
+
# Additional dependencies required only to rebuild compact shards from PDB poses
|
| 6 |
+
numpy>=1.24
|
| 7 |
+
scipy>=1.10
|
| 8 |
+
MDAnalysis>=2.5
|
| 9 |
+
tqdm>=4.65
|
code/compact_v1/smoke_test_compact_dataset.py
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Compute-node smoke test for :class:`CompactGraphDataset`.
|
| 3 |
+
|
| 4 |
+
The test intentionally samples rather than scans the complete dataset. It
|
| 5 |
+
exercises:
|
| 6 |
+
|
| 7 |
+
* deterministic random graph reconstruction;
|
| 8 |
+
* at least one graph from every selected shard and cross-shard batches;
|
| 9 |
+
* the per-process mmap shard cache through repeated access;
|
| 10 |
+
* PyG DataLoader collation with zero and multiple worker processes; and
|
| 11 |
+
* model-facing tensor shapes, dtypes, index ranges, and finite values.
|
| 12 |
+
|
| 13 |
+
Timing, process RSS/high-water marks, page faults, and filesystem I/O counters
|
| 14 |
+
are written to an atomic JSON report. GNU ``time -v`` and Slurm accounting in
|
| 15 |
+
the companion sbatch file provide job-wide measurements including workers.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import gc
|
| 22 |
+
import json
|
| 23 |
+
import math
|
| 24 |
+
import os
|
| 25 |
+
import random
|
| 26 |
+
import resource
|
| 27 |
+
import socket
|
| 28 |
+
import statistics
|
| 29 |
+
import sys
|
| 30 |
+
import time
|
| 31 |
+
import traceback
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
from typing import Any, Dict, List, Mapping, Sequence
|
| 34 |
+
|
| 35 |
+
import torch
|
| 36 |
+
import torch_geometric
|
| 37 |
+
from torch.utils.data import Subset
|
| 38 |
+
from torch_geometric.data import Batch, Data
|
| 39 |
+
from torch_geometric.loader import DataLoader
|
| 40 |
+
|
| 41 |
+
from compact_graph_dataset import CompactGraphDataset
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
MIB = 1024 * 1024
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def parse_args() -> argparse.Namespace:
|
| 48 |
+
parser = argparse.ArgumentParser(
|
| 49 |
+
description="Sample, batch, and profile a compact GNNCP dataset."
|
| 50 |
+
)
|
| 51 |
+
parser.add_argument("--compact", required=True, help="Compact dataset directory")
|
| 52 |
+
parser.add_argument("--report", help="Atomic JSON report path")
|
| 53 |
+
parser.add_argument("--num-random", type=int, default=16)
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--max-shards",
|
| 56 |
+
type=int,
|
| 57 |
+
default=0,
|
| 58 |
+
help="Maximum shards to probe; 0 tests every shard",
|
| 59 |
+
)
|
| 60 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 61 |
+
parser.add_argument("--num-workers", type=int, default=2)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--worker-timeout-s",
|
| 64 |
+
type=float,
|
| 65 |
+
default=180.0,
|
| 66 |
+
help="Multi-worker DataLoader timeout; zero disables it",
|
| 67 |
+
)
|
| 68 |
+
parser.add_argument("--max-batches", type=int, default=8)
|
| 69 |
+
parser.add_argument("--max-cached-shards", type=int, default=2)
|
| 70 |
+
parser.add_argument("--repeat-count", type=int, default=3)
|
| 71 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 72 |
+
parser.add_argument(
|
| 73 |
+
"--torch-threads",
|
| 74 |
+
type=int,
|
| 75 |
+
default=min(4, int(os.environ.get("SLURM_CPUS_PER_TASK", "4"))),
|
| 76 |
+
)
|
| 77 |
+
parser.add_argument(
|
| 78 |
+
"--no-strict",
|
| 79 |
+
action="store_true",
|
| 80 |
+
help="Disable loader invariant checks (not recommended for smoke tests)",
|
| 81 |
+
)
|
| 82 |
+
args = parser.parse_args()
|
| 83 |
+
positive = {
|
| 84 |
+
"num_random": args.num_random,
|
| 85 |
+
"batch_size": args.batch_size,
|
| 86 |
+
"max_batches": args.max_batches,
|
| 87 |
+
"max_cached_shards": args.max_cached_shards,
|
| 88 |
+
"repeat_count": args.repeat_count,
|
| 89 |
+
"torch_threads": args.torch_threads,
|
| 90 |
+
}
|
| 91 |
+
for name, value in positive.items():
|
| 92 |
+
if value < 1:
|
| 93 |
+
parser.error(f"--{name.replace('_', '-')} must be >= 1")
|
| 94 |
+
if args.num_workers < 0:
|
| 95 |
+
parser.error("--num-workers must be >= 0")
|
| 96 |
+
if args.worker_timeout_s < 0:
|
| 97 |
+
parser.error("--worker-timeout-s must be >= 0")
|
| 98 |
+
if args.max_shards < 0:
|
| 99 |
+
parser.error("--max-shards must be >= 0")
|
| 100 |
+
return args
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _proc_status_mib(field: str) -> float | None:
|
| 104 |
+
try:
|
| 105 |
+
with Path("/proc/self/status").open("r", encoding="utf-8") as handle:
|
| 106 |
+
for line in handle:
|
| 107 |
+
if line.startswith(f"{field}:"):
|
| 108 |
+
return float(line.split()[1]) / 1024.0
|
| 109 |
+
except OSError:
|
| 110 |
+
return None
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _proc_io_bytes() -> Dict[str, int]:
|
| 115 |
+
result = {"read_bytes": 0, "write_bytes": 0}
|
| 116 |
+
try:
|
| 117 |
+
with Path("/proc/self/io").open("r", encoding="utf-8") as handle:
|
| 118 |
+
for line in handle:
|
| 119 |
+
key, raw_value = line.split(":", 1)
|
| 120 |
+
if key in result:
|
| 121 |
+
result[key] = int(raw_value.strip())
|
| 122 |
+
except OSError:
|
| 123 |
+
pass
|
| 124 |
+
return result
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def resource_snapshot() -> Dict[str, float | int | None]:
|
| 128 |
+
usage = resource.getrusage(resource.RUSAGE_SELF)
|
| 129 |
+
children = resource.getrusage(resource.RUSAGE_CHILDREN)
|
| 130 |
+
io_bytes = _proc_io_bytes()
|
| 131 |
+
# ru_maxrss is KiB on Linux, which is the target Slurm platform.
|
| 132 |
+
return {
|
| 133 |
+
"monotonic_s": time.perf_counter(),
|
| 134 |
+
"rss_mib": _proc_status_mib("VmRSS"),
|
| 135 |
+
"hwm_mib": _proc_status_mib("VmHWM"),
|
| 136 |
+
"ru_maxrss_mib": float(usage.ru_maxrss) / 1024.0,
|
| 137 |
+
"minor_faults": int(usage.ru_minflt),
|
| 138 |
+
"major_faults": int(usage.ru_majflt),
|
| 139 |
+
"self_user_cpu_s": float(usage.ru_utime),
|
| 140 |
+
"self_system_cpu_s": float(usage.ru_stime),
|
| 141 |
+
"children_ru_maxrss_mib": float(children.ru_maxrss) / 1024.0,
|
| 142 |
+
"children_minor_faults": int(children.ru_minflt),
|
| 143 |
+
"children_major_faults": int(children.ru_majflt),
|
| 144 |
+
"children_user_cpu_s": float(children.ru_utime),
|
| 145 |
+
"children_system_cpu_s": float(children.ru_stime),
|
| 146 |
+
"read_bytes": io_bytes["read_bytes"],
|
| 147 |
+
"write_bytes": io_bytes["write_bytes"],
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def resource_delta(
|
| 152 |
+
before: Mapping[str, float | int | None],
|
| 153 |
+
after: Mapping[str, float | int | None],
|
| 154 |
+
) -> Dict[str, float | int | None]:
|
| 155 |
+
def subtract(key: str) -> float | int | None:
|
| 156 |
+
left = after.get(key)
|
| 157 |
+
right = before.get(key)
|
| 158 |
+
if left is None or right is None:
|
| 159 |
+
return None
|
| 160 |
+
return left - right
|
| 161 |
+
|
| 162 |
+
return {
|
| 163 |
+
"elapsed_s": subtract("monotonic_s"),
|
| 164 |
+
"rss_mib_after": after.get("rss_mib"),
|
| 165 |
+
"rss_mib_delta": subtract("rss_mib"),
|
| 166 |
+
"hwm_mib_after": after.get("hwm_mib"),
|
| 167 |
+
"ru_maxrss_mib_after": after.get("ru_maxrss_mib"),
|
| 168 |
+
"minor_faults_delta": subtract("minor_faults"),
|
| 169 |
+
"major_faults_delta": subtract("major_faults"),
|
| 170 |
+
"self_user_cpu_s_delta": subtract("self_user_cpu_s"),
|
| 171 |
+
"self_system_cpu_s_delta": subtract("self_system_cpu_s"),
|
| 172 |
+
"children_ru_maxrss_mib_after": after.get("children_ru_maxrss_mib"),
|
| 173 |
+
"children_minor_faults_delta": subtract("children_minor_faults"),
|
| 174 |
+
"children_major_faults_delta": subtract("children_major_faults"),
|
| 175 |
+
"children_user_cpu_s_delta": subtract("children_user_cpu_s"),
|
| 176 |
+
"children_system_cpu_s_delta": subtract("children_system_cpu_s"),
|
| 177 |
+
"read_mib_delta": (
|
| 178 |
+
None
|
| 179 |
+
if subtract("read_bytes") is None
|
| 180 |
+
else float(subtract("read_bytes")) / MIB
|
| 181 |
+
),
|
| 182 |
+
"write_mib_delta": (
|
| 183 |
+
None
|
| 184 |
+
if subtract("write_bytes") is None
|
| 185 |
+
else float(subtract("write_bytes")) / MIB
|
| 186 |
+
),
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def latency_summary(values: Sequence[float]) -> Dict[str, float | int]:
|
| 191 |
+
if not values:
|
| 192 |
+
return {"count": 0}
|
| 193 |
+
ordered = sorted(values)
|
| 194 |
+
p95_index = max(0, math.ceil(0.95 * len(ordered)) - 1)
|
| 195 |
+
return {
|
| 196 |
+
"count": len(ordered),
|
| 197 |
+
"total_s": float(sum(ordered)),
|
| 198 |
+
"mean_ms": float(statistics.fmean(ordered) * 1000.0),
|
| 199 |
+
"median_ms": float(statistics.median(ordered) * 1000.0),
|
| 200 |
+
"p95_ms": float(ordered[p95_index] * 1000.0),
|
| 201 |
+
"min_ms": float(ordered[0] * 1000.0),
|
| 202 |
+
"max_ms": float(ordered[-1] * 1000.0),
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def ensure_finite(name: str, tensor: torch.Tensor) -> None:
|
| 207 |
+
if not bool(torch.isfinite(tensor).all().item()):
|
| 208 |
+
raise RuntimeError(f"{name} contains NaN or infinity")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def check_graph(data: Data, dataset_index: int) -> Dict[str, Any]:
|
| 212 |
+
required = (
|
| 213 |
+
"x",
|
| 214 |
+
"edge_index",
|
| 215 |
+
"edge_attr",
|
| 216 |
+
"pos",
|
| 217 |
+
"is_protein",
|
| 218 |
+
"y_true",
|
| 219 |
+
"y_pred",
|
| 220 |
+
"y_grt",
|
| 221 |
+
)
|
| 222 |
+
missing = [name for name in required if not hasattr(data, name)]
|
| 223 |
+
if missing:
|
| 224 |
+
raise RuntimeError(f"graph {dataset_index} is missing fields: {missing}")
|
| 225 |
+
|
| 226 |
+
num_nodes = int(data.num_nodes)
|
| 227 |
+
if data.x.shape != (num_nodes, 82) or data.x.dtype != torch.float32:
|
| 228 |
+
raise RuntimeError(
|
| 229 |
+
f"graph {dataset_index}: x={tuple(data.x.shape)} {data.x.dtype}"
|
| 230 |
+
)
|
| 231 |
+
if data.edge_index.ndim != 2 or data.edge_index.shape[0] != 2:
|
| 232 |
+
raise RuntimeError(
|
| 233 |
+
f"graph {dataset_index}: edge_index={tuple(data.edge_index.shape)}"
|
| 234 |
+
)
|
| 235 |
+
if data.edge_index.dtype != torch.int64:
|
| 236 |
+
raise RuntimeError(
|
| 237 |
+
f"graph {dataset_index}: edge_index dtype={data.edge_index.dtype}"
|
| 238 |
+
)
|
| 239 |
+
num_edges = int(data.edge_index.shape[1])
|
| 240 |
+
if data.edge_attr.shape != (num_edges, 4):
|
| 241 |
+
raise RuntimeError(
|
| 242 |
+
f"graph {dataset_index}: edge_attr={tuple(data.edge_attr.shape)}"
|
| 243 |
+
)
|
| 244 |
+
if data.edge_attr.dtype != torch.float32:
|
| 245 |
+
raise RuntimeError(
|
| 246 |
+
f"graph {dataset_index}: edge_attr dtype={data.edge_attr.dtype}"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
node_shapes = {
|
| 250 |
+
"pos": (num_nodes, 3),
|
| 251 |
+
"is_protein": (num_nodes, 1),
|
| 252 |
+
"y_true": (num_nodes, 1),
|
| 253 |
+
"y_pred": (num_nodes, 3),
|
| 254 |
+
"y_grt": (num_nodes, 3),
|
| 255 |
+
}
|
| 256 |
+
for name, expected in node_shapes.items():
|
| 257 |
+
tensor = getattr(data, name)
|
| 258 |
+
if tuple(tensor.shape) != expected or tensor.dtype != torch.float32:
|
| 259 |
+
raise RuntimeError(
|
| 260 |
+
f"graph {dataset_index}: {name}={tuple(tensor.shape)} {tensor.dtype}"
|
| 261 |
+
)
|
| 262 |
+
ensure_finite(f"graph {dataset_index} {name}", tensor)
|
| 263 |
+
|
| 264 |
+
ensure_finite(f"graph {dataset_index} x", data.x)
|
| 265 |
+
ensure_finite(f"graph {dataset_index} edge_attr", data.edge_attr)
|
| 266 |
+
if not torch.equal(data.pos, data.y_pred):
|
| 267 |
+
raise RuntimeError(f"graph {dataset_index}: pos and y_pred differ")
|
| 268 |
+
if num_edges:
|
| 269 |
+
edge_min = int(data.edge_index.min().item())
|
| 270 |
+
edge_max = int(data.edge_index.max().item())
|
| 271 |
+
if edge_min < 0 or edge_max >= num_nodes:
|
| 272 |
+
raise RuntimeError(
|
| 273 |
+
f"graph {dataset_index}: edge endpoints [{edge_min},{edge_max}] "
|
| 274 |
+
f"outside [0,{num_nodes})"
|
| 275 |
+
)
|
| 276 |
+
protein_values = torch.unique(data.is_protein)
|
| 277 |
+
if not bool(torch.all((protein_values == 0) | (protein_values == 1)).item()):
|
| 278 |
+
raise RuntimeError(f"graph {dataset_index}: is_protein is not binary")
|
| 279 |
+
|
| 280 |
+
return {
|
| 281 |
+
"dataset_index": dataset_index,
|
| 282 |
+
"num_nodes": num_nodes,
|
| 283 |
+
"num_edges": num_edges,
|
| 284 |
+
"num_protein_nodes": int(data.is_protein.sum().item()),
|
| 285 |
+
"max_y_true": float(data.y_true.max().item()) if num_nodes else 0.0,
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def check_batch(batch: Batch, expected_graphs: int) -> Dict[str, Any]:
|
| 290 |
+
actual_graphs = int(batch.num_graphs)
|
| 291 |
+
if actual_graphs != expected_graphs:
|
| 292 |
+
raise RuntimeError(
|
| 293 |
+
f"batch reports {actual_graphs} graphs, expected {expected_graphs}"
|
| 294 |
+
)
|
| 295 |
+
num_nodes = int(batch.x.shape[0])
|
| 296 |
+
if batch.x.ndim != 2 or batch.x.shape[1] != 82:
|
| 297 |
+
raise RuntimeError(f"batched x has shape {tuple(batch.x.shape)}")
|
| 298 |
+
if batch.edge_attr.ndim != 2 or batch.edge_attr.shape[1] != 4:
|
| 299 |
+
raise RuntimeError(
|
| 300 |
+
f"batched edge_attr has shape {tuple(batch.edge_attr.shape)}"
|
| 301 |
+
)
|
| 302 |
+
if batch.batch.numel() != num_nodes:
|
| 303 |
+
raise RuntimeError("PyG batch assignment length does not match node count")
|
| 304 |
+
if batch.ptr.numel() != actual_graphs + 1:
|
| 305 |
+
raise RuntimeError("PyG batch ptr length is invalid")
|
| 306 |
+
if not torch.equal(batch.pos, batch.y_pred):
|
| 307 |
+
raise RuntimeError("batched pos and y_pred differ")
|
| 308 |
+
ensure_finite("batch x", batch.x)
|
| 309 |
+
ensure_finite("batch edge_attr", batch.edge_attr)
|
| 310 |
+
ensure_finite("batch pos", batch.pos)
|
| 311 |
+
return {
|
| 312 |
+
"num_graphs": actual_graphs,
|
| 313 |
+
"num_nodes": num_nodes,
|
| 314 |
+
"num_edges": int(batch.edge_index.shape[1]),
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evenly_spaced(values: Sequence[int], limit: int) -> List[int]:
|
| 319 |
+
if limit <= 0 or len(values) <= limit:
|
| 320 |
+
return list(values)
|
| 321 |
+
if limit == 1:
|
| 322 |
+
return [values[0]]
|
| 323 |
+
positions = {
|
| 324 |
+
round(index * (len(values) - 1) / (limit - 1)) for index in range(limit)
|
| 325 |
+
}
|
| 326 |
+
return [values[position] for position in sorted(positions)]
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def global_indices_by_shard(dataset: CompactGraphDataset) -> List[List[int]]:
|
| 330 |
+
result: List[List[int]] = [[] for _ in dataset.shards]
|
| 331 |
+
graph_map = dataset.manifest.get("graph_map")
|
| 332 |
+
if graph_map is not None:
|
| 333 |
+
for global_index, entry in enumerate(graph_map):
|
| 334 |
+
if isinstance(entry, Mapping):
|
| 335 |
+
shard_index = entry.get("shard", entry.get("shard_index"))
|
| 336 |
+
else:
|
| 337 |
+
shard_index = entry[0]
|
| 338 |
+
result[int(shard_index)].append(global_index)
|
| 339 |
+
else:
|
| 340 |
+
global_index = 0
|
| 341 |
+
for shard_index, count in enumerate(dataset._shard_counts):
|
| 342 |
+
result[shard_index].extend(range(global_index, global_index + count))
|
| 343 |
+
global_index += count
|
| 344 |
+
empty = [index for index, indices in enumerate(result) if not indices]
|
| 345 |
+
if empty:
|
| 346 |
+
raise RuntimeError(f"manifest contains empty shards: {empty}")
|
| 347 |
+
return result
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def load_direct(
|
| 351 |
+
dataset: CompactGraphDataset,
|
| 352 |
+
indices: Sequence[int],
|
| 353 |
+
) -> Dict[str, Any]:
|
| 354 |
+
before = resource_snapshot()
|
| 355 |
+
latencies: List[float] = []
|
| 356 |
+
samples: List[Dict[str, Any]] = []
|
| 357 |
+
total_nodes = 0
|
| 358 |
+
total_edges = 0
|
| 359 |
+
for dataset_index in indices:
|
| 360 |
+
started = time.perf_counter()
|
| 361 |
+
graph = dataset[dataset_index]
|
| 362 |
+
latency = time.perf_counter() - started
|
| 363 |
+
metrics = check_graph(graph, dataset_index)
|
| 364 |
+
metadata = dataset.metadata(dataset_index)
|
| 365 |
+
metrics.update(
|
| 366 |
+
{
|
| 367 |
+
"shard_index": int(metadata["shard_index"]),
|
| 368 |
+
"source_graph_index": int(metadata["source_graph_index"]),
|
| 369 |
+
"latency_ms": latency * 1000.0,
|
| 370 |
+
}
|
| 371 |
+
)
|
| 372 |
+
if "system_id" in metadata:
|
| 373 |
+
metrics["system_id"] = metadata["system_id"]
|
| 374 |
+
samples.append(metrics)
|
| 375 |
+
latencies.append(latency)
|
| 376 |
+
total_nodes += metrics["num_nodes"]
|
| 377 |
+
total_edges += metrics["num_edges"]
|
| 378 |
+
del graph
|
| 379 |
+
gc.collect()
|
| 380 |
+
after = resource_snapshot()
|
| 381 |
+
resources = resource_delta(before, after)
|
| 382 |
+
elapsed = float(resources["elapsed_s"] or 0.0)
|
| 383 |
+
return {
|
| 384 |
+
"indices": list(indices),
|
| 385 |
+
"latency": latency_summary(latencies),
|
| 386 |
+
"total_nodes": total_nodes,
|
| 387 |
+
"total_edges": total_edges,
|
| 388 |
+
"graphs_per_s": len(indices) / elapsed if elapsed > 0 else None,
|
| 389 |
+
"nodes_per_s": total_nodes / elapsed if elapsed > 0 else None,
|
| 390 |
+
"samples": samples,
|
| 391 |
+
"resources": resources,
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def run_loader(
|
| 396 |
+
dataset: CompactGraphDataset,
|
| 397 |
+
indices: Sequence[int],
|
| 398 |
+
*,
|
| 399 |
+
batch_size: int,
|
| 400 |
+
num_workers: int,
|
| 401 |
+
max_batches: int,
|
| 402 |
+
worker_timeout_s: float,
|
| 403 |
+
) -> Dict[str, Any]:
|
| 404 |
+
before = resource_snapshot()
|
| 405 |
+
subset = Subset(dataset, list(indices))
|
| 406 |
+
loader = DataLoader(
|
| 407 |
+
subset,
|
| 408 |
+
batch_size=batch_size,
|
| 409 |
+
shuffle=False,
|
| 410 |
+
num_workers=num_workers,
|
| 411 |
+
persistent_workers=False,
|
| 412 |
+
pin_memory=False,
|
| 413 |
+
timeout=worker_timeout_s if num_workers else 0,
|
| 414 |
+
)
|
| 415 |
+
latencies: List[float] = []
|
| 416 |
+
batch_metrics: List[Dict[str, Any]] = []
|
| 417 |
+
iterator = iter(loader)
|
| 418 |
+
prior = time.perf_counter()
|
| 419 |
+
try:
|
| 420 |
+
for batch_number, batch in enumerate(iterator):
|
| 421 |
+
now = time.perf_counter()
|
| 422 |
+
latency = now - prior
|
| 423 |
+
latencies.append(latency)
|
| 424 |
+
metrics = check_batch(batch, min(batch_size, len(indices) - batch_number * batch_size))
|
| 425 |
+
metrics["batch_number"] = batch_number
|
| 426 |
+
metrics["latency_ms"] = latency * 1000.0
|
| 427 |
+
batch_metrics.append(metrics)
|
| 428 |
+
del batch
|
| 429 |
+
if batch_number + 1 >= max_batches:
|
| 430 |
+
break
|
| 431 |
+
prior = time.perf_counter()
|
| 432 |
+
finally:
|
| 433 |
+
del iterator
|
| 434 |
+
del loader
|
| 435 |
+
del subset
|
| 436 |
+
gc.collect()
|
| 437 |
+
after = resource_snapshot()
|
| 438 |
+
resources = resource_delta(before, after)
|
| 439 |
+
elapsed = float(resources["elapsed_s"] or 0.0)
|
| 440 |
+
total_graphs = sum(item["num_graphs"] for item in batch_metrics)
|
| 441 |
+
total_nodes = sum(item["num_nodes"] for item in batch_metrics)
|
| 442 |
+
total_edges = sum(item["num_edges"] for item in batch_metrics)
|
| 443 |
+
return {
|
| 444 |
+
"num_workers": num_workers,
|
| 445 |
+
"worker_timeout_s": worker_timeout_s if num_workers else 0,
|
| 446 |
+
"batch_size": batch_size,
|
| 447 |
+
"input_indices": list(indices),
|
| 448 |
+
"batches_tested": len(batch_metrics),
|
| 449 |
+
"graphs_tested": total_graphs,
|
| 450 |
+
"total_nodes": total_nodes,
|
| 451 |
+
"total_edges": total_edges,
|
| 452 |
+
"graphs_per_s": total_graphs / elapsed if elapsed > 0 else None,
|
| 453 |
+
"nodes_per_s": total_nodes / elapsed if elapsed > 0 else None,
|
| 454 |
+
"latency": latency_summary(latencies),
|
| 455 |
+
"batches": batch_metrics,
|
| 456 |
+
"resources": resources,
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def write_report(path: Path, report: Mapping[str, Any]) -> None:
|
| 461 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 462 |
+
temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}")
|
| 463 |
+
with temporary.open("w", encoding="utf-8") as handle:
|
| 464 |
+
json.dump(report, handle, indent=2, sort_keys=True, ensure_ascii=False)
|
| 465 |
+
handle.write("\n")
|
| 466 |
+
os.replace(temporary, path)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def run(args: argparse.Namespace) -> Dict[str, Any]:
|
| 470 |
+
compact = Path(args.compact).expanduser().resolve()
|
| 471 |
+
default_report = compact / (
|
| 472 |
+
f"smoke_report_{os.environ.get('SLURM_JOB_ID', str(os.getpid()))}.json"
|
| 473 |
+
)
|
| 474 |
+
report_path = (
|
| 475 |
+
Path(args.report).expanduser().resolve() if args.report else default_report
|
| 476 |
+
)
|
| 477 |
+
report: Dict[str, Any] = {
|
| 478 |
+
"status": "running",
|
| 479 |
+
"compact": str(compact),
|
| 480 |
+
"report": str(report_path),
|
| 481 |
+
"started_utc_epoch_s": time.time(),
|
| 482 |
+
"environment": {
|
| 483 |
+
"hostname": socket.gethostname(),
|
| 484 |
+
"pid": os.getpid(),
|
| 485 |
+
"python": sys.version,
|
| 486 |
+
"torch": torch.__version__,
|
| 487 |
+
"torch_geometric": torch_geometric.__version__,
|
| 488 |
+
"slurm_job_id": os.environ.get("SLURM_JOB_ID"),
|
| 489 |
+
"slurm_array_job_id": os.environ.get("SLURM_ARRAY_JOB_ID"),
|
| 490 |
+
"slurm_array_task_id": os.environ.get("SLURM_ARRAY_TASK_ID"),
|
| 491 |
+
"slurm_cpus_per_task": os.environ.get("SLURM_CPUS_PER_TASK"),
|
| 492 |
+
},
|
| 493 |
+
"config": vars(args),
|
| 494 |
+
"resources_at_start": resource_snapshot(),
|
| 495 |
+
}
|
| 496 |
+
try:
|
| 497 |
+
torch.set_num_threads(args.torch_threads)
|
| 498 |
+
initialization_before = resource_snapshot()
|
| 499 |
+
dataset = CompactGraphDataset(
|
| 500 |
+
compact,
|
| 501 |
+
max_cached_shards=args.max_cached_shards,
|
| 502 |
+
strict=not args.no_strict,
|
| 503 |
+
)
|
| 504 |
+
initialization_after = resource_snapshot()
|
| 505 |
+
if len(dataset) < 1:
|
| 506 |
+
raise RuntimeError("compact dataset is empty")
|
| 507 |
+
|
| 508 |
+
report["dataset"] = {
|
| 509 |
+
"num_graphs": len(dataset),
|
| 510 |
+
"num_shards": len(dataset.shards),
|
| 511 |
+
"n_systems": dataset.manifest.get("n_systems"),
|
| 512 |
+
"method": dataset.manifest.get("method"),
|
| 513 |
+
"size": dataset.manifest.get("size"),
|
| 514 |
+
"initialization": resource_delta(
|
| 515 |
+
initialization_before, initialization_after
|
| 516 |
+
),
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
shard_indices = global_indices_by_shard(dataset)
|
| 520 |
+
selected_shards = evenly_spaced(
|
| 521 |
+
list(range(len(shard_indices))), args.max_shards
|
| 522 |
+
)
|
| 523 |
+
boundary_indices: List[int] = []
|
| 524 |
+
first_per_shard: List[int] = []
|
| 525 |
+
for shard_index in selected_shards:
|
| 526 |
+
indices = shard_indices[shard_index]
|
| 527 |
+
first_per_shard.append(indices[0])
|
| 528 |
+
boundary_indices.append(indices[0])
|
| 529 |
+
if indices[-1] != indices[0]:
|
| 530 |
+
boundary_indices.append(indices[-1])
|
| 531 |
+
report["shard_probe"] = {
|
| 532 |
+
"selected_shards": selected_shards,
|
| 533 |
+
"boundary_indices": boundary_indices,
|
| 534 |
+
"all_shards_selected": len(selected_shards) == len(dataset.shards),
|
| 535 |
+
}
|
| 536 |
+
report["direct_cross_shard"] = load_direct(dataset, boundary_indices)
|
| 537 |
+
|
| 538 |
+
rng = random.Random(args.seed)
|
| 539 |
+
random_count = min(args.num_random, len(dataset))
|
| 540 |
+
random_indices = rng.sample(range(len(dataset)), random_count)
|
| 541 |
+
report["direct_random"] = load_direct(dataset, random_indices)
|
| 542 |
+
|
| 543 |
+
repeat_index = random_indices[0]
|
| 544 |
+
repeat_latencies: List[float] = []
|
| 545 |
+
repeat_before = resource_snapshot()
|
| 546 |
+
for _ in range(args.repeat_count):
|
| 547 |
+
started = time.perf_counter()
|
| 548 |
+
graph = dataset[repeat_index]
|
| 549 |
+
repeat_latencies.append(time.perf_counter() - started)
|
| 550 |
+
check_graph(graph, repeat_index)
|
| 551 |
+
del graph
|
| 552 |
+
gc.collect()
|
| 553 |
+
repeat_after = resource_snapshot()
|
| 554 |
+
report["repeated_access"] = {
|
| 555 |
+
"index": repeat_index,
|
| 556 |
+
"latency": latency_summary(repeat_latencies),
|
| 557 |
+
"resources": resource_delta(repeat_before, repeat_after),
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
cross_loader_indices = first_per_shard[
|
| 561 |
+
: args.batch_size * args.max_batches
|
| 562 |
+
]
|
| 563 |
+
report["cross_shard_dataloader"] = run_loader(
|
| 564 |
+
dataset,
|
| 565 |
+
cross_loader_indices,
|
| 566 |
+
batch_size=min(args.batch_size, len(cross_loader_indices)),
|
| 567 |
+
num_workers=0,
|
| 568 |
+
max_batches=args.max_batches,
|
| 569 |
+
worker_timeout_s=args.worker_timeout_s,
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
worker_indices = list(dict.fromkeys(random_indices + boundary_indices))
|
| 573 |
+
worker_indices = worker_indices[: args.batch_size * args.max_batches]
|
| 574 |
+
# Forked workers should start with an empty mmap cache. Constructing a
|
| 575 |
+
# fresh dataset here also catches errors in opening the same manifest
|
| 576 |
+
# independently from more than one process.
|
| 577 |
+
worker_dataset = CompactGraphDataset(
|
| 578 |
+
compact,
|
| 579 |
+
max_cached_shards=args.max_cached_shards,
|
| 580 |
+
strict=not args.no_strict,
|
| 581 |
+
)
|
| 582 |
+
report["multiworker_dataloader"] = run_loader(
|
| 583 |
+
worker_dataset,
|
| 584 |
+
worker_indices,
|
| 585 |
+
batch_size=min(args.batch_size, len(worker_indices)),
|
| 586 |
+
num_workers=args.num_workers,
|
| 587 |
+
max_batches=args.max_batches,
|
| 588 |
+
worker_timeout_s=args.worker_timeout_s,
|
| 589 |
+
)
|
| 590 |
+
del worker_dataset
|
| 591 |
+
|
| 592 |
+
report["resources_at_end"] = resource_snapshot()
|
| 593 |
+
report["completed_utc_epoch_s"] = time.time()
|
| 594 |
+
report["elapsed_s"] = (
|
| 595 |
+
report["completed_utc_epoch_s"] - report["started_utc_epoch_s"]
|
| 596 |
+
)
|
| 597 |
+
report["status"] = "passed"
|
| 598 |
+
except Exception as error:
|
| 599 |
+
report["status"] = "failed"
|
| 600 |
+
report["completed_utc_epoch_s"] = time.time()
|
| 601 |
+
report["elapsed_s"] = (
|
| 602 |
+
report["completed_utc_epoch_s"] - report["started_utc_epoch_s"]
|
| 603 |
+
)
|
| 604 |
+
report["error"] = f"{type(error).__name__}: {error}"
|
| 605 |
+
report["traceback"] = traceback.format_exc()
|
| 606 |
+
write_report(report_path, report)
|
| 607 |
+
raise
|
| 608 |
+
|
| 609 |
+
write_report(report_path, report)
|
| 610 |
+
print(
|
| 611 |
+
json.dumps(
|
| 612 |
+
{
|
| 613 |
+
"status": report["status"],
|
| 614 |
+
"report": str(report_path),
|
| 615 |
+
"num_graphs": report["dataset"]["num_graphs"],
|
| 616 |
+
"num_shards": report["dataset"]["num_shards"],
|
| 617 |
+
"elapsed_s": report["elapsed_s"],
|
| 618 |
+
"rss_mib": report["resources_at_end"]["rss_mib"],
|
| 619 |
+
"hwm_mib": report["resources_at_end"]["hwm_mib"],
|
| 620 |
+
},
|
| 621 |
+
indent=2,
|
| 622 |
+
sort_keys=True,
|
| 623 |
+
),
|
| 624 |
+
flush=True,
|
| 625 |
+
)
|
| 626 |
+
return report
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def main() -> int:
|
| 630 |
+
args = parse_args()
|
| 631 |
+
report = run(args)
|
| 632 |
+
return 0 if report["status"] == "passed" else 1
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
if __name__ == "__main__":
|
| 636 |
+
raise SystemExit(main())
|
code/compact_v1/test_build_compact_v1_direct.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Small, CPU-only tests for the resumable direct compact_v1 builder."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import tempfile
|
| 8 |
+
import time
|
| 9 |
+
import unittest
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from unittest import mock
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch_geometric.data import Data
|
| 15 |
+
|
| 16 |
+
import build_compact_v1_direct as direct
|
| 17 |
+
from compact_graph_dataset import CompactGraphDataset
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _synthetic_graph(
|
| 21 |
+
system_id: str,
|
| 22 |
+
pose_number: int,
|
| 23 |
+
*,
|
| 24 |
+
split_static: bool = False,
|
| 25 |
+
) -> Data:
|
| 26 |
+
n_protein = 2
|
| 27 |
+
n_nodes = 4
|
| 28 |
+
x = torch.zeros((n_nodes, 82), dtype=torch.float32)
|
| 29 |
+
x[:, 0] = 1.0
|
| 30 |
+
x[:n_protein, 11] = 1.0
|
| 31 |
+
x[n_protein:, 31] = 1.0
|
| 32 |
+
x[:n_protein, 32] = 1.0
|
| 33 |
+
x[n_protein:, 33] = 1.0
|
| 34 |
+
x[:, 61:71] = 0.25
|
| 35 |
+
x[:, 34:61] = float(pose_number)
|
| 36 |
+
x[:, 71:82] = float(pose_number) / 10.0
|
| 37 |
+
if split_static and pose_number == 2:
|
| 38 |
+
x[2, 0] = 0.0
|
| 39 |
+
x[2, 1] = 1.0
|
| 40 |
+
|
| 41 |
+
system_offset = 5.0 if system_id == "sys_b" else 0.0
|
| 42 |
+
protein_pos = torch.tensor(
|
| 43 |
+
[[system_offset, 0.0, 0.0], [system_offset + 1.0, 0.0, 0.0]],
|
| 44 |
+
dtype=torch.float32,
|
| 45 |
+
)
|
| 46 |
+
ligand_pos = torch.tensor(
|
| 47 |
+
[
|
| 48 |
+
[system_offset + 1.5, 0.1 * pose_number, 0.0],
|
| 49 |
+
[system_offset + 2.0, 0.2 * pose_number, 0.0],
|
| 50 |
+
],
|
| 51 |
+
dtype=torch.float32,
|
| 52 |
+
)
|
| 53 |
+
native_ligand = torch.tensor(
|
| 54 |
+
[
|
| 55 |
+
[system_offset + 1.5, 0.0, 0.0],
|
| 56 |
+
[system_offset + 2.0, 0.0, 0.0],
|
| 57 |
+
],
|
| 58 |
+
dtype=torch.float32,
|
| 59 |
+
)
|
| 60 |
+
pos = torch.cat((protein_pos, ligand_pos), dim=0)
|
| 61 |
+
y_grt = torch.cat((protein_pos, native_ligand), dim=0)
|
| 62 |
+
y_true = torch.linalg.vector_norm(pos - y_grt, dim=1, keepdim=True)
|
| 63 |
+
edge_index = torch.tensor(
|
| 64 |
+
[[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]],
|
| 65 |
+
dtype=torch.int64,
|
| 66 |
+
)
|
| 67 |
+
src, dst = edge_index
|
| 68 |
+
distance = torch.linalg.vector_norm(
|
| 69 |
+
pos[src].to(torch.float64) - pos[dst].to(torch.float64),
|
| 70 |
+
dim=1,
|
| 71 |
+
)
|
| 72 |
+
edge_attr = torch.stack(
|
| 73 |
+
(
|
| 74 |
+
(distance / 6.0).to(torch.float32),
|
| 75 |
+
torch.exp(-distance / 3.0).to(torch.float32),
|
| 76 |
+
(src < n_protein).to(torch.float32),
|
| 77 |
+
(dst < n_protein).to(torch.float32),
|
| 78 |
+
),
|
| 79 |
+
dim=1,
|
| 80 |
+
)
|
| 81 |
+
is_protein = torch.zeros((n_nodes, 1), dtype=torch.float32)
|
| 82 |
+
is_protein[:n_protein] = 1.0
|
| 83 |
+
return Data(
|
| 84 |
+
x=x,
|
| 85 |
+
edge_index=edge_index,
|
| 86 |
+
edge_attr=edge_attr,
|
| 87 |
+
pos=pos,
|
| 88 |
+
is_protein=is_protein,
|
| 89 |
+
y_true=y_true,
|
| 90 |
+
y_pred=pos.clone(),
|
| 91 |
+
y_grt=y_grt,
|
| 92 |
+
num_nodes=n_nodes,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class DirectCompactBuilderTest(unittest.TestCase):
|
| 97 |
+
def test_exclusive_output_lock_rejects_concurrent_resume(self) -> None:
|
| 98 |
+
with tempfile.TemporaryDirectory(prefix="direct_compact_lock_") as temp:
|
| 99 |
+
output = Path(temp) / "compact"
|
| 100 |
+
with direct._exclusive_build_lock(output):
|
| 101 |
+
with self.assertRaisesRegex(
|
| 102 |
+
RuntimeError, "another direct compact build"
|
| 103 |
+
):
|
| 104 |
+
with direct._exclusive_build_lock(output):
|
| 105 |
+
self.fail("the second lock must not be acquired")
|
| 106 |
+
|
| 107 |
+
def test_corrupt_pose_checkpoint_is_rebuilt(self) -> None:
|
| 108 |
+
with tempfile.TemporaryDirectory(prefix="direct_compact_corrupt_") as temp:
|
| 109 |
+
root = Path(temp)
|
| 110 |
+
for name in ("protein.pdb", "native.pdb", "pose_1.pdb"):
|
| 111 |
+
(root / name).write_text("test\n", encoding="utf-8")
|
| 112 |
+
pose = direct.PoseSpec(
|
| 113 |
+
source_graph_index=0,
|
| 114 |
+
system_id="sys_a",
|
| 115 |
+
protein=(root / "protein.pdb"),
|
| 116 |
+
ligand_native=(root / "native.pdb"),
|
| 117 |
+
ligand_pred=(root / "pose_1.pdb"),
|
| 118 |
+
)
|
| 119 |
+
system = direct.SystemSpec(
|
| 120 |
+
ordinal=0,
|
| 121 |
+
system_id="sys_a",
|
| 122 |
+
protein=pose.protein,
|
| 123 |
+
ligand_native=pose.ligand_native,
|
| 124 |
+
poses=(pose,),
|
| 125 |
+
)
|
| 126 |
+
work_dir = root / "work"
|
| 127 |
+
work_dir.mkdir()
|
| 128 |
+
corrupt = direct._pose_graph_path(work_dir, 0)
|
| 129 |
+
corrupt.write_bytes(b"not a torch checkpoint")
|
| 130 |
+
calls = []
|
| 131 |
+
|
| 132 |
+
def graph_builder(**kwargs):
|
| 133 |
+
calls.append(kwargs["ligand_pred_pdb"])
|
| 134 |
+
return _synthetic_graph("sys_a", 1)
|
| 135 |
+
|
| 136 |
+
config = direct.BuildConfig(
|
| 137 |
+
data_dir=root,
|
| 138 |
+
output_dir=root / "output",
|
| 139 |
+
method="protenix",
|
| 140 |
+
)
|
| 141 |
+
graphs = direct.build_pose_graphs(
|
| 142 |
+
system,
|
| 143 |
+
work_dir,
|
| 144 |
+
config,
|
| 145 |
+
graph_builder=graph_builder,
|
| 146 |
+
)
|
| 147 |
+
self.assertEqual(len(calls), 1)
|
| 148 |
+
self.assertEqual(len(graphs), 1)
|
| 149 |
+
rebuilt = torch.load(corrupt, map_location="cpu", weights_only=False)
|
| 150 |
+
self.assertTrue(torch.equal(rebuilt.x, graphs[0].x))
|
| 151 |
+
|
| 152 |
+
def test_resume_atomic_publish_and_original_system_index(self) -> None:
|
| 153 |
+
with tempfile.TemporaryDirectory(prefix="direct_compact_test_") as temp:
|
| 154 |
+
root = Path(temp)
|
| 155 |
+
data_dir = root / "docking"
|
| 156 |
+
output_dir = root / "compact"
|
| 157 |
+
raw_poses = []
|
| 158 |
+
for system_id in ("sys_a", "sys_b"):
|
| 159 |
+
system_dir = data_dir / system_id
|
| 160 |
+
system_dir.mkdir(parents=True)
|
| 161 |
+
protein = system_dir / "protein.pdb"
|
| 162 |
+
native = system_dir / "ligand_native.pdb"
|
| 163 |
+
protein.write_text("test\n", encoding="utf-8")
|
| 164 |
+
native.write_text("test\n", encoding="utf-8")
|
| 165 |
+
for pose_number in (1, 2):
|
| 166 |
+
pose = system_dir / f"{system_id}_pose_{pose_number}.pdb"
|
| 167 |
+
pose.write_text("test\n", encoding="utf-8")
|
| 168 |
+
raw_poses.append(
|
| 169 |
+
{
|
| 170 |
+
"pdb_id": system_id,
|
| 171 |
+
"protein": str(protein),
|
| 172 |
+
"ligand_native": str(native),
|
| 173 |
+
"ligand_pred": str(pose),
|
| 174 |
+
}
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def graph_builder(**kwargs):
|
| 178 |
+
pose_path = Path(kwargs["ligand_pred_pdb"])
|
| 179 |
+
system_id = pose_path.parent.name
|
| 180 |
+
pose_number = int(pose_path.stem.rsplit("_", 1)[1])
|
| 181 |
+
return _synthetic_graph(
|
| 182 |
+
system_id,
|
| 183 |
+
pose_number,
|
| 184 |
+
split_static=system_id == "sys_b",
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
def first_attempt_builder(**kwargs):
|
| 188 |
+
if Path(kwargs["ligand_pred_pdb"]).parent.name == "sys_b":
|
| 189 |
+
raise RuntimeError("intentional interruption")
|
| 190 |
+
return graph_builder(**kwargs)
|
| 191 |
+
|
| 192 |
+
config = direct.BuildConfig(
|
| 193 |
+
data_dir=data_dir.resolve(),
|
| 194 |
+
output_dir=output_dir.resolve(),
|
| 195 |
+
method="protenix",
|
| 196 |
+
target_shard_mib=1,
|
| 197 |
+
num_workers=1,
|
| 198 |
+
)
|
| 199 |
+
with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses):
|
| 200 |
+
with self.assertRaisesRegex(RuntimeError, "intentional interruption"):
|
| 201 |
+
direct.run(config, graph_builder=first_attempt_builder)
|
| 202 |
+
|
| 203 |
+
progress_path = (
|
| 204 |
+
output_dir.with_name(".compact.building")
|
| 205 |
+
/ ".build_state"
|
| 206 |
+
/ "progress.json"
|
| 207 |
+
)
|
| 208 |
+
with progress_path.open("r", encoding="utf-8") as handle:
|
| 209 |
+
progress = json.load(handle)
|
| 210 |
+
self.assertEqual(progress["next_system_index"], 1)
|
| 211 |
+
self.assertEqual(progress["successful_source_systems"], 1)
|
| 212 |
+
|
| 213 |
+
resumed = direct.BuildConfig(
|
| 214 |
+
**{**config.__dict__, "resume": True}
|
| 215 |
+
)
|
| 216 |
+
manifest = direct.run(resumed, graph_builder=graph_builder)
|
| 217 |
+
|
| 218 |
+
self.assertTrue((output_dir / "manifest.json").is_file())
|
| 219 |
+
self.assertFalse(output_dir.with_name(".compact.building").exists())
|
| 220 |
+
self.assertFalse((output_dir / ".build_state").exists())
|
| 221 |
+
self.assertEqual(manifest["n_graphs"], 4)
|
| 222 |
+
self.assertEqual(manifest["n_source_systems"], 2)
|
| 223 |
+
# sys_b is intentionally split into two exact-content storage groups.
|
| 224 |
+
self.assertEqual(manifest["n_systems"], 3)
|
| 225 |
+
|
| 226 |
+
with (output_dir / "system_index.json").open(
|
| 227 |
+
"r", encoding="utf-8"
|
| 228 |
+
) as handle:
|
| 229 |
+
system_index = json.load(handle)
|
| 230 |
+
self.assertEqual(
|
| 231 |
+
system_index["graph_to_system"],
|
| 232 |
+
["sys_a", "sys_a", "sys_b", "sys_b"],
|
| 233 |
+
)
|
| 234 |
+
self.assertEqual(system_index["n_systems"], 2)
|
| 235 |
+
|
| 236 |
+
dataset = CompactGraphDataset(output_dir)
|
| 237 |
+
self.assertEqual(len(dataset), 4)
|
| 238 |
+
expected = [
|
| 239 |
+
_synthetic_graph("sys_a", 1),
|
| 240 |
+
_synthetic_graph("sys_a", 2),
|
| 241 |
+
_synthetic_graph("sys_b", 1, split_static=True),
|
| 242 |
+
_synthetic_graph("sys_b", 2, split_static=True),
|
| 243 |
+
]
|
| 244 |
+
for actual, reference in zip(dataset, expected):
|
| 245 |
+
for name in (
|
| 246 |
+
"x",
|
| 247 |
+
"edge_index",
|
| 248 |
+
"edge_attr",
|
| 249 |
+
"pos",
|
| 250 |
+
"is_protein",
|
| 251 |
+
"y_true",
|
| 252 |
+
"y_pred",
|
| 253 |
+
"y_grt",
|
| 254 |
+
):
|
| 255 |
+
self.assertTrue(
|
| 256 |
+
torch.allclose(
|
| 257 |
+
getattr(actual, name),
|
| 258 |
+
getattr(reference, name),
|
| 259 |
+
rtol=1e-6,
|
| 260 |
+
atol=1e-6,
|
| 261 |
+
),
|
| 262 |
+
msg=name,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
def test_parallel_system_build_matches_serial_order(self) -> None:
|
| 266 |
+
"""Out-of-order worker completion must not change source graph order."""
|
| 267 |
+
with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_") as temp:
|
| 268 |
+
root = Path(temp)
|
| 269 |
+
data_dir = root / "docking"
|
| 270 |
+
raw_poses = []
|
| 271 |
+
for system_id in ("sys_a", "sys_b", "sys_c"):
|
| 272 |
+
system_dir = data_dir / system_id
|
| 273 |
+
system_dir.mkdir(parents=True)
|
| 274 |
+
protein = system_dir / "protein.pdb"
|
| 275 |
+
native = system_dir / "ligand_native.pdb"
|
| 276 |
+
protein.write_text("test\n", encoding="utf-8")
|
| 277 |
+
native.write_text("test\n", encoding="utf-8")
|
| 278 |
+
for pose_number in (1, 2):
|
| 279 |
+
pose = system_dir / f"{system_id}_pose_{pose_number}.pdb"
|
| 280 |
+
pose.write_text("test\n", encoding="utf-8")
|
| 281 |
+
raw_poses.append(
|
| 282 |
+
{
|
| 283 |
+
"pdb_id": system_id,
|
| 284 |
+
"protein": str(protein),
|
| 285 |
+
"ligand_native": str(native),
|
| 286 |
+
"ligand_pred": str(pose),
|
| 287 |
+
}
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
def graph_builder(**kwargs):
|
| 291 |
+
pose_path = Path(kwargs["ligand_pred_pdb"])
|
| 292 |
+
system_id = pose_path.parent.name
|
| 293 |
+
# sys_a is deliberately slower so workers complete out of order.
|
| 294 |
+
if system_id == "sys_a":
|
| 295 |
+
time.sleep(0.15)
|
| 296 |
+
pose_number = int(pose_path.stem.rsplit("_", 1)[1])
|
| 297 |
+
return _synthetic_graph(system_id, pose_number)
|
| 298 |
+
|
| 299 |
+
serial_output = root / "serial"
|
| 300 |
+
parallel_output = root / "parallel"
|
| 301 |
+
serial_config = direct.BuildConfig(
|
| 302 |
+
data_dir=data_dir.resolve(),
|
| 303 |
+
output_dir=serial_output.resolve(),
|
| 304 |
+
method="protenix",
|
| 305 |
+
target_shard_mib=1,
|
| 306 |
+
num_workers=1,
|
| 307 |
+
)
|
| 308 |
+
parallel_config = direct.BuildConfig(
|
| 309 |
+
data_dir=data_dir.resolve(),
|
| 310 |
+
output_dir=parallel_output.resolve(),
|
| 311 |
+
method="protenix",
|
| 312 |
+
target_shard_mib=1,
|
| 313 |
+
num_workers=1,
|
| 314 |
+
system_workers=2,
|
| 315 |
+
memory_budget_gib=8.0,
|
| 316 |
+
)
|
| 317 |
+
with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses):
|
| 318 |
+
serial_manifest = direct.run(serial_config, graph_builder=graph_builder)
|
| 319 |
+
parallel_manifest = direct.run(parallel_config, graph_builder=graph_builder)
|
| 320 |
+
|
| 321 |
+
self.assertEqual(serial_manifest["n_graphs"], parallel_manifest["n_graphs"])
|
| 322 |
+
self.assertEqual(serial_manifest["graph_map"], parallel_manifest["graph_map"])
|
| 323 |
+
self.assertEqual(serial_manifest["shards"], parallel_manifest["shards"])
|
| 324 |
+
with (serial_output / "system_index.json").open("r", encoding="utf-8") as handle:
|
| 325 |
+
serial_index = json.load(handle)
|
| 326 |
+
with (parallel_output / "system_index.json").open("r", encoding="utf-8") as handle:
|
| 327 |
+
parallel_index = json.load(handle)
|
| 328 |
+
self.assertEqual(serial_index, parallel_index)
|
| 329 |
+
|
| 330 |
+
def test_parallel_ready_checkpoint_resumes_in_source_order(self) -> None:
|
| 331 |
+
"""A later ready system survives interruption before the earlier system."""
|
| 332 |
+
with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_resume_") as temp:
|
| 333 |
+
root = Path(temp)
|
| 334 |
+
data_dir = root / "docking"
|
| 335 |
+
output_dir = root / "compact"
|
| 336 |
+
raw_poses = []
|
| 337 |
+
for system_id in ("sys_a", "sys_b"):
|
| 338 |
+
system_dir = data_dir / system_id
|
| 339 |
+
system_dir.mkdir(parents=True)
|
| 340 |
+
protein = system_dir / "protein.pdb"
|
| 341 |
+
native = system_dir / "ligand_native.pdb"
|
| 342 |
+
protein.write_text("test\n", encoding="utf-8")
|
| 343 |
+
native.write_text("test\n", encoding="utf-8")
|
| 344 |
+
for pose_number in (1, 2):
|
| 345 |
+
pose = system_dir / f"{system_id}_pose_{pose_number}.pdb"
|
| 346 |
+
pose.write_text("test\n", encoding="utf-8")
|
| 347 |
+
raw_poses.append(
|
| 348 |
+
{
|
| 349 |
+
"pdb_id": system_id,
|
| 350 |
+
"protein": str(protein),
|
| 351 |
+
"ligand_native": str(native),
|
| 352 |
+
"ligand_pred": str(pose),
|
| 353 |
+
}
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
def graph_builder(**kwargs):
|
| 357 |
+
pose_path = Path(kwargs["ligand_pred_pdb"])
|
| 358 |
+
system_id = pose_path.parent.name
|
| 359 |
+
pose_number = int(pose_path.stem.rsplit("_", 1)[1])
|
| 360 |
+
return _synthetic_graph(system_id, pose_number)
|
| 361 |
+
|
| 362 |
+
def interrupted_builder(**kwargs):
|
| 363 |
+
pose_path = Path(kwargs["ligand_pred_pdb"])
|
| 364 |
+
if pose_path.parent.name == "sys_a":
|
| 365 |
+
time.sleep(0.35)
|
| 366 |
+
raise RuntimeError("intentional parallel interruption")
|
| 367 |
+
return graph_builder(**kwargs)
|
| 368 |
+
|
| 369 |
+
config = direct.BuildConfig(
|
| 370 |
+
data_dir=data_dir.resolve(),
|
| 371 |
+
output_dir=output_dir.resolve(),
|
| 372 |
+
method="protenix",
|
| 373 |
+
target_shard_mib=1,
|
| 374 |
+
num_workers=1,
|
| 375 |
+
system_workers=2,
|
| 376 |
+
memory_budget_gib=8.0,
|
| 377 |
+
)
|
| 378 |
+
with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses):
|
| 379 |
+
with self.assertRaisesRegex(RuntimeError, "parallel worker.*sys_a"):
|
| 380 |
+
direct.run(config, graph_builder=interrupted_builder)
|
| 381 |
+
|
| 382 |
+
stage_dir = output_dir.with_name(".compact.building")
|
| 383 |
+
progress_path = stage_dir / ".build_state" / "progress.json"
|
| 384 |
+
with progress_path.open("r", encoding="utf-8") as handle:
|
| 385 |
+
progress = json.load(handle)
|
| 386 |
+
self.assertEqual(progress["next_system_index"], 0)
|
| 387 |
+
self.assertTrue(
|
| 388 |
+
(stage_dir / ".build_state" / "ready" / "system_00000001.pt").is_file()
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
resumed = direct.BuildConfig(**{**config.__dict__, "resume": True})
|
| 392 |
+
manifest = direct.run(resumed, graph_builder=graph_builder)
|
| 393 |
+
|
| 394 |
+
self.assertEqual(manifest["n_graphs"], 4)
|
| 395 |
+
with (output_dir / "system_index.json").open("r", encoding="utf-8") as handle:
|
| 396 |
+
system_index = json.load(handle)
|
| 397 |
+
self.assertEqual(
|
| 398 |
+
system_index["graph_to_system"], ["sys_a", "sys_a", "sys_b", "sys_b"]
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
if __name__ == "__main__":
|
| 403 |
+
unittest.main()
|
code/compact_v1/test_compact_graph_dataset.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Tiny synthetic round-trip test for CompactGraphDataset.
|
| 3 |
+
|
| 4 |
+
The test creates only a few dozen tensor values in a temporary directory. It
|
| 5 |
+
does not read any production dataset.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import pickle
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import unittest
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Dict, List, Sequence, Tuple
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch_geometric.data import Data
|
| 21 |
+
from torch_geometric.loader import DataLoader
|
| 22 |
+
|
| 23 |
+
from compact_graph_dataset import CompactGraphDataset
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
CUTOFF = 2.5
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _upper_edges(pos: torch.Tensor, n_protein: int) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 30 |
+
pairs: List[Tuple[int, int]] = []
|
| 31 |
+
nonpp: List[Tuple[int, int]] = []
|
| 32 |
+
for src in range(pos.shape[0]):
|
| 33 |
+
for dst in range(src + 1, pos.shape[0]):
|
| 34 |
+
distance = torch.sqrt(
|
| 35 |
+
torch.sum(
|
| 36 |
+
(pos[src].to(torch.float64) - pos[dst].to(torch.float64)) ** 2
|
| 37 |
+
)
|
| 38 |
+
)
|
| 39 |
+
if float(distance) <= CUTOFF:
|
| 40 |
+
if dst < n_protein:
|
| 41 |
+
pairs.append((src, dst))
|
| 42 |
+
else:
|
| 43 |
+
nonpp.append((src, dst))
|
| 44 |
+
pp_tensor = (
|
| 45 |
+
torch.tensor(pairs, dtype=torch.int32).t().contiguous()
|
| 46 |
+
if pairs
|
| 47 |
+
else torch.empty((2, 0), dtype=torch.int32)
|
| 48 |
+
)
|
| 49 |
+
nonpp_tensor = (
|
| 50 |
+
torch.tensor(nonpp, dtype=torch.int32).t().contiguous()
|
| 51 |
+
if nonpp
|
| 52 |
+
else torch.empty((2, 0), dtype=torch.int32)
|
| 53 |
+
)
|
| 54 |
+
return pp_tensor, nonpp_tensor
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _legacy_graph(
|
| 58 |
+
static: torch.Tensor,
|
| 59 |
+
dynamic: torch.Tensor,
|
| 60 |
+
protein: torch.Tensor,
|
| 61 |
+
ligand: torch.Tensor,
|
| 62 |
+
native: torch.Tensor,
|
| 63 |
+
pp_upper: torch.Tensor,
|
| 64 |
+
nonpp_upper: torch.Tensor,
|
| 65 |
+
) -> Data:
|
| 66 |
+
n_protein = protein.shape[0]
|
| 67 |
+
n = static.shape[0]
|
| 68 |
+
x = torch.empty((n, 82), dtype=torch.float32)
|
| 69 |
+
x[:, :34] = static[:, :34]
|
| 70 |
+
x[:, 34:61] = dynamic[:, :27]
|
| 71 |
+
x[:, 61:71] = static[:, 34:44]
|
| 72 |
+
x[:, 71:82] = dynamic[:, 27:38]
|
| 73 |
+
pos = torch.cat((protein, ligand), dim=0)
|
| 74 |
+
y_grt = torch.cat((protein, native), dim=0)
|
| 75 |
+
is_protein = torch.zeros((n, 1), dtype=torch.float32)
|
| 76 |
+
is_protein[:n_protein] = 1
|
| 77 |
+
y_true = torch.zeros((n, 1), dtype=torch.float32)
|
| 78 |
+
y_true[n_protein:, 0] = torch.sqrt(
|
| 79 |
+
torch.sum((ligand - native) ** 2, dim=1)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
upper = torch.cat((pp_upper.to(torch.int64), nonpp_upper.to(torch.int64)), dim=1)
|
| 83 |
+
src = torch.cat((upper[0], upper[1]))
|
| 84 |
+
dst = torch.cat((upper[1], upper[0]))
|
| 85 |
+
distance = torch.sqrt(
|
| 86 |
+
torch.sum(
|
| 87 |
+
(
|
| 88 |
+
pos[upper[0]].to(torch.float64)
|
| 89 |
+
- pos[upper[1]].to(torch.float64)
|
| 90 |
+
)
|
| 91 |
+
** 2,
|
| 92 |
+
dim=1,
|
| 93 |
+
)
|
| 94 |
+
)
|
| 95 |
+
attr0 = torch.cat(((distance / CUTOFF).float(), (distance / CUTOFF).float()))
|
| 96 |
+
attr1 = torch.cat((torch.exp(-distance / 3).float(), torch.exp(-distance / 3).float()))
|
| 97 |
+
order = torch.argsort(src * n + dst)
|
| 98 |
+
src, dst = src[order], dst[order]
|
| 99 |
+
edge_index = torch.stack((src, dst))
|
| 100 |
+
edge_attr = torch.stack(
|
| 101 |
+
(
|
| 102 |
+
attr0[order],
|
| 103 |
+
attr1[order],
|
| 104 |
+
(src < n_protein).float(),
|
| 105 |
+
(dst < n_protein).float(),
|
| 106 |
+
),
|
| 107 |
+
dim=1,
|
| 108 |
+
)
|
| 109 |
+
return Data(
|
| 110 |
+
x=x,
|
| 111 |
+
edge_index=edge_index,
|
| 112 |
+
edge_attr=edge_attr,
|
| 113 |
+
pos=pos,
|
| 114 |
+
is_protein=is_protein,
|
| 115 |
+
y_true=y_true,
|
| 116 |
+
y_pred=pos,
|
| 117 |
+
y_grt=y_grt,
|
| 118 |
+
num_nodes=n,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _make_dataset(root: Path) -> Sequence[Data]:
|
| 123 |
+
generator = torch.Generator().manual_seed(17)
|
| 124 |
+
|
| 125 |
+
protein_a = torch.tensor(
|
| 126 |
+
[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
|
| 127 |
+
dtype=torch.float32,
|
| 128 |
+
)
|
| 129 |
+
native_a = torch.tensor([[1.4, 1.1, 0.0], [2.0, 1.0, 0.0]], dtype=torch.float32)
|
| 130 |
+
ligands_a = [
|
| 131 |
+
native_a + torch.tensor([[0.1, 0.0, 0.0], [0.0, -0.2, 0.1]]),
|
| 132 |
+
native_a + torch.tensor([[-0.2, 0.1, 0.0], [0.2, 0.0, -0.1]]),
|
| 133 |
+
]
|
| 134 |
+
protein_b = torch.tensor([[10.0, 0.0, 0.0], [11.0, 0.0, 0.0]], dtype=torch.float32)
|
| 135 |
+
native_b = torch.tensor([[10.5, 1.0, 0.0]], dtype=torch.float32)
|
| 136 |
+
ligands_b = [native_b + torch.tensor([[0.0, 0.2, -0.1]])]
|
| 137 |
+
|
| 138 |
+
systems = [
|
| 139 |
+
(protein_a, native_a, ligands_a),
|
| 140 |
+
(protein_b, native_b, ligands_b),
|
| 141 |
+
]
|
| 142 |
+
static_parts = [
|
| 143 |
+
torch.randn((protein.shape[0] + native.shape[0], 44), generator=generator)
|
| 144 |
+
for protein, native, _ in systems
|
| 145 |
+
]
|
| 146 |
+
pp_parts: List[torch.Tensor] = []
|
| 147 |
+
for protein, native, _ in systems:
|
| 148 |
+
pp, _ = _upper_edges(torch.cat((protein, native), dim=0), protein.shape[0])
|
| 149 |
+
pp_parts.append(pp)
|
| 150 |
+
|
| 151 |
+
# Local pose order: A0, A1, B0. Original/source order: B0, A0, A1.
|
| 152 |
+
pose_system = torch.tensor([0, 0, 1], dtype=torch.int32)
|
| 153 |
+
source_graph_index = torch.tensor([1, 2, 0], dtype=torch.int64)
|
| 154 |
+
dynamic_parts: List[torch.Tensor] = []
|
| 155 |
+
ligand_parts: List[torch.Tensor] = []
|
| 156 |
+
nonpp_parts: List[torch.Tensor] = []
|
| 157 |
+
local_graphs: List[Data] = []
|
| 158 |
+
for system_index, (_, _, ligands) in enumerate(systems):
|
| 159 |
+
protein, native, _ = systems[system_index]
|
| 160 |
+
for ligand in ligands:
|
| 161 |
+
n = protein.shape[0] + ligand.shape[0]
|
| 162 |
+
dynamic = torch.randn((n, 38), generator=generator)
|
| 163 |
+
_, nonpp = _upper_edges(torch.cat((protein, ligand), dim=0), protein.shape[0])
|
| 164 |
+
dynamic_parts.append(dynamic)
|
| 165 |
+
ligand_parts.append(ligand)
|
| 166 |
+
nonpp_parts.append(nonpp)
|
| 167 |
+
local_graphs.append(
|
| 168 |
+
_legacy_graph(
|
| 169 |
+
static_parts[system_index],
|
| 170 |
+
dynamic,
|
| 171 |
+
protein,
|
| 172 |
+
ligand,
|
| 173 |
+
native,
|
| 174 |
+
pp_parts[system_index],
|
| 175 |
+
nonpp,
|
| 176 |
+
)
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def pointer(lengths: Sequence[int]) -> torch.Tensor:
|
| 180 |
+
result = [0]
|
| 181 |
+
for length in lengths:
|
| 182 |
+
result.append(result[-1] + int(length))
|
| 183 |
+
return torch.tensor(result, dtype=torch.int64)
|
| 184 |
+
|
| 185 |
+
shard: Dict[str, torch.Tensor] = {
|
| 186 |
+
"schema_version": torch.tensor([1], dtype=torch.int32),
|
| 187 |
+
"system_graph_ptr": torch.tensor([0, 2, 3], dtype=torch.int64),
|
| 188 |
+
"pose_system": pose_system,
|
| 189 |
+
"source_graph_index": source_graph_index,
|
| 190 |
+
"system_node_ptr": pointer([part.shape[0] for part in static_parts]),
|
| 191 |
+
"n_protein": torch.tensor(
|
| 192 |
+
[protein.shape[0] for protein, _, _ in systems], dtype=torch.int32
|
| 193 |
+
),
|
| 194 |
+
"x_static": torch.cat(static_parts, dim=0),
|
| 195 |
+
"protein_ptr": pointer([protein.shape[0] for protein, _, _ in systems]),
|
| 196 |
+
"protein_pos": torch.cat([protein for protein, _, _ in systems], dim=0),
|
| 197 |
+
"native_ligand_ptr": pointer([native.shape[0] for _, native, _ in systems]),
|
| 198 |
+
"native_ligand_pos": torch.cat([native for _, native, _ in systems], dim=0),
|
| 199 |
+
"pose_node_ptr": pointer([part.shape[0] for part in dynamic_parts]),
|
| 200 |
+
"x_dynamic": torch.cat(dynamic_parts, dim=0),
|
| 201 |
+
"pose_ligand_ptr": pointer([part.shape[0] for part in ligand_parts]),
|
| 202 |
+
"ligand_pos": torch.cat(ligand_parts, dim=0),
|
| 203 |
+
"pp_edge_ptr": pointer([part.shape[1] for part in pp_parts]),
|
| 204 |
+
"pp_edge_upper": torch.cat(pp_parts, dim=1),
|
| 205 |
+
"nonpp_edge_ptr": pointer([part.shape[1] for part in nonpp_parts]),
|
| 206 |
+
"nonpp_edge_upper": torch.cat(nonpp_parts, dim=1),
|
| 207 |
+
}
|
| 208 |
+
(root / "shards").mkdir()
|
| 209 |
+
torch.save(shard, root / "shards" / "shard_00000.pt")
|
| 210 |
+
manifest = {
|
| 211 |
+
"format": "gnncp_compact_v1",
|
| 212 |
+
"schema_version": 1,
|
| 213 |
+
"cutoff": CUTOFF,
|
| 214 |
+
"num_graphs": 3,
|
| 215 |
+
"static_columns": [[0, 34], [61, 71]],
|
| 216 |
+
"dynamic_columns": [[34, 61], [71, 82]],
|
| 217 |
+
"shards": [
|
| 218 |
+
{
|
| 219 |
+
"path": "shards/shard_00000.pt",
|
| 220 |
+
"num_graphs": 3,
|
| 221 |
+
"system_ids": ["system_a", "system_b"],
|
| 222 |
+
}
|
| 223 |
+
],
|
| 224 |
+
"graph_map": [[0, 2], [0, 0], [0, 1]],
|
| 225 |
+
}
|
| 226 |
+
(root / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
|
| 227 |
+
return [local_graphs[2], local_graphs[0], local_graphs[1]]
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class CompactGraphDatasetTest(unittest.TestCase):
|
| 231 |
+
def test_round_trip_and_batch(self) -> None:
|
| 232 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 233 |
+
root = Path(temporary)
|
| 234 |
+
references = _make_dataset(root)
|
| 235 |
+
dataset = CompactGraphDataset(root)
|
| 236 |
+
self.assertEqual(len(dataset), 3)
|
| 237 |
+
for index, reference in enumerate(references):
|
| 238 |
+
actual = dataset[index]
|
| 239 |
+
for field in (
|
| 240 |
+
"x",
|
| 241 |
+
"edge_index",
|
| 242 |
+
"edge_attr",
|
| 243 |
+
"pos",
|
| 244 |
+
"is_protein",
|
| 245 |
+
"y_true",
|
| 246 |
+
"y_pred",
|
| 247 |
+
"y_grt",
|
| 248 |
+
):
|
| 249 |
+
self.assertTrue(
|
| 250 |
+
torch.equal(getattr(actual, field), getattr(reference, field)),
|
| 251 |
+
msg=f"mismatch at graph={index}, field={field}",
|
| 252 |
+
)
|
| 253 |
+
self.assertEqual(dataset.metadata(index)["source_graph_index"], index)
|
| 254 |
+
|
| 255 |
+
batch = next(iter(DataLoader(dataset, batch_size=2, shuffle=False)))
|
| 256 |
+
self.assertEqual(batch.x.shape[1], 82)
|
| 257 |
+
self.assertEqual(batch.edge_attr.shape[1], 4)
|
| 258 |
+
self.assertEqual(batch.num_graphs, 2)
|
| 259 |
+
|
| 260 |
+
# DataLoader spawn/fork must not serialise mmap shard objects.
|
| 261 |
+
restored = pickle.loads(pickle.dumps(dataset))
|
| 262 |
+
self.assertEqual(len(restored._cache), 0)
|
| 263 |
+
self.assertTrue(torch.equal(restored[-1].x, references[-1].x))
|
| 264 |
+
|
| 265 |
+
def test_converter_cli_round_trip(self) -> None:
|
| 266 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 267 |
+
root = Path(temporary)
|
| 268 |
+
seed_root = root / "seed"
|
| 269 |
+
seed_root.mkdir()
|
| 270 |
+
references = _make_dataset(seed_root)
|
| 271 |
+
legacy = root / "legacy.pt"
|
| 272 |
+
system_index = root / "system_index.json"
|
| 273 |
+
output = root / "converted"
|
| 274 |
+
torch.save(list(references), legacy)
|
| 275 |
+
system_index.write_text(
|
| 276 |
+
json.dumps(
|
| 277 |
+
{"graph_to_system": ["system_b", "system_a", "system_a"]}
|
| 278 |
+
),
|
| 279 |
+
encoding="utf-8",
|
| 280 |
+
)
|
| 281 |
+
script = Path(__file__).with_name("convert_to_compact_v1.py")
|
| 282 |
+
subprocess.run(
|
| 283 |
+
[
|
| 284 |
+
sys.executable,
|
| 285 |
+
str(script),
|
| 286 |
+
"--input",
|
| 287 |
+
str(legacy),
|
| 288 |
+
"--output-dir",
|
| 289 |
+
str(output),
|
| 290 |
+
"--method",
|
| 291 |
+
"synthetic",
|
| 292 |
+
"--system-index",
|
| 293 |
+
str(system_index),
|
| 294 |
+
"--target-shard-mib",
|
| 295 |
+
"1",
|
| 296 |
+
"--cutoff",
|
| 297 |
+
str(CUTOFF),
|
| 298 |
+
],
|
| 299 |
+
check=True,
|
| 300 |
+
cwd=script.parent,
|
| 301 |
+
capture_output=True,
|
| 302 |
+
text=True,
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
dataset = CompactGraphDataset(output)
|
| 306 |
+
self.assertEqual(len(dataset), len(references))
|
| 307 |
+
for index, reference in enumerate(references):
|
| 308 |
+
actual = dataset[index]
|
| 309 |
+
for field in (
|
| 310 |
+
"x",
|
| 311 |
+
"edge_index",
|
| 312 |
+
"edge_attr",
|
| 313 |
+
"pos",
|
| 314 |
+
"is_protein",
|
| 315 |
+
"y_true",
|
| 316 |
+
"y_pred",
|
| 317 |
+
"y_grt",
|
| 318 |
+
):
|
| 319 |
+
self.assertTrue(
|
| 320 |
+
torch.equal(getattr(actual, field), getattr(reference, field)),
|
| 321 |
+
msg=f"writer round-trip mismatch graph={index}, field={field}",
|
| 322 |
+
)
|
| 323 |
+
self.assertEqual(dataset.metadata(index)["source_graph_index"], index)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
if __name__ == "__main__":
|
| 327 |
+
unittest.main()
|
code/compact_v1/validate_compact_dataset.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Sample-level validation for a GNNCP compact graph dataset.
|
| 3 |
+
|
| 4 |
+
This program never iterates the full legacy dataset. When ``--legacy`` is
|
| 5 |
+
provided it opens the old monolithic .pt with ``torch.load(..., mmap=True)``
|
| 6 |
+
and touches only the requested sample tensors.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import random
|
| 14 |
+
import resource
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from compact_graph_dataset import CompactGraphDataset
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
CORE_FIELDS = (
|
| 25 |
+
"x",
|
| 26 |
+
"edge_index",
|
| 27 |
+
"edge_attr",
|
| 28 |
+
"pos",
|
| 29 |
+
"is_protein",
|
| 30 |
+
"y_true",
|
| 31 |
+
"y_pred",
|
| 32 |
+
"y_grt",
|
| 33 |
+
)
|
| 34 |
+
FLOAT_FIELDS = {
|
| 35 |
+
"x",
|
| 36 |
+
"edge_attr",
|
| 37 |
+
"pos",
|
| 38 |
+
"is_protein",
|
| 39 |
+
"y_true",
|
| 40 |
+
"y_pred",
|
| 41 |
+
"y_grt",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _rss_mib() -> float:
|
| 46 |
+
value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
| 47 |
+
# Linux reports KiB; macOS reports bytes.
|
| 48 |
+
if sys.platform == "darwin":
|
| 49 |
+
return value / (1024.0 * 1024.0)
|
| 50 |
+
return value / 1024.0
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _parse_indices(text: Optional[str], length: int) -> Optional[List[int]]:
|
| 54 |
+
if text is None:
|
| 55 |
+
return None
|
| 56 |
+
values: List[int] = []
|
| 57 |
+
for token in text.split(","):
|
| 58 |
+
token = token.strip()
|
| 59 |
+
if not token:
|
| 60 |
+
continue
|
| 61 |
+
if ":" in token:
|
| 62 |
+
parts = token.split(":")
|
| 63 |
+
if len(parts) not in (2, 3):
|
| 64 |
+
raise ValueError(f"bad index range: {token!r}")
|
| 65 |
+
start = int(parts[0]) if parts[0] else 0
|
| 66 |
+
stop = int(parts[1]) if parts[1] else length
|
| 67 |
+
step = int(parts[2]) if len(parts) == 3 and parts[2] else 1
|
| 68 |
+
values.extend(range(start, stop, step))
|
| 69 |
+
else:
|
| 70 |
+
values.append(int(token))
|
| 71 |
+
normalised = []
|
| 72 |
+
for index in values:
|
| 73 |
+
if index < 0:
|
| 74 |
+
index += length
|
| 75 |
+
if not 0 <= index < length:
|
| 76 |
+
raise IndexError(f"sample index {index} outside [0,{length})")
|
| 77 |
+
normalised.append(index)
|
| 78 |
+
return list(dict.fromkeys(normalised))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _choose_indices(length: int, count: int, seed: int) -> List[int]:
|
| 82 |
+
if length <= 0:
|
| 83 |
+
return []
|
| 84 |
+
count = min(max(int(count), 1), length)
|
| 85 |
+
selected = {0, length - 1}
|
| 86 |
+
rng = random.Random(seed)
|
| 87 |
+
while len(selected) < count:
|
| 88 |
+
selected.add(rng.randrange(length))
|
| 89 |
+
return sorted(selected)[:count]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _tensor_stats(
|
| 93 |
+
actual: torch.Tensor,
|
| 94 |
+
expected: torch.Tensor,
|
| 95 |
+
*,
|
| 96 |
+
atol: float,
|
| 97 |
+
rtol: float,
|
| 98 |
+
) -> Dict[str, Any]:
|
| 99 |
+
result: Dict[str, Any] = {
|
| 100 |
+
"actual_shape": list(actual.shape),
|
| 101 |
+
"expected_shape": list(expected.shape),
|
| 102 |
+
"actual_dtype": str(actual.dtype),
|
| 103 |
+
"expected_dtype": str(expected.dtype),
|
| 104 |
+
}
|
| 105 |
+
if tuple(actual.shape) != tuple(expected.shape):
|
| 106 |
+
result.update({"passed": False, "reason": "shape_mismatch"})
|
| 107 |
+
return result
|
| 108 |
+
if actual.dtype != expected.dtype:
|
| 109 |
+
result["dtype_match"] = False
|
| 110 |
+
else:
|
| 111 |
+
result["dtype_match"] = True
|
| 112 |
+
|
| 113 |
+
if actual.numel() == 0:
|
| 114 |
+
result.update(
|
| 115 |
+
{
|
| 116 |
+
"passed": bool(result["dtype_match"]),
|
| 117 |
+
"exact": True,
|
| 118 |
+
"max_abs": 0.0,
|
| 119 |
+
"mean_abs": 0.0,
|
| 120 |
+
}
|
| 121 |
+
)
|
| 122 |
+
return result
|
| 123 |
+
|
| 124 |
+
if actual.is_floating_point() or expected.is_floating_point():
|
| 125 |
+
actual_f64 = actual.to(torch.float64)
|
| 126 |
+
expected_f64 = expected.to(torch.float64)
|
| 127 |
+
finite_match = torch.equal(torch.isfinite(actual_f64), torch.isfinite(expected_f64))
|
| 128 |
+
diff = torch.abs(actual_f64 - expected_f64)
|
| 129 |
+
finite_diff = diff[torch.isfinite(diff)]
|
| 130 |
+
max_abs = float(finite_diff.max().item()) if finite_diff.numel() else float("inf")
|
| 131 |
+
mean_abs = float(finite_diff.mean().item()) if finite_diff.numel() else float("inf")
|
| 132 |
+
close = bool(
|
| 133 |
+
torch.allclose(actual_f64, expected_f64, atol=atol, rtol=rtol, equal_nan=True)
|
| 134 |
+
)
|
| 135 |
+
result.update(
|
| 136 |
+
{
|
| 137 |
+
"passed": bool(close and result["dtype_match"] and finite_match),
|
| 138 |
+
"exact": bool(torch.equal(actual, expected)),
|
| 139 |
+
"finite_pattern_match": finite_match,
|
| 140 |
+
"max_abs": max_abs,
|
| 141 |
+
"mean_abs": mean_abs,
|
| 142 |
+
}
|
| 143 |
+
)
|
| 144 |
+
else:
|
| 145 |
+
exact = bool(torch.equal(actual, expected))
|
| 146 |
+
result.update(
|
| 147 |
+
{
|
| 148 |
+
"passed": bool(exact and result["dtype_match"]),
|
| 149 |
+
"exact": exact,
|
| 150 |
+
}
|
| 151 |
+
)
|
| 152 |
+
return result
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _invariants(graph: Any, cutoff: float, atol: float) -> Dict[str, Any]:
|
| 156 |
+
checks: Dict[str, bool] = {}
|
| 157 |
+
n = int(graph.num_nodes)
|
| 158 |
+
checks["x_Nx82"] = tuple(graph.x.shape) == (n, 82)
|
| 159 |
+
checks["edge_index_2xE"] = graph.edge_index.ndim == 2 and graph.edge_index.shape[0] == 2
|
| 160 |
+
edge_count = int(graph.edge_index.shape[1]) if checks["edge_index_2xE"] else -1
|
| 161 |
+
checks["edge_attr_Ex4"] = tuple(graph.edge_attr.shape) == (edge_count, 4)
|
| 162 |
+
checks["pos_Nx3"] = tuple(graph.pos.shape) == (n, 3)
|
| 163 |
+
checks["is_protein_Nx1"] = tuple(graph.is_protein.shape) == (n, 1)
|
| 164 |
+
checks["y_true_Nx1"] = tuple(graph.y_true.shape) == (n, 1)
|
| 165 |
+
checks["y_pred_Nx3"] = tuple(graph.y_pred.shape) == (n, 3)
|
| 166 |
+
checks["y_grt_Nx3"] = tuple(graph.y_grt.shape) == (n, 3)
|
| 167 |
+
checks["x_float32"] = graph.x.dtype == torch.float32
|
| 168 |
+
checks["edge_index_int64"] = graph.edge_index.dtype == torch.int64
|
| 169 |
+
checks["edge_attr_float32"] = graph.edge_attr.dtype == torch.float32
|
| 170 |
+
checks["coordinates_float32"] = (
|
| 171 |
+
graph.pos.dtype == graph.y_pred.dtype == graph.y_grt.dtype == torch.float32
|
| 172 |
+
)
|
| 173 |
+
checks["pos_equals_y_pred"] = bool(torch.equal(graph.pos, graph.y_pred))
|
| 174 |
+
|
| 175 |
+
if edge_count >= 0 and graph.edge_index.numel():
|
| 176 |
+
src, dst = graph.edge_index
|
| 177 |
+
checks["edge_bounds"] = bool(
|
| 178 |
+
(src.min() >= 0)
|
| 179 |
+
and (dst.min() >= 0)
|
| 180 |
+
and (src.max() < n)
|
| 181 |
+
and (dst.max() < n)
|
| 182 |
+
)
|
| 183 |
+
checks["no_self_edges"] = bool(torch.all(src != dst).item())
|
| 184 |
+
key = src * n + dst
|
| 185 |
+
checks["legacy_edge_order"] = bool(torch.all(key[1:] > key[:-1]).item())
|
| 186 |
+
reversed_key = dst * n + src
|
| 187 |
+
checks["edges_are_bidirectional"] = bool(
|
| 188 |
+
torch.equal(torch.sort(key).values, torch.sort(reversed_key).values)
|
| 189 |
+
)
|
| 190 |
+
distance = torch.sqrt(
|
| 191 |
+
torch.sum(
|
| 192 |
+
(
|
| 193 |
+
graph.pos[src].to(torch.float64)
|
| 194 |
+
- graph.pos[dst].to(torch.float64)
|
| 195 |
+
)
|
| 196 |
+
** 2,
|
| 197 |
+
dim=1,
|
| 198 |
+
)
|
| 199 |
+
)
|
| 200 |
+
checks["edges_within_cutoff"] = bool(
|
| 201 |
+
torch.all(distance <= cutoff + atol).item()
|
| 202 |
+
)
|
| 203 |
+
checks["edge_attr_distance"] = bool(
|
| 204 |
+
torch.allclose(
|
| 205 |
+
graph.edge_attr[:, 0].to(torch.float64),
|
| 206 |
+
distance / cutoff,
|
| 207 |
+
atol=atol,
|
| 208 |
+
rtol=0.0,
|
| 209 |
+
)
|
| 210 |
+
)
|
| 211 |
+
is_protein = graph.is_protein[:, 0]
|
| 212 |
+
checks["edge_attr_endpoint_types"] = bool(
|
| 213 |
+
torch.equal(graph.edge_attr[:, 2], is_protein[src])
|
| 214 |
+
and torch.equal(graph.edge_attr[:, 3], is_protein[dst])
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
checks["edge_bounds"] = True
|
| 218 |
+
checks["no_self_edges"] = True
|
| 219 |
+
checks["legacy_edge_order"] = True
|
| 220 |
+
checks["edges_are_bidirectional"] = True
|
| 221 |
+
checks["edges_within_cutoff"] = True
|
| 222 |
+
checks["edge_attr_distance"] = True
|
| 223 |
+
checks["edge_attr_endpoint_types"] = True
|
| 224 |
+
|
| 225 |
+
protein = graph.is_protein[:, 0] > 0.5
|
| 226 |
+
checks["protein_first"] = bool(
|
| 227 |
+
not protein.numel()
|
| 228 |
+
or not bool((~protein).any().item())
|
| 229 |
+
or not bool(protein[torch.nonzero(~protein, as_tuple=False)[0, 0] :].any().item())
|
| 230 |
+
)
|
| 231 |
+
checks["protein_y_true_zero"] = bool(
|
| 232 |
+
torch.all(graph.y_true[protein] == 0).item()
|
| 233 |
+
)
|
| 234 |
+
ligand_error = torch.sqrt(
|
| 235 |
+
torch.sum((graph.y_pred[~protein] - graph.y_grt[~protein]) ** 2, dim=1)
|
| 236 |
+
)
|
| 237 |
+
checks["ligand_y_true_matches_coordinates"] = bool(
|
| 238 |
+
torch.allclose(
|
| 239 |
+
graph.y_true[~protein, 0],
|
| 240 |
+
ligand_error,
|
| 241 |
+
atol=atol,
|
| 242 |
+
rtol=0.0,
|
| 243 |
+
)
|
| 244 |
+
)
|
| 245 |
+
return {"passed": all(checks.values()), "checks": checks}
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _load_legacy(path: Path, allow_eager: bool) -> Sequence[Any]:
|
| 249 |
+
try:
|
| 250 |
+
return torch.load(
|
| 251 |
+
path,
|
| 252 |
+
map_location="cpu",
|
| 253 |
+
mmap=True,
|
| 254 |
+
weights_only=False,
|
| 255 |
+
)
|
| 256 |
+
except (TypeError, RuntimeError, ValueError) as exc:
|
| 257 |
+
if not allow_eager:
|
| 258 |
+
raise RuntimeError(
|
| 259 |
+
f"could not mmap legacy dataset {path}: {exc}. "
|
| 260 |
+
"Refusing an eager multi-GB load; pass --allow-eager-legacy "
|
| 261 |
+
"only inside a suitably sized Slurm job."
|
| 262 |
+
) from exc
|
| 263 |
+
return torch.load(path, map_location="cpu", weights_only=False)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def validate(args: argparse.Namespace) -> Dict[str, Any]:
|
| 267 |
+
dataset = CompactGraphDataset(
|
| 268 |
+
args.compact,
|
| 269 |
+
max_cached_shards=args.max_cached_shards,
|
| 270 |
+
strict=True,
|
| 271 |
+
)
|
| 272 |
+
indices = _parse_indices(args.indices, len(dataset))
|
| 273 |
+
if indices is None:
|
| 274 |
+
indices = _choose_indices(len(dataset), args.num_samples, args.seed)
|
| 275 |
+
|
| 276 |
+
report: Dict[str, Any] = {
|
| 277 |
+
"compact": str(Path(args.compact).resolve()),
|
| 278 |
+
"num_graphs": len(dataset),
|
| 279 |
+
"indices": indices,
|
| 280 |
+
"atol": args.atol,
|
| 281 |
+
"rtol": args.rtol,
|
| 282 |
+
"rss_mib_before_samples": _rss_mib(),
|
| 283 |
+
"samples": [],
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
legacy: Optional[Sequence[Any]] = None
|
| 287 |
+
if args.legacy is not None:
|
| 288 |
+
legacy = _load_legacy(Path(args.legacy), args.allow_eager_legacy)
|
| 289 |
+
report["legacy"] = str(Path(args.legacy).resolve())
|
| 290 |
+
report["legacy_num_graphs"] = len(legacy)
|
| 291 |
+
if len(legacy) != len(dataset):
|
| 292 |
+
report["length_match"] = False
|
| 293 |
+
else:
|
| 294 |
+
report["length_match"] = True
|
| 295 |
+
|
| 296 |
+
all_passed = report.get("length_match", True)
|
| 297 |
+
for index in indices:
|
| 298 |
+
graph = dataset[index]
|
| 299 |
+
sample_report: Dict[str, Any] = {
|
| 300 |
+
"index": index,
|
| 301 |
+
"metadata": dataset.metadata(index),
|
| 302 |
+
"invariants": _invariants(graph, dataset.cutoff, args.atol),
|
| 303 |
+
}
|
| 304 |
+
sample_passed = bool(sample_report["invariants"]["passed"])
|
| 305 |
+
|
| 306 |
+
if legacy is not None and index < len(legacy):
|
| 307 |
+
reference = legacy[index]
|
| 308 |
+
parity: Dict[str, Any] = {}
|
| 309 |
+
for field in CORE_FIELDS:
|
| 310 |
+
if not hasattr(reference, field):
|
| 311 |
+
parity[field] = {
|
| 312 |
+
"passed": False,
|
| 313 |
+
"reason": "missing_in_legacy_graph",
|
| 314 |
+
}
|
| 315 |
+
continue
|
| 316 |
+
actual = getattr(graph, field)
|
| 317 |
+
expected = getattr(reference, field)
|
| 318 |
+
if not torch.is_tensor(actual) or not torch.is_tensor(expected):
|
| 319 |
+
parity[field] = {
|
| 320 |
+
"passed": False,
|
| 321 |
+
"reason": "field_is_not_tensor",
|
| 322 |
+
}
|
| 323 |
+
continue
|
| 324 |
+
parity[field] = _tensor_stats(
|
| 325 |
+
actual,
|
| 326 |
+
expected,
|
| 327 |
+
atol=args.atol if field in FLOAT_FIELDS else 0.0,
|
| 328 |
+
rtol=args.rtol if field in FLOAT_FIELDS else 0.0,
|
| 329 |
+
)
|
| 330 |
+
sample_report["parity"] = parity
|
| 331 |
+
sample_passed = sample_passed and all(
|
| 332 |
+
bool(result["passed"]) for result in parity.values()
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
sample_report["passed"] = sample_passed
|
| 336 |
+
all_passed = all_passed and sample_passed
|
| 337 |
+
report["samples"].append(sample_report)
|
| 338 |
+
|
| 339 |
+
report["rss_mib_after_samples"] = _rss_mib()
|
| 340 |
+
report["passed"] = bool(all_passed)
|
| 341 |
+
return report
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 345 |
+
parser = argparse.ArgumentParser(
|
| 346 |
+
description="Validate compact GNNCP graphs and optionally compare with legacy tensors."
|
| 347 |
+
)
|
| 348 |
+
parser.add_argument(
|
| 349 |
+
"--compact",
|
| 350 |
+
required=True,
|
| 351 |
+
help="Compact dataset directory or manifest.json",
|
| 352 |
+
)
|
| 353 |
+
parser.add_argument(
|
| 354 |
+
"--legacy",
|
| 355 |
+
help="Legacy list[torch_geometric.data.Data] .pt for mmap parity checks",
|
| 356 |
+
)
|
| 357 |
+
parser.add_argument(
|
| 358 |
+
"--num-samples",
|
| 359 |
+
type=int,
|
| 360 |
+
default=8,
|
| 361 |
+
help="Number of deterministic samples when --indices is omitted (default: 8)",
|
| 362 |
+
)
|
| 363 |
+
parser.add_argument(
|
| 364 |
+
"--indices",
|
| 365 |
+
help="Comma-separated indices/ranges, e.g. '0,10,20:24,-1'",
|
| 366 |
+
)
|
| 367 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 368 |
+
parser.add_argument(
|
| 369 |
+
"--atol",
|
| 370 |
+
type=float,
|
| 371 |
+
default=1e-6,
|
| 372 |
+
help="Absolute tolerance for reconstructed floating tensors",
|
| 373 |
+
)
|
| 374 |
+
parser.add_argument("--rtol", type=float, default=1e-6)
|
| 375 |
+
parser.add_argument("--max-cached-shards", type=int, default=2)
|
| 376 |
+
parser.add_argument(
|
| 377 |
+
"--allow-eager-legacy",
|
| 378 |
+
action="store_true",
|
| 379 |
+
help="Allow fallback to an eager legacy torch.load if mmap is unavailable",
|
| 380 |
+
)
|
| 381 |
+
parser.add_argument(
|
| 382 |
+
"--report",
|
| 383 |
+
help="Optional JSON report path (written atomically by the caller/job filesystem)",
|
| 384 |
+
)
|
| 385 |
+
return parser
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def main() -> int:
|
| 389 |
+
args = build_parser().parse_args()
|
| 390 |
+
report = validate(args)
|
| 391 |
+
rendered = json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)
|
| 392 |
+
print(rendered)
|
| 393 |
+
if args.report:
|
| 394 |
+
output = Path(args.report)
|
| 395 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 396 |
+
output.write_text(rendered + "\n", encoding="utf-8")
|
| 397 |
+
return 0 if report["passed"] else 1
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
if __name__ == "__main__":
|
| 401 |
+
raise SystemExit(main())
|
code/release/upload_copuladock.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Prepare and publish the completed HiQBind compact datasets to Hugging Face.
|
| 3 |
+
|
| 4 |
+
The published repository layout is intentionally simple and stable::
|
| 5 |
+
|
| 6 |
+
README.md
|
| 7 |
+
docs/
|
| 8 |
+
code/compact_v1/
|
| 9 |
+
data/hiqbind_5k_v1/
|
| 10 |
+
autodock_vina_full_v1/
|
| 11 |
+
diffdock_full_v1/
|
| 12 |
+
|
| 13 |
+
``--prepare`` makes a persistent local staging tree. Tensor shards are
|
| 14 |
+
*hard-linked* from the completed local datasets, so the staging tree does not
|
| 15 |
+
duplicate the roughly 93 GB payload. The two JSON files which could expose
|
| 16 |
+
local source paths (``manifest.json`` and ``source_index.json``) are copied
|
| 17 |
+
after recursively replacing absolute paths with a non-path marker.
|
| 18 |
+
|
| 19 |
+
``--upload`` accepts ``HF_TOKEN``, ``--token``, or a token saved by
|
| 20 |
+
``huggingface_hub.login()``. It authenticates with ``whoami`` and checks the
|
| 21 |
+
target dataset repository before invoking ``HfApi.upload_large_folder``. The
|
| 22 |
+
latter keeps its resume metadata below the staging tree, therefore retain the
|
| 23 |
+
same ``--stage-root`` if an upload is interrupted.
|
| 24 |
+
|
| 25 |
+
Examples
|
| 26 |
+
--------
|
| 27 |
+
Inspect without writing or contacting Hugging Face::
|
| 28 |
+
|
| 29 |
+
/u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --dry-run
|
| 30 |
+
|
| 31 |
+
Build and inspect the reusable staging tree::
|
| 32 |
+
|
| 33 |
+
/u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --verify
|
| 34 |
+
|
| 35 |
+
Upload after review (the token is intentionally not printed)::
|
| 36 |
+
|
| 37 |
+
HF_TOKEN=... /u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py \
|
| 38 |
+
--prepare --verify --upload --num-workers 8
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
from __future__ import annotations
|
| 42 |
+
|
| 43 |
+
import argparse
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import shutil
|
| 47 |
+
import sys
|
| 48 |
+
from dataclasses import dataclass
|
| 49 |
+
from pathlib import Path
|
| 50 |
+
from typing import Any, Iterable, Mapping, Sequence
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
RELEASE_ROOT = Path(__file__).resolve().parent
|
| 54 |
+
PROJECT_ROOT = RELEASE_ROOT.parent
|
| 55 |
+
WORKSPACE_ROOT = PROJECT_ROOT.parent
|
| 56 |
+
DEFAULT_DATASET_ROOT = PROJECT_ROOT / "datasets_compact_hiqbind_v1"
|
| 57 |
+
DEFAULT_STAGE_ROOT = RELEASE_ROOT / "hf_stage_copuladock"
|
| 58 |
+
DEFAULT_REPO_ID = "liofoil/copuladock"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(frozen=True)
|
| 62 |
+
class DatasetSpec:
|
| 63 |
+
"""A completed compact dataset and its release-relative destination."""
|
| 64 |
+
|
| 65 |
+
source_name: str
|
| 66 |
+
release_name: str
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
DATASETS: tuple[DatasetSpec, ...] = (
|
| 70 |
+
DatasetSpec("autodock_vina_full_v1", "autodock_vina_full_v1"),
|
| 71 |
+
DatasetSpec("diffdock_full_v1", "diffdock_full_v1"),
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# These are the minimal reproducible construction/reader components. They
|
| 75 |
+
# intentionally exclude raw docking outputs and cluster logs.
|
| 76 |
+
CODE_SOURCES: tuple[tuple[Path, Path], ...] = (
|
| 77 |
+
(
|
| 78 |
+
WORKSPACE_ROOT / "docking_base/scripts/materialize_hiqbind_gnncp.py",
|
| 79 |
+
Path("code/compact_v1/materialize_hiqbind_gnncp.py"),
|
| 80 |
+
),
|
| 81 |
+
(
|
| 82 |
+
PROJECT_ROOT / "system_split_code/build_compact_v1_direct.py",
|
| 83 |
+
Path("code/compact_v1/build_compact_v1_direct.py"),
|
| 84 |
+
),
|
| 85 |
+
(
|
| 86 |
+
PROJECT_ROOT / "system_split_code/build_compact_v1_direct.sbatch",
|
| 87 |
+
Path("code/compact_v1/build_compact_v1_direct.sbatch"),
|
| 88 |
+
),
|
| 89 |
+
(
|
| 90 |
+
PROJECT_ROOT / "system_split_code/build_graph_unified_enhanced.py",
|
| 91 |
+
Path("code/compact_v1/build_graph_unified_enhanced.py"),
|
| 92 |
+
),
|
| 93 |
+
(
|
| 94 |
+
PROJECT_ROOT / "system_split_code/convert_to_compact_v1.py",
|
| 95 |
+
Path("code/compact_v1/convert_to_compact_v1.py"),
|
| 96 |
+
),
|
| 97 |
+
(
|
| 98 |
+
PROJECT_ROOT / "system_split_code/compact_graph_dataset.py",
|
| 99 |
+
Path("code/compact_v1/compact_graph_dataset.py"),
|
| 100 |
+
),
|
| 101 |
+
(
|
| 102 |
+
PROJECT_ROOT / "system_split_code/build_system_index.py",
|
| 103 |
+
Path("code/compact_v1/build_system_index.py"),
|
| 104 |
+
),
|
| 105 |
+
(
|
| 106 |
+
PROJECT_ROOT / "system_split_code/validate_compact_dataset.py",
|
| 107 |
+
Path("code/compact_v1/validate_compact_dataset.py"),
|
| 108 |
+
),
|
| 109 |
+
(
|
| 110 |
+
PROJECT_ROOT / "system_split_code/smoke_test_compact_dataset.py",
|
| 111 |
+
Path("code/compact_v1/smoke_test_compact_dataset.py"),
|
| 112 |
+
),
|
| 113 |
+
(
|
| 114 |
+
PROJECT_ROOT / "system_split_code/test_build_compact_v1_direct.py",
|
| 115 |
+
# Keep tests alongside the modules they import. The upstream tests
|
| 116 |
+
# intentionally resolve convert_to_compact_v1.py by sibling path.
|
| 117 |
+
Path("code/compact_v1/test_build_compact_v1_direct.py"),
|
| 118 |
+
),
|
| 119 |
+
(
|
| 120 |
+
PROJECT_ROOT / "system_split_code/test_compact_graph_dataset.py",
|
| 121 |
+
Path("code/compact_v1/test_compact_graph_dataset.py"),
|
| 122 |
+
),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Previous staging revisions placed the two tests under ``tests/``. Prune
|
| 126 |
+
# only these exact, generated staging copies during --prepare so an old stage
|
| 127 |
+
# cannot publish duplicate stale tests. No dataset data are ever removed.
|
| 128 |
+
OBSOLETE_STAGE_FILES: tuple[Path, ...] = (
|
| 129 |
+
Path("code/compact_v1/tests/test_build_compact_v1_direct.py"),
|
| 130 |
+
Path("code/compact_v1/tests/test_compact_graph_dataset.py"),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class ReleaseError(RuntimeError):
|
| 135 |
+
"""A release-preparation or release-verification failure."""
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _relative_to(path: Path, root: Path) -> Path:
|
| 139 |
+
"""Return ``path`` relative to ``root`` or raise a contextual error."""
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
return path.relative_to(root)
|
| 143 |
+
except ValueError as exc:
|
| 144 |
+
raise ReleaseError(f"path escapes its expected root: {path} (root={root})") from exc
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _is_absolute_path_text(value: str) -> bool:
|
| 148 |
+
"""Detect POSIX/Windows-looking absolute paths without interpreting IDs."""
|
| 149 |
+
|
| 150 |
+
return value.startswith("/") or (len(value) >= 3 and value[1:3] in (":\\", ":/"))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _sanitize_value(value: Any) -> Any:
|
| 154 |
+
"""Copy JSON-like values while removing every absolute-path string."""
|
| 155 |
+
|
| 156 |
+
if isinstance(value, dict):
|
| 157 |
+
return {str(key): _sanitize_value(item) for key, item in value.items()}
|
| 158 |
+
if isinstance(value, list):
|
| 159 |
+
return [_sanitize_value(item) for item in value]
|
| 160 |
+
if isinstance(value, str) and _is_absolute_path_text(value):
|
| 161 |
+
return "<local-path-removed>"
|
| 162 |
+
return value
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _find_absolute_path_values(value: Any, prefix: str = "$") -> list[str]:
|
| 166 |
+
"""Return JSON locations that still contain an absolute path string."""
|
| 167 |
+
|
| 168 |
+
found: list[str] = []
|
| 169 |
+
if isinstance(value, Mapping):
|
| 170 |
+
for key, item in value.items():
|
| 171 |
+
found.extend(_find_absolute_path_values(item, f"{prefix}.{key}"))
|
| 172 |
+
elif isinstance(value, list):
|
| 173 |
+
for index, item in enumerate(value):
|
| 174 |
+
found.extend(_find_absolute_path_values(item, f"{prefix}[{index}]"))
|
| 175 |
+
elif isinstance(value, str) and _is_absolute_path_text(value):
|
| 176 |
+
found.append(prefix)
|
| 177 |
+
return found
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _read_json(path: Path) -> Any:
|
| 181 |
+
try:
|
| 182 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 183 |
+
return json.load(handle)
|
| 184 |
+
except (OSError, json.JSONDecodeError) as exc:
|
| 185 |
+
raise ReleaseError(f"cannot read JSON {path}: {exc}") from exc
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _write_json(path: Path, payload: Any) -> None:
|
| 189 |
+
"""Write a small JSON file atomically inside the staging tree."""
|
| 190 |
+
|
| 191 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 192 |
+
temporary = path.with_name(path.name + ".tmp")
|
| 193 |
+
try:
|
| 194 |
+
with temporary.open("w", encoding="utf-8") as handle:
|
| 195 |
+
json.dump(payload, handle, ensure_ascii=False, indent=2)
|
| 196 |
+
handle.write("\n")
|
| 197 |
+
handle.flush()
|
| 198 |
+
os.fsync(handle.fileno())
|
| 199 |
+
os.replace(temporary, path)
|
| 200 |
+
finally:
|
| 201 |
+
# If json.dump failed before os.replace, only remove the known temp file.
|
| 202 |
+
if temporary.exists():
|
| 203 |
+
temporary.unlink()
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _copy_file(source: Path, destination: Path) -> None:
|
| 207 |
+
"""Snapshot a small code/document file without following unsafe parents."""
|
| 208 |
+
|
| 209 |
+
if not source.is_file():
|
| 210 |
+
raise ReleaseError(f"required release file is missing: {source}")
|
| 211 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 212 |
+
temporary = destination.with_name(destination.name + ".tmp")
|
| 213 |
+
try:
|
| 214 |
+
shutil.copy2(source, temporary)
|
| 215 |
+
os.replace(temporary, destination)
|
| 216 |
+
finally:
|
| 217 |
+
if temporary.exists():
|
| 218 |
+
temporary.unlink()
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _hardlink_file(source: Path, destination: Path) -> None:
|
| 222 |
+
"""Make one idempotent hard link; never silently copy a tensor shard."""
|
| 223 |
+
|
| 224 |
+
if not source.is_file():
|
| 225 |
+
raise ReleaseError(f"source file is missing: {source}")
|
| 226 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 227 |
+
if destination.exists():
|
| 228 |
+
source_stat = source.stat()
|
| 229 |
+
destination_stat = destination.stat()
|
| 230 |
+
if (source_stat.st_dev, source_stat.st_ino) == (destination_stat.st_dev, destination_stat.st_ino):
|
| 231 |
+
return
|
| 232 |
+
raise ReleaseError(
|
| 233 |
+
"staging file already exists but is not the expected hard link; "
|
| 234 |
+
f"refusing to replace it: {destination}"
|
| 235 |
+
)
|
| 236 |
+
try:
|
| 237 |
+
os.link(source, destination)
|
| 238 |
+
except OSError as exc:
|
| 239 |
+
raise ReleaseError(
|
| 240 |
+
"hard-link failed; staging and source must share a filesystem. "
|
| 241 |
+
f"source={source}, destination={destination}: {exc}"
|
| 242 |
+
) from exc
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _dataset_source(dataset_root: Path, spec: DatasetSpec) -> Path:
|
| 246 |
+
source = (dataset_root / spec.source_name).resolve()
|
| 247 |
+
if not source.is_dir():
|
| 248 |
+
raise ReleaseError(f"completed compact dataset is missing: {source}")
|
| 249 |
+
manifest = source / "manifest.json"
|
| 250 |
+
if not manifest.is_file():
|
| 251 |
+
raise ReleaseError(f"completed compact dataset has no manifest: {manifest}")
|
| 252 |
+
value = _read_json(manifest)
|
| 253 |
+
if not isinstance(value, dict) or value.get("status") != "complete":
|
| 254 |
+
raise ReleaseError(f"dataset is not a complete compact release: {source}")
|
| 255 |
+
return source
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _release_dataset_root(stage_root: Path, spec: DatasetSpec) -> Path:
|
| 259 |
+
return stage_root / "data" / "hiqbind_5k_v1" / spec.release_name
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _sanitized_json_payload(source: Path) -> Any:
|
| 263 |
+
payload = _sanitize_value(_read_json(source))
|
| 264 |
+
leftovers = _find_absolute_path_values(payload)
|
| 265 |
+
if leftovers:
|
| 266 |
+
raise ReleaseError(f"path sanitizer left absolute paths in {source}: {leftovers[:5]}")
|
| 267 |
+
return payload
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _stage_dataset(source: Path, destination: Path) -> None:
|
| 271 |
+
"""Stage a compact dataset, hard-linking all immutable source artifacts."""
|
| 272 |
+
|
| 273 |
+
for source_file in sorted(source.rglob("*")):
|
| 274 |
+
if not source_file.is_file():
|
| 275 |
+
continue
|
| 276 |
+
relative = _relative_to(source_file, source)
|
| 277 |
+
target = destination / relative
|
| 278 |
+
# These two records contain source provenance. Their release versions
|
| 279 |
+
# preserve logical relative fields but never disclose local paths.
|
| 280 |
+
if source_file.name in {"manifest.json", "source_index.json"}:
|
| 281 |
+
_write_json(target, _sanitized_json_payload(source_file))
|
| 282 |
+
else:
|
| 283 |
+
_hardlink_file(source_file, target)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _release_assets() -> list[tuple[Path, Path]]:
|
| 287 |
+
"""Discover authored release documents plus the static code mapping."""
|
| 288 |
+
|
| 289 |
+
assets = list(CODE_SOURCES)
|
| 290 |
+
|
| 291 |
+
# README is the Hugging Face dataset card. Other authored Markdown files
|
| 292 |
+
# are companion documents, keeping the remote root uncluttered.
|
| 293 |
+
for source in sorted(RELEASE_ROOT.glob("*.md"), key=lambda item: item.name.casefold()):
|
| 294 |
+
remote = Path("README.md") if source.name == "README.md" else Path("docs") / source.name
|
| 295 |
+
assets.append((source, remote))
|
| 296 |
+
|
| 297 |
+
# Release-authored companion docs and the small hand-written package notes
|
| 298 |
+
# live in the release tree itself. Include them recursively while
|
| 299 |
+
# deliberately excluding generated __pycache__ / staging content.
|
| 300 |
+
authored_docs = RELEASE_ROOT / "docs"
|
| 301 |
+
if authored_docs.is_dir():
|
| 302 |
+
for source in sorted(authored_docs.rglob("*"), key=lambda item: str(item).casefold()):
|
| 303 |
+
if source.is_file() and "__pycache__" not in source.parts:
|
| 304 |
+
assets.append((source, Path("docs") / _relative_to(source, authored_docs)))
|
| 305 |
+
|
| 306 |
+
authored_code = RELEASE_ROOT / "code" / "compact_v1"
|
| 307 |
+
if authored_code.is_dir():
|
| 308 |
+
for source in sorted(authored_code.rglob("*"), key=lambda item: str(item).casefold()):
|
| 309 |
+
if source.is_file() and "__pycache__" not in source.parts:
|
| 310 |
+
assets.append((source, Path("code/compact_v1") / _relative_to(source, authored_code)))
|
| 311 |
+
|
| 312 |
+
# A dependency file placed at the release root is also supported for
|
| 313 |
+
# convenience; a code/compact_v1 version takes precedence by causing an
|
| 314 |
+
# explicit duplicate-destination error rather than silent replacement.
|
| 315 |
+
for name in ("requirements.txt", "environment.yml", "environment.yaml"):
|
| 316 |
+
source = RELEASE_ROOT / name
|
| 317 |
+
if source.is_file():
|
| 318 |
+
assets.append((source, Path("code/compact_v1") / name))
|
| 319 |
+
|
| 320 |
+
# Include the reproducible release entry points themselves, but not this
|
| 321 |
+
# staging directory or arbitrary local files.
|
| 322 |
+
for name in ("upload_copuladock.py", "upload_copuladock.sbatch"):
|
| 323 |
+
source = RELEASE_ROOT / name
|
| 324 |
+
if source.is_file():
|
| 325 |
+
assets.append((source, Path("code/release") / name))
|
| 326 |
+
|
| 327 |
+
return assets
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _stage_assets(stage_root: Path) -> list[Path]:
|
| 331 |
+
staged: list[Path] = []
|
| 332 |
+
seen_destinations: set[Path] = set()
|
| 333 |
+
for source, remote in _release_assets():
|
| 334 |
+
if remote in seen_destinations:
|
| 335 |
+
raise ReleaseError(f"duplicate release destination: {remote}")
|
| 336 |
+
seen_destinations.add(remote)
|
| 337 |
+
if not source.is_file():
|
| 338 |
+
raise ReleaseError(f"required construction code is missing: {source}")
|
| 339 |
+
target = stage_root / remote
|
| 340 |
+
_copy_file(source, target)
|
| 341 |
+
staged.append(target)
|
| 342 |
+
return staged
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _prune_obsolete_stage_files(stage_root: Path) -> None:
|
| 346 |
+
"""Remove only known stale generated code copies from an older layout."""
|
| 347 |
+
|
| 348 |
+
for relative in OBSOLETE_STAGE_FILES:
|
| 349 |
+
target = stage_root / relative
|
| 350 |
+
if target.is_file():
|
| 351 |
+
target.unlink()
|
| 352 |
+
# Leave a directory untouched when it contains anything unexpected;
|
| 353 |
+
# upload_large_folder ignores empty directories in any event.
|
| 354 |
+
parent = target.parent
|
| 355 |
+
if parent.is_dir() and not any(parent.iterdir()):
|
| 356 |
+
parent.rmdir()
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _validate_stage_location(stage_root: Path, dataset_root: Path) -> None:
|
| 360 |
+
"""Prevent accidental recursive staging into either source dataset root."""
|
| 361 |
+
|
| 362 |
+
stage_root = stage_root.resolve()
|
| 363 |
+
dataset_root = dataset_root.resolve()
|
| 364 |
+
if stage_root == dataset_root:
|
| 365 |
+
raise ReleaseError("--stage-root must not equal --dataset-root")
|
| 366 |
+
try:
|
| 367 |
+
stage_root.relative_to(dataset_root)
|
| 368 |
+
except ValueError:
|
| 369 |
+
return
|
| 370 |
+
raise ReleaseError("--stage-root must not be inside --dataset-root")
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _expected_tensor_files(source: Path) -> list[Path]:
|
| 374 |
+
return sorted(path for path in source.rglob("*.pt") if path.is_file())
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _human_bytes(number: int) -> str:
|
| 378 |
+
value = float(number)
|
| 379 |
+
for suffix in ("B", "KiB", "MiB", "GiB", "TiB"):
|
| 380 |
+
if value < 1024.0 or suffix == "TiB":
|
| 381 |
+
return f"{value:.1f} {suffix}"
|
| 382 |
+
value /= 1024.0
|
| 383 |
+
return f"{number} B"
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _source_summary(dataset_root: Path) -> list[dict[str, Any]]:
|
| 387 |
+
summary: list[dict[str, Any]] = []
|
| 388 |
+
for spec in DATASETS:
|
| 389 |
+
source = _dataset_source(dataset_root, spec)
|
| 390 |
+
manifest = _read_json(source / "manifest.json")
|
| 391 |
+
tensors = _expected_tensor_files(source)
|
| 392 |
+
summary.append(
|
| 393 |
+
{
|
| 394 |
+
"name": spec.release_name,
|
| 395 |
+
"source": str(source),
|
| 396 |
+
"systems": int(manifest.get("n_systems", 0)),
|
| 397 |
+
"graphs": int(manifest.get("n_graphs", 0)),
|
| 398 |
+
"shards": len(tensors),
|
| 399 |
+
"tensor_bytes": sum(path.stat().st_size for path in tensors),
|
| 400 |
+
}
|
| 401 |
+
)
|
| 402 |
+
return summary
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def prepare_stage(stage_root: Path, dataset_root: Path, *, dry_run: bool) -> None:
|
| 406 |
+
"""Create/update the reusable stage. ``dry_run`` performs no writes."""
|
| 407 |
+
|
| 408 |
+
_validate_stage_location(stage_root, dataset_root)
|
| 409 |
+
summaries = _source_summary(dataset_root)
|
| 410 |
+
assets = _release_assets()
|
| 411 |
+
print(f"stage root: {stage_root}")
|
| 412 |
+
for item in summaries:
|
| 413 |
+
print(
|
| 414 |
+
f" {item['name']}: {item['systems']} systems, {item['graphs']} graphs, "
|
| 415 |
+
f"{item['shards']} .pt shards, {_human_bytes(item['tensor_bytes'])}"
|
| 416 |
+
)
|
| 417 |
+
print(f" construction/release files: {len(assets)}")
|
| 418 |
+
if dry_run:
|
| 419 |
+
print("dry-run: source checks passed; no staging files were created or changed.")
|
| 420 |
+
return
|
| 421 |
+
|
| 422 |
+
stage_root.mkdir(parents=True, exist_ok=True)
|
| 423 |
+
for spec in DATASETS:
|
| 424 |
+
_stage_dataset(_dataset_source(dataset_root, spec), _release_dataset_root(stage_root, spec))
|
| 425 |
+
_stage_assets(stage_root)
|
| 426 |
+
_prune_obsolete_stage_files(stage_root)
|
| 427 |
+
print("staging preparation completed (tensor shards are hard links).")
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def verify_stage(stage_root: Path, dataset_root: Path, *, require_readme: bool) -> None:
|
| 431 |
+
"""Check staging layout, sanitization, and every tensor hard link."""
|
| 432 |
+
|
| 433 |
+
if not stage_root.is_dir():
|
| 434 |
+
raise ReleaseError(f"staging root does not exist: {stage_root}")
|
| 435 |
+
|
| 436 |
+
errors: list[str] = []
|
| 437 |
+
checked_tensors = 0
|
| 438 |
+
for spec in DATASETS:
|
| 439 |
+
source = _dataset_source(dataset_root, spec)
|
| 440 |
+
staged = _release_dataset_root(stage_root, spec)
|
| 441 |
+
if not staged.is_dir():
|
| 442 |
+
errors.append(f"missing staged dataset directory: {staged}")
|
| 443 |
+
continue
|
| 444 |
+
for name in ("manifest.json", "source_index.json", "system_index.json"):
|
| 445 |
+
candidate = staged / name
|
| 446 |
+
if not candidate.is_file():
|
| 447 |
+
errors.append(f"missing staged metadata: {candidate}")
|
| 448 |
+
|
| 449 |
+
for name in ("manifest.json", "source_index.json"):
|
| 450 |
+
candidate = staged / name
|
| 451 |
+
if candidate.is_file():
|
| 452 |
+
try:
|
| 453 |
+
leftovers = _find_absolute_path_values(_read_json(candidate))
|
| 454 |
+
except ReleaseError as exc:
|
| 455 |
+
errors.append(str(exc))
|
| 456 |
+
else:
|
| 457 |
+
if leftovers:
|
| 458 |
+
errors.append(f"absolute paths remain in {candidate}: {leftovers[:5]}")
|
| 459 |
+
|
| 460 |
+
for source_tensor in _expected_tensor_files(source):
|
| 461 |
+
staged_tensor = staged / _relative_to(source_tensor, source)
|
| 462 |
+
if not staged_tensor.is_file():
|
| 463 |
+
errors.append(f"missing staged tensor: {staged_tensor}")
|
| 464 |
+
continue
|
| 465 |
+
source_stat = source_tensor.stat()
|
| 466 |
+
staged_stat = staged_tensor.stat()
|
| 467 |
+
if (source_stat.st_dev, source_stat.st_ino) != (staged_stat.st_dev, staged_stat.st_ino):
|
| 468 |
+
errors.append(f"tensor is not a hard link: {staged_tensor}")
|
| 469 |
+
if source_stat.st_size != staged_stat.st_size:
|
| 470 |
+
errors.append(f"tensor size differs: {staged_tensor}")
|
| 471 |
+
checked_tensors += 1
|
| 472 |
+
|
| 473 |
+
for source, remote in _release_assets():
|
| 474 |
+
staged_file = stage_root / remote
|
| 475 |
+
if not staged_file.is_file():
|
| 476 |
+
errors.append(f"missing staged release asset: {staged_file}")
|
| 477 |
+
elif staged_file.stat().st_size != source.stat().st_size:
|
| 478 |
+
errors.append(f"staged release asset size differs: {staged_file}")
|
| 479 |
+
|
| 480 |
+
readme = stage_root / "README.md"
|
| 481 |
+
if require_readme and not readme.is_file():
|
| 482 |
+
errors.append("README.md is required before upload; add it under release_copuladock/")
|
| 483 |
+
if errors:
|
| 484 |
+
raise ReleaseError("staging verification failed:\n - " + "\n - ".join(errors))
|
| 485 |
+
print(f"staging verification passed: {checked_tensors} tensor hard links checked; no local absolute paths in release metadata.")
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def _get_token(args: argparse.Namespace) -> str:
|
| 489 |
+
token = args.token or os.environ.get("HF_TOKEN")
|
| 490 |
+
if token:
|
| 491 |
+
return token
|
| 492 |
+
try:
|
| 493 |
+
from huggingface_hub import get_token
|
| 494 |
+
except ImportError as exc:
|
| 495 |
+
raise ReleaseError(
|
| 496 |
+
"--upload requires --token/HF_TOKEN or a saved Hugging Face login; "
|
| 497 |
+
"huggingface_hub is unavailable."
|
| 498 |
+
) from exc
|
| 499 |
+
token = get_token()
|
| 500 |
+
if not token:
|
| 501 |
+
raise ReleaseError(
|
| 502 |
+
"--upload requires --token, HF_TOKEN, or a saved Hugging Face login. "
|
| 503 |
+
"Run `python -c 'from huggingface_hub import login; login()'` first."
|
| 504 |
+
)
|
| 505 |
+
return token
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def upload_stage(args: argparse.Namespace) -> None:
|
| 509 |
+
"""Authenticate safely and perform the one resumable folder upload."""
|
| 510 |
+
|
| 511 |
+
if args.dry_run:
|
| 512 |
+
print(
|
| 513 |
+
"dry-run: would verify credentials and call HfApi.upload_large_folder "
|
| 514 |
+
f"for dataset repo {args.repo_id!r} from {args.stage_root}."
|
| 515 |
+
)
|
| 516 |
+
return
|
| 517 |
+
token = _get_token(args)
|
| 518 |
+
try:
|
| 519 |
+
from huggingface_hub import HfApi
|
| 520 |
+
except ImportError as exc:
|
| 521 |
+
raise ReleaseError(
|
| 522 |
+
"huggingface_hub is unavailable. Run with "
|
| 523 |
+
"/u/hhao/anaconda3/envs/hgf/bin/python."
|
| 524 |
+
) from exc
|
| 525 |
+
|
| 526 |
+
api = HfApi(token=token)
|
| 527 |
+
try:
|
| 528 |
+
account = api.whoami(token=token)
|
| 529 |
+
api.repo_info(args.repo_id, repo_type="dataset", revision=args.revision, token=token)
|
| 530 |
+
except Exception as exc: # The Hub library exposes several transport/auth exception types.
|
| 531 |
+
raise ReleaseError(
|
| 532 |
+
f"cannot authenticate to or access dataset repository {args.repo_id!r}: {exc}"
|
| 533 |
+
) from exc
|
| 534 |
+
# The user identity is useful operational evidence but contains no secret.
|
| 535 |
+
account_name = account.get("name") if isinstance(account, Mapping) else None
|
| 536 |
+
print(f"Hugging Face authentication verified for account: {account_name or '<unknown>'}")
|
| 537 |
+
print(
|
| 538 |
+
"starting resumable upload_large_folder: "
|
| 539 |
+
f"repo={args.repo_id}, revision={args.revision}, workers={args.num_workers}"
|
| 540 |
+
)
|
| 541 |
+
try:
|
| 542 |
+
api.upload_large_folder(
|
| 543 |
+
repo_id=args.repo_id,
|
| 544 |
+
folder_path=args.stage_root,
|
| 545 |
+
repo_type="dataset",
|
| 546 |
+
revision=args.revision,
|
| 547 |
+
num_workers=args.num_workers,
|
| 548 |
+
# upload_large_folder writes resumable state below .cache; it is
|
| 549 |
+
# operational metadata, not part of the scientific release.
|
| 550 |
+
ignore_patterns=[".cache/**", "**/__pycache__/**", "*.pyc", "*.tmp"],
|
| 551 |
+
print_report=True,
|
| 552 |
+
)
|
| 553 |
+
except Exception as exc:
|
| 554 |
+
raise ReleaseError(
|
| 555 |
+
"Hugging Face upload did not complete. Keep the staging root unchanged and rerun "
|
| 556 |
+
"the same command to resume: "
|
| 557 |
+
f"{exc}"
|
| 558 |
+
) from exc
|
| 559 |
+
print("upload_large_folder completed successfully.")
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 563 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 564 |
+
parser.add_argument("--prepare", action="store_true", help="create/update the persistent staging tree")
|
| 565 |
+
parser.add_argument("--verify", action="store_true", help="verify an existing staging tree")
|
| 566 |
+
parser.add_argument("--upload", action="store_true", help="upload a verified staging tree to Hugging Face")
|
| 567 |
+
parser.add_argument(
|
| 568 |
+
"--dry-run",
|
| 569 |
+
action="store_true",
|
| 570 |
+
help="show prepare/upload actions without staging writes or network access",
|
| 571 |
+
)
|
| 572 |
+
parser.add_argument("--repo-id", default=DEFAULT_REPO_ID, help=f"target dataset repo (default: {DEFAULT_REPO_ID})")
|
| 573 |
+
parser.add_argument("--revision", default="main", help="target revision (default: main)")
|
| 574 |
+
parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT)
|
| 575 |
+
parser.add_argument("--stage-root", type=Path, default=DEFAULT_STAGE_ROOT)
|
| 576 |
+
parser.add_argument("--num-workers", type=int, default=8, help="upload_large_folder worker count (default: 8)")
|
| 577 |
+
parser.add_argument("--token", help="Hugging Face token; prefer HF_TOKEN in a job environment")
|
| 578 |
+
return parser
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def main(argv: Sequence[str] | None = None) -> int:
|
| 582 |
+
args = build_parser().parse_args(argv)
|
| 583 |
+
if not (args.prepare or args.verify or args.upload):
|
| 584 |
+
raise ReleaseError("select at least one action: --prepare, --verify, and/or --upload")
|
| 585 |
+
if args.num_workers < 1:
|
| 586 |
+
raise ReleaseError("--num-workers must be at least 1")
|
| 587 |
+
args.dataset_root = args.dataset_root.expanduser().resolve()
|
| 588 |
+
args.stage_root = args.stage_root.expanduser().resolve()
|
| 589 |
+
|
| 590 |
+
if args.prepare:
|
| 591 |
+
prepare_stage(args.stage_root, args.dataset_root, dry_run=args.dry_run)
|
| 592 |
+
if args.verify or args.upload:
|
| 593 |
+
# A dry-run upload has no staging side effects, but validates a real
|
| 594 |
+
# stage when one is already present. This catches layout mistakes
|
| 595 |
+
# before credentials/network access are involved.
|
| 596 |
+
verify_stage(args.stage_root, args.dataset_root, require_readme=args.upload and not args.dry_run)
|
| 597 |
+
if args.upload:
|
| 598 |
+
upload_stage(args)
|
| 599 |
+
return 0
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
if __name__ == "__main__":
|
| 603 |
+
try:
|
| 604 |
+
raise SystemExit(main())
|
| 605 |
+
except ReleaseError as exc:
|
| 606 |
+
print(f"ERROR: {exc}", file=sys.stderr)
|
| 607 |
+
raise SystemExit(2)
|
code/release/upload_copuladock.sbatch
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Reusable, resumable Hugging Face release upload for liofoil/copuladock.
|
| 3 |
+
#
|
| 4 |
+
# Submit only after reviewing the staging tree. Authentication may come from
|
| 5 |
+
# HF_TOKEN in the submission environment or a token saved by
|
| 6 |
+
# `huggingface_hub.login()`; never put a token in this file.
|
| 7 |
+
# sbatch upload_copuladock.sbatch
|
| 8 |
+
#
|
| 9 |
+
# If a network transfer is interrupted, submit the same script again. Do not
|
| 10 |
+
# remove hf_stage_copuladock/: huggingface_hub retains its upload state there.
|
| 11 |
+
|
| 12 |
+
#SBATCH --account=bghp-delta-cpu
|
| 13 |
+
#SBATCH --partition=cpu
|
| 14 |
+
#SBATCH --nodes=1
|
| 15 |
+
#SBATCH --ntasks-per-node=1
|
| 16 |
+
#SBATCH --cpus-per-task=8
|
| 17 |
+
#SBATCH --mem=32G
|
| 18 |
+
#SBATCH --time=2-00:00:00
|
| 19 |
+
#SBATCH --job-name=copuladock_hf_upload
|
| 20 |
+
#SBATCH --output=/work/nvme/bghp/hhao/gnncp/release_copuladock/copuladock_hf_upload_%j.out
|
| 21 |
+
#SBATCH --error=/work/nvme/bghp/hhao/gnncp/release_copuladock/copuladock_hf_upload_%j.err
|
| 22 |
+
#SBATCH --open-mode=append
|
| 23 |
+
#SBATCH --mail-type=FAIL,END
|
| 24 |
+
|
| 25 |
+
set -Eeuo pipefail
|
| 26 |
+
umask 007
|
| 27 |
+
|
| 28 |
+
readonly RELEASE_ROOT=/work/nvme/bghp/hhao/gnncp/release_copuladock
|
| 29 |
+
readonly PYTHON=/u/hhao/anaconda3/envs/hgf/bin/python
|
| 30 |
+
readonly UPLOAD_WORKERS="${UPLOAD_WORKERS:-8}"
|
| 31 |
+
|
| 32 |
+
finish()
|
| 33 |
+
{
|
| 34 |
+
local rc=$?
|
| 35 |
+
echo "[$(date --iso-8601=seconds)] job=${SLURM_JOB_ID:-unknown} exit=${rc}"
|
| 36 |
+
}
|
| 37 |
+
trap finish EXIT
|
| 38 |
+
|
| 39 |
+
test -x "${PYTHON}"
|
| 40 |
+
test -r "${RELEASE_ROOT}/upload_copuladock.py"
|
| 41 |
+
echo "[$(date --iso-8601=seconds)] host=$(hostname) workers=${UPLOAD_WORKERS}"
|
| 42 |
+
|
| 43 |
+
"${PYTHON}" "${RELEASE_ROOT}/upload_copuladock.py" \
|
| 44 |
+
--prepare --verify --upload --num-workers "${UPLOAD_WORKERS}"
|
data/hiqbind_5k_v1/autodock_vina_full_v1/manifest.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:841527641a6035c77a0446b515a6eaae7c1e8fe604f240375b02bed5397dd8dd
|
| 3 |
+
size 14884303
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00015.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3f6c5e126c2bef0e0c9c7a64285b42ee9cc7d9032cf58cacf199d1f36600b2de
|
| 3 |
+
size 534092249
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00016.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:393f5d1a3be510750ae0accd7c698d4295dbc61d81e5cb8f135b6f2cc1b621da
|
| 3 |
+
size 535229273
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00023.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6e6c6453428bef1c27930537b12686dbdc8a91e3baa473162ae11fb1b3eac753
|
| 3 |
+
size 529267865
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00024.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e600f4a0910fb99f716b681aabccbc22283faa302db92b106cb500db08addb76
|
| 3 |
+
size 530521753
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00025.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ac05897b319e04175b5939decd3e0cfc57adab0ed9b2e4077e90e262a5596e55
|
| 3 |
+
size 528331609
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00026.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:da426b81143436dc79d2fa0207e0b90a721c24b59c24e70e11b3de3a043d9b80
|
| 3 |
+
size 534128345
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00027.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9423f17b5e0e1989acd92b73c3b5b5f6918b48ad9eb9fd0176e4b008dd0f2a70
|
| 3 |
+
size 535495961
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00038.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b08a73cf2ffff0f4ba3334b720a38b21cfd2db12b9a53495b5062366041cd823
|
| 3 |
+
size 525024473
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00042.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4ee42f9b3ffe1fca4e47523d610b1ffea938a5ff789b3b256d653205135bc557
|
| 3 |
+
size 529624857
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00043.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8169ec37de9a23df15f978706818c4c78ac6ac6c7e9bab370ebf7c72c04fe4d1
|
| 3 |
+
size 536233881
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00050.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0a6757f24419fbc66f6b617524be753725e0085725072531cb138dd6a0c4683a
|
| 3 |
+
size 535844569
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00052.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c3ee0f4eadda859b71bcbc305434c56cb8393cf9027cd42bc2f7420975edd185
|
| 3 |
+
size 527677081
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00053.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a5d03e0067d28e1f7458c3e7fad63f0100618c0f4fd2eea70029d3e1eb77532f
|
| 3 |
+
size 536549849
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00056.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d5f533a35ca2c973cee8a8cbcc8c3844874bad39271f0034c9af9626302f60c2
|
| 3 |
+
size 519235801
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00059.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e7aa44ac4d0008281dd3ce21516a9538cb90194c23bc7f0880b83ee5f2d9cf8e
|
| 3 |
+
size 534088793
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00063.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:caf1f91fbb3915bb2f8b3a3e6fa8169d1bb01678e32f2e7e3534f042d888a89f
|
| 3 |
+
size 535543385
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00067.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c120eebd2ee4656bd448991c77ecc5c9094942baebf41e7c10706a94bb3bcc33
|
| 3 |
+
size 529791833
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00074.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c140b2c3076bf3300c968a433d5bfbca3b61ea7e018388ba9e2f1a61cda8f6e1
|
| 3 |
+
size 524637849
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00075.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7eed91d4c944606de9211f2c9dd45be8c0f5cfb1ee0386c180041d290b03c310
|
| 3 |
+
size 533015065
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00082.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:df57012302574ac27379e16cb348d12718b79e2111fea4debbc3d8f8ac31dcf2
|
| 3 |
+
size 530900377
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00083.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7e47a8ff6dbe4a742e6bb019ce99571b7409dedc3722678320bb1a00dcf26c34
|
| 3 |
+
size 522335129
|
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00086.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:500dc13556cc42fda7b2101f6c600ae384690d548abc66a2647df92423f0e79e
|
| 3 |
+
size 535780761
|
data/hiqbind_5k_v1/autodock_vina_full_v1/source_index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/hiqbind_5k_v1/autodock_vina_full_v1/system_index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00008.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:365759c19d43e31d44487b7320947ee87f75e873d7111ad680fc016578499e63
|
| 3 |
+
size 528301785
|
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00029.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:de26f8ee0a0dff7d85edab50217198742a7cc4c1f9ec70e4c3f03d9f5316ee79
|
| 3 |
+
size 533930713
|
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00036.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c9a63663b4a8dadc09c3441c7ef37948a17b26622367648af5a5cd98c8412ff2
|
| 3 |
+
size 524476377
|
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00048.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:50a0939dfddd0162b462ac3ac22f1600081e72a3d47af55af2056e4df99f2817
|
| 3 |
+
size 534420377
|
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00049.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f7d9af1c108359ad37a7ce82dcc90dc6d6ade3c483a26036022399647dfd8506
|
| 3 |
+
size 536033305
|
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00065.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8dde60a8d5a936372665daec9d92adc337241fdc77b571d4be7d74901e01a866
|
| 3 |
+
size 535040537
|
data/hiqbind_5k_v1/diffdock_full_v1/system_index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
docs/DATASET_USAGE_ZH.md
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CopulaDock HiQBind 5K compact 数据集使用说明
|
| 2 |
+
|
| 3 |
+
## 1. 数据集的单位与规模
|
| 4 |
+
|
| 5 |
+
本发布包含 HiQBind 5K cohort 的两个 docking baseline 输出,经统一构图后保存为 `gnncp_compact_v1`。
|
| 6 |
+
|
| 7 |
+
| 方法 | system(protein–ligand pair) | graph(docking pose) | 完成状态 |
|
| 8 |
+
| --- | ---: | ---: | --- |
|
| 9 |
+
| DiffDock | 4,979 | 97,988 | complete / strict validation passed |
|
| 10 |
+
| AutoDock Vina | 4,887 | 85,824 | complete / strict validation passed |
|
| 11 |
+
|
| 12 |
+
定义如下:
|
| 13 |
+
|
| 14 |
+
- **system**:一个 protein–ligand pair,也是数据划分的最小单位。
|
| 15 |
+
- **graph**:该 system 的一个预测 docking pose 构成的一张原子图。
|
| 16 |
+
- 每个 system 最多请求 20 个 pose;实际 graph 数量可能少于 20,因为个别 pose 被方法或几何检查拒绝。
|
| 17 |
+
|
| 18 |
+
因此,例如构图阶段的“158 个 system 产生 2,849 个 graph”是正常的:它说明这些 pair 的有效 pose 总数为 2,849,并不表示出现了 2,849 个不同的 protein–ligand pair。
|
| 19 |
+
|
| 20 |
+
两个方法的共同 system 为 4,868 个。若做 DiffDock 与 Vina 的逐 system 对照,请先取 `system_index.json` 中 `systems` 字段的交集。
|
| 21 |
+
|
| 22 |
+
## 2. 下载
|
| 23 |
+
|
| 24 |
+
完整下载约需 93 GiB 可用空间。通常只需下载一个方法以及 reader 代码:
|
| 25 |
+
|
| 26 |
+
```python
|
| 27 |
+
from huggingface_hub import snapshot_download
|
| 28 |
+
|
| 29 |
+
snapshot_download(
|
| 30 |
+
repo_id="liofoil/copuladock",
|
| 31 |
+
repo_type="dataset",
|
| 32 |
+
local_dir="copuladock",
|
| 33 |
+
allow_patterns=[
|
| 34 |
+
"code/compact_v1/compact_graph_dataset.py",
|
| 35 |
+
"data/hiqbind_5k_v1/diffdock_full_v1/**",
|
| 36 |
+
],
|
| 37 |
+
)
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
若使用命令行客户端,也可执行:
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
hf download liofoil/copuladock \
|
| 44 |
+
--repo-type dataset \
|
| 45 |
+
--local-dir copuladock \
|
| 46 |
+
--include 'code/compact_v1/compact_graph_dataset.py' \
|
| 47 |
+
--include 'data/hiqbind_5k_v1/diffdock_full_v1/**'
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
将 `diffdock_full_v1` 替换为 `autodock_vina_full_v1` 即可下载 Vina 数据。
|
| 51 |
+
|
| 52 |
+
## 3. 环境
|
| 53 |
+
|
| 54 |
+
读取 compact 数据至少需要支持 `torch.load(..., mmap=True, weights_only=True)` 的 PyTorch 和 PyTorch Geometric:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
pip install 'torch>=2.3' torch-geometric
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
若需要从 PDB pose 重新构图,再安装发布目录 `code/compact_v1/requirements.txt` 中的完整依赖:
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
pip install -r code/compact_v1/requirements.txt
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## 4. 正确加载数据
|
| 67 |
+
|
| 68 |
+
不要直接把 `shards/shard_*.pt` 当作 `list[torch_geometric.data.Data]` 来读取。它们是压缩后的内部张量存储;请通过 `CompactGraphDataset` 进行按需重建。
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
import sys
|
| 72 |
+
from pathlib import Path
|
| 73 |
+
|
| 74 |
+
from torch_geometric.loader import DataLoader
|
| 75 |
+
|
| 76 |
+
repo_root = Path("copuladock")
|
| 77 |
+
sys.path.insert(0, str(repo_root / "code" / "compact_v1"))
|
| 78 |
+
from compact_graph_dataset import CompactGraphDataset
|
| 79 |
+
|
| 80 |
+
data_root = (
|
| 81 |
+
repo_root / "data" / "hiqbind_5k_v1" / "diffdock_full_v1"
|
| 82 |
+
)
|
| 83 |
+
dataset = CompactGraphDataset(
|
| 84 |
+
data_root,
|
| 85 |
+
max_cached_shards=2,
|
| 86 |
+
strict=True,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
print(len(dataset)) # 97,988 for DiffDock
|
| 90 |
+
graph = dataset[0] # torch_geometric.data.Data
|
| 91 |
+
metadata = dataset.metadata(0) # 包含 system_id、shard 与 source graph 索引
|
| 92 |
+
|
| 93 |
+
loader = DataLoader(
|
| 94 |
+
dataset,
|
| 95 |
+
batch_size=4,
|
| 96 |
+
shuffle=True,
|
| 97 |
+
num_workers=4,
|
| 98 |
+
persistent_workers=True,
|
| 99 |
+
)
|
| 100 |
+
batch = next(iter(loader))
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
该 reader 以 mmap 方式打开 shard,并在取样时重建一张 PyG 图;避免先执行 `[dataset[i] for i in range(len(dataset))]`,否则会失去紧凑格式的内存优势。
|
| 104 |
+
|
| 105 |
+
## 5. 返回图的字段
|
| 106 |
+
|
| 107 |
+
| 字段 | 形状 / dtype | 含义 |
|
| 108 |
+
| --- | --- | --- |
|
| 109 |
+
| `x` | `[N, 82]`, `float32` | 节点特征 |
|
| 110 |
+
| `edge_index` | `[2, E]`, `int64` | 双向图边 |
|
| 111 |
+
| `edge_attr` | `[E, 4]`, `float32` | 距离 / 距离衰减 / 边两端蛋白标记 |
|
| 112 |
+
| `pos` | `[N, 3]`, `float32` | 当前 docking pose 坐标 |
|
| 113 |
+
| `y_pred` | `[N, 3]`, `float32` | 预测 pose 坐标;数值上与 `pos` 相同 |
|
| 114 |
+
| `y_grt` | `[N, 3]`, `float32` | native/reference 坐标 |
|
| 115 |
+
| `is_protein` | `[N, 1]`, `float32` | 蛋白节点为 1,配体节点为 0 |
|
| 116 |
+
| `y_true` | `[N, 1]`, `float32` | 配体原子的 `||y_pred - y_grt||_2`;蛋白节点为 0 |
|
| 117 |
+
|
| 118 |
+
计算配体 pose 误差或训练 CQR-GNN 时,应以 `is_protein == 0` 选择配体节点。蛋白节点的 `y_true=0` 并不代表预测误差为零,而是本构图定义中蛋白坐标固定。
|
| 119 |
+
|
| 120 |
+
## 6. 必须按 system 划分数据
|
| 121 |
+
|
| 122 |
+
同一 system 的多个 pose 共享蛋白、配体和 native reference。若把 pose 随机切分到 train/validation/test,会造成严重的信息泄漏。
|
| 123 |
+
|
| 124 |
+
`system_index.json` 提供 `systems`、`graph_to_system`、`system_counts` 和 `source_graph_indices`。推荐先在 system ID 层级使用 PLINDER 或其他规则完成划分,再展开为 graph index:
|
| 125 |
+
|
| 126 |
+
```python
|
| 127 |
+
import json
|
| 128 |
+
from collections import defaultdict
|
| 129 |
+
from torch.utils.data import Subset
|
| 130 |
+
|
| 131 |
+
with (data_root / "system_index.json").open() as handle:
|
| 132 |
+
system_index = json.load(handle)
|
| 133 |
+
|
| 134 |
+
indices_by_system = defaultdict(list)
|
| 135 |
+
for graph_index, system_id in enumerate(system_index["graph_to_system"]):
|
| 136 |
+
indices_by_system[system_id].append(graph_index)
|
| 137 |
+
|
| 138 |
+
# 这里应由 PLINDER / 时间切分 / 家族切分等外部规则提供 system ID 集合。
|
| 139 |
+
train_systems = set(...)
|
| 140 |
+
train_indices = [
|
| 141 |
+
graph_index
|
| 142 |
+
for system_id in train_systems
|
| 143 |
+
for graph_index in indices_by_system[system_id]
|
| 144 |
+
]
|
| 145 |
+
train_dataset = Subset(dataset, train_indices)
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
这批 HiQBind 数据没有自带 PLINDER split,也不应被解释为最终泛化评估集。它的主要用途是验证从 baseline pose 到 CQR-GNN 训练样本的端到端流程。
|
| 149 |
+
|
| 150 |
+
## 7. compact 格式为何更小
|
| 151 |
+
|
| 152 |
+
同一个 system 的蛋白静态节点特征、native 配体坐标和 protein–protein 边仅存储一次;每个 pose 只保存必要的动态特征、配体坐标和含配体边。`CompactGraphDataset` 会无损重建模型使用的标准 PyG `Data` 字段。
|
| 153 |
+
|
| 154 |
+
因此,虽然图数接近每个 system 20 个 pose,磁盘中不会为每个 pose 重复保存整份蛋白图。
|
| 155 |
+
|
| 156 |
+
## 8. 从 Docking Base 输出重新构建
|
| 157 |
+
|
| 158 |
+
本仓库发布的内容足以加载和训练,不包含原始 HiQBind PDB/SDF 或原始 docking 输出。若希望重建 compact 数据,过程为:
|
| 159 |
+
|
| 160 |
+
1. 准备符合 Docking Base common-output contract 的已发布 docking 结果;
|
| 161 |
+
2. 使用 `materialize_hiqbind_gnncp.py` 将嵌套输出硬链接为扁平 PDB pose 目录;
|
| 162 |
+
3. 使用 `build_compact_v1_direct.py` 构建可断点续跑的 compact shard;
|
| 163 |
+
4. 使用 `validate_compact_dataset.py` 或 `smoke_test_compact_dataset.py` 抽样验证。
|
| 164 |
+
|
| 165 |
+
扁平输入中的每个 system 至少需要:
|
| 166 |
+
|
| 167 |
+
```text
|
| 168 |
+
<system_id>/
|
| 169 |
+
├── protein.pdb
|
| 170 |
+
├── ligand.pdb
|
| 171 |
+
└── <system_id>_pose_001.pdb ...
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
构图入口只接受 PDB pose。典型命令:
|
| 175 |
+
|
| 176 |
+
```bash
|
| 177 |
+
python materialize_hiqbind_gnncp.py \
|
| 178 |
+
--method diffdock \
|
| 179 |
+
--source-root /path/to/docking_run \
|
| 180 |
+
--output-root /path/to/materialized_diffdock
|
| 181 |
+
|
| 182 |
+
python build_compact_v1_direct.py \
|
| 183 |
+
--data-dir /path/to/materialized_diffdock \
|
| 184 |
+
--output-dir /path/to/diffdock_compact_v1 \
|
| 185 |
+
--method diffdock \
|
| 186 |
+
--target-shard-mib 512 \
|
| 187 |
+
--system-workers 28 \
|
| 188 |
+
--num-workers 1 \
|
| 189 |
+
--memory-budget-gib 150 \
|
| 190 |
+
--on-error skip-system \
|
| 191 |
+
--resume
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
`--system-workers > 1` 时必须令 `--num-workers=1`,避免跨 system 并行和 pose 并行嵌套造成不可控内存峰值。上例是适用于 32 CPU / 192 GiB 节点的保守配置;请根据蛋白规模和节点内存调低 `--system-workers` 或 `--memory-budget-gib`。
|
| 195 |
+
|
| 196 |
+
## 9. 溯源字段
|
| 197 |
+
|
| 198 |
+
`manifest.json`、`source_index.json` 中的 source 字段只描述构图来源;它们不是下载后必须存在的本地路径。训练和 system-level split 仅需要 compact 根目录、`manifest.json`、`system_index.json` 和 `shards/`。
|