|
1 | 1 | """Wrap GPU, MLU etc |
2 | 2 | """ |
| 3 | +import contextlib |
3 | 4 | from datetime import timedelta |
4 | 5 | import functools |
5 | 6 | import logging |
6 | 7 | from typing import Optional |
7 | 8 |
|
8 | 9 | import torch |
9 | 10 |
|
10 | | -from profold2.utils import default, env |
| 11 | +from profold2.utils import default, env, version_cmp |
11 | 12 |
|
12 | 13 |
|
13 | 14 | def device_count(): |
14 | 15 | return torch.cuda.device_count() |
15 | 16 |
|
| 17 | + |
16 | 18 | def device_type(): |
17 | 19 | if torch.cuda.is_available(): |
18 | 20 | return 'cuda' |
19 | 21 | return 'cpu' |
20 | 22 |
|
| 23 | + |
21 | 24 | def world_size(nnodes: Optional[int] = None): |
22 | 25 | return env('WORLD_SIZE', defval=device_count() * default(nnodes, 1), dtype=int) |
23 | 26 |
|
| 27 | + |
24 | 28 | autocast = functools.partial(torch.amp.autocast, device_type()) |
25 | 29 | GradScaler = functools.partial(torch.amp.GradScaler, device_type()) |
26 | 30 |
|
| 31 | + |
| 32 | +@contextlib.contextmanager |
| 33 | +def amp(enabled: bool = True): |
| 34 | + if enabled: |
| 35 | + dtype = torch.float16 |
| 36 | + if hasattr(torch.cuda, 'is_bf16_supported'): |
| 37 | + if torch.cuda.is_bf16_supported(): |
| 38 | + dtype = torch.bfloat16 |
| 39 | + ctx = functools.partial(autocast, dtype=dtype) |
| 40 | + # FIXED ME: cache_enabled=True will crash :( |
| 41 | + if version_cmp(torch.__version__, '1.10.0') >= 0: |
| 42 | + ctx = functools.partial(ctx, cache_enabled=False) |
| 43 | + with ctx(): |
| 44 | + yield |
| 45 | + else: |
| 46 | + yield |
| 47 | + |
| 48 | + |
27 | 49 | class XPU(object): |
28 | 50 | """Wrap distibuted XPU(GPU,MLU etc) |
29 | 51 | """ |
@@ -51,9 +73,7 @@ def device(self): |
51 | 73 | @property |
52 | 74 | def rank(self): |
53 | 75 | return env( |
54 | | - 'RANK', |
55 | | - defval=device_count() * self.node_rank + self.local_rank, |
56 | | - dtype=int |
| 76 | + 'RANK', defval=device_count() * self.node_rank + self.local_rank, dtype=int |
57 | 77 | ) |
58 | 78 |
|
59 | 79 | def memory_summary(self): |
|
0 commit comments