-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
81 lines (59 loc) · 1.7 KB
/
Copy pathutils.py
File metadata and controls
81 lines (59 loc) · 1.7 KB
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
# @Author : Ruopeng Gao
# @Date : 2022/7/5
# @Description : Some utils.
import os
import random
import yaml
import torch
import torch.distributed
import random
import numpy as np
def set_seed(seed: int):
seed = seed + distributed_rank() # 用于避免每张卡的随机结果是一样的
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
return
def is_distributed():
if not (torch.distributed.is_available() and torch.distributed.is_initialized()):
return False
return True
def distributed_rank():
if not is_distributed():
return 0
else:
return torch.distributed.get_rank()
def is_main_process():
return distributed_rank() == 0
def distributed_world_size():
if is_distributed():
return torch.distributed.get_world_size()
else:
return 1
# raise RuntimeError("'world size' is not available when distributed mode is not started.")
def yaml_to_dict(path: str):
"""
Read a yaml file into a dict.
Args:
path (str): The path of yaml file.
Returns:
A dict.
"""
with open(path) as f:
return yaml.load(f.read(), yaml.FullLoader)
def labels_to_one_hot(labels: np.ndarray, class_num: int):
"""
Args:
labels: Original labels.
class_num:
Returns:
Labels in one-hot.
"""
return np.eye(N=class_num)[labels].reshape((len(labels), -1))
# return np.eye(N=class_num)[labels]
if __name__ == '__main__':
config = yaml_to_dict("../configs/resnet18_mnist.yaml")