File size: 1,097 Bytes
c388140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")