|
1 | 1 | # some convenient methods for all models |
2 | 2 | import numpy as np |
3 | 3 | import regex as re |
| 4 | +import torch |
4 | 5 |
|
5 | 6 | # seed is fixed for reproducibility |
6 | 7 | from numpy.random import seed |
7 | 8 |
|
8 | 9 | seed(7) |
9 | 10 | import argparse |
| 11 | +import os |
10 | 12 | import os.path |
11 | 13 | import shutil |
12 | 14 | from urllib.parse import urlparse |
|
16 | 18 | from tqdm import tqdm |
17 | 19 |
|
18 | 20 |
|
| 21 | +def best_device() -> torch.device: |
| 22 | + """ |
| 23 | + Pick the best available compute device: CUDA → MPS (Apple Silicon) → CPU. |
| 24 | +
|
| 25 | + When MPS is selected, transparently enables CPU fallback for ops that don't |
| 26 | + have MPS kernels yet, so unsupported ops degrade gracefully instead of |
| 27 | + raising NotImplementedError mid-training. |
| 28 | + """ |
| 29 | + if torch.cuda.is_available(): |
| 30 | + return torch.device("cuda") |
| 31 | + if torch.backends.mps.is_available(): |
| 32 | + os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1") |
| 33 | + return torch.device("mps") |
| 34 | + return torch.device("cpu") |
| 35 | + |
| 36 | + |
| 37 | +def pick_device(device=None) -> torch.device: |
| 38 | + """ |
| 39 | + Resolve a device (auto-pick when device=None, else honor the caller's choice) |
| 40 | + and print a one-line summary so the user can see which compute is in use. |
| 41 | + """ |
| 42 | + if device is None: |
| 43 | + d = best_device() |
| 44 | + elif isinstance(device, torch.device): |
| 45 | + d = device |
| 46 | + else: |
| 47 | + d = torch.device(device) |
| 48 | + |
| 49 | + if d.type == "cuda": |
| 50 | + n = torch.cuda.device_count() |
| 51 | + name = torch.cuda.get_device_name(d) |
| 52 | + plural = "" if n == 1 else "s" |
| 53 | + print(f"Running on {d} ({name}); {n} CUDA device{plural} available") |
| 54 | + elif d.type == "mps": |
| 55 | + print(f"Running on {d} (Apple Silicon GPU via Metal Performance Shaders)") |
| 56 | + else: |
| 57 | + print(f"Running on {d}") |
| 58 | + return d |
| 59 | + |
| 60 | + |
19 | 61 | def truncate_batch_values(batch_values: list, max_sequence_length: int) -> list: |
20 | 62 | return [row[:max_sequence_length] for row in batch_values] |
21 | 63 |
|
|
0 commit comments