from __future__ import annotations import json import math import os import random import time import uuid from pathlib import Path from typing import Any import numpy as np import torch import yaml def load_config(path: str | Path) -> dict[str, Any]: with Path(path).open("r", encoding="utf-8") as handle: return yaml.safe_load(handle) def save_json(data: Any, path: str | Path) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(data, handle, indent=2, sort_keys=True) def load_json(path: str | Path) -> Any: with Path(path).open("r", encoding="utf-8") as handle: return json.load(handle) def resolve_manifest_path( value: str | Path, *, asset_root: str | Path | None = None, manifest: str | Path | None = None, ) -> Path: """Resolve a manifest path without requiring the caller's working directory.""" path = Path(value).expanduser() if path.is_absolute(): return path.resolve() if asset_root is not None and str(asset_root).strip(): return (Path(asset_root).expanduser() / path).resolve() if manifest is not None: return (Path(manifest).expanduser().resolve().parent / path).resolve() raise ValueError( f"Cannot resolve relative path {value!s}: no asset_root or manifest was supplied" ) def seed_everything(seed: int) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) def select_device(requested: str = "cuda") -> torch.device: requested = requested.lower() if requested == "cuda": if not torch.cuda.is_available(): raise RuntimeError( "CUDA is the default device but no CUDA GPU is available. Check the PyTorch " "CUDA build, NVIDIA driver, and GPU passthrough. Use --device cpu only for an " "intentional CPU run." ) return torch.device("cuda") if requested == "auto": if torch.cuda.is_available(): return torch.device("cuda") if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): return torch.device("mps") return torch.device("cpu") if requested == "mps": if not getattr(torch.backends, "mps", None) or not torch.backends.mps.is_available(): raise RuntimeError("MPS was requested but is unavailable") return torch.device("mps") return torch.device(requested) def autocast_context(device: torch.device): if device.type == "cuda": dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 return torch.amp.autocast("cuda", dtype=dtype) return torch.amp.autocast(device.type, enabled=False) def grad_scaler_enabled(device: torch.device) -> bool: return device.type == "cuda" and not torch.cuda.is_bf16_supported() def configure_torch_runtime(device: torch.device) -> None: torch.set_float32_matmul_precision("high") if device.type == "cuda": torch.backends.cudnn.benchmark = True torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True def cosine_warmup_multiplier(step: int, total_steps: int, warmup_steps: int) -> float: if warmup_steps > 0 and step < warmup_steps: return float(step + 1) / float(warmup_steps) if total_steps <= warmup_steps: return 1.0 progress = (step - warmup_steps) / max(1, total_steps - warmup_steps) return 0.5 * (1.0 + math.cos(math.pi * min(max(progress, 0.0), 1.0))) def atomic_torch_save(payload: dict[str, Any], path: str | Path) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) # A fixed ``.tmp`` name is vulnerable to stale files and Windows scanners # briefly opening either the source or destination. Use a unique sibling # and retry atomic replacement while transient handles are released. temporary = path.with_name( f"{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp" ) torch.save(payload, temporary) attempts = 12 for attempt in range(attempts): try: os.replace(temporary, path) return except PermissionError: if attempt + 1 == attempts: try: temporary.unlink(missing_ok=True) except OSError: pass raise time.sleep(min(0.05 * (2**attempt), 1.0)) class RunningMoments: def __init__(self) -> None: self.count = 0 self.total = 0.0 self.total_sq = 0.0 self.minimum = float("inf") self.maximum = float("-inf") def update(self, values: np.ndarray | float) -> None: array = np.asarray(values, dtype=np.float64) finite = array[np.isfinite(array)] if finite.size == 0: return self.count += int(finite.size) self.total += float(finite.sum()) self.total_sq += float(np.square(finite).sum()) self.minimum = min(self.minimum, float(finite.min())) self.maximum = max(self.maximum, float(finite.max())) def as_dict(self) -> dict[str, float | int]: if self.count == 0: return {"count": 0, "mean": 0.0, "std": 1.0, "min": 0.0, "max": 0.0} mean = self.total / self.count variance = max(self.total_sq / self.count - mean * mean, 1e-12) return { "count": self.count, "mean": mean, "std": math.sqrt(variance), "min": self.minimum, "max": self.maximum, }