-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_module.py
473 lines (426 loc) · 17.1 KB
/
test_module.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
from pathlib import Path
import copy
import time
import torch.optim as optim
import numpy as np
import torch
from torch.autograd import Variable
from model import *
from data_utils import *
import torch.nn as nn
from loguru import logger
feature_dim = 8
block_size = 16
pad=2
n_conv=3
thresh=0.5
debug = False
def test_bottom_io():
tsdf = [torch.from_numpy(np.random.rand(1, 1, block_size+2*pad+2*n_conv,
block_size+2*pad+2*n_conv,
block_size+2*pad+2*n_conv)).float().to(device)]
prev = {(0, 0, 0): torch.from_numpy(np.random.rand(1, feature_dim,
block_size//2+2*pad, block_size//2+2*pad, block_size//2+2*pad)
).float().to(device)}
mod = BottomLevel(feature_dim, block_size=block_size)
if device == 'cuda':
mod.cuda()
out = mod(tsdf, prev)
assert type(out) == list
assert len(out) == 1
out = out[0]
assert len(out) == 1
for X in out.keys():
assert out[X].shape == (1, 2, block_size, block_size, block_size), out[X].shape
def test_convtrans():
conv1 = nn.ConvTranspose3d(10, 10, kernel_size=4, stride=2, output_padding=0, padding=0, bias=False)
dat = torch.ones(1, 10, block_size, block_size, block_size)
y = conv1(dat)
assert y.shape[-1] == block_size*2+2 , (y.shape, dat.shape)
pad = nn.ReplicationPad3d(1)
conv1 = nn.ConvTranspose3d(1, 1, kernel_size=3, stride=2,
output_padding=1, padding=1, bias=False)
dat = Variable(torch.ones(1, 1, 4, 4, 4))
y = conv1(dat)
assert y.shape[-1] == 8, y.shape
def test_data():
data = TsdfGenerator(64)
vis = visdom.Visdom()
gt, tsdf_in = data.__getitem__(0)
assert np.abs(tsdf_in).max() < 33
def test_ellipsoid():
arr = ellipsoid(10, 10, 10, levelset=True)*10 # the output is ~normalized. multiple by 10
assert arr.shape == (23, 23, 23), arr.shape
dist = np.sqrt(11**2*3)-10
assert np.abs(arr[0, 0, 0]) > dist, (arr[0, 0, 0], dist)
print(arr[0, 0, 0], dist)
a, b, c = 10, 15, 25
arr = ellipsoid(a, b, c, levelset=True)
# if we move 1 voxel in space the sdf should also not change by more than 1
# compare to 1.01 for numeric reasons
assert np.all(np.abs(np.diff(arr, axis=0)) <= 1.01), np.abs(np.diff(arr, axis=0)).max()
assert np.all(np.abs(np.diff(arr, axis=1)) <= 1.01)
assert np.all(np.abs(np.diff(arr, axis=2)) <= 1.01)
def test_criteria_trivial():
data = TsdfGenerator(block_size, sigma=0.)
gt, tsdf_in = data.__getitem_split__()
gt = gt[None, :] # add dim for batch
assert np.abs(tsdf_in).max() < 33
gt_label = np.zeros_like(gt)
gt_label[gt >= 0] = 1
gt_label = torch.from_numpy(gt_label.astype(int))
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
assert len(criteria.gt_octree) == 1
mock_out = np.concatenate((tsdf_in[None,:]<0, tsdf_in[None,:]>=0),
axis=1).astype(float)
mock_out=1000*(mock_out-0.5)
mock_out = [{(0,0,0):torch.from_numpy(mock_out).float()}]
loss = criteria(mock_out)
assert loss.dim()==0
assert loss < 0.01, loss
def test_gt():
pass
#get gt,
#get gt_octree
#retnder gt
#render gt_octree
def test_criteria(levels=2):
res=2**(levels-1)*block_size
data = TsdfGenerator(res, sigma=0.9)
gt, tsdf_in = data.__getitem_split__()
gt = gt[None, :] # add dim for batch
assert np.abs(tsdf_in).max() < res
#labels should be symetric
def count_label(gt, label, level=1):
gt_label = np.zeros_like(gt)
gt_label[gt >= 0] = 1
gt_label = torch.from_numpy(gt_label.astype(int))
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
gt=criteria.gt_octree[level]
return np.count_nonzero(np.array(list(gt.values()))==label)
n_outside = count_label(gt, OUTSIDE)
n_inside = count_label(gt, INSIDE)
n_mixed = count_label(gt, MIXED)
assert n_outside+n_inside+n_mixed==(2**(levels-2))**3
rev_inside = count_label(-gt, OUTSIDE)
assert n_inside==rev_inside, (n_inside, rev_inside)
gt_label = np.zeros_like(gt)
gt_label[gt >= 0] = 1
gt_label = torch.from_numpy(gt_label.astype(int))
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
assert len(criteria.gt_octree) == levels
assert len(criteria.gt_octree[0]) == (2**(levels-1))**3, len(criteria.gt_octree[0])
assert len(criteria.gt_octree[-1]) == 1, len(criteria.gt_octree[-1])
for l, level in enumerate(criteria.gt_octree):
for k, v in level.items():
assert v.dim() > 0, (l, k, v)
def test_basic_debug():
T = torch.zeros(1,1,36,36,36)
outplane = 16
mod = nn.Conv3d(1, outplane, kernel_size=3, stride=1,
padding=0, bias=False)
T = mod(T)
mod = nn.BatchNorm3d(outplane)
T = mod(T)
mod = nn.ReLU(inplace=True)
T = mod(T)
mod = nn.Conv3d(outplane, outplane, kernel_size=3, stride=1,
padding=0, bias=False)
T = mod(T)
mod = nn.BatchNorm3d(outplane)
T = mod(T)
assert T.shape == (1,16,32,32,32)
def test_simple_net_single_data():
data = TsdfGenerator(block_size, sigma=0.9)
vis = visdom.Visdom()
gt, tsdf_in = data.__getitem__(0)
gt = gt[None, :] # add dim for batch
assert np.abs(tsdf_in).max() < block_size
gt_label = np.zeros_like(gt)
gt_label[gt >= 0] = 1
gt_label = torch.from_numpy(gt_label.astype(int)).to(device)
rep_pad = nn.ReplicationPad3d(pad+n_conv)
tsdf = [rep_pad(torch.from_numpy(copy.copy(tsdf_in)[None, :]).float().to(device))]
#prev = {(0, 0, 0): torch.rand(1, feature_dim, block_size//2, block_size//2,
# block_size//2).float().to(device)}
prev = {(0, 0, 0): torch.from_numpy(np.random.rand(1, feature_dim,
block_size//2+2*pad, block_size//2+2*pad, block_size//2+2*pad)
).float().to(device)}
#assert tsdf[0].shape == (1, 1, block_size, block_size, block_size)
assert gt_label.shape == (1, block_size, block_size, block_size)
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
mod = BottomLevel(feature_dim, block_size)
if device=='cuda':
mod.cuda()
criteria.cuda()
optimizer = optim.Adam(mod.parameters(), lr=0.001) # , momentum=0.9)
for it in range(1, 100):
out = mod(tsdf, prev)
assert len(out) == 1
assert out[0][(0,0,0)].shape[1] == 2, out.shape
loss = criteria(out)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (it+1) % 10 == 0:
sdf_ = octree_to_sdf(out, block_size)
print('level ', np.count_nonzero(sdf_ == 1))
err = plotVoxelVisdom(gt[0], sdf_, tsdf_in[0], vis)
assert np.abs(tsdf_in).max() < 33
print(err)
print(it, loss)
assert err < 2
def test_bottom_layer( block_size = 32):
dataset = TsdfGenerator(block_size, n_elips=1, sigma=0.9, epoch_size=1000)
train_loader = torch.utils.data.DataLoader(dataset, batch_size=1,
num_workers=4)
vis = visdom.Visdom()
mod = BottomLevel(feature_dim, block_size)
if device=='cuda':
mod.cuda()
optimizer = optim.SGD(mod.parameters(), lr=0.0001, momentum=0.9)
m = nn.ReplicationPad3d(mod.pad+mod.n_conv)
prev = {(0, 0, 0): torch.rand(1, feature_dim,
block_size//2+2*pad, block_size//2+2*pad, block_size//2+2*pad
).float().to(device)}
gt_label = None
for it, (gt, tsdf_in) in enumerate(train_loader):
assert np.abs(tsdf_in).max() < 33
assert gt.max() > 1 and gt.min() < -1
gt_label = torch.ones_like(gt)*INSIDE
gt_label[gt >= 0] = OUTSIDE
gt_label = gt_label.long().to(device)
tsdf = [m(tsdf_in).float().to(device)]
for T in prev.values():
assert torch.all(torch.isfinite(T))
for T in tsdf:
assert torch.all(torch.isfinite(T))
out = mod(tsdf, prev)
assert out[0][(0,0,0)].max()>out[0][(0,0,0)].min()
for oct in out:
if not np.all([torch.all(torch.isfinite(o)) for o in oct.values()]):
import ipdb; ipdb.set_trace()
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
if device=='cuda':
criteria.cuda()
loss = criteria(out)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(it, loss)
if it>1 and it%100 == 0:
sdf_ = octree_to_sdf(out, block_size)
err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0][0].numpy(), vis)
print(it, err)
assert err < 2, err
def test_2tier_net_single_data():
res = block_size*2
dataset = TsdfGenerator(res, n_elips=3, sigma=0.9, epoch_size=100)
vis = visdom.Visdom()
mod = TopLevel(feature_dim, BottomLevel(feature_dim, block_size), block_size=block_size)
if device == 'cuda':
mod.cuda()
optimizer = optim.Adam(mod.parameters(), lr=0.01)#, momentum=0.9)
gt, tsdf_in = dataset.__getitem__(0)
assert np.abs(tsdf_in).max() < 33
assert gt.max() > 1 and gt.min() < -1
gt = torch.from_numpy(gt[None, :])
gt_label = torch.zeros_like(gt)
gt_label[gt >= 0] = 1
gt_label = gt_label.long().to(device)
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
if device == 'cuda':
criteria.cuda()
tsdf = torch.from_numpy(copy.copy(tsdf_in)[None, :]).float().to(device)
for it in range(1000):
out = mod(tsdf)
assert len(out) == 2
for l in out[1:]:
for v in l.values():
# only level 0 can have a full bloc
assert v.shape[-1] < block_size, (v.shape)
loss = criteria(out)
assert len(out) == 2
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(it, loss)
if (it+1) % 10 == 0:
#mod.eval()
sdf_ = octree_to_sdf(out, block_size)
err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0], vis)
#mod.train()
print(it, err)
assert err < 2,err
def test_4tier_data(block_size=block_size):
res=block_size*(2**3)
dataset = TsdfGenerator(res, n_elips=3, sigma=0.9, epoch_size=1000)
gt, tsdf = dataset.__getitem__(0)
mod = BottomLevel(feature_dim, block_size)
for i in range(2): #add 2 mid layers
print('adding mid layer')
mod = MidLevel(feature_dim, feature_dim, mod, block_size,
thresh=thresh, budget=4)
mod = TopLevel(feature_dim, mod, block_size=block_size)
out = mod(torch.from_numpy(tsdf[None,:]).float())
def test_2tier_net(res=64, block_size=block_size):
dataset = TsdfGenerator(res, n_elips=1, sigma=0.9, epoch_size=10000, debug=False)
train_loader = torch.utils.data.DataLoader(dataset, batch_size=1,
num_workers=2)
vis = visdom.Visdom()
Force = False
if not Force and Path('model_2tier.pth').exists():
mod = torch.load('model_2tier.pth')
else:
layers = []
layers.append(BottomLevel(feature_dim, block_size))
while block_size*2**len(layers) <= res/2:
print('adding mid layer', len(layers))
layers.append(MidLevel(feature_dim, feature_dim, layers[-1],
block_size, thresh=0.5, budget=4))
mod = TopLevel(feature_dim, layers[-1], block_size=block_size)
if device == 'cuda':
mod.cuda()
optimizer = optim.SGD(mod.parameters(), lr=0.0001, momentum=0.95)
for it, (gt, tsdf_in) in enumerate(train_loader):
assert np.abs(tsdf_in).max() < res
assert gt.max() > 1 and gt.min() < -1
gt_label = torch.zeros_like(gt, device=device)
gt_label[gt >= 0] = 1
gt_label = gt_label.long().to(device)
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
if device == 'cuda':
criteria.cuda()
#tsdf = tsdf_in.float().cuda()
t_start = time.time()
tsdf = tsdf_in.float().to(device)
pred = mod(tsdf)
forward_t = time.time()-t_start
t = time.time()
loss = criteria(pred)
loss_t = time.time()-t
t = time.time()
optimizer.zero_grad()
loss.backward()
back_t = time.time()-t
t = time.time()
optimizer.step()
step_t = time.time()-t
t = time.time()
print(it, loss.data)
print('valuated ', [len(o) for o in pred])
print('GT voxels ', np.count_nonzero([o.numel()>3 for o in criteria.gt_octree]))
print('timing:{total:.3f}. forward {forward_t:.3f}, loss {loss_t:.3f}, back {back_t:.3f}, step {step_t:.3f}'.format(
total=t-t_start, forward_t=forward_t, loss_t=loss_t, back_t=back_t, step_t=step_t))
if (it+1) % 100 == 0:
mod.eval()
out = mod(tsdf)
loss = criteria(out)
for i in range(len(out)):
resample = (2**i)
print('Eval: level %d, %d/%d evaluated' % (i, len(out[i]),
(res/block_size/resample)**3))
sdf_ = octree_to_sdf(out, block_size)
err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0][0].numpy(), vis)
if loss.data<1:
import ipdb; ipdb.set_trace()
mod.train()
print(it, err)
torch.save(mod, 'model_2tier.pth')
if err < 2 :
break
#assert err < 2
def create_model(block_size, feature_dim, res):
layers = []
layers.append(BottomLevel(feature_dim, block_size))
while block_size*2**len(layers) <= res/2:
print('adding mid layer', len(layers))
layers.append(MidLevel(feature_dim, feature_dim, layers[-1],
block_size, thresh=0.1))
mod = TopLevel(feature_dim, layers[-1], block_size=block_size)
return mod
def test_simple_split(res=64, block_size=block_size):
dataset = TsdfGenerator(res, n_elips=3, sigma=0.9, epoch_size=1000, debug=True)
vis = visdom.Visdom()
mod = torch.load('model.pth')
if device == 'cuda':
mod.cuda()
mod.eval()
gt, tsdf_in = dataset.__getitem_split__()
gt = torch.from_numpy(gt[None, :])
tsdf_in = torch.from_numpy(tsdf_in[None, :])
gt_label = torch.zeros_like(gt, device=device)
gt_label[gt >= 0] = 1
gt_label = gt_label.long().to(device)
criteria = OctreeCrossEntropyLoss(gt_label, block_size)
if device == 'cuda':
criteria.cuda()
tsdf = tsdf_in.float().to(device)
pred = mod(tsdf)
loss = criteria(pred)
print(loss.data)
print('evaluated ', [len(o) for o in pred])
for X in pred[0]:
X_ = tuple(np.array(X)//2)
print (X, pred[1][X_])
assert pred[1][X_][0,2]>0.5
sdf_ = octree_to_sdf(pred, block_size)
err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0][0].numpy(), vis)
import ipdb; ipdb.set_trace()
for X,v in criteria.gt_octree[0].items():
if v.numel()>1:
assert X[2]==1 #that's how we built the space
def test_split_subtree(padding=0):
feat = torch.rand(1, feature_dim, block_size+2*padding,
block_size+2*padding,
block_size+2*padding
).float()
split = split_tree(feat,padding=padding)
assert len(split) == 8, len(split)
assert torch.all(split[(0, 0, 0)][0, :, padding, padding, padding] ==
feat[0, :, padding, padding, padding])
assert torch.all(split[(1, 0, 0)][0, :, padding, padding, padding] ==
feat[0, :, block_size//2+padding, padding, padding])
split[(1, 0, 0)][0, 0, padding, padding, padding] = 12.13
#this is no longer true, I don't know how to do this inplace
#assert feat[0, 0, block_size//2, 0, 0] == 12.13
def test_split_subtree_with_padding():
padding=2
feat = torch.rand(1, feature_dim, block_size, block_size,
block_size).float()
split = split_tree(feat, padding=2)
assert len(split) == 8, len(split)
octant = split[(0,0,0)]
assert torch.all(octant[0, :padding, 0, 0, 0] == 0)
assert torch.all(octant[0, -padding:, 0, 0, 0] == 0)
assert octant.shape[-3:]==feat.shape[-3:]//2+padding*2
assert torch.all(octant[0, padding:-padding, 0, 0, 0] == feat[0, :, 0, 0, 0])
assert torch.all(octant[0, padding:-padding, 0, 0, 0] == feat[0, :, 0, 0, 0])
assert torch.all(split[(1, 0, 0)][0, :, padding, padding, padding] ==
feat[0, :, block_size//2, 0, 0])
split[(1, 0, 0)][0, 0, 0, 0, 0] = 12.13
assert feat[0, 0, block_size//2+padding, 0, 0] == 12.13
if __name__ == '__main__':
import sys
logger.remove()
logger.add(sys.stderr , format="{time} {level} {message}", level="INFO")
#test_4tier_data()
#test_criteria_trivial()
#test_criteria()
#test_criteria(4)
#test_data()
#test_ellipsoid()
#test_convtrans()
#test_split_subtree()
#test_split_subtree(padding=2)
#test_basic_debug()
#test_bottom_io()
#test_simple_net_single_data()
#test_bottom_layer()
# TODO why does this not converge? interesting
#test_2tier_net_single_data()
#test_2tier_net(res=32, block_size=block_size)
test_2tier_net(res=64, block_size=block_size)
test_simple_split(res=64, block_size=block_size)
import ipdb; ipdb.set_trace()
test_2tier_net(res=128, block_size=block_size)