File size: 2,254 Bytes
2eb3475 | 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 | """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)
|