"""Common helpers: config loading with ${var} interpolation, seeding, IO.""" from __future__ import annotations import json import os import random import re from pathlib import Path from typing import Any, Dict import numpy as np import torch import yaml _INTERP_RE = re.compile(r"\$\{([^}]+)\}") def _resolve(value: Any, root: Dict[str, Any]) -> Any: if isinstance(value, str): prev = None while prev != value and "${" in value: prev = value def repl(m: re.Match) -> str: key = m.group(1) node: Any = root for part in key.split("."): node = node[part] return str(node) value = _INTERP_RE.sub(repl, value) return value if isinstance(value, dict): return {k: _resolve(v, root) for k, v in value.items()} if isinstance(value, list): return [_resolve(v, root) for v in value] return value def load_config(path: str | Path) -> Dict[str, Any]: # encoding is explicit: several configs carry an em-dash in their header # comment, and open() defaults to the locale encoding, which is ASCII here. # Without this, deberta_toxigen/newsgroups/yelp fail at byte 29 with a # UnicodeDecodeError that names the YAML reader rather than the file. with open(path, "r", encoding="utf-8") as f: cfg = yaml.safe_load(f) cfg = _resolve(cfg, cfg) return cfg 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 ensure_dir(path: str | Path) -> Path: p = Path(path) p.mkdir(parents=True, exist_ok=True) return p def save_json(obj: Any, path: str | Path) -> None: with open(path, "w") as f: json.dump(obj, f, indent=2, default=str) def load_json(path: str | Path) -> Any: with open(path, "r") as f: return json.load(f) def device_from_cfg(cfg: Dict[str, Any]) -> torch.device: requested = cfg.get("inference", {}).get("device", "cuda") if requested == "cuda" and not torch.cuda.is_available(): return torch.device("cpu") return torch.device(requested)