"""Server-side preparation of the model-independent EVI core v2 data. This command intentionally stops after building the local release and training inputs. It never uploads to Hugging Face and never launches a GPU training run. The checked-in server runbook continues from its output. """ from __future__ import annotations import argparse import hashlib import json import os import shutil import subprocess import sys import tarfile import urllib.error import urllib.request import zipfile from collections.abc import Mapping, Sequence from dataclasses import dataclass from pathlib import Path, PurePosixPath from typing import IO, Any import yaml from ..atomic_io import atomic_write_json from ..paths import repo_root _CHUNK_BYTES = 8 * 1024 * 1024 _PROGRESS_BYTES = 256 * 1024 * 1024 class ServerPreparationError(RuntimeError): """The server cannot safely complete the registered preparation plan.""" @dataclass(frozen=True) class ServerLayout: root: Path downloads: Path raw: Path tools: Path plotqa_release: Path release: Path training_inputs: Path gqa_image_cache: Path clevr_dataset_gen: Path blender_root: Path def _mapping(value: Any, label: str) -> Mapping[str, Any]: if not isinstance(value, Mapping): raise ServerPreparationError(f"{label} must be a mapping") return value def _load_json(path: Path) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise ServerPreparationError(f"cannot read {path}: {exc}") from exc return dict(_mapping(value, str(path))) def _load_yaml(path: Path) -> dict[str, Any]: try: value = yaml.safe_load(path.read_text(encoding="utf-8")) except (OSError, yaml.YAMLError) as exc: raise ServerPreparationError(f"cannot read {path}: {exc}") from exc return dict(_mapping(value, str(path))) def _git_head(root: Path) -> str: completed = _run( ["git", "rev-parse", "HEAD"], cwd=root, capture=True, ) revision = completed.stdout.strip() if len(revision) != 40 or any(char not in "0123456789abcdef" for char in revision): raise ServerPreparationError(f"repository HEAD is not a full Git revision: {revision!r}") return revision def _verify_clean_master(root: Path, expected_commit: str) -> None: if _git_head(root) != expected_commit: raise ServerPreparationError("--code-commit differs from the current repository HEAD") branch = _run( ["git", "branch", "--show-current"], cwd=root, capture=True, ).stdout.strip() if branch != "master": raise ServerPreparationError(f"server preparation requires master, found {branch!r}") dirty = _run( ["git", "status", "--porcelain"], cwd=root, capture=True, ).stdout.strip() if dirty: raise ServerPreparationError("server preparation requires a clean Git checkout") def _layout(workspace: Path, published: Mapping[str, Any], code_commit: str) -> ServerLayout: extracted = _mapping(published["extracted_artifacts"], "extracted_artifacts") release_relative = _safe_relative_path( str(extracted["release_directory"]), label="PlotQA seed release_directory", ) return ServerLayout( root=workspace, downloads=workspace / "downloads", raw=workspace / "raw", tools=workspace / "tools", plotqa_release=workspace / "plotqa-seed" / release_relative, release=workspace / "releases" / f"evi-core-v2-{code_commit[:12]}", training_inputs=workspace / "training-inputs" / f"evi-core-v2-{code_commit[:12]}", gqa_image_cache=workspace / "cache" / "gqa-selected-images", clevr_dataset_gen=workspace / "tools" / "clevr-dataset-gen", blender_root=workspace / "tools" / "blender-2.79b", ) def _safe_relative_path(value: str, *, label: str) -> Path: path = PurePosixPath(value) if path.is_absolute() or not path.parts or any(part in {"", ".", ".."} for part in path.parts): raise ServerPreparationError(f"{label} is not a safe relative path: {value!r}") return Path(*path.parts) def _assert_workspace_outside_repo(workspace: Path, root: Path) -> None: resolved = workspace.resolve() repository = root.resolve() try: resolved.relative_to(repository) except ValueError: return raise ServerPreparationError( f"data workspace must be outside the Git checkout so data cannot be committed: {resolved}" ) def _run( command: Sequence[str], *, cwd: Path | None = None, env: Mapping[str, str] | None = None, capture: bool = False, ) -> subprocess.CompletedProcess[str]: try: completed = subprocess.run( list(command), cwd=cwd, env=dict(env) if env is not None else None, check=False, text=True, capture_output=capture, ) except OSError as exc: raise ServerPreparationError(f"cannot run {command[0]}: {exc}") from exc if completed.returncode != 0: details = (completed.stderr or completed.stdout or "").strip() if len(details) > 2000: details = details[-2000:] raise ServerPreparationError( f"command failed ({completed.returncode}): {' '.join(command)}" + (f"\n{details}" if details else "") ) return completed def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(_CHUNK_BYTES): digest.update(chunk) return digest.hexdigest() def _verify_download( path: Path, *, expected_bytes: int, expected_sha256: str, label: str, ) -> None: if not path.is_file(): raise ServerPreparationError(f"{label} is missing: {path}") actual_bytes = path.stat().st_size if actual_bytes != expected_bytes: raise ServerPreparationError( f"{label} byte count differs: {actual_bytes} != {expected_bytes}" ) actual_sha256 = _sha256(path) if actual_sha256 != expected_sha256: raise ServerPreparationError( f"{label} download checksum differs: {actual_sha256} != {expected_sha256}" ) def _download( *, url: str, destination: Path, expected_bytes: int, expected_sha256: str, label: str, ) -> Path: if destination.is_file(): _verify_download( destination, expected_bytes=expected_bytes, expected_sha256=expected_sha256, label=label, ) print(f"[prepare] reuse {label}: {destination}", file=sys.stderr, flush=True) return destination destination.parent.mkdir(parents=True, exist_ok=True) partial = destination.with_name(destination.name + ".part") request = urllib.request.Request( url, headers={"User-Agent": "explicit-learning-server-prepare/1"}, ) written = 0 next_progress = _PROGRESS_BYTES try: with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as output: while chunk := response.read(_CHUNK_BYTES): output.write(chunk) written += len(chunk) if written >= next_progress: print( f"[prepare] {label}: {written / (1024**3):.2f} GiB", file=sys.stderr, flush=True, ) next_progress += _PROGRESS_BYTES os.replace(partial, destination) except (OSError, urllib.error.URLError) as exc: partial.unlink(missing_ok=True) raise ServerPreparationError(f"cannot download {label}: {exc}") from exc _verify_download( destination, expected_bytes=expected_bytes, expected_sha256=expected_sha256, label=label, ) return destination def _download_plotqa_seed( *, published: Mapping[str, Any], destination_root: Path, ) -> Path: repository = _mapping(published["dataset_repository"], "dataset_repository") bundle = _mapping(published["bundle"], "bundle") relative = _safe_relative_path(str(bundle["path_in_repo"]), label="HF bundle path") destination_root.mkdir(parents=True, exist_ok=True) try: from huggingface_hub import hf_hub_download except ImportError as exc: raise ServerPreparationError( "huggingface-hub is required; install requirements/data.in" ) from exc try: downloaded = Path( hf_hub_download( repo_id=str(repository["repo_id"]), repo_type="dataset", filename=relative.as_posix(), revision=str(repository["revision"]), token=os.environ.get("HF_TOKEN"), local_dir=destination_root, ) ) except Exception as exc: raise ServerPreparationError(f"cannot download private PlotQA seed: {exc}") from exc _verify_download( downloaded, expected_bytes=int(bundle["bytes"]), expected_sha256=str(bundle["sha256"]), label="private PlotQA seed bundle", ) return downloaded def _write_stream_atomic(source: IO[bytes], destination: Path) -> None: destination.parent.mkdir(parents=True, exist_ok=True) partial = destination.with_name(destination.name + ".part") try: with partial.open("wb") as output: shutil.copyfileobj(source, output, length=_CHUNK_BYTES) os.replace(partial, destination) except OSError: partial.unlink(missing_ok=True) raise def _extract_zip_members( archive: Path, destination: Path, members: Mapping[str, str], ) -> None: destination.mkdir(parents=True, exist_ok=True) try: with zipfile.ZipFile(archive) as source: available = set(source.namelist()) missing = sorted(set(members) - available) if missing: raise ServerPreparationError( f"{archive.name} is missing required members: {missing}" ) for member_name, output_name in members.items(): target = destination / _safe_relative_path(output_name, label="ZIP output path") info = source.getinfo(member_name) if target.is_file() and target.stat().st_size == info.file_size: continue with source.open(info) as handle: _write_stream_atomic(handle, target) except (OSError, zipfile.BadZipFile) as exc: raise ServerPreparationError(f"cannot extract {archive}: {exc}") from exc def _extract_tar_prefix(archive: Path, destination: Path, prefix: str) -> None: safe_prefix = PurePosixPath(prefix) if safe_prefix.is_absolute() or ".." in safe_prefix.parts: raise ServerPreparationError(f"unsafe TAR prefix: {prefix!r}") found = False try: with tarfile.open(archive, mode="r:*") as source: for member in source: member_path = PurePosixPath(member.name) if member_path == safe_prefix: relative = PurePosixPath(".") else: try: relative = member_path.relative_to(safe_prefix) except ValueError: continue found = True target = destination / Path(*relative.parts) if member.isdir(): target.mkdir(parents=True, exist_ok=True) continue if not member.isfile(): raise ServerPreparationError( f"unsupported link/device in PlotQA seed archive: {member.name}" ) handle = source.extractfile(member) if handle is None: raise ServerPreparationError(f"cannot read TAR member: {member.name}") with handle: _write_stream_atomic(handle, target) except (OSError, tarfile.TarError) as exc: raise ServerPreparationError(f"cannot extract {archive}: {exc}") from exc if not found: raise ServerPreparationError(f"PlotQA seed archive has no {prefix!r} subtree") def _extract_tar_all(archive: Path, destination: Path) -> None: try: with tarfile.open(archive, mode="r:*") as source: for member in source: relative = _safe_relative_path(member.name, label="TAR member") target = destination / relative if member.isdir(): target.mkdir(parents=True, exist_ok=True) continue if not member.isfile(): raise ServerPreparationError( f"unsupported link/device in tool archive: {member.name}" ) if target.is_file() and target.stat().st_size == member.size: continue handle = source.extractfile(member) if handle is None: raise ServerPreparationError(f"cannot read TAR member: {member.name}") with handle: _write_stream_atomic(handle, target) except (OSError, tarfile.TarError) as exc: raise ServerPreparationError(f"cannot extract {archive}: {exc}") from exc def _prepare_repository( *, destination: Path, url: str, revision: str, ) -> None: if (destination / ".git").is_dir(): head = _git_head(destination) if head == revision: return _run(["git", "fetch", "--depth", "1", "origin", revision], cwd=destination) _run(["git", "checkout", "--detach", revision], cwd=destination) elif destination.exists(): raise ServerPreparationError( f"official CLEVR tool path exists but is not a Git checkout: {destination}" ) else: destination.parent.mkdir(parents=True, exist_ok=True) _run(["git", "clone", "--no-checkout", url, str(destination)]) _run(["git", "checkout", "--detach", revision], cwd=destination) if _git_head(destination) != revision: raise ServerPreparationError("official CLEVR generator did not resolve to pinned revision") def _blender_environment(runtime_library_dir: Path | None) -> dict[str, str]: environment = dict(os.environ) if runtime_library_dir is not None: current = environment.get("LD_LIBRARY_PATH") environment["LD_LIBRARY_PATH"] = ( f"{runtime_library_dir}{os.pathsep}{current}" if current else str(runtime_library_dir) ) return environment def _check_blender(executable: Path, runtime_library_dir: Path | None) -> None: if not executable.is_file(): raise ServerPreparationError(f"Blender executable is missing: {executable}") try: completed = subprocess.run( [str(executable), "--version"], env=_blender_environment(runtime_library_dir), check=False, text=True, capture_output=True, timeout=30, ) except (OSError, subprocess.TimeoutExpired) as exc: raise ServerPreparationError(f"cannot execute Blender 2.79b: {exc}") from exc if completed.returncode != 0: details = (completed.stderr or completed.stdout or "").strip()[-2000:] raise ServerPreparationError( "Blender 2.79b runtime check failed. Install libglu1-mesa or pass " f"--blender-runtime-library-dir. Details: {details}" ) def _validate_existing_training_inputs(path: Path) -> bool: manifest_path = path / "manifest.json" if not manifest_path.is_file(): return False manifest = _load_json(manifest_path) expected = { "kind": "certified_model_independent_training_inputs", "trained": False, "group_count": 12000, "view_count": 46000, "comparison_slot_count": 46000, "full_only_raw_rows": 12000, "full_plus_intervention_raw_rows": 46000, "admission_mode": "structural_no_content_hash_replay", "reasoning_vlm_calls": 0, "per_example_human_decisions": 0, } if any(manifest.get(key) != value for key, value in expected.items()): return False return all( (path / name).is_file() for name in ( "comparison-slots.jsonl", "full-only.raw.jsonl", "full-plus-intervention.raw.jsonl", ) ) def _plan( *, layout: ServerLayout, published: Mapping[str, Any], resources: Mapping[str, Any], code_commit: str, ) -> dict[str, Any]: repository = _mapping(published["dataset_repository"], "dataset_repository") gqa = _mapping(_mapping(resources["structured_sources"], "structured_sources")["gqa"], "gqa") clevr = _mapping( _mapping(resources["structured_sources"], "structured_sources")["clevr"], "clevr", ) return { "contract": "server_prepare_evi_core_v2", "code_commit": code_commit, "workspace": str(layout.root), "inputs": { "plotqa_seed": { "repo_id": repository["repo_id"], "revision": repository["revision"], "groups": 4000, }, "gqa": { "revision": gqa["revision"], "groups": 6000, }, "clevr": { "revision": clevr["revision"], "groups": 5000, "renderer": "official Blender 2.79b Cycles", }, }, "outputs": { "release": str(layout.release), "training_inputs": str(layout.training_inputs), "train_groups": 12000, "validation_groups": 2000, "certified_eval_groups": 1000, "views": 58000, "training_slots": 46000, }, "reasoning_vlm_calls": 0, "per_example_human_decisions": 0, "content_hash_replay_required": False, "hf_upload_performed": False, } def prepare_server_data(args: argparse.Namespace) -> dict[str, Any]: root = repo_root() workspace = args.workspace.resolve() _assert_workspace_outside_repo(workspace, root) resources = _load_yaml(root / "configs" / "resources.yaml") published = _load_json(root / "configs" / "published_release.json") code_commit = args.code_commit or _git_head(root) layout = _layout(workspace, published, code_commit) plan = _plan( layout=layout, published=published, resources=resources, code_commit=code_commit, ) if args.dry_run: return plan _verify_clean_master(root, code_commit) layout.root.mkdir(parents=True, exist_ok=True) structured = _mapping(resources["structured_sources"], "structured_sources") gqa = _mapping(structured["gqa"], "structured_sources.gqa") gqa_archives = _mapping(gqa["source_archives"], "gqa.source_archives") clevr = _mapping(structured["clevr"], "structured_sources.clevr") clevr_archive = _mapping(clevr["no_images_archive"], "clevr.no_images_archive") renderer = _mapping(clevr["official_renderer"], "clevr.official_renderer") repositories = _mapping(resources["repositories"], "repositories") generator = _mapping( repositories[str(renderer["repository"])], "repositories.clevr_dataset_gen", ) print("[prepare] download/extract pinned PlotQA seed", file=sys.stderr, flush=True) plotqa_archive = _download_plotqa_seed( published=published, destination_root=layout.downloads / "plotqa-seed", ) if not (layout.plotqa_release / "manifest.json").is_file(): release_prefix = str( _mapping(published["extracted_artifacts"], "extracted_artifacts")["release_directory"] ) _extract_tar_prefix( plotqa_archive, layout.plotqa_release, release_prefix, ) print("[prepare] download/extract official GQA annotations", file=sys.stderr, flush=True) gqa_question_spec = _mapping(gqa_archives["questions"], "GQA questions archive") gqa_scene_spec = _mapping(gqa_archives["scene_graphs"], "GQA scene archive") gqa_questions = _download( url=str(gqa_question_spec["url"]), destination=layout.downloads / "gqa" / str(gqa_question_spec["filename"]), expected_bytes=int(gqa_question_spec["bytes"]), expected_sha256=str(gqa_question_spec["sha256"]), label="GQA 1.2 questions", ) gqa_scenes = _download( url=str(gqa_scene_spec["url"]), destination=layout.downloads / "gqa" / str(gqa_scene_spec["filename"]), expected_bytes=int(gqa_scene_spec["bytes"]), expected_sha256=str(gqa_scene_spec["sha256"]), label="GQA 1.2 scene graphs", ) gqa_root = layout.raw / "gqa" _extract_zip_members( gqa_questions, gqa_root, { "train_balanced_questions.json": "train_balanced_questions.json", "val_balanced_questions.json": "val_balanced_questions.json", "readme.txt": "questions-readme.txt", }, ) _extract_zip_members( gqa_scenes, gqa_root, { "train_sceneGraphs.json": "train_sceneGraphs.json", "val_sceneGraphs.json": "val_sceneGraphs.json", "readme.txt": "scene-graphs-readme.txt", }, ) print("[prepare] download/extract official CLEVR annotations", file=sys.stderr, flush=True) clevr_zip = _download( url=str(clevr_archive["url"]), destination=layout.downloads / "clevr" / str(clevr_archive["filename"]), expected_bytes=int(clevr_archive["bytes"]), expected_sha256=str(clevr_archive["sha256"]), label="CLEVR v1 no-images annotations", ) clevr_root = layout.raw / "clevr" / "CLEVR_v1.0" _extract_zip_members( clevr_zip, clevr_root, { "CLEVR_v1.0/questions/CLEVR_train_questions.json": ( "questions/CLEVR_train_questions.json" ), "CLEVR_v1.0/questions/CLEVR_val_questions.json": ("questions/CLEVR_val_questions.json"), "CLEVR_v1.0/scenes/CLEVR_train_scenes.json": ("scenes/CLEVR_train_scenes.json"), "CLEVR_v1.0/scenes/CLEVR_val_scenes.json": "scenes/CLEVR_val_scenes.json", "CLEVR_v1.0/LICENSE.txt": "LICENSE.txt", }, ) print("[prepare] install pinned official CLEVR renderer", file=sys.stderr, flush=True) _prepare_repository( destination=layout.clevr_dataset_gen, url=str(generator["url"]), revision=str(generator["revision"]), ) blender_archive = _download( url=str(renderer["blender_url"]), destination=layout.downloads / "clevr" / str(renderer["blender_archive"]), expected_bytes=int(renderer["blender_archive_bytes"]), expected_sha256=str(renderer["blender_archive_sha256"]), label="Blender 2.79b Linux archive", ) blender_executable = layout.blender_root / "blender" if not blender_executable.is_file(): _extract_tar_all(blender_archive, layout.tools) runtime_library_dir = ( args.blender_runtime_library_dir.resolve() if args.blender_runtime_library_dir is not None else layout.blender_root / "lib" ) _check_blender(blender_executable, runtime_library_dir) if layout.release.exists(): _run( [ sys.executable, "-m", "explicit_learning.cli.data", "validate-evi-core-release", "--release", str(layout.release), ], cwd=root, ) print(f"[prepare] reuse validated release: {layout.release}", file=sys.stderr) else: print("[prepare] build PlotQA+GQA+CLEVR EVI core release", file=sys.stderr, flush=True) _run( [ sys.executable, "-m", "explicit_learning.cli.data", "build-evi-core-release", "--plotqa-release", str(layout.plotqa_release), "--gqa-train-questions", str(gqa_root / "train_balanced_questions.json"), "--gqa-train-scene-graphs", str(gqa_root / "train_sceneGraphs.json"), "--gqa-val-questions", str(gqa_root / "val_balanced_questions.json"), "--gqa-val-scene-graphs", str(gqa_root / "val_sceneGraphs.json"), "--gqa-image-cache", str(layout.gqa_image_cache), "--clevr-train-questions", str(clevr_root / "questions" / "CLEVR_train_questions.json"), "--clevr-train-scenes", str(clevr_root / "scenes" / "CLEVR_train_scenes.json"), "--clevr-val-questions", str(clevr_root / "questions" / "CLEVR_val_questions.json"), "--clevr-val-scenes", str(clevr_root / "scenes" / "CLEVR_val_scenes.json"), "--clevr-blender-executable", str(blender_executable), "--clevr-dataset-gen-root", str(layout.clevr_dataset_gen), "--clevr-blender-runtime-library-dir", str(runtime_library_dir), "--output", str(layout.release), "--release-config", str(root / "configs" / "release.evi-core-v2.json"), "--code-commit", code_commit, "--workers", str(args.workers), "--download-workers", str(args.download_workers), ], cwd=root, ) _run( [ sys.executable, "-m", "explicit_learning.cli.data", "validate-evi-core-release", "--release", str(layout.release), ], cwd=root, ) if layout.training_inputs.exists(): if not _validate_existing_training_inputs(layout.training_inputs): raise ServerPreparationError( f"existing training-input directory is incomplete: {layout.training_inputs}" ) print( f"[prepare] reuse validated training inputs: {layout.training_inputs}", file=sys.stderr, ) else: print("[prepare] build 46K registered training slots", file=sys.stderr, flush=True) _run( [ sys.executable, "-m", "explicit_learning.cli.train", "build-training-inputs", "--dataset", str(layout.release / "train" / "groups.jsonl"), "--asset-root", str(layout.release), "--release-manifest", str(layout.release / "manifest.json"), "--output-dir", str(layout.training_inputs), "--code-commit", code_commit, "--max-slots", "46000", "--workers", str(args.workers), ], cwd=root, ) if not _validate_existing_training_inputs(layout.training_inputs): raise ServerPreparationError("final training-input validation failed") completed = { **plan, "status": "ready_for_model_dependent_server_steps", "release_manifest": str(layout.release / "manifest.json"), "training_inputs_manifest": str(layout.training_inputs / "manifest.json"), } atomic_write_json(layout.root / "server-preparation-summary.json", completed) return completed def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="explicit-prepare", description=( "Download the PlotQA seed and official GQA/CLEVR sources, build the local " "EVI core v2 release with official Blender, and create training inputs. " "No Hugging Face upload is performed." ), ) parser.add_argument("--workspace", type=Path, required=True) parser.add_argument("--code-commit") parser.add_argument("--workers", type=int, default=8) parser.add_argument("--download-workers", type=int, default=24) parser.add_argument("--blender-runtime-library-dir", type=Path) parser.add_argument( "--dry-run", action="store_true", help="Print the immutable plan without network, files, rendering, or training.", ) return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) if args.workers < 1 or args.download_workers < 1: print("explicit-prepare: worker counts must be positive", file=sys.stderr) return 2 if args.code_commit is not None and ( len(args.code_commit) != 40 or any(char not in "0123456789abcdef" for char in args.code_commit) ): print("explicit-prepare: --code-commit must be a full lowercase 40-hex", file=sys.stderr) return 2 try: result = prepare_server_data(args) except ServerPreparationError as exc: print(f"explicit-prepare: {exc}", file=sys.stderr) return 1 print(json.dumps(result, sort_keys=True)) return 0 if __name__ == "__main__": raise SystemExit(main())