File size: 4,033 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Content-addressed snapshot and admission for the installed GPU environment."""

from __future__ import annotations

import importlib
import importlib.metadata
import json
import platform
import re
import sys
from pathlib import Path
from typing import Any

from ..atomic_io import atomic_write_json

_NORMALIZE_NAME = re.compile(r"[-_.]+")


def _name(value: str) -> str:
    return _NORMALIZE_NAME.sub("-", value).lower()


def installed_distributions() -> dict[str, str]:
    """Return every installed distribution as a canonical name/version map."""

    values: dict[str, str] = {}
    for distribution in importlib.metadata.distributions():
        raw_name = distribution.metadata.get("Name")
        if not raw_name:
            continue
        name = _name(str(raw_name))
        version = str(distribution.version)
        previous = values.get(name)
        if previous is not None and previous != version:
            raise RuntimeError(f"multiple installed versions for {name}: {previous}, {version}")
        values[name] = version
    return dict(sorted(values.items()))


def current_environment_snapshot() -> dict[str, Any]:
    """Capture Python, every wheel version, torch/CUDA, and visible GPU facts."""

    torch_record: dict[str, Any] | None = None
    try:
        torch = importlib.import_module("torch")
    except ImportError:
        torch = None
    if torch is not None:
        cuda = torch.cuda
        devices = []
        if bool(cuda.is_available()):
            for index in range(int(cuda.device_count())):
                properties = cuda.get_device_properties(index)
                devices.append(
                    {
                        "index": index,
                        "name": str(properties.name),
                        "capability": list(cuda.get_device_capability(index)),
                        "total_memory": int(properties.total_memory),
                    }
                )
        cudnn = getattr(torch.backends, "cudnn", None)
        torch_record = {
            "version": str(torch.__version__),
            "compiled_cuda": str(torch.version.cuda),
            "cudnn_version": int(cudnn.version())
            if cudnn is not None and cudnn.version() is not None
            else None,
            "cuda_available": bool(cuda.is_available()),
            "devices": devices,
        }
    return {
        "schema_version": 1,
        "kind": "training_environment_lock",
        "python": {
            "version": platform.python_version(),
            "implementation": platform.python_implementation(),
            "executable": str(Path(sys.executable).resolve()),
        },
        "platform": platform.platform(),
        "distributions": installed_distributions(),
        "torch": torch_record,
    }


def write_environment_snapshot(path: str | Path) -> dict[str, Any]:
    destination = Path(path)
    if destination.exists():
        raise FileExistsError(f"refusing to overwrite environment lock: {destination}")
    snapshot = current_environment_snapshot()
    atomic_write_json(destination, snapshot)
    return snapshot


def environment_lock_errors(path: str | Path) -> list[str]:
    """Compare the current process against an immutable environment snapshot."""

    source = Path(path)
    try:
        expected = json.loads(source.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        return [f"cannot read training environment lock: {exc}"]
    if not isinstance(expected, dict) or expected.get("schema_version") != 1:
        return ["training environment lock must use schema_version=1"]
    if expected.get("kind") != "training_environment_lock":
        return ["environment lock has the wrong kind"]
    actual = current_environment_snapshot()
    errors: list[str] = []
    for field in ("python", "platform", "distributions", "torch"):
        if expected.get(field) != actual.get(field):
            errors.append(f"installed environment differs from lock field {field}")
    return errors