Newer
Older
TongueSegModel / src / tongue_seg_model / training / device.py
"""計算装置の決定(設定の `train.device`.SPEC_02「設定項目」).

`resolve_device` は GPU の有無を引数で受け取る純関数,`select_device` はそれに今の環境の
GPU の状態を渡す縁の関数である.
"""

from __future__ import annotations

import torch


def resolve_device(spec: str, *, cuda_available: bool, cuda_device_count: int) -> str:
    """設定の計算装置の指定を,実際に使う装置の名前にする.

    原本は `cuda if torch.cuda.is_available() else cpu`(設定の `auto` と同じ).

    Args:
        spec: 設定の `train.device`(`auto`・`cpu`・`cuda`・`cuda:N`.形はスキーマで検証済み).
        cuda_available: GPU を使えるか(`torch.cuda.is_available()`).
        cuda_device_count: 使える GPU の数(`torch.cuda.device_count()`).

    Returns:
        `cpu`・`cuda`・`cuda:N` のいずれか.

    Raises:
        ValueError: GPU を指定したのに使えない,または番号が GPU の数以上の場合.
    """
    if spec == "auto":
        return "cuda" if cuda_available else "cpu"
    if spec == "cpu":
        return "cpu"
    if not cuda_available:
        raise ValueError(
            f"設定 train.device が {spec} だが GPU を使えない(CPU で回すなら cpu か auto にする)"
        )
    if spec.startswith("cuda:"):
        index = int(spec.removeprefix("cuda:"))
        if index >= cuda_device_count:
            raise ValueError(
                f"設定 train.device の GPU の番号 {index} が使える GPU の数 "
                f"{cuda_device_count} 以上である"
            )
    return spec


def select_device(spec: str) -> torch.device:
    """今の環境で,設定の指定に合う計算装置を返す.

    Args:
        spec: 設定の `train.device`.

    Returns:
        使う計算装置.

    Raises:
        ValueError: 指定の GPU を使えない場合(`resolve_device`).
    """
    available = torch.cuda.is_available()
    count = torch.cuda.device_count() if available else 0
    return torch.device(resolve_device(spec, cuda_available=available, cuda_device_count=count))