File size: 7,672 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Shared utilities: seeding, provenance, results writing, config loading.

Every results file written through :func:`write_result` carries its seed, git
commit, config hash and hardware description, so that no number in the paper is
untraceable.
"""
from __future__ import annotations

import hashlib
import json
import os
import platform
import random
import socket
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable

ROOT = Path(__file__).resolve().parents[2]
SRC = ROOT / "src"
CONFIGS = ROOT / "configs"
RESULTS = ROOT / "results"
DATA = ROOT / "data"
FIGURES = ROOT / "figures"
LOGS = ROOT / "logs"

for _p in (RESULTS, LOGS, FIGURES):
    _p.mkdir(parents=True, exist_ok=True)


# --------------------------------------------------------------------------- #
# Determinism
# --------------------------------------------------------------------------- #
def set_threads(n: int | None = None) -> int:
    """Limit CPU threads so the host machine stays responsive.

    Default comes from configs/compute.yaml guard rails, overridable with the
    CLSA_THREADS environment variable.
    """
    if n is None:
        n = int(os.environ.get("CLSA_THREADS", "4"))
    n = max(1, int(n))
    os.environ.setdefault("OMP_NUM_THREADS", str(n))
    os.environ.setdefault("MKL_NUM_THREADS", str(n))
    try:
        import torch

        torch.set_num_threads(n)
        torch.set_num_interop_threads(1)
    except Exception:  # pragma: no cover - torch always present in this repo
        pass
    return n


def seed_everything(seed: int = 0) -> int:
    seed = int(seed)
    random.seed(seed)
    os.environ["PYTHONHASHSEED"] = str(seed)
    try:
        import numpy as np

        np.random.seed(seed)
    except Exception:  # pragma: no cover
        pass
    try:
        import torch

        torch.manual_seed(seed)
    except Exception:  # pragma: no cover
        pass
    return seed


# --------------------------------------------------------------------------- #
# Hashing and provenance
# --------------------------------------------------------------------------- #
def sha256_json(obj: Any) -> str:
    """Stable sha256 over a JSON-serialisable object."""
    payload = json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def sha256_file(path: str | Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def utc_now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def git_commit() -> str:
    try:
        out = subprocess.run(
            ["git", "rev-parse", "HEAD"],
            cwd=str(ROOT),
            capture_output=True,
            text=True,
            timeout=10,
        )
        if out.returncode == 0:
            return out.stdout.strip()
    except Exception:
        pass
    return "unknown"


def hardware_info() -> dict:
    info = {
        "hostname": socket.gethostname(),
        "platform": platform.platform(),
        "machine": platform.machine(),
        "processor": platform.processor() or "unknown",
        "python": sys.version.split()[0],
    }
    try:
        import psutil

        info["ram_gb"] = round(psutil.virtual_memory().total / (1024**3), 2)
        info["cpu_logical"] = psutil.cpu_count(logical=True)
        info["cpu_physical"] = psutil.cpu_count(logical=False)
        info["disk_free_gb"] = round(psutil.disk_usage(str(ROOT)).free / (1024**3), 2)
    except Exception:  # pragma: no cover
        pass
    try:
        import torch

        info["torch"] = torch.__version__
        info["cuda_available"] = bool(torch.cuda.is_available())
        info["gpu"] = (
            torch.cuda.get_device_name(0) if torch.cuda.is_available() else "none"
        )
    except Exception:  # pragma: no cover
        pass
    return info


# --------------------------------------------------------------------------- #
# Config and results IO
# --------------------------------------------------------------------------- #
def load_config(path_or_name: str | Path) -> dict:
    """Load a YAML config from configs/ (by name) or by explicit path."""
    import yaml

    p = Path(path_or_name)
    if not p.suffix:
        p = CONFIGS / f"{p}.yaml"
    elif not p.is_absolute() and not p.exists():
        p = CONFIGS / p.name
    with open(p, "r", encoding="utf-8") as fh:
        cfg = yaml.safe_load(fh) or {}
    cfg["_config_path"] = str(p.relative_to(ROOT)) if p.is_relative_to(ROOT) else str(p)
    cfg["_config_hash"] = sha256_file(p)
    return cfg


def write_result(
    name: str,
    payload: dict,
    config: dict | None = None,
    seed: int | None = None,
    notes: str = "",
) -> Path:
    """Write a results JSON with full provenance. Never hand-edit results."""
    RESULTS.mkdir(parents=True, exist_ok=True)
    record = {
        "run": name,
        "created_utc": utc_now(),
        "git_commit": git_commit(),
        "seed": seed,
        "config_path": (config or {}).get("_config_path"),
        "config_hash": (config or {}).get("_config_hash"),
        "hardware": hardware_info(),
        "notes": notes,
        "results": payload,
    }
    path = RESULTS / f"{name}.json"
    atomic_write_json(path, record)
    return path


def atomic_write_json(path: str | Path, obj: Any) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(obj, fh, indent=2, sort_keys=True, default=str)
    os.replace(tmp, path)


def read_json(path: str | Path) -> Any:
    with open(path, "r", encoding="utf-8") as fh:
        return json.load(fh)


def read_jsonl(path: str | Path) -> list[dict]:
    rows = []
    with open(path, "r", encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def write_jsonl(path: str | Path, rows: Iterable[dict]) -> int:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    n = 0
    with open(path, "w", encoding="utf-8") as fh:
        for row in rows:
            fh.write(json.dumps(row, sort_keys=True))
            fh.write("\n")
            n += 1
    return n


# --------------------------------------------------------------------------- #
# Cost accounting
# --------------------------------------------------------------------------- #
def compute_cost_usd(
    tokens: float, latency_ms: float, cfg: dict | None = None
) -> float:
    """Reference compute cost in USD for a local open-weight model.

    The marginal API price of a local model is zero. To make cost comparisons
    meaningful we charge a documented *reference* rate for electricity plus
    hardware amortisation, taken from configs/controller.yaml (cost_model).
    This is a reference rate, not a market price, and is charged for every
    component: monitor, simulation, verification and the allocator itself.
    """
    cm = (cfg or {}).get("cost_model", {}) or {}
    usd_per_1k_tokens = float(cm.get("usd_per_1k_tokens", 0.0006))
    usd_per_hour = float(cm.get("usd_per_gpu_hour", 0.0)) or float(
        cm.get("usd_per_cpu_hour", 0.02)
    )
    token_cost = tokens / 1000.0 * usd_per_1k_tokens
    time_cost = (latency_ms / 3_600_000.0) * usd_per_hour
    return float(token_cost + time_cost)