from __future__ import annotations import json import random from pathlib import Path from typing import Any import numpy as np def seed_everything(seed: int) -> None: random.seed(seed) np.random.seed(seed) try: import torch torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = True except Exception: pass def ensure_dir(path: str | Path) -> Path: path = Path(path) path.mkdir(parents=True, exist_ok=True) return path def write_json(obj: dict[str, Any], path: str | Path) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as f: json.dump(obj, f, indent=2) def count_parameters(model: Any) -> int: return sum(p.numel() for p in model.parameters() if p.requires_grad) def get_device(name: str): import torch if name.startswith("cuda") and torch.cuda.is_available(): return torch.device(name) return torch.device("cpu")