clsa-code / src /clsa /util.py
fahadhafeezofficial's picture
Upload folder using huggingface_hub
fd5366a verified
Raw History Blame Contribute Delete
7.67 kB
# 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)