forked from apple/ml-cvnets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon_utils.py
128 lines (100 loc) · 3.49 KB
/
common_utils.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import random
import torch
import numpy as np
import os
from typing import Union, Dict, Optional, Tuple
from torch import Tensor
from sys import platform
from utils import logger
from utils.ddp_utils import is_master
from cvnets.layers import norm_layers_tuple
def check_compatibility():
ver = torch.__version__.split(".")
major_version = int(ver[0])
minor_version = int(ver[0])
if major_version < 1 and minor_version < 7:
logger.error(
"Min pytorch version required is 1.7.0. Got: {}".format(".".join(ver))
)
def check_frozen_norm_layer(model: torch.nn.Module) -> (bool, int):
if hasattr(model, "module"):
model = model.module
count_norm = 0
frozen_state = False
for m in model.modules():
if isinstance(m, norm_layers_tuple):
frozen_state = m.weight.requires_grad
return frozen_state, count_norm
def device_setup(opts):
random_seed = getattr(opts, "common.seed", 0)
random.seed(random_seed)
torch.manual_seed(random_seed)
np.random.seed(random_seed)
is_master_node = is_master(opts)
if is_master_node:
logger.log("Random seeds are set to {}".format(random_seed))
logger.log("Using PyTorch version {}".format(torch.__version__))
n_gpus = torch.cuda.device_count()
if n_gpus == 0:
if is_master_node:
logger.warning("No GPUs available. Using CPU")
device = torch.device("cpu")
n_gpus = 0
else:
if is_master_node:
logger.log("Available GPUs: {}".format(n_gpus))
device = torch.device("cuda")
if torch.backends.cudnn.is_available():
import torch.backends.cudnn as cudnn
torch.backends.cudnn.enabled = True
cudnn.benchmark = False
cudnn.deterministic = True
if is_master_node:
logger.log("CUDNN is enabled")
setattr(opts, "dev.device", device)
setattr(opts, "dev.num_gpus", n_gpus)
return opts
def create_directories(dir_path: str, is_master_node: bool) -> None:
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
if is_master_node:
logger.log("Directory created at: {}".format(dir_path))
else:
if is_master_node:
logger.log("Directory exists at: {}".format(dir_path))
def move_to_device(
opts,
x: Union[Dict, Tensor],
device: Optional[str] = "cpu",
non_blocking: Optional[bool] = True,
*args,
**kwargs
) -> Union[Dict, Tensor]:
# if getattr(opts, "dataset.decode_data_on_gpu", False):
# # data is already on GPU
# return x
if isinstance(x, Dict):
# return the tensor because if its already on device
if "on_gpu" in x and x["on_gpu"]:
return x
for k, v in x.items():
if isinstance(v, Dict):
x[k] = move_to_device(opts=opts, x=v, device=device)
elif isinstance(v, Tensor):
x[k] = v.to(device=device, non_blocking=non_blocking)
elif isinstance(x, Tensor):
x = x.to(device=device, non_blocking=non_blocking)
else:
logger.error(
"Inputs of type Tensor or Dict of Tensors are only supported right now"
)
return x
def is_coreml_conversion(opts) -> bool:
coreml_convert = getattr(opts, "common.enable_coreml_compatible_module", False)
if coreml_convert:
return True
return False