| |
| """ |
| Convert a legacy ``torch.save(list[torch_geometric.data.Data])`` dataset to |
| GNNCP compact_v1 shards. |
| |
| This program is intentionally meant to run in a Slurm compute job. The legacy |
| file is a single pickle, so it must be opened as a whole; ``mmap=True`` keeps |
| its tensor storages file-backed while the converter processes one system at a |
| time. |
| |
| The compact format is lossless for the stored float32 node features and |
| coordinates. It does not reduce the 82-dimensional model input: |
| |
| * 44 pose-invariant x columns are stored once per system. |
| * 38 pose-dependent x columns are stored once per pose. |
| * protein-protein undirected edges are stored once per system. |
| * all other undirected edges are stored once per pose. |
| * pos, is_protein, y_true, y_pred, y_grt, edge_attr and reverse edges are |
| derived by the loader. |
| |
| All systems remain wholly within one shard. ``manifest.json`` maps every |
| legacy graph index to ``[shard_index, local_pose_index]``. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import gc |
| import hashlib |
| import json |
| import os |
| import sys |
| from collections import Counter, defaultdict |
| from datetime import datetime, timezone |
| from pathlib import Path |
| from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Sequence, Tuple |
|
|
| import torch |
|
|
|
|
| FORMAT_NAME = "gnncp_compact_v1" |
| SCHEMA_VERSION = 1 |
|
|
| |
| |
| |
| |
| STATIC_COLUMNS: Tuple[int, ...] = tuple(range(0, 34)) + tuple(range(61, 71)) |
| DYNAMIC_COLUMNS: Tuple[int, ...] = tuple(range(34, 61)) + tuple(range(71, 82)) |
|
|
| UNKNOWN_LABELS = {"", "UNKNOWN", "NONE", "NULL", "N/A"} |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Convert a legacy GNNCP PyG list to compact_v1 tensor shards." |
| ) |
| parser.add_argument("--input", required=True, type=Path, help="Legacy *_enhanced_graphs.pt") |
| parser.add_argument("--output-dir", required=True, type=Path, help="New method output directory") |
| parser.add_argument("--method", required=True, help="Docking method name stored in manifest") |
| parser.add_argument( |
| "--system-index", |
| type=Path, |
| default=None, |
| help=( |
| "Optional JSON containing graph_to_system labels. Exact tensor " |
| "content remains the authoritative grouping key." |
| ), |
| ) |
| parser.add_argument( |
| "--target-shard-mib", |
| type=int, |
| default=512, |
| help="Approximate uncompressed tensor bytes per shard; systems never cross shards.", |
| ) |
| parser.add_argument( |
| "--cutoff", |
| type=float, |
| default=6.0, |
| help="Original graph cutoff, needed to reconstruct edge_attr (default: 6.0 A).", |
| ) |
| parser.add_argument( |
| "--no-mmap", |
| action="store_true", |
| help="Eagerly load tensor storage. Only use in a sufficiently large-memory compute job.", |
| ) |
| parser.add_argument( |
| "--skip-strict-validation", |
| action="store_true", |
| help="Skip expensive edge symmetry and redundant-field consistency checks.", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def tensor_bytes(tensor: torch.Tensor) -> int: |
| return tensor.numel() * tensor.element_size() |
|
|
|
|
| def require_tensor(graph: Any, name: str) -> torch.Tensor: |
| value = getattr(graph, name, None) |
| if not isinstance(value, torch.Tensor): |
| raise ValueError(f"graph is missing tensor field {name!r}") |
| if value.device.type != "cpu": |
| value = value.cpu() |
| return value |
|
|
|
|
| def infer_partition(graph: Any) -> Tuple[int, int, int]: |
| x = require_tensor(graph, "x") |
| if x.ndim != 2 or x.shape[1] != 82: |
| raise ValueError(f"expected x=[N,82], got {tuple(x.shape)}") |
| if x.dtype != torch.float32: |
| raise ValueError(f"expected float32 x, got {x.dtype}") |
|
|
| mask = require_tensor(graph, "is_protein").reshape(-1) |
| n_nodes = x.shape[0] |
| if mask.numel() != n_nodes: |
| raise ValueError("is_protein length does not match x") |
| is_protein = mask > 0.5 |
| n_protein = int(is_protein.sum().item()) |
| if n_protein <= 0 or n_protein >= n_nodes: |
| raise ValueError(f"invalid protein/ligand partition: N={n_nodes}, Np={n_protein}") |
| expected = torch.arange(n_nodes) < n_protein |
| if not torch.equal(is_protein, expected): |
| raise ValueError("compact_v1 requires protein nodes first and ligand nodes last") |
| return n_nodes, n_protein, n_nodes - n_protein |
|
|
|
|
| def graph_content_hashes(graph: Any) -> Tuple[str, str]: |
| """Return exact native-structure and pose-shared-content hashes. |
| |
| The legacy per-method indices are useful labels, but some of them are not |
| aligned perfectly with the graph list. The shared-content hash is |
| therefore the authoritative grouping key. It also includes all 44 |
| nominally static x columns: a few legacy poses use different ligand atom |
| annotations despite sharing the same native coordinates, and those poses |
| must not silently share an incompatible x_static tensor. |
| """ |
| n_nodes, n_protein, n_ligand = infer_partition(graph) |
| y_grt = require_tensor(graph, "y_grt") |
| if y_grt.dtype != torch.float32 or tuple(y_grt.shape) != (n_nodes, 3): |
| raise ValueError(f"expected y_grt float32 [{n_nodes},3], got {y_grt.dtype} {tuple(y_grt.shape)}") |
| x = require_tensor(graph, "x") |
| static_index = torch.tensor(STATIC_COLUMNS, dtype=torch.int64) |
| x_static = x.index_select(1, static_index).contiguous() |
|
|
| prefix = bytearray(b"gnncp-native-v1\0") |
| prefix.extend(n_nodes.to_bytes(8, "little", signed=False)) |
| prefix.extend(n_protein.to_bytes(8, "little", signed=False)) |
| prefix.extend(n_ligand.to_bytes(8, "little", signed=False)) |
|
|
| native_digest = hashlib.sha256() |
| native_digest.update(prefix) |
| native_digest.update(memoryview(y_grt.detach().contiguous().numpy())) |
| native_hash = native_digest.hexdigest() |
|
|
| shared_digest = hashlib.sha256() |
| shared_digest.update(b"gnncp-shared-v1\0") |
| shared_digest.update(bytes.fromhex(native_hash)) |
| shared_digest.update(memoryview(x_static.detach().numpy())) |
| return native_hash, shared_digest.hexdigest() |
|
|
|
|
| def read_system_labels(path: Path | None, n_graphs: int) -> Tuple[List[str | None], str]: |
| if path is None: |
| return [None] * n_graphs, "y_grt_sha256" |
| with path.open("r", encoding="utf-8") as handle: |
| payload = json.load(handle) |
| labels = payload.get("graph_to_system") |
| if not isinstance(labels, list): |
| raise ValueError(f"{path}: graph_to_system is not a list") |
| if len(labels) != n_graphs: |
| raise ValueError( |
| f"{path}: graph_to_system has {len(labels)} entries, legacy dataset has {n_graphs}" |
| ) |
| normalized: List[str | None] = [] |
| for value in labels: |
| label = str(value).strip() if value is not None else "" |
| normalized.append(None if label.upper() in UNKNOWN_LABELS else label) |
| return normalized, "graph_to_system_plus_y_grt_sha256" |
|
|
|
|
| def group_graphs( |
| graphs: Sequence[Any], labels: Sequence[str | None] |
| ) -> List[Dict[str, Any]]: |
| """ |
| Group solely by exact pose-shared tensor content. |
| |
| External system labels are deliberately not part of the grouping key. |
| They are attached only when every labelled member agrees. This prevents a |
| stale/misaligned index from either merging unrelated graphs or splitting |
| poses that have identical shared tensors. |
| """ |
| grouped: MutableMapping[str, List[int]] = defaultdict(list) |
| native_hash_by_shared: Dict[str, str] = {} |
| n_graphs = len(graphs) |
| for graph_index, graph in enumerate(graphs): |
| native_hash, shared_hash = graph_content_hashes(graph) |
| grouped[shared_hash].append(graph_index) |
| previous_native_hash = native_hash_by_shared.setdefault(shared_hash, native_hash) |
| if previous_native_hash != native_hash: |
| raise RuntimeError("shared-content SHA-256 collision detected") |
| if (graph_index + 1) % 500 == 0 or graph_index + 1 == n_graphs: |
| print(f"[group] hashed {graph_index + 1}/{n_graphs} graphs", flush=True) |
|
|
| systems: List[Dict[str, Any]] = [] |
| for shared_hash, graph_indices in grouped.items(): |
| label_counts = Counter( |
| labels[index] for index in graph_indices if labels[index] is not None |
| ) |
| agreed_label = next(iter(label_counts)) if len(label_counts) == 1 else None |
| systems.append( |
| { |
| "system_id": agreed_label or f"hash_{shared_hash[:20]}", |
| "source_label": agreed_label, |
| "source_label_counts": dict(sorted(label_counts.items())), |
| "native_hash": native_hash_by_shared[shared_hash], |
| "shared_hash": shared_hash, |
| "graph_indices": sorted(graph_indices), |
| } |
| ) |
|
|
| |
| |
| label_occurrences = Counter( |
| item["source_label"] for item in systems if item["source_label"] is not None |
| ) |
| for item in systems: |
| label = item["source_label"] |
| if label is not None and label_occurrences[label] > 1: |
| item["system_id"] = f"{label}__{item['shared_hash'][:12]}" |
|
|
| |
| systems.sort(key=lambda item: (item["system_id"], item["graph_indices"][0])) |
| return systems |
|
|
|
|
| def canonical_upper_edges( |
| edge_index: torch.Tensor, n_nodes: int, strict: bool |
| ) -> torch.Tensor: |
| """Return each symmetric directed edge pair once, with local src < dst.""" |
| if edge_index.ndim != 2 or edge_index.shape[0] != 2: |
| raise ValueError(f"expected edge_index=[2,E], got {tuple(edge_index.shape)}") |
| edge = edge_index.to(dtype=torch.int64) |
| src, dst = edge[0], edge[1] |
| if edge.numel() and ( |
| int(edge.min().item()) < 0 or int(edge.max().item()) >= n_nodes |
| ): |
| raise ValueError("edge_index contains an out-of-range node index") |
| if torch.any(src == dst): |
| raise ValueError("legacy graph unexpectedly contains self edges") |
|
|
| upper_mask = src < dst |
| upper = edge[:, upper_mask] |
| if strict: |
| lower_mask = src > dst |
| if int(upper_mask.sum()) != int(lower_mask.sum()): |
| raise ValueError("edge_index is not a symmetric directed edge list") |
| upper_key = upper[0] * n_nodes + upper[1] |
| reverse_lower_key = dst[lower_mask] * n_nodes + src[lower_mask] |
| upper_key = torch.sort(upper_key).values |
| reverse_lower_key = torch.sort(reverse_lower_key).values |
| if not torch.equal(upper_key, reverse_lower_key): |
| raise ValueError("edge_index is missing one or more reverse edges") |
| if upper_key.numel() > 1 and torch.any(upper_key[1:] == upper_key[:-1]): |
| raise ValueError("edge_index contains duplicate edges") |
| return upper.to(dtype=torch.int32).contiguous() |
|
|
|
|
| def assert_equal(name: str, actual: torch.Tensor, expected: torch.Tensor) -> None: |
| if actual.dtype != expected.dtype or actual.shape != expected.shape: |
| raise ValueError( |
| f"{name} differs: {actual.dtype}{tuple(actual.shape)} vs " |
| f"{expected.dtype}{tuple(expected.shape)}" |
| ) |
| if not torch.equal(actual, expected): |
| raise ValueError(f"{name} is not identical within a system") |
|
|
|
|
| def build_system_record( |
| graphs: Sequence[Any], |
| system: Mapping[str, Any], |
| strict: bool, |
| ) -> Dict[str, Any]: |
| graph_indices: List[int] = list(system["graph_indices"]) |
| reference = graphs[graph_indices[0]] |
| n_nodes, n_protein, n_ligand = infer_partition(reference) |
| n_poses = len(graph_indices) |
|
|
| static_index = torch.tensor(STATIC_COLUMNS, dtype=torch.int64) |
| dynamic_index = torch.tensor(DYNAMIC_COLUMNS, dtype=torch.int64) |
|
|
| ref_x = require_tensor(reference, "x") |
| x_static = ref_x.index_select(1, static_index).contiguous().clone() |
| ref_pos = require_tensor(reference, "pos") |
| ref_y_pred = require_tensor(reference, "y_pred") |
| ref_y_grt = require_tensor(reference, "y_grt") |
| for field_name, value in ( |
| ("pos", ref_pos), |
| ("y_pred", ref_y_pred), |
| ("y_grt", ref_y_grt), |
| ): |
| if value.dtype != torch.float32 or tuple(value.shape) != (n_nodes, 3): |
| raise ValueError( |
| f"{system['system_id']}: expected {field_name} float32 [{n_nodes},3]" |
| ) |
| if strict: |
| assert_equal("reference pos/y_pred", ref_pos, ref_y_pred) |
|
|
| protein_pos = ref_pos[:n_protein].contiguous().clone() |
| native_ligand_pos = ref_y_grt[n_protein:].contiguous().clone() |
| x_dynamic = torch.empty((n_poses * n_nodes, len(DYNAMIC_COLUMNS)), dtype=torch.float32) |
| ligand_pos = torch.empty((n_poses * n_ligand, 3), dtype=torch.float32) |
|
|
| ref_upper = canonical_upper_edges( |
| require_tensor(reference, "edge_index"), n_nodes, strict |
| ) |
| ref_pp_mask = (ref_upper[0] < n_protein) & (ref_upper[1] < n_protein) |
| pp_edge_upper = ref_upper[:, ref_pp_mask].contiguous().clone() |
|
|
| nonpp_edges: List[torch.Tensor] = [] |
| nonpp_counts: List[int] = [] |
|
|
| for pose_index, graph_index in enumerate(graph_indices): |
| graph = graphs[graph_index] |
| shape = infer_partition(graph) |
| if shape != (n_nodes, n_protein, n_ligand): |
| raise ValueError( |
| f"{system['system_id']}: graph {graph_index} changed node partition " |
| f"from {(n_nodes, n_protein, n_ligand)} to {shape}" |
| ) |
|
|
| x = require_tensor(graph, "x") |
| current_static = x.index_select(1, static_index) |
| assert_equal("x static columns", current_static, x_static) |
| dynamic_start = pose_index * n_nodes |
| x_dynamic[dynamic_start : dynamic_start + n_nodes].copy_( |
| x.index_select(1, dynamic_index) |
| ) |
|
|
| pos = require_tensor(graph, "pos") |
| y_pred = require_tensor(graph, "y_pred") |
| y_grt = require_tensor(graph, "y_grt") |
| for field_name, value in (("pos", pos), ("y_pred", y_pred), ("y_grt", y_grt)): |
| if value.dtype != torch.float32 or tuple(value.shape) != (n_nodes, 3): |
| raise ValueError( |
| f"{system['system_id']}: graph {graph_index} has invalid {field_name}" |
| ) |
| assert_equal("protein coordinates", pos[:n_protein], protein_pos) |
| assert_equal("native ligand coordinates", y_grt[n_protein:], native_ligand_pos) |
| if strict: |
| assert_equal("pos/y_pred", pos, y_pred) |
| assert_equal("ground-truth protein coordinates", y_grt[:n_protein], protein_pos) |
| y_true = require_tensor(graph, "y_true").reshape(-1) |
| if y_true.dtype != torch.float32 or y_true.numel() != n_nodes: |
| raise ValueError("invalid y_true") |
| expected_error = torch.linalg.vector_norm(pos - y_grt, dim=1) |
| if not torch.allclose(y_true, expected_error, rtol=1e-5, atol=1e-5): |
| raise ValueError("y_true cannot be reconstructed from pos and y_grt") |
|
|
| ligand_start = pose_index * n_ligand |
| ligand_pos[ligand_start : ligand_start + n_ligand].copy_(pos[n_protein:]) |
|
|
| upper = canonical_upper_edges(require_tensor(graph, "edge_index"), n_nodes, strict) |
| pp_mask = (upper[0] < n_protein) & (upper[1] < n_protein) |
| assert_equal("protein-protein edges", upper[:, pp_mask], pp_edge_upper) |
| nonpp = upper[:, ~pp_mask].contiguous().clone() |
| nonpp_edges.append(nonpp) |
| nonpp_counts.append(nonpp.shape[1]) |
|
|
| if strict: |
| edge_attr = require_tensor(graph, "edge_attr") |
| if edge_attr.dtype != torch.float32 or tuple(edge_attr.shape) != ( |
| require_tensor(graph, "edge_index").shape[1], |
| 4, |
| ): |
| raise ValueError("invalid edge_attr") |
|
|
| if nonpp_edges: |
| nonpp_edge_upper = torch.cat(nonpp_edges, dim=1) |
| else: |
| nonpp_edge_upper = torch.empty((2, 0), dtype=torch.int32) |
|
|
| record: Dict[str, Any] = { |
| |
| "_system_id": system["system_id"], |
| "_source_label": system["source_label"], |
| "_source_label_counts": system["source_label_counts"], |
| "_native_hash": system["native_hash"], |
| "_shared_hash": system["shared_hash"], |
| "_n_nodes": n_nodes, |
| "_n_protein": n_protein, |
| "_n_ligand": n_ligand, |
| "_n_poses": n_poses, |
| |
| "x_static": x_static, |
| "protein_pos": protein_pos, |
| "native_ligand_pos": native_ligand_pos, |
| "x_dynamic": x_dynamic, |
| "ligand_pos": ligand_pos, |
| "pp_edge_upper": pp_edge_upper, |
| "nonpp_edge_upper": nonpp_edge_upper, |
| "nonpp_edge_counts": torch.tensor(nonpp_counts, dtype=torch.int64), |
| "source_graph_index": torch.tensor(graph_indices, dtype=torch.int64), |
| } |
| record["_tensor_bytes"] = sum( |
| tensor_bytes(value) for value in record.values() if isinstance(value, torch.Tensor) |
| ) |
| return record |
|
|
|
|
| def cumulative_ptr(lengths: Iterable[int]) -> torch.Tensor: |
| values = [0] |
| for length in lengths: |
| values.append(values[-1] + int(length)) |
| return torch.tensor(values, dtype=torch.int64) |
|
|
|
|
| def concatenate(records: Sequence[Mapping[str, Any]], key: str, dim: int = 0) -> torch.Tensor: |
| tensors = [record[key] for record in records] |
| return torch.cat(tensors, dim=dim) |
|
|
|
|
| def pack_shard(records: Sequence[Mapping[str, Any]]) -> Dict[str, torch.Tensor]: |
| n_poses = [record["_n_poses"] for record in records] |
| n_nodes = [record["_n_nodes"] for record in records] |
| n_protein = [record["_n_protein"] for record in records] |
| n_ligand = [record["_n_ligand"] for record in records] |
|
|
| pose_system = torch.repeat_interleave( |
| torch.arange(len(records), dtype=torch.int32), |
| torch.tensor(n_poses, dtype=torch.int64), |
| ) |
| pose_node_lengths: List[int] = [] |
| pose_ligand_lengths: List[int] = [] |
| for p, n, nl in zip(n_poses, n_nodes, n_ligand): |
| pose_node_lengths.extend([n] * p) |
| pose_ligand_lengths.extend([nl] * p) |
|
|
| return { |
| "schema_version": torch.tensor([SCHEMA_VERSION], dtype=torch.int32), |
| "system_graph_ptr": cumulative_ptr(n_poses), |
| "pose_system": pose_system, |
| "source_graph_index": concatenate(records, "source_graph_index"), |
| "system_node_ptr": cumulative_ptr(n_nodes), |
| "n_protein": torch.tensor(n_protein, dtype=torch.int32), |
| "x_static": concatenate(records, "x_static"), |
| "protein_ptr": cumulative_ptr(n_protein), |
| "protein_pos": concatenate(records, "protein_pos"), |
| "native_ligand_ptr": cumulative_ptr(n_ligand), |
| "native_ligand_pos": concatenate(records, "native_ligand_pos"), |
| "pose_node_ptr": cumulative_ptr(pose_node_lengths), |
| "x_dynamic": concatenate(records, "x_dynamic"), |
| "pose_ligand_ptr": cumulative_ptr(pose_ligand_lengths), |
| "ligand_pos": concatenate(records, "ligand_pos"), |
| "pp_edge_ptr": cumulative_ptr( |
| record["pp_edge_upper"].shape[1] for record in records |
| ), |
| "pp_edge_upper": concatenate(records, "pp_edge_upper", dim=1), |
| "nonpp_edge_ptr": cumulative_ptr( |
| int(count) |
| for record in records |
| for count in record["nonpp_edge_counts"].tolist() |
| ), |
| "nonpp_edge_upper": concatenate(records, "nonpp_edge_upper", dim=1), |
| } |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
| input_path = args.input.resolve() |
| output_dir = args.output_dir.resolve() |
| system_index = args.system_index.resolve() if args.system_index else None |
|
|
| if not input_path.is_file(): |
| raise FileNotFoundError(input_path) |
| if system_index is not None and not system_index.is_file(): |
| raise FileNotFoundError(system_index) |
| if output_dir.exists(): |
| raise FileExistsError( |
| f"refusing to overwrite existing output directory: {output_dir}" |
| ) |
| if args.target_shard_mib <= 0: |
| raise ValueError("--target-shard-mib must be positive") |
|
|
| output_dir.parent.mkdir(parents=True, exist_ok=True) |
| run_id = os.environ.get("SLURM_JOB_ID") or str(os.getpid()) |
| staging_dir = output_dir.with_name(f".{output_dir.name}.building.{run_id}") |
| if staging_dir.exists(): |
| raise FileExistsError(f"staging directory already exists: {staging_dir}") |
| shard_dir = staging_dir / "shards" |
| shard_dir.mkdir(parents=True) |
|
|
| print(f"input: {input_path}", flush=True) |
| print(f"output: {output_dir}", flush=True) |
| print(f"staging: {staging_dir}", flush=True) |
| print(f"method: {args.method}", flush=True) |
| print(f"mmap: {not args.no_mmap}", flush=True) |
| print(f"strict: {not args.skip_strict_validation}", flush=True) |
|
|
| try: |
| graphs = torch.load( |
| input_path, |
| map_location="cpu", |
| weights_only=False, |
| mmap=not args.no_mmap, |
| ) |
| except RuntimeError as exc: |
| if not args.no_mmap: |
| raise RuntimeError( |
| "mmap loading failed. Re-submit a sufficiently large-memory Slurm job " |
| "with --no-mmap if this file uses legacy torch serialization." |
| ) from exc |
| raise |
| if not isinstance(graphs, (list, tuple)): |
| raise TypeError(f"expected legacy list/tuple, got {type(graphs).__name__}") |
| n_graphs = len(graphs) |
| if n_graphs == 0: |
| raise ValueError("legacy dataset is empty") |
| print(f"opened {n_graphs} legacy graphs", flush=True) |
|
|
| labels, grouping_mode = read_system_labels(system_index, n_graphs) |
| systems = group_graphs(graphs, labels) |
| print( |
| f"grouped into {len(systems)} systems via exact shared-content hash " |
| f"(labels: {grouping_mode})", |
| flush=True, |
| ) |
|
|
| target_bytes = args.target_shard_mib * 1024 * 1024 |
| strict = not args.skip_strict_validation |
| graph_map: List[List[int] | None] = [None] * n_graphs |
| shard_manifest: List[Dict[str, Any]] = [] |
| pending: List[Dict[str, Any]] = [] |
| pending_bytes = 0 |
| compact_bytes = 0 |
|
|
| def flush_pending() -> None: |
| nonlocal pending, pending_bytes, compact_bytes |
| if not pending: |
| return |
| shard_index = len(shard_manifest) |
| relative_path = f"shards/shard_{shard_index:05d}.pt" |
| final_path = staging_dir / relative_path |
| temp_path = final_path.with_suffix(".pt.tmp") |
| packed = pack_shard(pending) |
| torch.save(packed, temp_path) |
| os.replace(temp_path, final_path) |
| size_bytes = final_path.stat().st_size |
| compact_bytes += size_bytes |
|
|
| local_pose = 0 |
| system_entries: List[Dict[str, Any]] = [] |
| for record in pending: |
| source_indices = record["source_graph_index"].tolist() |
| for offset, source_index in enumerate(source_indices): |
| graph_map[source_index] = [shard_index, local_pose + offset] |
| system_entries.append( |
| { |
| "system_id": record["_system_id"], |
| "source_label": record["_source_label"], |
| "source_label_counts": record["_source_label_counts"], |
| "native_hash": record["_native_hash"], |
| "shared_hash": record["_shared_hash"], |
| "num_graphs": record["_n_poses"], |
| "num_nodes": record["_n_nodes"], |
| "num_protein_nodes": record["_n_protein"], |
| "num_ligand_nodes": record["_n_ligand"], |
| } |
| ) |
| local_pose += record["_n_poses"] |
|
|
| shard_manifest.append( |
| { |
| "path": relative_path, |
| "num_graphs": local_pose, |
| "num_systems": len(pending), |
| "size_bytes": size_bytes, |
| "systems": system_entries, |
| } |
| ) |
| print( |
| f"[write] {relative_path}: {len(pending)} systems, {local_pose} graphs, " |
| f"{size_bytes / 2**20:.1f} MiB", |
| flush=True, |
| ) |
| del packed |
| pending = [] |
| pending_bytes = 0 |
| gc.collect() |
|
|
| for system_number, system in enumerate(systems, start=1): |
| record = build_system_record(graphs, system, strict=strict) |
| record_bytes = int(record["_tensor_bytes"]) |
| if pending and pending_bytes + record_bytes > target_bytes: |
| flush_pending() |
| pending.append(record) |
| pending_bytes += record_bytes |
| print( |
| f"[system] {system_number}/{len(systems)} {system['system_id']}: " |
| f"{record['_n_poses']} poses, {record_bytes / 2**20:.1f} MiB raw compact", |
| flush=True, |
| ) |
| flush_pending() |
|
|
| if any(item is None for item in graph_map): |
| raise RuntimeError("internal error: graph_map is incomplete") |
|
|
| source_stat = input_path.stat() |
| manifest: Dict[str, Any] = { |
| "format": FORMAT_NAME, |
| "schema_version": SCHEMA_VERSION, |
| "status": "complete", |
| "created_utc": datetime.now(timezone.utc).isoformat(), |
| "method": args.method, |
| "cutoff": args.cutoff, |
| "source": { |
| "path": str(input_path), |
| "size_bytes": source_stat.st_size, |
| "mtime_ns": source_stat.st_mtime_ns, |
| "system_index": str(system_index) if system_index else None, |
| }, |
| "grouping": { |
| "mode": "exact_shared_content_hash", |
| "label_source": grouping_mode, |
| "authoritative_key": ( |
| "sha256(exact float32 y_grt + node partition + " |
| "x[:,0:34] + x[:,61:71])" |
| ), |
| "external_labels_are_metadata_only": True, |
| }, |
| "features": { |
| "full_dimension": 82, |
| "dtype": "float32", |
| "static_dimension": len(STATIC_COLUMNS), |
| "static_columns": list(STATIC_COLUMNS), |
| "dynamic_dimension": len(DYNAMIC_COLUMNS), |
| "dynamic_columns": list(DYNAMIC_COLUMNS), |
| }, |
| "edges": { |
| "index_dtype_on_disk": "int32", |
| "stored_direction": "upper_triangle_src_lt_dst", |
| "protein_protein_scope": "once_per_system", |
| "non_protein_protein_scope": "once_per_pose", |
| "edge_attr": "derived_from_float32_coordinates_and_endpoint_types", |
| }, |
| "derived_fields": [ |
| "pos", |
| "is_protein", |
| "y_true", |
| "y_pred", |
| "y_grt", |
| "edge_index_reverse_direction", |
| "edge_attr", |
| "num_nodes", |
| ], |
| "n_graphs": n_graphs, |
| "n_systems": len(systems), |
| "n_shards": len(shard_manifest), |
| "graph_map": graph_map, |
| "shards": shard_manifest, |
| "size": { |
| "legacy_bytes": source_stat.st_size, |
| "compact_shard_bytes": compact_bytes, |
| "legacy_to_compact_ratio": ( |
| source_stat.st_size / compact_bytes if compact_bytes else None |
| ), |
| }, |
| "strict_validation": strict, |
| } |
| manifest_path = staging_dir / "manifest.json" |
| temp_manifest = staging_dir / "manifest.json.tmp" |
| with temp_manifest.open("w", encoding="utf-8") as handle: |
| json.dump(manifest, handle, indent=2, ensure_ascii=False) |
| handle.write("\n") |
| os.replace(temp_manifest, manifest_path) |
|
|
| |
| os.replace(staging_dir, output_dir) |
| print(f"complete: {output_dir / 'manifest.json'}", flush=True) |
| print( |
| f"legacy={source_stat.st_size / 2**30:.2f} GiB, " |
| f"compact_shards={compact_bytes / 2**30:.2f} GiB, " |
| f"ratio={source_stat.st_size / compact_bytes:.2f}x", |
| flush=True, |
| ) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| try: |
| raise SystemExit(main()) |
| except Exception as error: |
| print(f"ERROR: {error}", file=sys.stderr, flush=True) |
| raise |
|
|