forked from zalandoresearch/SWARM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraces.py
198 lines (157 loc) · 6.75 KB
/
traces.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
import matplotlib.pyplot as plt
import os
import numpy as np
import time
from itertools import chain
class Trace(object):
def __init__(self, model, n, sample_fn, batches_per_epoch=None, name='traces', batch_thinout=1,
epoch_thinout=1, columns=2):
self.model = model
self.n = n
self.traces = {}
self.sample_fn = sample_fn
self.name = name
self.batch_thinout = batch_thinout
self.epoch_thinout = epoch_thinout
self.columns = columns
self.batches_per_epoch = batches_per_epoch
self.metrics_names = set()
self.weight_names = [name for name, _ in chain(self.model.named_parameters(), self.model.named_buffers())]
super(Trace, self).__init__()
def on_epoch_begin(self, epoch, logs=None):
self.epoch = epoch
def on_epoch_end(self, epoch, logs=None):
self.batches_per_epoch = self.batches_per_epoch or self.last_batch
self.add_metrics_to_traces(self.batches_per_epoch, logs)
if epoch % self.epoch_thinout == 0:
self.plot_all()
def plot_all(self, use_MPLD3=False):
for plot_fn, descr in [(self.plot_all_items, 'weights'),
(self.plot_all_metrics, 'metrics'),
(self.plot_all_samples, 'samples')
]:
try:
fig = plot_fn(self.batches_per_epoch)
filename = self.name + '/' + descr + ('.html' if use_MPLD3 else '.png')
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
if use_MPLD3:
with open(filename, 'w') as file:
mpld3.save_html(fig, file)
else:
plt.savefig(filename)
plt.close(fig)
except TypeError: # in particular catch missing sample_fn
pass
def on_batch_end(self, batch, logs=None):
self.last_batch = batch
def some_weights(w, n):
sz = w.size
if sz > n:
return w.flatten()[np.round(np.linspace(0, sz - 1, n)).astype(np.int)]
else:
return w.flatten()
if batch % self.batch_thinout == 0:
for name, w in chain(self.model.named_parameters(), self.model.named_buffers()):
# w = w.detach().cpu().numpy()
w = w.data.cpu().numpy()
# w = np.random.randn(100,200)
v = some_weights(w, self.n)
item = self.traces.setdefault(name, {'values': [], 'batch': [], 'epoch': []})
item['values'].append(v)
item['batch'].append(batch)
item['epoch'].append(self.epoch)
self.add_metrics_to_traces(batch, logs)
def add_metrics_to_traces(self, batch, logs):
logs = logs or {}
for name, v in logs.items():
item = self.traces.setdefault(name, {'values': [], 'batch': [], 'epoch': []})
item['values'].append(v)
item['batch'].append(batch)
item['epoch'].append(self.epoch)
self.metrics_names = self.metrics_names.union(
{k.replace('val_', '') for k, v in logs.items() if k.startswith('val_')})
self.metrics_names = self.metrics_names.union(
{k for k, v in logs.items() if not k.startswith('val_') and k is not 'size' and k is not 'batch'})
def plot_item(self, ax, item, batches_per_epoch):
x = np.array(item['batch'], dtype='double') / batches_per_epoch + np.array(item['epoch'])
y = np.stack(item['values'])
ylim = np.percentile(y, [2.5, 97.5])
ylim = [ylim[0] - 0.1 / 0.95 * (ylim[1] - ylim[0]), ylim[1] + 0.1 / 0.95 * (ylim[1] - ylim[0])]
if ax.lines:
ylim_ = ax.get_ylim()
ylim = [min(ylim[0], ylim_[0]), max(ylim[1], ylim_[1])]
if x.shape[0] < 1000:
_ = ax.plot(x, y, '-')
ax.set_ylim(*ylim)
else:
i = np.round(np.linspace(0, x.shape[0] - 1, 1000)).astype(np.int32)
_ = ax.plot(x[i], y[i], '-')
ax.set_ylim(*ylim)
def plot_all_items(self, batches_per_epoch):
M = self.columns
N = len(self.weight_names) // M + 1
fig = plt.figure(figsize=(6 * M, 4 * N))
fig.clf()
fig.subplots(nrows=N, ncols=M)
# for i,(name,item) in enumerate(sorted(self.traces.iteritems())):
for i, name in enumerate(sorted(self.weight_names)):
try:
item = self.traces[name]
ax = plt.subplot(N, M, i + 1)
self.plot_item(ax, item, batches_per_epoch)
plt.title(name)
except:
pass
ax = plt.axes([0, 0.9, 1.0, 0.1], frameon=False)
# ax.axis('off')
ax.grid(False)
# ax.set_axis_off()
# ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.5, 0.5, self.name + ' \nweight traces \n' + time.strftime("%c"), ha='center', fontsize=24)
return fig
def plot_all_metrics(self, batches_per_epoch):
M = 2
N = (len(self.metrics_names) + 1) // M
fig = plt.figure(figsize=(6 * M, 4 * N))
fig.clf()
fig.subplots(nrows=N, ncols=M)
# for i,(name,item) in enumerate(sorted(self.traces.iteritems())):
for i, name in enumerate(sorted(self.metrics_names)):
for name_ in [name, 'val_' + name]:
try:
item = self.traces[name_]
ax = plt.subplot(N, M, i + 1)
self.plot_item(ax, item, batches_per_epoch)
ax.grid(True)
# ax.set_xscale('log')
except:
pass
plt.title(name)
ax = plt.axes([0, 0.9, 1.0, 0.1], frameon=False)
# ax.axis('off')
ax.grid(False)
ax.set_xscale('log')
# ax.set_axis_off()
# ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.5, 0.5, self.name + ' \nmetrics \n' + time.strftime("%c"), ha='center', fontsize=24)
return fig
def plot_all_samples(self, batches_per_epoch):
fig = self.sample_fn()
ax = plt.axes([0, 0.9, 1.0, 0.1], frameon=False)
# ax.axis('off')
ax.grid(False)
# ax.set_axis_off()
# ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.5, 0.5, self.name + ' \nsamples \n' + time.strftime("%c"), ha='center', fontsize=24)
return fig