File size: 24,545 Bytes
0cb481f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 | #!/usr/bin/env python3
"""Prepare and publish the completed HiQBind compact datasets to Hugging Face.
The published repository layout is intentionally simple and stable::
README.md
docs/
code/compact_v1/
data/hiqbind_5k_v1/
autodock_vina_full_v1/
diffdock_full_v1/
``--prepare`` makes a persistent local staging tree. Tensor shards are
*hard-linked* from the completed local datasets, so the staging tree does not
duplicate the roughly 93 GB payload. The two JSON files which could expose
local source paths (``manifest.json`` and ``source_index.json``) are copied
after recursively replacing absolute paths with a non-path marker.
``--upload`` accepts ``HF_TOKEN``, ``--token``, or a token saved by
``huggingface_hub.login()``. It authenticates with ``whoami`` and checks the
target dataset repository before invoking ``HfApi.upload_large_folder``. The
latter keeps its resume metadata below the staging tree, therefore retain the
same ``--stage-root`` if an upload is interrupted.
Examples
--------
Inspect without writing or contacting Hugging Face::
/u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --dry-run
Build and inspect the reusable staging tree::
/u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --verify
Upload after review (the token is intentionally not printed)::
HF_TOKEN=... /u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py \
--prepare --verify --upload --num-workers 8
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Mapping, Sequence
RELEASE_ROOT = Path(__file__).resolve().parent
PROJECT_ROOT = RELEASE_ROOT.parent
WORKSPACE_ROOT = PROJECT_ROOT.parent
DEFAULT_DATASET_ROOT = PROJECT_ROOT / "datasets_compact_hiqbind_v1"
DEFAULT_STAGE_ROOT = RELEASE_ROOT / "hf_stage_copuladock"
DEFAULT_REPO_ID = "liofoil/copuladock"
@dataclass(frozen=True)
class DatasetSpec:
"""A completed compact dataset and its release-relative destination."""
source_name: str
release_name: str
DATASETS: tuple[DatasetSpec, ...] = (
DatasetSpec("autodock_vina_full_v1", "autodock_vina_full_v1"),
DatasetSpec("diffdock_full_v1", "diffdock_full_v1"),
)
# These are the minimal reproducible construction/reader components. They
# intentionally exclude raw docking outputs and cluster logs.
CODE_SOURCES: tuple[tuple[Path, Path], ...] = (
(
WORKSPACE_ROOT / "docking_base/scripts/materialize_hiqbind_gnncp.py",
Path("code/compact_v1/materialize_hiqbind_gnncp.py"),
),
(
PROJECT_ROOT / "system_split_code/build_compact_v1_direct.py",
Path("code/compact_v1/build_compact_v1_direct.py"),
),
(
PROJECT_ROOT / "system_split_code/build_compact_v1_direct.sbatch",
Path("code/compact_v1/build_compact_v1_direct.sbatch"),
),
(
PROJECT_ROOT / "system_split_code/build_graph_unified_enhanced.py",
Path("code/compact_v1/build_graph_unified_enhanced.py"),
),
(
PROJECT_ROOT / "system_split_code/convert_to_compact_v1.py",
Path("code/compact_v1/convert_to_compact_v1.py"),
),
(
PROJECT_ROOT / "system_split_code/compact_graph_dataset.py",
Path("code/compact_v1/compact_graph_dataset.py"),
),
(
PROJECT_ROOT / "system_split_code/build_system_index.py",
Path("code/compact_v1/build_system_index.py"),
),
(
PROJECT_ROOT / "system_split_code/validate_compact_dataset.py",
Path("code/compact_v1/validate_compact_dataset.py"),
),
(
PROJECT_ROOT / "system_split_code/smoke_test_compact_dataset.py",
Path("code/compact_v1/smoke_test_compact_dataset.py"),
),
(
PROJECT_ROOT / "system_split_code/test_build_compact_v1_direct.py",
# Keep tests alongside the modules they import. The upstream tests
# intentionally resolve convert_to_compact_v1.py by sibling path.
Path("code/compact_v1/test_build_compact_v1_direct.py"),
),
(
PROJECT_ROOT / "system_split_code/test_compact_graph_dataset.py",
Path("code/compact_v1/test_compact_graph_dataset.py"),
),
)
# Previous staging revisions placed the two tests under ``tests/``. Prune
# only these exact, generated staging copies during --prepare so an old stage
# cannot publish duplicate stale tests. No dataset data are ever removed.
OBSOLETE_STAGE_FILES: tuple[Path, ...] = (
Path("code/compact_v1/tests/test_build_compact_v1_direct.py"),
Path("code/compact_v1/tests/test_compact_graph_dataset.py"),
)
class ReleaseError(RuntimeError):
"""A release-preparation or release-verification failure."""
def _relative_to(path: Path, root: Path) -> Path:
"""Return ``path`` relative to ``root`` or raise a contextual error."""
try:
return path.relative_to(root)
except ValueError as exc:
raise ReleaseError(f"path escapes its expected root: {path} (root={root})") from exc
def _is_absolute_path_text(value: str) -> bool:
"""Detect POSIX/Windows-looking absolute paths without interpreting IDs."""
return value.startswith("/") or (len(value) >= 3 and value[1:3] in (":\\", ":/"))
def _sanitize_value(value: Any) -> Any:
"""Copy JSON-like values while removing every absolute-path string."""
if isinstance(value, dict):
return {str(key): _sanitize_value(item) for key, item in value.items()}
if isinstance(value, list):
return [_sanitize_value(item) for item in value]
if isinstance(value, str) and _is_absolute_path_text(value):
return "<local-path-removed>"
return value
def _find_absolute_path_values(value: Any, prefix: str = "$") -> list[str]:
"""Return JSON locations that still contain an absolute path string."""
found: list[str] = []
if isinstance(value, Mapping):
for key, item in value.items():
found.extend(_find_absolute_path_values(item, f"{prefix}.{key}"))
elif isinstance(value, list):
for index, item in enumerate(value):
found.extend(_find_absolute_path_values(item, f"{prefix}[{index}]"))
elif isinstance(value, str) and _is_absolute_path_text(value):
found.append(prefix)
return found
def _read_json(path: Path) -> Any:
try:
with path.open("r", encoding="utf-8") as handle:
return json.load(handle)
except (OSError, json.JSONDecodeError) as exc:
raise ReleaseError(f"cannot read JSON {path}: {exc}") from exc
def _write_json(path: Path, payload: Any) -> None:
"""Write a small JSON file atomically inside the staging tree."""
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + ".tmp")
try:
with temporary.open("w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
finally:
# If json.dump failed before os.replace, only remove the known temp file.
if temporary.exists():
temporary.unlink()
def _copy_file(source: Path, destination: Path) -> None:
"""Snapshot a small code/document file without following unsafe parents."""
if not source.is_file():
raise ReleaseError(f"required release file is missing: {source}")
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = destination.with_name(destination.name + ".tmp")
try:
shutil.copy2(source, temporary)
os.replace(temporary, destination)
finally:
if temporary.exists():
temporary.unlink()
def _hardlink_file(source: Path, destination: Path) -> None:
"""Make one idempotent hard link; never silently copy a tensor shard."""
if not source.is_file():
raise ReleaseError(f"source file is missing: {source}")
destination.parent.mkdir(parents=True, exist_ok=True)
if destination.exists():
source_stat = source.stat()
destination_stat = destination.stat()
if (source_stat.st_dev, source_stat.st_ino) == (destination_stat.st_dev, destination_stat.st_ino):
return
raise ReleaseError(
"staging file already exists but is not the expected hard link; "
f"refusing to replace it: {destination}"
)
try:
os.link(source, destination)
except OSError as exc:
raise ReleaseError(
"hard-link failed; staging and source must share a filesystem. "
f"source={source}, destination={destination}: {exc}"
) from exc
def _dataset_source(dataset_root: Path, spec: DatasetSpec) -> Path:
source = (dataset_root / spec.source_name).resolve()
if not source.is_dir():
raise ReleaseError(f"completed compact dataset is missing: {source}")
manifest = source / "manifest.json"
if not manifest.is_file():
raise ReleaseError(f"completed compact dataset has no manifest: {manifest}")
value = _read_json(manifest)
if not isinstance(value, dict) or value.get("status") != "complete":
raise ReleaseError(f"dataset is not a complete compact release: {source}")
return source
def _release_dataset_root(stage_root: Path, spec: DatasetSpec) -> Path:
return stage_root / "data" / "hiqbind_5k_v1" / spec.release_name
def _sanitized_json_payload(source: Path) -> Any:
payload = _sanitize_value(_read_json(source))
leftovers = _find_absolute_path_values(payload)
if leftovers:
raise ReleaseError(f"path sanitizer left absolute paths in {source}: {leftovers[:5]}")
return payload
def _stage_dataset(source: Path, destination: Path) -> None:
"""Stage a compact dataset, hard-linking all immutable source artifacts."""
for source_file in sorted(source.rglob("*")):
if not source_file.is_file():
continue
relative = _relative_to(source_file, source)
target = destination / relative
# These two records contain source provenance. Their release versions
# preserve logical relative fields but never disclose local paths.
if source_file.name in {"manifest.json", "source_index.json"}:
_write_json(target, _sanitized_json_payload(source_file))
else:
_hardlink_file(source_file, target)
def _release_assets() -> list[tuple[Path, Path]]:
"""Discover authored release documents plus the static code mapping."""
assets = list(CODE_SOURCES)
# README is the Hugging Face dataset card. Other authored Markdown files
# are companion documents, keeping the remote root uncluttered.
for source in sorted(RELEASE_ROOT.glob("*.md"), key=lambda item: item.name.casefold()):
remote = Path("README.md") if source.name == "README.md" else Path("docs") / source.name
assets.append((source, remote))
# Release-authored companion docs and the small hand-written package notes
# live in the release tree itself. Include them recursively while
# deliberately excluding generated __pycache__ / staging content.
authored_docs = RELEASE_ROOT / "docs"
if authored_docs.is_dir():
for source in sorted(authored_docs.rglob("*"), key=lambda item: str(item).casefold()):
if source.is_file() and "__pycache__" not in source.parts:
assets.append((source, Path("docs") / _relative_to(source, authored_docs)))
authored_code = RELEASE_ROOT / "code" / "compact_v1"
if authored_code.is_dir():
for source in sorted(authored_code.rglob("*"), key=lambda item: str(item).casefold()):
if source.is_file() and "__pycache__" not in source.parts:
assets.append((source, Path("code/compact_v1") / _relative_to(source, authored_code)))
# A dependency file placed at the release root is also supported for
# convenience; a code/compact_v1 version takes precedence by causing an
# explicit duplicate-destination error rather than silent replacement.
for name in ("requirements.txt", "environment.yml", "environment.yaml"):
source = RELEASE_ROOT / name
if source.is_file():
assets.append((source, Path("code/compact_v1") / name))
# Include the reproducible release entry points themselves, but not this
# staging directory or arbitrary local files.
for name in ("upload_copuladock.py", "upload_copuladock.sbatch"):
source = RELEASE_ROOT / name
if source.is_file():
assets.append((source, Path("code/release") / name))
return assets
def _stage_assets(stage_root: Path) -> list[Path]:
staged: list[Path] = []
seen_destinations: set[Path] = set()
for source, remote in _release_assets():
if remote in seen_destinations:
raise ReleaseError(f"duplicate release destination: {remote}")
seen_destinations.add(remote)
if not source.is_file():
raise ReleaseError(f"required construction code is missing: {source}")
target = stage_root / remote
_copy_file(source, target)
staged.append(target)
return staged
def _prune_obsolete_stage_files(stage_root: Path) -> None:
"""Remove only known stale generated code copies from an older layout."""
for relative in OBSOLETE_STAGE_FILES:
target = stage_root / relative
if target.is_file():
target.unlink()
# Leave a directory untouched when it contains anything unexpected;
# upload_large_folder ignores empty directories in any event.
parent = target.parent
if parent.is_dir() and not any(parent.iterdir()):
parent.rmdir()
def _validate_stage_location(stage_root: Path, dataset_root: Path) -> None:
"""Prevent accidental recursive staging into either source dataset root."""
stage_root = stage_root.resolve()
dataset_root = dataset_root.resolve()
if stage_root == dataset_root:
raise ReleaseError("--stage-root must not equal --dataset-root")
try:
stage_root.relative_to(dataset_root)
except ValueError:
return
raise ReleaseError("--stage-root must not be inside --dataset-root")
def _expected_tensor_files(source: Path) -> list[Path]:
return sorted(path for path in source.rglob("*.pt") if path.is_file())
def _human_bytes(number: int) -> str:
value = float(number)
for suffix in ("B", "KiB", "MiB", "GiB", "TiB"):
if value < 1024.0 or suffix == "TiB":
return f"{value:.1f} {suffix}"
value /= 1024.0
return f"{number} B"
def _source_summary(dataset_root: Path) -> list[dict[str, Any]]:
summary: list[dict[str, Any]] = []
for spec in DATASETS:
source = _dataset_source(dataset_root, spec)
manifest = _read_json(source / "manifest.json")
tensors = _expected_tensor_files(source)
summary.append(
{
"name": spec.release_name,
"source": str(source),
"systems": int(manifest.get("n_systems", 0)),
"graphs": int(manifest.get("n_graphs", 0)),
"shards": len(tensors),
"tensor_bytes": sum(path.stat().st_size for path in tensors),
}
)
return summary
def prepare_stage(stage_root: Path, dataset_root: Path, *, dry_run: bool) -> None:
"""Create/update the reusable stage. ``dry_run`` performs no writes."""
_validate_stage_location(stage_root, dataset_root)
summaries = _source_summary(dataset_root)
assets = _release_assets()
print(f"stage root: {stage_root}")
for item in summaries:
print(
f" {item['name']}: {item['systems']} systems, {item['graphs']} graphs, "
f"{item['shards']} .pt shards, {_human_bytes(item['tensor_bytes'])}"
)
print(f" construction/release files: {len(assets)}")
if dry_run:
print("dry-run: source checks passed; no staging files were created or changed.")
return
stage_root.mkdir(parents=True, exist_ok=True)
for spec in DATASETS:
_stage_dataset(_dataset_source(dataset_root, spec), _release_dataset_root(stage_root, spec))
_stage_assets(stage_root)
_prune_obsolete_stage_files(stage_root)
print("staging preparation completed (tensor shards are hard links).")
def verify_stage(stage_root: Path, dataset_root: Path, *, require_readme: bool) -> None:
"""Check staging layout, sanitization, and every tensor hard link."""
if not stage_root.is_dir():
raise ReleaseError(f"staging root does not exist: {stage_root}")
errors: list[str] = []
checked_tensors = 0
for spec in DATASETS:
source = _dataset_source(dataset_root, spec)
staged = _release_dataset_root(stage_root, spec)
if not staged.is_dir():
errors.append(f"missing staged dataset directory: {staged}")
continue
for name in ("manifest.json", "source_index.json", "system_index.json"):
candidate = staged / name
if not candidate.is_file():
errors.append(f"missing staged metadata: {candidate}")
for name in ("manifest.json", "source_index.json"):
candidate = staged / name
if candidate.is_file():
try:
leftovers = _find_absolute_path_values(_read_json(candidate))
except ReleaseError as exc:
errors.append(str(exc))
else:
if leftovers:
errors.append(f"absolute paths remain in {candidate}: {leftovers[:5]}")
for source_tensor in _expected_tensor_files(source):
staged_tensor = staged / _relative_to(source_tensor, source)
if not staged_tensor.is_file():
errors.append(f"missing staged tensor: {staged_tensor}")
continue
source_stat = source_tensor.stat()
staged_stat = staged_tensor.stat()
if (source_stat.st_dev, source_stat.st_ino) != (staged_stat.st_dev, staged_stat.st_ino):
errors.append(f"tensor is not a hard link: {staged_tensor}")
if source_stat.st_size != staged_stat.st_size:
errors.append(f"tensor size differs: {staged_tensor}")
checked_tensors += 1
for source, remote in _release_assets():
staged_file = stage_root / remote
if not staged_file.is_file():
errors.append(f"missing staged release asset: {staged_file}")
elif staged_file.stat().st_size != source.stat().st_size:
errors.append(f"staged release asset size differs: {staged_file}")
readme = stage_root / "README.md"
if require_readme and not readme.is_file():
errors.append("README.md is required before upload; add it under release_copuladock/")
if errors:
raise ReleaseError("staging verification failed:\n - " + "\n - ".join(errors))
print(f"staging verification passed: {checked_tensors} tensor hard links checked; no local absolute paths in release metadata.")
def _get_token(args: argparse.Namespace) -> str:
token = args.token or os.environ.get("HF_TOKEN")
if token:
return token
try:
from huggingface_hub import get_token
except ImportError as exc:
raise ReleaseError(
"--upload requires --token/HF_TOKEN or a saved Hugging Face login; "
"huggingface_hub is unavailable."
) from exc
token = get_token()
if not token:
raise ReleaseError(
"--upload requires --token, HF_TOKEN, or a saved Hugging Face login. "
"Run `python -c 'from huggingface_hub import login; login()'` first."
)
return token
def upload_stage(args: argparse.Namespace) -> None:
"""Authenticate safely and perform the one resumable folder upload."""
if args.dry_run:
print(
"dry-run: would verify credentials and call HfApi.upload_large_folder "
f"for dataset repo {args.repo_id!r} from {args.stage_root}."
)
return
token = _get_token(args)
try:
from huggingface_hub import HfApi
except ImportError as exc:
raise ReleaseError(
"huggingface_hub is unavailable. Run with "
"/u/hhao/anaconda3/envs/hgf/bin/python."
) from exc
api = HfApi(token=token)
try:
account = api.whoami(token=token)
api.repo_info(args.repo_id, repo_type="dataset", revision=args.revision, token=token)
except Exception as exc: # The Hub library exposes several transport/auth exception types.
raise ReleaseError(
f"cannot authenticate to or access dataset repository {args.repo_id!r}: {exc}"
) from exc
# The user identity is useful operational evidence but contains no secret.
account_name = account.get("name") if isinstance(account, Mapping) else None
print(f"Hugging Face authentication verified for account: {account_name or '<unknown>'}")
print(
"starting resumable upload_large_folder: "
f"repo={args.repo_id}, revision={args.revision}, workers={args.num_workers}"
)
try:
api.upload_large_folder(
repo_id=args.repo_id,
folder_path=args.stage_root,
repo_type="dataset",
revision=args.revision,
num_workers=args.num_workers,
# upload_large_folder writes resumable state below .cache; it is
# operational metadata, not part of the scientific release.
ignore_patterns=[".cache/**", "**/__pycache__/**", "*.pyc", "*.tmp"],
print_report=True,
)
except Exception as exc:
raise ReleaseError(
"Hugging Face upload did not complete. Keep the staging root unchanged and rerun "
"the same command to resume: "
f"{exc}"
) from exc
print("upload_large_folder completed successfully.")
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--prepare", action="store_true", help="create/update the persistent staging tree")
parser.add_argument("--verify", action="store_true", help="verify an existing staging tree")
parser.add_argument("--upload", action="store_true", help="upload a verified staging tree to Hugging Face")
parser.add_argument(
"--dry-run",
action="store_true",
help="show prepare/upload actions without staging writes or network access",
)
parser.add_argument("--repo-id", default=DEFAULT_REPO_ID, help=f"target dataset repo (default: {DEFAULT_REPO_ID})")
parser.add_argument("--revision", default="main", help="target revision (default: main)")
parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT)
parser.add_argument("--stage-root", type=Path, default=DEFAULT_STAGE_ROOT)
parser.add_argument("--num-workers", type=int, default=8, help="upload_large_folder worker count (default: 8)")
parser.add_argument("--token", help="Hugging Face token; prefer HF_TOKEN in a job environment")
return parser
def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
if not (args.prepare or args.verify or args.upload):
raise ReleaseError("select at least one action: --prepare, --verify, and/or --upload")
if args.num_workers < 1:
raise ReleaseError("--num-workers must be at least 1")
args.dataset_root = args.dataset_root.expanduser().resolve()
args.stage_root = args.stage_root.expanduser().resolve()
if args.prepare:
prepare_stage(args.stage_root, args.dataset_root, dry_run=args.dry_run)
if args.verify or args.upload:
# A dry-run upload has no staging side effects, but validates a real
# stage when one is already present. This catches layout mistakes
# before credentials/network access are involved.
verify_stage(args.stage_root, args.dataset_root, require_readme=args.upload and not args.dry_run)
if args.upload:
upload_stage(args)
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except ReleaseError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
raise SystemExit(2)
|