File size: 1,000 Bytes
4e316d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Device auto-detection utility.

Selects the best available compute device in priority order:
CUDA (NVIDIA GPU) > MPS (Apple Silicon) > CPU.
Provides a single entry point so model and tensor placement
is consistent across the codebase.
"""

import torch

def get_default_device(force_cpu: bool = False):
    """
    Automatically selects the best available device.
    Priority: CUDA > MPS (Apple Silicon) > CPU
    
    Args:
        force_cpu: If True, forces CPU usage (useful for debugging).
    """
    if force_cpu:
        return torch.device("cpu")

    if torch.cuda.is_available():
        return torch.device("cuda")
    elif torch.backends.mps.is_available():
        return torch.device("mps")
    else:
        return torch.device("cpu")

def move_to_device(model, device=None):
    """
    Helper to move model to device and print status.
    """
    if device is None:
        device = get_default_device()
        
    model.to(device)
    print(f"🚀 Model moved to: {device}")