forked from ashawkey/torch-ngp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1137 lines (840 loc) · 42.1 KB
/
utils.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import glob
import tqdm
import math
import imageio
import random
import warnings
import tensorboardX
import numpy as np
import pandas as pd
import time
from datetime import datetime
import cv2
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.distributed as dist
from torch.utils.data import Dataset, DataLoader
import trimesh
import mcubes
from rich.console import Console
from torch_ema import ExponentialMovingAverage
from packaging import version as pver
import lpips
from torchmetrics.functional import structural_similarity_index_measure
def custom_meshgrid(*args):
# ref: https://pytorch.org/docs/stable/generated/torch.meshgrid.html?highlight=meshgrid#torch.meshgrid
if pver.parse(torch.__version__) < pver.parse('1.10'):
return torch.meshgrid(*args)
else:
return torch.meshgrid(*args, indexing='ij')
@torch.jit.script
def linear_to_srgb(x):
return torch.where(x < 0.0031308, 12.92 * x, 1.055 * x ** 0.41666 - 0.055)
@torch.jit.script
def srgb_to_linear(x):
return torch.where(x < 0.04045, x / 12.92, ((x + 0.055) / 1.055) ** 2.4)
@torch.cuda.amp.autocast(enabled=False)
def get_rays(poses, intrinsics, H, W, N=-1, error_map=None, patch_size=1):
''' get rays
Args:
poses: [B, 4, 4], cam2world
intrinsics: [4]
H, W, N: int
error_map: [B, 128 * 128], sample probability based on training error
Returns:
rays_o, rays_d: [B, N, 3]
inds: [B, N]
'''
device = poses.device
B = poses.shape[0]
fx, fy, cx, cy = intrinsics
i, j = custom_meshgrid(torch.linspace(0, W-1, W, device=device), torch.linspace(0, H-1, H, device=device)) # float
i = i.t().reshape([1, H*W]).expand([B, H*W]) + 0.5
j = j.t().reshape([1, H*W]).expand([B, H*W]) + 0.5
results = {}
if N > 0:
N = min(N, H*W)
# if use patch-based sampling, ignore error_map
if patch_size > 1:
# random sample left-top cores.
# NOTE: this impl will lead to less sampling on the image corner pixels... but I don't have other ideas.
num_patch = N // (patch_size ** 2)
inds_x = torch.randint(0, H - patch_size, size=[num_patch], device=device)
inds_y = torch.randint(0, W - patch_size, size=[num_patch], device=device)
inds = torch.stack([inds_x, inds_y], dim=-1) # [np, 2]
# create meshgrid for each patch
pi, pj = custom_meshgrid(torch.arange(patch_size, device=device), torch.arange(patch_size, device=device))
offsets = torch.stack([pi.reshape(-1), pj.reshape(-1)], dim=-1) # [p^2, 2]
inds = inds.unsqueeze(1) + offsets.unsqueeze(0) # [np, p^2, 2]
inds = inds.view(-1, 2) # [N, 2]
inds = inds[:, 0] * W + inds[:, 1] # [N], flatten
inds = inds.expand([B, N])
elif error_map is None:
inds = torch.randint(0, H*W, size=[N], device=device) # may duplicate
inds = inds.expand([B, N])
else:
# weighted sample on a low-reso grid
inds_coarse = torch.multinomial(error_map.to(device), N, replacement=False) # [B, N], but in [0, 128*128)
# map to the original resolution with random perturb.
inds_x, inds_y = inds_coarse // 128, inds_coarse % 128 # `//` will throw a warning in torch 1.10... anyway.
sx, sy = H / 128, W / 128
inds_x = (inds_x * sx + torch.rand(B, N, device=device) * sx).long().clamp(max=H - 1)
inds_y = (inds_y * sy + torch.rand(B, N, device=device) * sy).long().clamp(max=W - 1)
inds = inds_x * W + inds_y
results['inds_coarse'] = inds_coarse # need this when updating error_map
i = torch.gather(i, -1, inds)
j = torch.gather(j, -1, inds)
results['inds'] = inds
else:
inds = torch.arange(H*W, device=device).expand([B, H*W])
zs = torch.ones_like(i)
xs = (i - cx) / fx * zs
ys = (j - cy) / fy * zs
directions = torch.stack((xs, ys, zs), dim=-1)
directions = directions / torch.norm(directions, dim=-1, keepdim=True)
rays_d = directions @ poses[:, :3, :3].transpose(-1, -2) # (B, N, 3)
rays_o = poses[..., :3, 3] # [B, 3]
rays_o = rays_o[..., None, :].expand_as(rays_d) # [B, N, 3]
results['rays_o'] = rays_o
results['rays_d'] = rays_d
return results
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
#torch.backends.cudnn.deterministic = True
#torch.backends.cudnn.benchmark = True
def torch_vis_2d(x, renormalize=False):
# x: [3, H, W] or [1, H, W] or [H, W]
import matplotlib.pyplot as plt
import numpy as np
import torch
if isinstance(x, torch.Tensor):
if len(x.shape) == 3:
x = x.permute(1,2,0).squeeze()
x = x.detach().cpu().numpy()
print(f'[torch_vis_2d] {x.shape}, {x.dtype}, {x.min()} ~ {x.max()}')
x = x.astype(np.float32)
# renormalize
if renormalize:
x = (x - x.min(axis=0, keepdims=True)) / (x.max(axis=0, keepdims=True) - x.min(axis=0, keepdims=True) + 1e-8)
plt.imshow(x)
plt.show()
def extract_fields(bound_min, bound_max, resolution, query_func, S=128):
X = torch.linspace(bound_min[0], bound_max[0], resolution).split(S)
Y = torch.linspace(bound_min[1], bound_max[1], resolution).split(S)
Z = torch.linspace(bound_min[2], bound_max[2], resolution).split(S)
u = np.zeros([resolution, resolution, resolution], dtype=np.float32)
with torch.no_grad():
for xi, xs in enumerate(X):
for yi, ys in enumerate(Y):
for zi, zs in enumerate(Z):
xx, yy, zz = custom_meshgrid(xs, ys, zs)
pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1) # [S, 3]
val = query_func(pts).reshape(len(xs), len(ys), len(zs)).detach().cpu().numpy() # [S, 1] --> [x, y, z]
u[xi * S: xi * S + len(xs), yi * S: yi * S + len(ys), zi * S: zi * S + len(zs)] = val
return u
def extract_geometry(bound_min, bound_max, resolution, threshold, query_func):
#print('threshold: {}'.format(threshold))
u = extract_fields(bound_min, bound_max, resolution, query_func)
#print(u.shape, u.max(), u.min(), np.percentile(u, 50))
vertices, triangles = mcubes.marching_cubes(u, threshold)
b_max_np = bound_max.detach().cpu().numpy()
b_min_np = bound_min.detach().cpu().numpy()
vertices = vertices / (resolution - 1.0) * (b_max_np - b_min_np)[None, :] + b_min_np[None, :]
return vertices, triangles
class PSNRMeter:
def __init__(self):
self.V = 0
self.N = 0
def clear(self):
self.V = 0
self.N = 0
def prepare_inputs(self, *inputs):
outputs = []
for i, inp in enumerate(inputs):
if torch.is_tensor(inp):
inp = inp.detach().cpu().numpy()
outputs.append(inp)
return outputs
def update(self, preds, truths):
preds, truths = self.prepare_inputs(preds, truths) # [B, N, 3] or [B, H, W, 3], range[0, 1]
# simplified since max_pixel_value is 1 here.
psnr = -10 * np.log10(np.mean((preds - truths) ** 2))
self.V += psnr
self.N += 1
def measure(self):
return self.V / self.N
def write(self, writer, global_step, prefix=""):
writer.add_scalar(os.path.join(prefix, "PSNR"), self.measure(), global_step)
def report(self):
return f'PSNR = {self.measure():.6f}'
class SSIMMeter:
def __init__(self, device=None):
self.V = 0
self.N = 0
self.device = device if device is not None else torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def clear(self):
self.V = 0
self.N = 0
def prepare_inputs(self, *inputs):
outputs = []
for i, inp in enumerate(inputs):
inp = inp.permute(0, 3, 1, 2).contiguous() # [B, 3, H, W]
inp = inp.to(self.device)
outputs.append(inp)
return outputs
def update(self, preds, truths):
preds, truths = self.prepare_inputs(preds, truths) # [B, H, W, 3] --> [B, 3, H, W], range in [0, 1]
ssim = structural_similarity_index_measure(preds, truths)
self.V += ssim
self.N += 1
def measure(self):
return self.V / self.N
def write(self, writer, global_step, prefix=""):
writer.add_scalar(os.path.join(prefix, "SSIM"), self.measure(), global_step)
def report(self):
return f'SSIM = {self.measure():.6f}'
class LPIPSMeter:
def __init__(self, net='alex', device=None):
self.V = 0
self.N = 0
self.net = net
self.device = device if device is not None else torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.fn = lpips.LPIPS(net=net).eval().to(self.device)
def clear(self):
self.V = 0
self.N = 0
def prepare_inputs(self, *inputs):
outputs = []
for i, inp in enumerate(inputs):
inp = inp.permute(0, 3, 1, 2).contiguous() # [B, 3, H, W]
inp = inp.to(self.device)
outputs.append(inp)
return outputs
def update(self, preds, truths):
preds, truths = self.prepare_inputs(preds, truths) # [B, H, W, 3] --> [B, 3, H, W], range in [0, 1]
v = self.fn(truths, preds, normalize=True).item() # normalize=True: [0, 1] to [-1, 1]
self.V += v
self.N += 1
def measure(self):
return self.V / self.N
def write(self, writer, global_step, prefix=""):
writer.add_scalar(os.path.join(prefix, f"LPIPS ({self.net})"), self.measure(), global_step)
def report(self):
return f'LPIPS ({self.net}) = {self.measure():.6f}'
class Trainer(object):
def __init__(self,
name, # name of this experiment
opt, # extra conf
model, # network
criterion=None, # loss function, if None, assume inline implementation in train_step
optimizer=None, # optimizer
ema_decay=None, # if use EMA, set the decay
lr_scheduler=None, # scheduler
metrics=[], # metrics for evaluation, if None, use val_loss to measure performance, else use the first metric.
local_rank=0, # which GPU am I
world_size=1, # total num of GPUs
device=None, # device to use, usually setting to None is OK. (auto choose device)
mute=False, # whether to mute all print
fp16=False, # amp optimize level
eval_interval=1, # eval once every $ epoch
max_keep_ckpt=2, # max num of saved ckpts in disk
workspace='workspace', # workspace to save logs & ckpts
best_mode='min', # the smaller/larger result, the better
use_loss_as_metric=True, # use loss as the first metric
report_metric_at_train=False, # also report metrics at training
use_checkpoint="latest", # which ckpt to use at init time
use_tensorboardX=True, # whether to use tensorboard for logging
scheduler_update_every_step=False, # whether to call scheduler.step() after every train step
):
self.name = name
self.opt = opt
self.mute = mute
self.metrics = metrics
self.local_rank = local_rank
self.world_size = world_size
self.workspace = workspace
self.ema_decay = ema_decay
self.fp16 = fp16
self.best_mode = best_mode
self.use_loss_as_metric = use_loss_as_metric
self.report_metric_at_train = report_metric_at_train
self.max_keep_ckpt = max_keep_ckpt
self.eval_interval = eval_interval
self.use_checkpoint = use_checkpoint
self.use_tensorboardX = use_tensorboardX
self.time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S")
self.scheduler_update_every_step = scheduler_update_every_step
self.device = device if device is not None else torch.device(f'cuda:{local_rank}' if torch.cuda.is_available() else 'cpu')
self.console = Console()
model.to(self.device)
if self.world_size > 1:
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank])
self.model = model
if isinstance(criterion, nn.Module):
criterion.to(self.device)
self.criterion = criterion
# optionally use LPIPS loss for patch-based training
if self.opt.patch_size > 1:
import lpips
self.criterion_lpips = lpips.LPIPS(net='alex').to(self.device)
if optimizer is None:
self.optimizer = optim.Adam(self.model.parameters(), lr=0.001, weight_decay=5e-4) # naive adam
else:
self.optimizer = optimizer(self.model)
if lr_scheduler is None:
self.lr_scheduler = optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lambda epoch: 1) # fake scheduler
else:
self.lr_scheduler = lr_scheduler(self.optimizer)
if ema_decay is not None:
self.ema = ExponentialMovingAverage(self.model.parameters(), decay=ema_decay)
else:
self.ema = None
self.scaler = torch.cuda.amp.GradScaler(enabled=self.fp16)
# variable init
self.epoch = 0
self.global_step = 0
self.local_step = 0
self.stats = {
"loss": [],
"valid_loss": [],
"results": [], # metrics[0], or valid_loss
"checkpoints": [], # record path of saved ckpt, to automatically remove old ckpt
"best_result": None,
}
# auto fix
if len(metrics) == 0 or self.use_loss_as_metric:
self.best_mode = 'min'
# workspace prepare
self.log_ptr = None
if self.workspace is not None:
os.makedirs(self.workspace, exist_ok=True)
self.log_path = os.path.join(workspace, f"log_{self.name}.txt")
self.log_ptr = open(self.log_path, "a+")
self.ckpt_path = os.path.join(self.workspace, 'checkpoints')
self.best_path = f"{self.ckpt_path}/{self.name}.pth"
os.makedirs(self.ckpt_path, exist_ok=True)
self.log(f'[INFO] Trainer: {self.name} | {self.time_stamp} | {self.device} | {"fp16" if self.fp16 else "fp32"} | {self.workspace}')
self.log(f'[INFO] #parameters: {sum([p.numel() for p in model.parameters() if p.requires_grad])}')
if self.workspace is not None:
if self.use_checkpoint == "scratch":
self.log("[INFO] Training from scratch ...")
elif self.use_checkpoint == "latest":
self.log("[INFO] Loading latest checkpoint ...")
self.load_checkpoint()
elif self.use_checkpoint == "latest_model":
self.log("[INFO] Loading latest checkpoint (model only)...")
self.load_checkpoint(model_only=True)
elif self.use_checkpoint == "best":
if os.path.exists(self.best_path):
self.log("[INFO] Loading best checkpoint ...")
self.load_checkpoint(self.best_path)
else:
self.log(f"[INFO] {self.best_path} not found, loading latest ...")
self.load_checkpoint()
else: # path to ckpt
self.log(f"[INFO] Loading {self.use_checkpoint} ...")
self.load_checkpoint(self.use_checkpoint)
# clip loss prepare
if opt.rand_pose >= 0: # =0 means only using CLIP loss, >0 means a hybrid mode.
from nerf.clip_utils import CLIPLoss
self.clip_loss = CLIPLoss(self.device)
self.clip_loss.prepare_text([self.opt.clip_text]) # only support one text prompt now...
def __del__(self):
if self.log_ptr:
self.log_ptr.close()
def log(self, *args, **kwargs):
if self.local_rank == 0:
if not self.mute:
#print(*args)
self.console.print(*args, **kwargs)
if self.log_ptr:
print(*args, file=self.log_ptr)
self.log_ptr.flush() # write immediately to file
### ------------------------------
def train_step(self, data):
rays_o = data['rays_o'] # [B, N, 3]
rays_d = data['rays_d'] # [B, N, 3]
# if there is no gt image, we train with CLIP loss.
if 'images' not in data:
B, N = rays_o.shape[:2]
H, W = data['H'], data['W']
# currently fix white bg, MUST force all rays!
outputs = self.model.render(rays_o, rays_d, staged=False, bg_color=None, perturb=True, force_all_rays=True, **vars(self.opt))
pred_rgb = outputs['image'].reshape(B, H, W, 3).permute(0, 3, 1, 2).contiguous()
# [debug] uncomment to plot the images used in train_step
#torch_vis_2d(pred_rgb[0])
loss = self.clip_loss(pred_rgb)
return pred_rgb, None, loss
images = data['images'] # [B, N, 3/4]
B, N, C = images.shape
if self.opt.color_space == 'linear':
images[..., :3] = srgb_to_linear(images[..., :3])
if C == 3 or self.model.bg_radius > 0:
bg_color = 1
# train with random background color if not using a bg model and has alpha channel.
else:
#bg_color = torch.ones(3, device=self.device) # [3], fixed white background
#bg_color = torch.rand(3, device=self.device) # [3], frame-wise random.
bg_color = torch.rand_like(images[..., :3]) # [N, 3], pixel-wise random.
if C == 4:
gt_rgb = images[..., :3] * images[..., 3:] + bg_color * (1 - images[..., 3:])
else:
gt_rgb = images
outputs = self.model.render(rays_o, rays_d, staged=False, bg_color=bg_color, perturb=True, force_all_rays=False if self.opt.patch_size == 1 else True, **vars(self.opt))
# outputs = self.model.render(rays_o, rays_d, staged=False, bg_color=bg_color, perturb=True, force_all_rays=True, **vars(self.opt))
pred_rgb = outputs['image']
# MSE loss
loss = self.criterion(pred_rgb, gt_rgb).mean(-1) # [B, N, 3] --> [B, N]
# patch-based rendering
if self.opt.patch_size > 1:
gt_rgb = gt_rgb.view(-1, self.opt.patch_size, self.opt.patch_size, 3).permute(0, 3, 1, 2).contiguous()
pred_rgb = pred_rgb.view(-1, self.opt.patch_size, self.opt.patch_size, 3).permute(0, 3, 1, 2).contiguous()
# torch_vis_2d(gt_rgb[0])
# torch_vis_2d(pred_rgb[0])
# LPIPS loss [not useful...]
loss = loss + 1e-3 * self.criterion_lpips(pred_rgb, gt_rgb)
# special case for CCNeRF's rank-residual training
if len(loss.shape) == 3: # [K, B, N]
loss = loss.mean(0)
# update error_map
if self.error_map is not None:
index = data['index'] # [B]
inds = data['inds_coarse'] # [B, N]
# take out, this is an advanced indexing and the copy is unavoidable.
error_map = self.error_map[index] # [B, H * W]
# [debug] uncomment to save and visualize error map
# if self.global_step % 1001 == 0:
# tmp = error_map[0].view(128, 128).cpu().numpy()
# print(f'[write error map] {tmp.shape} {tmp.min()} ~ {tmp.max()}')
# tmp = (tmp - tmp.min()) / (tmp.max() - tmp.min())
# cv2.imwrite(os.path.join(self.workspace, f'{self.global_step}.jpg'), (tmp * 255).astype(np.uint8))
error = loss.detach().to(error_map.device) # [B, N], already in [0, 1]
# ema update
ema_error = 0.1 * error_map.gather(1, inds) + 0.9 * error
error_map.scatter_(1, inds, ema_error)
# put back
self.error_map[index] = error_map
loss = loss.mean()
# extra loss
# pred_weights_sum = outputs['weights_sum'] + 1e-8
# loss_ws = - 1e-1 * pred_weights_sum * torch.log(pred_weights_sum) # entropy to encourage weights_sum to be 0 or 1.
# loss = loss + loss_ws.mean()
return pred_rgb, gt_rgb, loss
def eval_step(self, data):
rays_o = data['rays_o'] # [B, N, 3]
rays_d = data['rays_d'] # [B, N, 3]
images = data['images'] # [B, H, W, 3/4]
B, H, W, C = images.shape
if self.opt.color_space == 'linear':
images[..., :3] = srgb_to_linear(images[..., :3])
# eval with fixed background color
bg_color = 1
if C == 4:
gt_rgb = images[..., :3] * images[..., 3:] + bg_color * (1 - images[..., 3:])
else:
gt_rgb = images
outputs = self.model.render(rays_o, rays_d, staged=True, bg_color=bg_color, perturb=False, **vars(self.opt))
pred_rgb = outputs['image'].reshape(B, H, W, 3)
pred_depth = outputs['depth'].reshape(B, H, W)
loss = self.criterion(pred_rgb, gt_rgb).mean()
return pred_rgb, pred_depth, gt_rgb, loss
# moved out bg_color and perturb for more flexible control...
def test_step(self, data, bg_color=None, perturb=False):
rays_o = data['rays_o'] # [B, N, 3]
rays_d = data['rays_d'] # [B, N, 3]
H, W = data['H'], data['W']
if bg_color is not None:
bg_color = bg_color.to(self.device)
outputs = self.model.render(rays_o, rays_d, staged=True, bg_color=bg_color, perturb=perturb, **vars(self.opt))
pred_rgb = outputs['image'].reshape(-1, H, W, 3)
pred_depth = outputs['depth'].reshape(-1, H, W)
return pred_rgb, pred_depth
def save_mesh(self, save_path=None, resolution=256, threshold=10):
if save_path is None:
save_path = os.path.join(self.workspace, 'meshes', f'{self.name}_{self.epoch}.ply')
self.log(f"==> Saving mesh to {save_path}")
os.makedirs(os.path.dirname(save_path), exist_ok=True)
def query_func(pts):
with torch.no_grad():
with torch.cuda.amp.autocast(enabled=self.fp16):
sigma = self.model.density(pts.to(self.device))['sigma']
return sigma
vertices, triangles = extract_geometry(self.model.aabb_infer[:3], self.model.aabb_infer[3:], resolution=resolution, threshold=threshold, query_func=query_func)
mesh = trimesh.Trimesh(vertices, triangles, process=False) # important, process=True leads to seg fault...
mesh.export(save_path)
self.log(f"==> Finished saving mesh.")
### ------------------------------
def train(self, train_loader, valid_loader, max_epochs):
if self.use_tensorboardX and self.local_rank == 0:
self.writer = tensorboardX.SummaryWriter(os.path.join(self.workspace, "run", self.name))
# mark untrained region (i.e., not covered by any camera from the training dataset)
if self.model.cuda_ray:
self.model.mark_untrained_grid(train_loader._data.poses, train_loader._data.intrinsics)
# get a ref to error_map
self.error_map = train_loader._data.error_map
for epoch in range(self.epoch + 1, max_epochs + 1):
self.epoch = epoch
self.train_one_epoch(train_loader)
if self.workspace is not None and self.local_rank == 0:
self.save_checkpoint(full=True, best=False)
if self.epoch % self.eval_interval == 0:
self.evaluate_one_epoch(valid_loader)
self.save_checkpoint(full=False, best=True)
if self.use_tensorboardX and self.local_rank == 0:
self.writer.close()
def evaluate(self, loader, name=None):
self.use_tensorboardX, use_tensorboardX = False, self.use_tensorboardX
self.evaluate_one_epoch(loader, name)
self.use_tensorboardX = use_tensorboardX
def test(self, loader, save_path=None, name=None, write_video=True):
if save_path is None:
save_path = os.path.join(self.workspace, 'results')
if name is None:
name = f'{self.name}_ep{self.epoch:04d}'
os.makedirs(save_path, exist_ok=True)
self.log(f"==> Start Test, save results to {save_path}")
pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')
self.model.eval()
if write_video:
all_preds = []
all_preds_depth = []
with torch.no_grad():
for i, data in enumerate(loader):
with torch.cuda.amp.autocast(enabled=self.fp16):
preds, preds_depth = self.test_step(data)
if self.opt.color_space == 'linear':
preds = linear_to_srgb(preds)
pred = preds[0].detach().cpu().numpy()
pred = (pred * 255).astype(np.uint8)
pred_depth = preds_depth[0].detach().cpu().numpy()
pred_depth = (pred_depth * 255).astype(np.uint8)
if write_video:
all_preds.append(pred)
all_preds_depth.append(pred_depth)
else:
cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_rgb.png'), cv2.cvtColor(pred, cv2.COLOR_RGB2BGR))
cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_depth.png'), pred_depth)
pbar.update(loader.batch_size)
if write_video:
all_preds = np.stack(all_preds, axis=0)
all_preds_depth = np.stack(all_preds_depth, axis=0)
imageio.mimwrite(os.path.join(save_path, f'{name}_rgb.mp4'), all_preds, fps=25, quality=8, macro_block_size=1)
imageio.mimwrite(os.path.join(save_path, f'{name}_depth.mp4'), all_preds_depth, fps=25, quality=8, macro_block_size=1)
self.log(f"==> Finished Test.")
# [GUI] just train for 16 steps, without any other overhead that may slow down rendering.
def train_gui(self, train_loader, step=16):
self.model.train()
total_loss = torch.tensor([0], dtype=torch.float32, device=self.device)
loader = iter(train_loader)
# mark untrained grid
if self.global_step == 0:
self.model.mark_untrained_grid(train_loader._data.poses, train_loader._data.intrinsics)
for _ in range(step):
# mimic an infinite loop dataloader (in case the total dataset is smaller than step)
try:
data = next(loader)
except StopIteration:
loader = iter(train_loader)
data = next(loader)
# update grid every 16 steps
if self.model.cuda_ray and self.global_step % self.opt.update_extra_interval == 0:
with torch.cuda.amp.autocast(enabled=self.fp16):
self.model.update_extra_state()
self.global_step += 1
self.optimizer.zero_grad()
with torch.cuda.amp.autocast(enabled=self.fp16):
preds, truths, loss = self.train_step(data)
self.scaler.scale(loss).backward()
self.scaler.step(self.optimizer)
self.scaler.update()
if self.scheduler_update_every_step:
self.lr_scheduler.step()
total_loss += loss.detach()
if self.ema is not None:
self.ema.update()
average_loss = total_loss.item() / step
if not self.scheduler_update_every_step:
if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):
self.lr_scheduler.step(average_loss)
else:
self.lr_scheduler.step()
outputs = {
'loss': average_loss,
'lr': self.optimizer.param_groups[0]['lr'],
}
return outputs
# [GUI] test on a single image
def test_gui(self, pose, intrinsics, W, H, bg_color=None, spp=1, downscale=1):
# render resolution (may need downscale to for better frame rate)
rH = int(H * downscale)
rW = int(W * downscale)
intrinsics = intrinsics * downscale
pose = torch.from_numpy(pose).unsqueeze(0).to(self.device)
rays = get_rays(pose, intrinsics, rH, rW, -1)
data = {
'rays_o': rays['rays_o'],
'rays_d': rays['rays_d'],
'H': rH,
'W': rW,
}
self.model.eval()
if self.ema is not None:
self.ema.store()
self.ema.copy_to()
with torch.no_grad():
with torch.cuda.amp.autocast(enabled=self.fp16):
# here spp is used as perturb random seed! (but not perturb the first sample)
preds, preds_depth = self.test_step(data, bg_color=bg_color, perturb=False if spp == 1 else spp)
if self.ema is not None:
self.ema.restore()
# interpolation to the original resolution
if downscale != 1:
# TODO: have to permute twice with torch...
preds = F.interpolate(preds.permute(0, 3, 1, 2), size=(H, W), mode='nearest').permute(0, 2, 3, 1).contiguous()
preds_depth = F.interpolate(preds_depth.unsqueeze(1), size=(H, W), mode='nearest').squeeze(1)
if self.opt.color_space == 'linear':
preds = linear_to_srgb(preds)
pred = preds[0].detach().cpu().numpy()
pred_depth = preds_depth[0].detach().cpu().numpy()
outputs = {
'image': pred,
'depth': pred_depth,
}
return outputs
def train_one_epoch(self, loader):
self.log(f"==> Start Training Epoch {self.epoch}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...")
total_loss = 0
if self.local_rank == 0 and self.report_metric_at_train:
for metric in self.metrics:
metric.clear()
self.model.train()
# distributedSampler: must call set_epoch() to shuffle indices across multiple epochs
# ref: https://pytorch.org/docs/stable/data.html
if self.world_size > 1:
loader.sampler.set_epoch(self.epoch)
if self.local_rank == 0:
pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{desc}: {percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')
self.local_step = 0
for data in loader:
# update grid every 16 steps
if self.model.cuda_ray and self.global_step % self.opt.update_extra_interval == 0:
with torch.cuda.amp.autocast(enabled=self.fp16):
self.model.update_extra_state()
self.local_step += 1
self.global_step += 1
self.optimizer.zero_grad()
with torch.cuda.amp.autocast(enabled=self.fp16):
preds, truths, loss = self.train_step(data)
self.scaler.scale(loss).backward()
self.scaler.step(self.optimizer)
self.scaler.update()
if self.scheduler_update_every_step:
self.lr_scheduler.step()
loss_val = loss.item()
total_loss += loss_val
if self.local_rank == 0:
if self.report_metric_at_train:
for metric in self.metrics:
metric.update(preds, truths)
if self.use_tensorboardX:
self.writer.add_scalar("train/loss", loss_val, self.global_step)
self.writer.add_scalar("train/lr", self.optimizer.param_groups[0]['lr'], self.global_step)
if self.scheduler_update_every_step:
pbar.set_description(f"loss={loss_val:.4f} ({total_loss/self.local_step:.4f}), lr={self.optimizer.param_groups[0]['lr']:.6f}")
else:
pbar.set_description(f"loss={loss_val:.4f} ({total_loss/self.local_step:.4f})")
pbar.update(loader.batch_size)
if self.ema is not None:
self.ema.update()
average_loss = total_loss / self.local_step
self.stats["loss"].append(average_loss)
if self.local_rank == 0:
pbar.close()
if self.report_metric_at_train:
for metric in self.metrics:
self.log(metric.report(), style="red")
if self.use_tensorboardX:
metric.write(self.writer, self.epoch, prefix="train")
metric.clear()
if not self.scheduler_update_every_step:
if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):
self.lr_scheduler.step(average_loss)
else:
self.lr_scheduler.step()
self.log(f"==> Finished Epoch {self.epoch}.")
def evaluate_one_epoch(self, loader, name=None):
self.log(f"++> Evaluate at epoch {self.epoch} ...")
if name is None:
name = f'{self.name}_ep{self.epoch:04d}'
total_loss = 0
if self.local_rank == 0:
for metric in self.metrics:
metric.clear()
self.model.eval()
if self.ema is not None:
self.ema.store()
self.ema.copy_to()
if self.local_rank == 0:
pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{desc}: {percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')
with torch.no_grad():
self.local_step = 0
for data in loader:
self.local_step += 1
with torch.cuda.amp.autocast(enabled=self.fp16):
preds, preds_depth, truths, loss = self.eval_step(data)
# all_gather/reduce the statistics (NCCL only support all_*)
if self.world_size > 1:
dist.all_reduce(loss, op=dist.ReduceOp.SUM)
loss = loss / self.world_size
preds_list = [torch.zeros_like(preds).to(self.device) for _ in range(self.world_size)] # [[B, ...], [B, ...], ...]
dist.all_gather(preds_list, preds)
preds = torch.cat(preds_list, dim=0)
preds_depth_list = [torch.zeros_like(preds_depth).to(self.device) for _ in range(self.world_size)] # [[B, ...], [B, ...], ...]
dist.all_gather(preds_depth_list, preds_depth)
preds_depth = torch.cat(preds_depth_list, dim=0)
truths_list = [torch.zeros_like(truths).to(self.device) for _ in range(self.world_size)] # [[B, ...], [B, ...], ...]
dist.all_gather(truths_list, truths)
truths = torch.cat(truths_list, dim=0)
loss_val = loss.item()
total_loss += loss_val
# only rank = 0 will perform evaluation.
if self.local_rank == 0:
for metric in self.metrics:
metric.update(preds, truths)
# save image
save_path = os.path.join(self.workspace, 'validation', f'{name}_{self.local_step:04d}_rgb.png')
save_path_depth = os.path.join(self.workspace, 'validation', f'{name}_{self.local_step:04d}_depth.png')
#self.log(f"==> Saving validation image to {save_path}")
os.makedirs(os.path.dirname(save_path), exist_ok=True)
if self.opt.color_space == 'linear':
preds = linear_to_srgb(preds)
pred = preds[0].detach().cpu().numpy()
pred = (pred * 255).astype(np.uint8)
pred_depth = preds_depth[0].detach().cpu().numpy()
pred_depth = (pred_depth * 255).astype(np.uint8)
cv2.imwrite(save_path, cv2.cvtColor(pred, cv2.COLOR_RGB2BGR))
cv2.imwrite(save_path_depth, pred_depth)
pbar.set_description(f"loss={loss_val:.4f} ({total_loss/self.local_step:.4f})")
pbar.update(loader.batch_size)
average_loss = total_loss / self.local_step
self.stats["valid_loss"].append(average_loss)
if self.local_rank == 0:
pbar.close()
if not self.use_loss_as_metric and len(self.metrics) > 0:
result = self.metrics[0].measure()
self.stats["results"].append(result if self.best_mode == 'min' else - result) # if max mode, use -result