-
Notifications
You must be signed in to change notification settings - Fork 8
/
main_pwl.py
399 lines (312 loc) · 11.9 KB
/
main_pwl.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#!/usr/bin/env python3
import numpy as np
import tqdm
from simple_einet.dist import DataType, Domain
from simple_einet.layers.distributions.piecewise_linear import PiecewiseLinear
from simple_einet.layers.distributions.normal import Normal
from torch.distributions import Binomial
import matplotlib.pyplot as plt
import torch
from simple_einet.einet import Einet, EinetConfig
BINS = 100
def make_dataset(num_features_continuous, num_features_discrete, num_clusters, num_samples):
# Collect data and data domains
data = []
domains = []
# Construct continuous features
for i in range(num_features_continuous):
domains.append(Domain.continuous_inf_support())
feat_i = []
# if i == 3:
# breakpoint()
# Create a multimodal feature
for j in range(num_clusters):
feat_i.append(torch.randn(num_samples) * 1.0 + j * 3 * torch.randint(low=1, high=10, size=(1,))/10 + 5 * j - num_clusters * 2.5)
data.append(torch.cat(feat_i))
# Construct discrete features
for i in range(num_features_discrete):
domains.append(Domain.discrete_range(0, BINS))
feat_i = []
# Create a multimodal feature
for j in range(num_clusters):
feat_i.append(Binomial(total_count=BINS, probs=torch.rand(1)).sample((num_samples,)).view(-1))
data.append(torch.cat(feat_i))
data = torch.stack(data, dim=1)
data = data.view(data.shape[0], 1, num_features_continuous + num_features_discrete)
data = data[torch.randperm(data.shape[0])]
return data, domains
# if __name__ == "__main__":
# torch.manual_seed(0)
# ###################
# # Hyperparameters #
# ###################
# epochs = 3
# batch_size = 128
# depth = 2
# num_sums = 20
# num_leaves = 10
# num_repetitions = 10
# lr = 0.01
# num_features = 4
# ###############
# # Einet Setup #
# ###############
# config = EinetConfig(
# num_features=num_features,
# num_channels=1,
# depth=depth,
# num_sums=num_sums,
# num_leaves=num_leaves,
# num_repetitions=num_repetitions,
# num_classes=1,
# leaf_type=PiecewiseLinear,
# layer_type="einsum",
# dropout=0.0,
# )
# model = Einet(config)
# print(model)
# print("Number of parameters:", sum(p.numel() for p in model.parameters() if p.requires_grad))
# ##############
# # Data Setup #
# ##############
# # Simulate data
# data, domains = make_dataset(
# num_features_continuous=num_features // 2,
# num_features_discrete=num_features // 2,
# num_clusters=4,
# num_samples=1000,
# )
# ########################################
# # PiecewiseLinear Layer Initialization #
# ########################################
# model.leaf.base_leaf.initialize(data, domains=domains)
# # Init. first linsum layer weights to be the log of the mixture weights from the kmeans result in the PWL init phase
# model.layers[0].logits.data[:] = (
# model.leaf.base_leaf.mixture_weights.permute(1, 0).view(1, config.num_leaves, 1, config.num_repetitions).log()
# )
# ################
# # Optimization #
# ################
# # Optimize Einet parameters (weights and leaf params)
# optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[int(epochs * 0.5), int(epochs * 0.75)], gamma=0.1, verbose=True)
# model.train()
# for epoch in range(1, epochs + 1):
# # Since we don't have a train dataloader, we will loop over the data manually
# iter = range(0, len(data), batch_size)
# pbar = tqdm.tqdm(iter, desc="Train Epoch: {}".format(epoch))
# for batch_idx in pbar:
# optimizer.zero_grad()
# # Select batch
# data_batch = data[batch_idx : batch_idx + batch_size]
# # Generate outputs
# outputs = model(data_batch, cache_index=batch_idx)
# # Compute loss
# loss = -1 * outputs.mean()
# # Compute gradients
# loss.backward()
# # Update weights
# optimizer.step()
# # Logging
# if batch_idx % 10 == 0:
# pbar.set_description(
# "Train Epoch: {} [{}/{}] Loss: {:.2f}".format(
# epoch,
# batch_idx,
# len(data),
# loss.item(),
# )
# )
# scheduler.step()
# model.eval()
# #################
# # Visualization #
# #################
# # Generate samples
# samples = model.sample(10000)
# # Plot results
# fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10))
# for i, ax in enumerate([ax1, ax2, ax3, ax4]):
# # Get data subset
# if domains[i].data_type == DataType.DISCRETE:
# rng = (0, BINS + 1)
# bins = BINS + 1
# width = 1
# else:
# rng = None
# bins = 100
# width = (samples[:, :, i].max() - samples[:, :, i].min()) / bins
# # Plot histogram of data
# hist = torch.histogram(samples[:, :, i], bins=bins, density=True, range=rng)
# bin_edges = hist.bin_edges
# density = hist.hist
# if domains[i].data_type == DataType.DISCRETE:
# bin_edges -= 0.5
# # Center bars on value (e.g. bar for value 0 should have its center at value 0)
# bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
# ax.bar(bin_centers, density, width=width * 0.8, alpha=0.5, label="Samples")
# if domains[i].data_type == DataType.DISCRETE:
# rng = (0, BINS + 1)
# bins = BINS + 1
# width = 1
# else:
# rng = None
# bins = 100
# width = (data[:, :, i].max() - data[:, :, i].min()) / bins
# # Plot histogram of data
# hist = torch.histogram(data[:, :, i], bins=bins, density=True, range=rng)
# bin_edges = hist.bin_edges
# density = hist.hist
# if domains[i].data_type == DataType.DISCRETE:
# bin_edges -= 0.5
# # Center bars on value (e.g. bar for value 0 should have its center at value 0)
# bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
# ax.bar(bin_centers, density, width=width * 0.8, alpha=0.5, label="Data")
# # Plot PWL logprobs
# dummy = torch.full((bin_centers.shape[0], data.shape[1], data.shape[2]), np.nan)
# dummy[:, 0, i] = bin_centers
# with torch.no_grad():
# log_probs = model(dummy)
# probs = log_probs.exp().squeeze(-1).numpy()
# ax.plot(bin_centers, probs, linewidth=2, label="PWL Density")
# # MPE
# mpe = model.mpe()
# dummy = torch.full((mpe.shape[0], data.shape[1], data.shape[2]), np.nan)
# dummy[:, 0, i] = mpe[:, 0, i]
# with torch.no_grad():
# mpe_prob = model(dummy).exp().detach()
# ax.plot(mpe.squeeze()[i], mpe_prob.squeeze(), "rx", markersize=13, label="PWL MPE")
# ax.set_xlabel("Feature Value")
# ax.set_ylabel("Density")
# ax.set_title(f"Feature {i} ({str(domains[i].data_type)})")
# ax.legend()
# plt.tight_layout()
# plt.savefig(f"/tmp/pwl.png", dpi=300)
# # Conditional sampling example
# data_subset = data[:10]
# data[:, :, :2] = np.nan
# samples_cond = model.sample(evidence=data_subset)
# # Conditional MPE example
# mpe_cond = model.mpe(evidence=data_subset)
if __name__ == "__main__":
torch.manual_seed(0)
###################
# Hyperparameters #
###################
epochs = 5
batch_size = 200
depth = 2
num_sums = 10
num_leaves = 10
num_repetitions = 10
lr = 0.5
num_features = 4
###############
# Einet Setup #
###############
config = EinetConfig(
num_features=num_features,
num_channels=1,
depth=depth,
num_sums=num_sums,
num_leaves=num_leaves,
num_repetitions=num_repetitions,
num_classes=1,
leaf_type=Normal,
layer_type="einsum",
dropout=0.0,
)
model = Einet(config)
print(model)
print("Number of parameters:", sum(p.numel() for p in model.parameters() if p.requires_grad))
for name, ch in model.named_children():
print("Number of parameters:", name, sum(p.numel() for p in ch.parameters() if p.requires_grad))
##############
# Data Setup #
##############
# Simulate data
data, domains = make_dataset(
num_features_continuous=num_features,
num_features_discrete=0,
num_clusters=4,
num_samples=5000,
)
################
# Optimization #
################
# Optimize Einet parameters (weights and leaf params)
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer, milestones=[int(epochs * 0.8), int(epochs * 0.9)], gamma=0.5, verbose=True
)
model.train()
for epoch in range(1, epochs + 1):
# Since we don't have a train dataloader, we will loop over the data manually
iter = range(0, len(data), batch_size)
pbar = tqdm.tqdm(iter, desc="Train Epoch: {}".format(epoch))
for batch_idx in pbar:
optimizer.zero_grad()
# Select batch
data_batch = data[batch_idx : batch_idx + batch_size]
# Generate outputs
outputs = model(data_batch)
# Compute loss
loss = -1 * outputs.mean()
# Compute gradients
loss.backward()
# Update weights
optimizer.step()
# Logging
if batch_idx % 10 == 0:
pbar.set_description(
"Train Epoch: {} [{}/{}] Loss: {:.2f}".format(
epoch,
batch_idx,
len(data),
loss.item(),
)
)
scheduler.step()
model.eval()
#################
# Visualization #
#################
# # Generate samples
# samples = model.sample(10000)
# Plot results
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10))
for i, ax in enumerate([ax1, ax2, ax3, ax4]):
# Get data subset
rng = None
bins = 100
# width = (samples[:, :, i].max() - samples[:, :, i].min()) / bins
if domains[i].data_type == DataType.DISCRETE:
rng = (0, BINS + 1)
bins = BINS + 1
width = 1
else:
rng = None
bins = 100
width = (data[:, :, i].max() - data[:, :, i].min()) / bins
# Plot histogram of data
hist = torch.histogram(data[:, :, i], bins=bins, density=True, range=rng)
bin_edges = hist.bin_edges
density = hist.hist
if domains[i].data_type == DataType.DISCRETE:
bin_edges -= 0.5
# Center bars on value (e.g. bar for value 0 should have its center at value 0)
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
ax.bar(bin_centers, density, width=width * 0.8, alpha=0.5, label="Data")
# Plot PWL logprobs
dummy = torch.full((bin_centers.shape[0], data.shape[1], data.shape[2]), np.nan)
dummy[:, 0, i] = bin_centers
with torch.no_grad():
log_probs = model(dummy)
probs = log_probs.exp().squeeze(-1).numpy()
ax.plot(bin_centers, probs, linewidth=2, label="Density")
ax.set_xlabel("Feature Value")
ax.set_ylabel("Density")
ax.set_title(f"Feature {i} ({str(domains[i].data_type)})")
ax.legend()
plt.tight_layout()
plt.savefig(f"/tmp/pwl.png", dpi=300)