File size: 6,274 Bytes
8c587c9
 
 
 
 
 
 
 
 
 
6c4c2ba
8c587c9
6c4c2ba
8c587c9
 
 
6c4c2ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c587c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c4c2ba
8c587c9
 
 
 
 
 
 
 
 
 
 
 
 
 
6c4c2ba
8c587c9
 
 
6c4c2ba
 
8c587c9
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verify the frozen release, Python environment, driver and BF16 GPU execution."""
import argparse
import hashlib
import importlib.metadata
import importlib.util
import json
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import tempfile
import tomllib


def check_host() -> dict[str, object]:
    """Check the documented libc, native NVIDIA driver and host compiler prerequisites."""
    libc, version = platform.libc_ver()
    if libc != "glibc" or tuple(int(x) for x in version.split(".")[:2]) < (2, 31):
        raise ValueError(f"Expected glibc >= 2.31, found {libc} {version}")
    cxx = shutil.which(os.environ.get("CXX", "c++"))
    if cxx is None:
        raise ValueError("A host C++ compiler is required; install g++ or set CXX to its executable")
    drivers = subprocess.run(["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"],
                             capture_output=True, text=True, timeout=15, check=True).stdout.splitlines()
    if not drivers or any(int(driver.strip().split(".")[0]) < 580 for driver in drivers):
        raise ValueError("This release requires a native NVIDIA R580 or newer driver for CUDA 13.0")
    cxx_version = subprocess.run([cxx, "--version"], capture_output=True, text=True,
                                 timeout=15, check=True).stdout.splitlines()[0]
    return {"glibc": version, "host_cxx": cxx, "host_cxx_version": cxx_version,
            "driver_versions": sorted(set(drivers))}


def check_cuda_compile(cxx: str, capability: tuple[int, int]) -> None:
    """Compile a tiny CUDA kernel for the selected GPU; this is not a model-kernel test."""
    with tempfile.TemporaryDirectory(prefix="flyai-cuda-check-") as temporary:
        root = Path(temporary)
        source = root / "probe.cu"
        source.write_text('#include <cuda_runtime.h>\n__global__ void probe(float *x) { x[0] = 1.0f; }\n')
        command = [str(Path(os.environ["CUDA_HOME"]) / "bin/nvcc"), "-std=c++17", "-ccbin", cxx,
                   f"-arch=sm_{capability[0]}{capability[1]}", "-c", str(source), "-o", str(root / "probe.o")]
        result = subprocess.run(command, capture_output=True, text=True, timeout=120)
        if result.returncode:
            raise RuntimeError(f"CUDA/host compiler probe failed:\n{result.stderr[-4000:]}")


def main() -> None:
    """Fail before model loading when the release or installed environment differs."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    root = Path(__file__).resolve().parent
    if (platform.system(), platform.machine(), platform.python_version()) != ("Linux", "x86_64", "3.12.12"):
        raise ValueError("Expected Linux x86_64 and managed CPython 3.12.12")
    lock = tomllib.loads((root / "uv.lock").read_text())
    locked = {}
    for package in lock["package"]:
        locked.setdefault(package["name"], set()).add(package["version"])
    packages = {}
    for distribution in importlib.metadata.distributions():
        name = re.sub(r"[-_.]+", "-", distribution.metadata["Name"]).lower()
        version = distribution.version
        if version not in locked.get(name, set()):
            raise ValueError(f"Installed package differs from uv.lock: {name}=={version}")
        packages[name] = version
    for name in ("vllm", "torch", "transformers", "decision-index"):
        if name not in packages:
            raise ValueError(f"Missing required package: {name}")
    manifest_path = root / "source-manifest.json"
    manifest = json.loads(manifest_path.read_text())
    official = Path(importlib.util.find_spec("decision_index").origin).parent
    for name, expected in manifest.items():
        if hashlib.sha256((root / name).read_bytes()).hexdigest() != expected:
            raise ValueError(f"Release source changed: {name}")
        prefix = "official/decision_index/"
        if name.startswith(prefix):
            installed = official / name[len(prefix):]
            if hashlib.sha256(installed.read_bytes()).hexdigest() != expected:
                raise ValueError(f"Installed official evaluator differs from release: {name}")
    host = check_host()
    import torch

    if torch.cuda.device_count() != 1 or torch.version.cuda != "13.0" or torch.version.hip is not None:
        raise ValueError("Expected one visible NVIDIA GPU with the CUDA 13.0 PyTorch runtime")
    torch.manual_seed(20261023)
    values = torch.randn((32, 32), device="cuda", dtype=torch.bfloat16)
    result = values @ values.T
    if not torch.isfinite(result).all().item():
        raise ValueError("BF16 GPU matrix multiplication failed")
    torch.cuda.synchronize()
    compiler = subprocess.run([str(Path(os.environ["CUDA_HOME"]) / "bin/nvcc"), "--version"],
                              capture_output=True, text=True, timeout=15, check=True).stdout
    if "release 13.0," not in compiler:
        raise ValueError("Expected the locked CUDA 13.0 compiler for upstream JIT paths")
    check_cuda_compile(host["host_cxx"], torch.cuda.get_device_capability(0))
    report = {"python": platform.python_version(), "platform": platform.platform(), "packages": packages,
              "cuda": torch.version.cuda, "gpu": torch.cuda.get_device_name(0),
              "gpu_memory_bytes": torch.cuda.get_device_properties(0).total_memory,
              "gpu_capability": torch.cuda.get_device_capability(0), **host,
              "cuda_compile_probe_passed": True,
              "dependencies_and_sources_verified": True, "bf16_matmul_passed": True,
              "cuda_compiler": "13.0", "cuda_home": os.environ["CUDA_HOME"],
              "release_manifest_sha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
              "dependency_lock_sha256": hashlib.sha256((root / "uv.lock").read_bytes()).hexdigest()}
    if args.output:
        args.output.mkdir(parents=True, exist_ok=True)
        (args.output / "software-environment.json").write_text(json.dumps(report, indent=2) + "\n")
    print(json.dumps({"stage": "release_environment_verified", "packages": len(packages),
                      "gpu": report["gpu"], "python": report["python"], "bf16_matmul_passed": True}), flush=True)


if __name__ == "__main__":
    main()