File size: 2,472 Bytes
452723c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""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:
        # Python built‑ins
        random.seed(seed)
        os.environ['PYTHONHASHSEED'] = str(seed)
        
        # NumPy
        np.random.seed(seed)
        
        # PyTorch (CPU & CUDA)
        torch.manual_seed(seed)
        if torch.cuda.is_available():
            torch.cuda.manual_seed(seed)
            torch.cuda.manual_seed_all(seed)  # multiple GPUs
    
    # CuDNN backends
    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