from __future__ import annotations import os import random from typing import Optional import torch def seed_everything(seed: int, deterministic: bool = False) -> None: """ 统一设置随机种子,便于复现实验。 注意:deterministic=True 可能会降低性能。 """ os.environ["PYTHONHASHSEED"] = str(seed) random.seed(seed) torch.manual_seed(seed) # 重要:CPU 推理/CPU 环境下不要触发 CUDA 初始化,避免无谓开销或在无 CUDA 编译时报错。 if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) if deterministic: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False else: torch.backends.cudnn.benchmark = True def get_device(device: Optional[str] = None) -> torch.device: """ 返回训练设备。默认优先 CUDA,其次 CPU。 """ if device is not None: return torch.device(device) return torch.device("cuda" if torch.cuda.is_available() else "cpu")