#!/usr/bin/env python3 """Check the local GmNet runtime, storage, GPU, and optional S3 access.""" from __future__ import annotations import argparse import importlib import json import os import shutil import subprocess import sys import tempfile from pathlib import Path from typing import Any REQUIRED_MODULES = ( "torch", "torchvision", "timm", "yaml", "wandb", "boto3", "webdataset", "numpy", "scipy", ) CIFAR_SOURCE = Path("/s3-code/ywang29/datasets/cifar-10/cifar-10-python.tar.gz") CIFAR_BYTES = 170_498_071 IMAGENET_BUCKET = "snap-research-cv-code" IMAGENET_KEY = "ywang29/datasets/imagenet-1k/imagenet-1k.tar" IMAGENET_BYTES = 161_381_969_920 STRICT_VERSIONS = { "torch": "2.9.0+cu130", "torchvision": "0.24.0+cu130", "timm": "1.0.27", "yaml": "6.0.3", } def _module_version(module: Any) -> str: return str(getattr(module, "__version__", "unknown")) def _run(command: list[str], timeout: int = 30) -> subprocess.CompletedProcess[str]: return subprocess.run( command, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=timeout, ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--require-cuda", action="store_true") parser.add_argument("--min-gpus", type=int, default=0) parser.add_argument("--check-s3", action="store_true") parser.add_argument("--require-imagenet-space", action="store_true") parser.add_argument("--strict-versions", action="store_true") parser.add_argument("--min-free-bytes", type=int, default=350_000_000_000) parser.add_argument("--json", action="store_true", dest="as_json") return parser.parse_args() def main() -> int: args = parse_args() report: dict[str, Any] = { "ok": True, "python": sys.version.split()[0], "executable": sys.executable, "modules": {}, "warnings": [], "errors": [], } errors: list[str] = report["errors"] warnings: list[str] = report["warnings"] if sys.version_info < (3, 10): errors.append(f"Python >=3.10 is required, found {sys.version.split()[0]}") loaded: dict[str, Any] = {} for module_name in REQUIRED_MODULES: try: module = importlib.import_module(module_name) except Exception as error: # import-time binary errors matter here errors.append(f"cannot import {module_name}: {error}") else: loaded[module_name] = module report["modules"][module_name] = _module_version(module) if args.strict_versions: if sys.version_info[:2] != (3, 12): errors.append( f"strict environment requires Python 3.12, found {sys.version.split()[0]}" ) for module_name, expected in STRICT_VERSIONS.items(): if module_name in loaded: actual = _module_version(loaded[module_name]) if actual != expected: errors.append( f"strict environment requires {module_name}=={expected}, found {actual}" ) torch = loaded.get("torch") if torch is not None: cuda_available = bool(torch.cuda.is_available()) gpu_count = int(torch.cuda.device_count()) if cuda_available else 0 report["torch_cuda"] = str(torch.version.cuda) report["cuda_available"] = cuda_available report["gpu_count"] = gpu_count report["cudnn_version"] = torch.backends.cudnn.version() if args.require_cuda and not cuda_available: errors.append("CUDA is required but torch.cuda.is_available() is false") if gpu_count < args.min_gpus: errors.append(f"at least {args.min_gpus} GPUs are required, found {gpu_count}") tmp_path = Path(os.environ.get("TMPDIR", "/tmp")) try: tmp_path.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=tmp_path, prefix="gmnet-env-", delete=True) as handle: handle.write(b"ok") handle.flush() usage = shutil.disk_usage(tmp_path) report["tmp"] = { "path": str(tmp_path.resolve()), "free_bytes": usage.free, "total_bytes": usage.total, } if args.require_imagenet_space and usage.free < args.min_free_bytes: errors.append( f"ImageNet staging needs {args.min_free_bytes} free bytes; {tmp_path} has {usage.free}" ) except OSError as error: errors.append(f"temporary directory is not writable: {tmp_path}: {error}") aws = shutil.which("aws") report["aws_cli"] = aws if args.check_s3: if aws is None: errors.append("aws CLI was not found") else: identity = _run([aws, "sts", "get-caller-identity", "--output", "json"]) if identity.returncode != 0: errors.append(f"AWS identity check failed: {identity.stderr.strip()}") else: try: identity_data = json.loads(identity.stdout) report["aws_identity"] = { "account": identity_data.get("Account"), "arn": identity_data.get("Arn"), } except json.JSONDecodeError: warnings.append("AWS identity output was not valid JSON") head = _run( [ aws, "s3api", "head-object", "--bucket", IMAGENET_BUCKET, "--key", IMAGENET_KEY, "--query", "ContentLength", "--output", "text", ] ) if head.returncode != 0: errors.append(f"ImageNet S3 head-object failed: {head.stderr.strip()}") else: try: remote_size = int(head.stdout.strip()) except ValueError: errors.append(f"invalid ImageNet ContentLength: {head.stdout.strip()!r}") else: report["imagenet_s3_bytes"] = remote_size if remote_size != IMAGENET_BYTES: errors.append( f"ImageNet archive size is {remote_size}, expected {IMAGENET_BYTES}" ) if not CIFAR_SOURCE.is_file(): errors.append(f"CIFAR-10 S3 mount object is missing: {CIFAR_SOURCE}") else: cifar_size = CIFAR_SOURCE.stat().st_size report["cifar_mount_bytes"] = cifar_size if cifar_size != CIFAR_BYTES: errors.append(f"CIFAR-10 archive size is {cifar_size}, expected {CIFAR_BYTES}") report["ok"] = not errors if args.as_json: print(json.dumps(report, indent=2, sort_keys=True)) else: print(f"Python: {report['python']} ({report['executable']})") for name, version in report["modules"].items(): print(f" {name}: {version}") if "gpu_count" in report: print( f"CUDA: available={report['cuda_available']} " f"version={report['torch_cuda']} GPUs={report['gpu_count']}" ) if "tmp" in report: print(f"Temporary storage: {report['tmp']['path']} ({report['tmp']['free_bytes']} bytes free)") for warning in warnings: print(f"WARNING: {warning}", file=sys.stderr) for error in errors: print(f"ERROR: {error}", file=sys.stderr) print("Environment check passed" if report["ok"] else "Environment check failed") return 0 if report["ok"] else 1 if __name__ == "__main__": raise SystemExit(main())