|
|
"""Utility functions for torch devices.""" |
|
|
|
|
|
import torch |
|
|
from src.utils.logging_util import LoggingUtils |
|
|
|
|
|
logger = LoggingUtils.configure_logger(log_name=__name__) |
|
|
|
|
|
|
|
|
|
|
|
def get_device(device_str: str): |
|
|
"""Set device for pytorch operations.""" |
|
|
|
|
|
logger.info(f"PyTorch version: {torch.__version__}") |
|
|
|
|
|
if "cuda" in device_str and torch.cuda.is_available(): |
|
|
logger.info(f"GPU: {torch.cuda.get_device_name(0)}") |
|
|
device= torch.device(device_str) |
|
|
else: |
|
|
logger.warning("CUDA not available, resorting to CPU.") |
|
|
device= torch.device("cpu") |
|
|
|
|
|
logger.info(f"Device: {device}") |
|
|
return device |
|
|
|
|
|
|
|
|
|
|
|
def set_all_seed(seed: int = 42, deterministic: bool = True): |
|
|
"""Set random seed for reproducibility.""" |
|
|
|
|
|
import os |
|
|
import random |
|
|
import numpy as np |
|
|
import torch |
|
|
|
|
|
if seed == -1: |
|
|
logger.warning("Set seed disabled.") |
|
|
else: |
|
|
|
|
|
random.seed(seed) |
|
|
os.environ['PYTHONHASHSEED'] = str(seed) |
|
|
|
|
|
|
|
|
np.random.seed(seed) |
|
|
|
|
|
|
|
|
torch.manual_seed(seed) |
|
|
if torch.cuda.is_available(): |
|
|
torch.cuda.manual_seed(seed) |
|
|
torch.cuda.manual_seed_all(seed) |
|
|
|
|
|
|
|
|
if deterministic: |
|
|
torch.backends.cudnn.deterministic = True |
|
|
torch.backends.cudnn.benchmark = False |
|
|
|
|
|
|
|
|
def recursively_to_device_float(obj, to_device="cpu"): |
|
|
""" |
|
|
Recursively traverse any data structure and convert all torch tensors |
|
|
to float and optionally move to CPU. |
|
|
|
|
|
Args: |
|
|
obj: nested structure (tensor, dict, list, etc.) |
|
|
to_cpu (bool): whether to move tensors to CPU |
|
|
""" |
|
|
if isinstance(to_device, str): |
|
|
device = torch.device(to_device) |
|
|
elif isinstance(to_device, torch.device): |
|
|
device = to_device |
|
|
else: |
|
|
raise ValueError(to_device) |
|
|
|
|
|
if isinstance(obj, torch.Tensor): |
|
|
return obj.float().to(device) |
|
|
elif isinstance(obj, dict): |
|
|
return {k: recursively_to_device_float(v, to_device) for k, v in obj.items()} |
|
|
elif isinstance(obj, list): |
|
|
return [recursively_to_device_float(v, to_device) for v in obj] |
|
|
elif isinstance(obj, tuple): |
|
|
return tuple(recursively_to_device_float(v, to_device) for v in obj) |
|
|
elif isinstance(obj, set): |
|
|
return {recursively_to_device_float(v, to_device) for v in obj} |
|
|
else: |
|
|
return obj |