-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.pdbrc.py
More file actions
148 lines (110 loc) · 3.76 KB
/
Copy path.pdbrc.py
File metadata and controls
148 lines (110 loc) · 3.76 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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
try:
import torch
use_torch = True
except ImportError:
import numpy as np
use_torch = False
import hashlib
def hw(tensor):
if use_torch:
torch.save(tensor, "/tmp/hw")
else:
raise NotImplementedError("Only PyTorch tensors are supported")
def ref(tensor):
if use_torch:
torch.save(tensor, "/tmp/ref")
else:
raise NotImplementedError("Only PyTorch tensors are supported")
def compare(hw_path="/tmp/hw", ref_path="/tmp/ref"):
if not use_torch:
raise NotImplementedError("Only PyTorch tensors are supported")
device = "cuda" if torch.cuda.is_available() else "cpu"
hw = torch.load(f"{hw_path}", map_location="cpu").to(device)
ref = torch.load(f"{ref_path}", map_location="cpu").to(device)
print()
print(f"{hw.device=}")
print(f"{ref.device=}")
print()
print(f"{hw.dtype=}")
print(f"{ref.dtype=}")
print()
print(f"{hw.shape=}")
print(f"{ref.shape=}")
print()
abs_diff = torch.abs(hw - ref)
max_diff = torch.max(abs_diff).item()
median_diff = torch.median(abs_diff).item()
# Calculate relative errors, avoiding division by zeroj
with torch.no_grad():
nonzero_mask = ref != 0
relative_error = torch.zeros_like(ref)
relative_error[nonzero_mask] = abs_diff[nonzero_mask] / torch.abs(
ref[nonzero_mask]
)
median_relative_error = (
torch.median(relative_error[nonzero_mask]).item()
if torch.any(nonzero_mask)
else float("inf")
)
mean_relative_error = (
torch.mean(relative_error[nonzero_mask]).item()
if torch.any(nonzero_mask)
else float("inf")
)
print(f"{median_relative_error=}")
print(f"{mean_relative_error=}")
print(f"{max_diff=}")
print(f"{median_diff=}")
def get_ref(ref_path="/tmp/ref"):
if not use_torch:
raise NotImplementedError("Only PyTorch tensors are supported")
ref = torch.load(ref_path)
return ref
def get_hw(hw_path="/tmp/hw"):
if not use_torch:
raise NotImplementedError("Only PyTorch tensors are supported")
hw = torch.load(hw_path)
return hw
def tree_map(fn, tree):
"""
Recursively apply fn to every leaf node in 'tree'.
A 'leaf node' is anything that isn't list, tuple, or dict.
"""
if isinstance(tree, (list, tuple)):
return type(tree)(tree_map(fn, x) for x in tree)
elif isinstance(tree, dict):
return {k: tree_map(fn, v) for k, v in tree.items()}
else:
return fn(tree)
def hw_in_ref(hw_path="/tmp/hw", ref_path="/tmp/ref"):
if not use_torch:
raise NotImplementedError("Only PyTorch tensors are supported")
hw = torch.load(hw_path)
ref = torch.load(ref_path)
def convert_to_tensor(x):
if isinstance(x, torch.Tensor):
return x
elif isinstance(x, np.ndarray):
return torch.from_numpy(x)
elif isinstance(x, list):
return torch.tensor(x)
elif isinstance(x, torch.distributed.tensor.DTensor):
return x.to_local()
else:
raise ValueError(f"Unsupported type: {type(x)}")
hw = tree_map(convert_to_tensor, hw)
ref = tree_map(convert_to_tensor, ref)
hw_is_subset = torch.isin(hw, ref).all().item()
print(f"{hw_is_subset=}")
def pdb_replicate(tensor):
ndim = len(tensor.device_mesh.mesh_dim_names)
return tensor.redistribute(
placements=[torch.distributed.tensor.placement_types.Replicate()] * ndim
)
def pdb_hash(x):
if use_torch:
data = x.cpu().to(dtype=torch.float32).numpy()
else:
# Assume input is already a NumPy array
data = x.astype(np.float32)
print(hashlib.sha256(data.tobytes()).hexdigest())