-
Notifications
You must be signed in to change notification settings - Fork 0
/
weight_hist.py
executable file
·268 lines (227 loc) · 8.03 KB
/
weight_hist.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import torch
import plotly.graph_objects as go
import numpy as np
from torch import nn
from torch.nn import init
from scipy.stats import pearsonr
from torchvision.models.resnet import BasicBlock
from copy import deepcopy
benford = np.array([30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6]) / 100
benford_th = torch.FloatTensor(benford)
def non_bias(m, include_bn=False):
if include_bn:
if (
isinstance(m, nn.Linear)
or isinstance(m, nn.Conv2d)
or isinstance(m, nn.BatchNorm2d)
):
return m.weight
return None
else:
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
return m.weight
return None
def benford_r2(bin_percent):
return pearsonr(benford, bin_percent[1:])[0]
def bincount(tensor):
if isinstance(tensor, torch.Tensor):
ndim = len(tensor.shape)
if ndim == 2:
counts = torch.zeros((tensor.shape[0], 10))
for i in range(10):
counts[:, i] = torch.count_nonzero(tensor == i, dim=1)
return counts
counts = torch.zeros(10)
for i in range(10):
counts[i] = torch.count_nonzero(tensor == i)
return counts
ndim = len(tensor.shape)
if ndim == 2:
counts = np.zeros(size=(tensor.shape[0], 10))
for i in range(10):
counts[:, i] = np.count_nonzero(tensor == i, axis=1)
return counts
counts = np.zeros(10)
for i in range(10):
counts[i] = np.count_nonzero(tensor == i)
return counts
@torch.no_grad()
def bin_percent(tensor):
tensor = tensor.abs() * 1e10
tensor = tensor // 10 ** torch.log10(tensor).long()
tensor = bincount(tensor.numpy().astype("int64"))
return tensor / tensor.sum()
def block_bincount(net, include_bn=False):
bins = []
num_params = []
total_num_params = 0
for m in net.modules():
# Check if leaf module
if list(m.children()) == []:
weight = non_bias(m, include_bn=include_bn)
if weight is not None:
n_param = weight.numel()
num_params.append(n_param)
total_num_params += n_param
bins.append(bin_percent(weight.view(-1).detach()))
out = torch.zeros(10)
for b, n_param in zip(bins, num_params):
out += (b) * (n_param / total_num_params)
return out
def benford_r2_model(model, include_bn=False):
bins = block_bincount(deepcopy(model).cpu(), include_bn=include_bn)
return benford_r2(bins)
# def init_params(net, bias=False, kind="normal"):
# """Init layer parameters."""
# if kind == "normal":
# kaiming = init.kaiming_normal_
# xavier = init.normal_
# else:
# kaiming = init.kaiming_uniform_
# xavier = init.uniform_
# if bias:
# for m in net.modules():
# if isinstance(m, nn.Conv2d):
# kaiming(m.weight, mode="fan_out")
# if m.bias is not None:
# xavier(m.bias, std=1e-3)
# elif isinstance(m, nn.BatchNorm2d):
# xavier(m.weight, std=1e-3)
# xavier(m.bias, std=1e-3)
# elif isinstance(m, nn.Linear):
# kaiming(m.weight, mode="fan_out")
# if m.bias is not None:
# xavier(m.bias, std=1e-3)
# else:
# for m in net.modules():
# if isinstance(m, nn.Conv2d):
# kaiming(m.weight, mode="fan_out")
# if m.bias is not None:
# init.constant_(m.bias, 0)
# elif isinstance(m, nn.BatchNorm2d):
# init.constant_(m.weight, 1)
# init.constant_(m.bias, 0)
# elif isinstance(m, nn.Linear):
# init.normal_(m.weight, std=1e-3)
# if m.bias is not None:
# init.constant_(m.bias, 0)
arg_to_init_fn = {
'kaiming_uniform_': init.kaiming_uniform_,
'kaiming_normal_': init.kaiming_normal_,
'xavier_uniform_': init.xavier_uniform_,
'xavier_normal_': init.xavier_normal_,
'orthogonal_': init.orthogonal_,
'normal_': init.normal_,
'uniform_': init.uniform_
}
def init_params(net, initializer, bias=False):
'''Init layer parameters.'''
init_fn = arg_to_init_fn(initializer)
for m in net.modules():
if isinstance(m, nn.Conv2d):
init_fn(m.weight, mode='fan_out')
if m.bias is not None:
init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
init_fn(m.weight, std=1e-3)
if m.bias is not None:
init.constant_(m.bias, 0)
def get_params(m, include_bias=False):
"""Init layer parameters."""
defs = []
init_weights = []
bias = 0
if isinstance(m, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
defs.append(m.weight.shape)
init_weights.append(m.weight.detach().numpy().reshape(-1))
if m.bias is not None and include_bias:
bias = 1
defs.append(m.bias.shape)
return defs, bias, init_weights
def plot(bin_percent, title=None):
fig = go.Figure(
data=[
go.Bar(x=np.arange(10)[1:], y=bin_percent[1:], name="Weights"),
go.Scatter(x=np.arange(10)[1:], y=benford, name="Benford's Law"),
]
)
fig.update_layout(title=title)
fig.show()
def plot_model_bar(untrained, trained, title, exclude_fc=False, fc_only=False):
if fc_only:
p = trained.fc.weight.view(-1).detach()
bins_tr = bin_percent(p)
p = untrained.fc.weight.view(-1).detach()
bins_utr = bin_percent(p)
else:
p = deepcopy(trained)
if exclude_fc:
p.fc = None
bins_tr = block_bincount(p)
p = deepcopy(untrained)
if exclude_fc:
p.fc = None
bins_utr = block_bincount(p)
fig = go.Figure(
data=[
go.Bar(x=np.arange(10)[1:], y=bins_tr[1:], name="Trained"),
go.Bar(x=np.arange(10)[1:], y=bins_utr[1:], name="Random"),
go.Scatter(x=np.arange(10)[1:], y=benford, name="Benford's Law"),
]
)
fig.update_layout(title=title, barmode="group")
print(" " * 21 + "Pearson's R v/s Benford's Law")
print("{:20}".format("Random"), round(benford_r2(bins_utr), 4))
print("{:20}".format("Trained"), round(benford_r2(bins_tr), 4))
fig.show()
def plot_model_layerwise(untrained, trained, title, x, y, size, color, family, layer_names=None):
scores1, scores2 = [], []
flag = 0
if layer_names is None:
layer_names = []
flag = 1
i = 1
for m1, m2 in zip(trained.children(), untrained.children()):
if sum(p.numel() for p in m1.parameters()) == 0 or isinstance(
m1, nn.BatchNorm2d
):
continue
score1, score2 = benford_r2(block_bincount(m1)), benford_r2(block_bincount(m2))
scores1.append(score1)
scores2.append(score2)
if flag:
layer_names.append(f"Block{i}")
i += 1
if flag:
layer_names[-1] = "FC"
fig = go.Figure(
data=[
go.Scatter(x=layer_names, y=scores1, name="Trained"),
go.Scatter(x=layer_names, y=scores2, name="Random"),
]
)
fig.update_layout(legend=dict(
yanchor="bottom",
y=0.01,
xanchor="left",
x=0.01
))
fig.update_layout(title=title, xaxis=dict(title=x),
yaxis=dict(title=y), barmode="group", font=dict(
family=family,
size=size,
color=color
))
fig.show()
if __name__ == "__main__":
layer1 = torch.nn.Sequential(torch.nn.Linear(784, 10), torch.nn.Linear(784, 10))
layer2 = torch.nn.Sequential(torch.nn.Linear(784, 10), torch.nn.Linear(784, 10))
# f = bin_percent(layer.weight.view(-1))
# print(f)
# print(f.shape)
# plot(f, 'dummy title')
# plot_model_bar(layer1, layer2, 'mlp')
plot_model_layerwise(layer1, layer2, "layerwise")