-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
578 lines (496 loc) · 24.1 KB
/
train.py
File metadata and controls
578 lines (496 loc) · 24.1 KB
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
#
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use
# under the terms of the LICENSE.md file.
#
# For inquiries contact george.drettakis@inria.fr
#
import os
import torch
from random import randint
from utils.loss_utils import l1_loss, ssim
from gaussian_renderer import render, network_gui
import sys
from scene import Scene, GaussianModel
from utils.general_utils import safe_state, get_expon_lr_func
from utils.graphics_utils import fov2focal
import uuid
from tqdm import tqdm
from utils.image_utils import psnr
from argparse import ArgumentParser, Namespace
from arguments import ModelParams, PipelineParams, OptimizationParams
import lpips
from pytorch_msssim import ssim as ssim_metric
try:
from torch.utils.tensorboard import SummaryWriter
TENSORBOARD_FOUND = True
except ImportError:
TENSORBOARD_FOUND = False
try:
from fused_ssim import fused_ssim
FUSED_SSIM_AVAILABLE = True
except:
FUSED_SSIM_AVAILABLE = False
try:
from diff_gaussian_rasterization import SparseGaussianAdam
SPARSE_ADAM_AVAILABLE = True
except:
SPARSE_ADAM_AVAILABLE = False
# ========== DEBUG MODE: Enable/disable individual losses ==========
# Set these to False to disable specific losses for debugging
DEBUG_ENABLE_DEPTH_LOSS = False
DEBUG_ENABLE_NORMAL_CONSISTENCY_LOSS = False
DEBUG_ENABLE_SCALE_FLATTENING_LOSS = False
DEBUG_ENABLE_NORMAL_ALIGNMENT_LOSS = False
# ====================================================================
def normal_from_invdepth(invdepth, eps=1e-6):
"""
Approximate per-pixel surface normals from an inverse depth map using image-space gradients.
Returns a tensor of shape [3, H, W] with unit-length normals.
"""
if invdepth.dim() == 3:
invdepth = invdepth.squeeze(0)
H, W = invdepth.shape[-2], invdepth.shape[-1]
# Finite differences
dzdx = torch.zeros_like(invdepth)
dzdy = torch.zeros_like(invdepth)
dzdx[:, :-1] = invdepth[:, 1:] - invdepth[:, :-1]
dzdx[:, -1] = dzdx[:, -2]
dzdy[:-1, :] = invdepth[1:, :] - invdepth[:-1, :]
dzdy[-1, :] = dzdy[-2, :]
# Construct normals in camera/image space: (-dz/dx, -dz/dy, 1)
nx = -dzdx
ny = -dzdy
nz = torch.ones_like(invdepth)
n = torch.stack([nx, ny, nz], dim=0) # [3, H, W]
norm = torch.sqrt((n * n).sum(dim=0, keepdim=True) + eps)
n = n / norm
return n
def normal_consistency_loss(render_invdepth, mono_invdepth, depth_mask, eps=1e-6):
"""
L_nc = mean(1 - n_render · n_depth) over valid pixels,
where normals are derived from inverse depth maps by image-space gradients.
"""
# Ensure HxW
if render_invdepth.dim() == 3:
render_invdepth = render_invdepth.squeeze(0)
if mono_invdepth.dim() == 3:
mono_invdepth = mono_invdepth.squeeze(0)
if depth_mask.dim() == 3:
depth_mask = depth_mask.squeeze(0)
device = render_invdepth.device
n_render = normal_from_invdepth(render_invdepth)
n_depth = normal_from_invdepth(mono_invdepth)
valid = depth_mask > 0
if not valid.any():
return torch.zeros((), device=device, dtype=render_invdepth.dtype)
# Flatten valid positions
n_render_flat = n_render[:, valid] # [3, N]
n_depth_flat = n_depth[:, valid] # [3, N]
dots = (n_render_flat * n_depth_flat).sum(dim=0)
dots = torch.clamp(dots, -1.0, 1.0)
return (1.0 - dots).mean()
def pcc_patch_loss(render_invdepth, mono_invdepth, depth_mask, num_patches=8, patch_size=32, min_valid_frac=0.5, eps=1e-6):
"""
Pearson-correlation depth regularization on random (approximately) non-overlapping patches.
Returns: mean(1 - PCC) over valid patches.
"""
# Ensure HxW
if render_invdepth.dim() == 3:
render_invdepth = render_invdepth.squeeze(0)
if mono_invdepth.dim() == 3:
mono_invdepth = mono_invdepth.squeeze(0)
if depth_mask.dim() == 3:
depth_mask = depth_mask.squeeze(0)
H, W = render_invdepth.shape[-2], render_invdepth.shape[-1]
if H < patch_size or W < patch_size:
return torch.zeros((), device=render_invdepth.device, dtype=render_invdepth.dtype)
device = render_invdepth.device
used = torch.zeros((H, W), dtype=torch.bool, device=device)
losses = []
max_tries = num_patches * 50
tries = 0
while len(losses) < num_patches and tries < max_tries:
tries += 1
y0 = int(torch.randint(0, H - patch_size + 1, (1,), device=device).item())
x0 = int(torch.randint(0, W - patch_size + 1, (1,), device=device).item())
if used[y0:y0 + patch_size, x0:x0 + patch_size].any():
continue
m = depth_mask[y0:y0 + patch_size, x0:x0 + patch_size] > 0
valid = int(m.sum().item())
if valid < int(min_valid_frac * patch_size * patch_size):
continue
a = render_invdepth[y0:y0 + patch_size, x0:x0 + patch_size][m]
b = mono_invdepth[y0:y0 + patch_size, x0:x0 + patch_size][m]
a = a - a.mean()
b = b - b.mean()
if a.std() < 1e-5 or b.std() < 1e-5:
continue
var_a = (a * a).mean()
var_b = (b * b).mean()
denom = torch.sqrt(var_a * var_b) + eps
pcc = (a * b).mean() / denom
pcc = torch.clamp(pcc, -1.0, 1.0)
losses.append(1.0 - pcc)
used[y0:y0 + patch_size, x0:x0 + patch_size] = True
if len(losses) == 0:
return torch.zeros((), device=device, dtype=render_invdepth.dtype)
return torch.stack(losses).mean()
def training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from):
if not SPARSE_ADAM_AVAILABLE and opt.optimizer_type == "sparse_adam":
sys.exit(f"Trying to use sparse adam but it is not installed, please install the correct rasterizer using pip install [3dgs_accel].")
first_iter = 0
tb_writer = prepare_output_and_logger(dataset)
gaussians = GaussianModel(dataset.sh_degree, opt.optimizer_type)
scene = Scene(dataset, gaussians)
gaussians.training_setup(opt)
if checkpoint:
(model_params, first_iter) = torch.load(checkpoint)
gaussians.restore(model_params, opt)
bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]
background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
iter_start = torch.cuda.Event(enable_timing = True)
iter_end = torch.cuda.Event(enable_timing = True)
use_sparse_adam = opt.optimizer_type == "sparse_adam" and SPARSE_ADAM_AVAILABLE
depth_l1_weight = get_expon_lr_func(opt.depth_l1_weight_init, opt.depth_l1_weight_final, max_steps=opt.iterations)
viewpoint_stack = scene.getTrainCameras().copy()
viewpoint_indices = list(range(len(viewpoint_stack)))
ema_loss_for_log = 0.0
ema_Ll1depth_for_log = 0.0
ema_Ldnormal_for_log = 0.0
ema_Lscale_for_log = 0.0
ema_Lnormal_for_log = 0.0
progress_bar = tqdm(range(first_iter, opt.iterations), desc="Training progress", ncols=200)
lpips_fn = lpips.LPIPS(net='vgg').cuda()
lpips_fn.eval()
first_iter += 1
for iteration in range(first_iter, opt.iterations + 1):
if network_gui.conn == None:
network_gui.try_connect()
while network_gui.conn != None:
try:
net_image_bytes = None
custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive()
if custom_cam != None:
net_image = render(custom_cam, gaussians, pipe, background, scaling_modifier=scaling_modifer, use_trained_exp=dataset.train_test_exp, separate_sh=SPARSE_ADAM_AVAILABLE)["render"]
net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy())
network_gui.send(net_image_bytes, dataset.source_path)
if do_training and ((iteration < int(opt.iterations)) or not keep_alive):
break
except Exception as e:
network_gui.conn = None
iter_start.record()
gaussians.update_learning_rate(iteration)
# Every 1000 its we increase the levels of SH up to a maximum degree
if iteration % 1000 == 0:
gaussians.oneupSHdegree()
# Pick a random Camera
if not viewpoint_stack:
viewpoint_stack = scene.getTrainCameras().copy()
viewpoint_indices = list(range(len(viewpoint_stack)))
rand_idx = randint(0, len(viewpoint_indices) - 1)
viewpoint_cam = viewpoint_stack.pop(rand_idx)
vind = viewpoint_indices.pop(rand_idx)
# Render
if (iteration - 1) == debug_from:
pipe.debug = True
bg = torch.rand((3), device="cuda") if opt.random_background else background
render_pkg = render(viewpoint_cam, gaussians, pipe, bg, use_trained_exp=dataset.train_test_exp, separate_sh=SPARSE_ADAM_AVAILABLE)
image, viewspace_point_tensor, visibility_filter, radii = render_pkg["render"], render_pkg["viewspace_points"], render_pkg["visibility_filter"], render_pkg["radii"]
if viewpoint_cam.alpha_mask is not None:
alpha_mask = viewpoint_cam.alpha_mask.cuda()
image *= alpha_mask
# Loss
gt_image = viewpoint_cam.original_image.cuda()
Ll1 = l1_loss(image, gt_image)
if FUSED_SSIM_AVAILABLE:
ssim_value = fused_ssim(image.unsqueeze(0), gt_image.unsqueeze(0))
else:
ssim_value = ssim(image, gt_image)
loss = (1.0 - opt.lambda_dssim) * Ll1 + opt.lambda_dssim * (1.0 - ssim_value)
# Depth / normal / scale regularization
Ll1depth_pure = 0.0
Ll1depth = torch.tensor(0.0, device="cuda")
Ldnormal = torch.tensor(0.0, device="cuda")
Lscale = torch.tensor(0.0, device="cuda")
Lnormal = torch.tensor(0.0, device="cuda")
if viewpoint_cam.depth_reliable:
invDepth = render_pkg["depth"]
mono_invdepth = 1 - viewpoint_cam.invdepthmap.cuda()
depth_mask = viewpoint_cam.depth_mask.cuda()
debug_display = False
if DEBUG_ENABLE_DEPTH_LOSS:
Ll1depth_pure = pcc_patch_loss(invDepth, mono_invdepth, depth_mask, num_patches=16, patch_size=64)
lambda_nc = 0.1
Ll1depth = lambda_nc * Ll1depth_pure
# Ll1depth = depth_l1_weight(iteration) * Ll1depth_pure
loss += Ll1depth
if iteration % 1000 == 0 and debug_display:
import matplotlib.pyplot as plt
plt.subplot(121)
plt.imshow(invDepth.squeeze().detach().cpu().numpy())
plt.title("render")
plt.subplot(122)
plt.imshow(mono_invdepth.squeeze().detach().cpu().numpy())
plt.title("mono")
plt.show()
# Normal consistency loss between normals from rendered and monocular depth
if DEBUG_ENABLE_NORMAL_CONSISTENCY_LOSS:
Lnc = normal_consistency_loss(invDepth, mono_invdepth, depth_mask)
lambda_nc = 0.1
Ldnormal = lambda_nc * Lnc
loss += Ldnormal
if iteration % 1000 == 0 and debug_display:
import matplotlib.pyplot as plt
n_render = normal_from_invdepth(invDepth)
n_depth = normal_from_invdepth(mono_invdepth)
plt.subplot(121)
plt.imshow(((n_render.permute(1,2,0)+1)/2).detach().cpu().numpy())
plt.title("render normal")
plt.subplot(122)
plt.imshow(((n_depth.permute(1,2,0)+1)/2).detach().cpu().numpy())
plt.title("mono normal")
plt.show()
# Scale flattening loss Ls for line Gaussians (type 2)
# Encourages min(s1, s2, s3) to be small so Gaussians become disc-like.
if DEBUG_ENABLE_SCALE_FLATTENING_LOSS:
line_mask = (gaussians._point_types == 2)
if line_mask.any():
scales = gaussians.get_scaling[line_mask] # [N_line, 3]
min_scale = scales.min(dim=1).values
Ls = min_scale.abs().mean()
lambda_s = 100.0
Lscale = lambda_s * Ls
loss += Lscale
# Normal alignment loss L_n: line Gaussian flat normals vs monocular normal map (when -n provided)
if DEBUG_ENABLE_NORMAL_ALIGNMENT_LOSS and getattr(viewpoint_cam, "mono_normal_map", None) is not None:
xyz_line, n_flat_world = gaussians.get_flat_normals_line()
if xyz_line is not None and xyz_line.shape[0] > 0:
W2C = viewpoint_cam.world_view_transform
R_w2c = W2C[:3, :3]
t_w2c = W2C[:3, 3]
xyz_cam = (R_w2c @ xyz_line.T).T + t_w2c
z = xyz_cam[:, 2]
view_cam = xyz_cam / (xyz_cam.norm(dim=1, keepdim=True) + 1e-8)
n_cam = (R_w2c @ n_flat_world.T).T
flip = (n_cam * view_cam).sum(dim=1) < 0
n_cam = n_cam.clone()
n_cam[flip] = -n_cam[flip]
W, H = viewpoint_cam.image_width, viewpoint_cam.image_height
fx = fov2focal(viewpoint_cam.FoVx, W)
fy = fov2focal(viewpoint_cam.FoVy, H)
cx, cy = W / 2.0, H / 2.0
u = (fx * xyz_cam[:, 0] / z + cx).long().clamp(0, W - 1)
v = (fy * xyz_cam[:, 1] / z + cy).long().clamp(0, H - 1)
valid = (z > 0.1) & (u >= 0) & (u < W) & (v >= 0) & (v < H)
if valid.any():
nmap = viewpoint_cam.mono_normal_map # [3, H, W]
n_mono = nmap[:, v[valid], u[valid]].T # [N_valid, 3]
n_est = n_cam[valid]
n_est = torch.nn.functional.normalize(n_est, dim=1)
n_gt = torch.nn.functional.normalize(n_mono, dim=1)
Ln = torch.abs(n_est - n_gt).sum(dim=1).mean()
Lnormal = 0.5 * Ln
loss += Lnormal
loss.backward()
iter_end.record()
with torch.no_grad():
# Progress bar
ema_loss_for_log = 0.4 * loss.item() + 0.6 * ema_loss_for_log
ema_Ll1depth_for_log = 0.4 * Ll1depth.item() + 0.6 * ema_Ll1depth_for_log
ema_Ldnormal_for_log = 0.4 * Ldnormal.item() + 0.6 * ema_Ldnormal_for_log
ema_Lscale_for_log = 0.4 * Lscale.item() + 0.6 * ema_Lscale_for_log
ema_Lnormal_for_log = 0.4 * Lnormal.item() + 0.6 * ema_Lnormal_for_log
if iteration % 10 == 0:
progress_bar.set_postfix({"Loss": f"{ema_loss_for_log:.{7}f}", "Depth Loss": f"{ema_Ll1depth_for_log:.{7}f}", "Depth Normal Loss": f"{ema_Ldnormal_for_log:.{7}f}", "Scale Loss": f"{ema_Lscale_for_log:.{7}f}", "Mono Normal Loss": f"{ema_Lnormal_for_log:.{7}f}"})
progress_bar.update(10)
if iteration == opt.iterations:
progress_bar.close()
# Log and save
training_report(tb_writer, iteration, Ll1, loss, l1_loss, iter_start.elapsed_time(iter_end), testing_iterations, scene, render, (pipe, background, 1., SPARSE_ADAM_AVAILABLE, None, dataset.train_test_exp), dataset.train_test_exp, lpips_fn)
if (iteration in saving_iterations):
print("\n[ITER {}] Saving Gaussians".format(iteration))
scene.save(iteration)
# Densification
if iteration < opt.densify_until_iter:
# Keep track of max radii in image-space for pruning
gaussians.max_radii2D[visibility_filter] = torch.max(
gaussians.max_radii2D[visibility_filter], radii[visibility_filter]
)
gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter)
if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0:
size_threshold = 20 if iteration > opt.opacity_reset_interval else None
gaussians.densify_and_prune(
opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold, radii, iteration
)
if iteration % opt.opacity_reset_interval == 0 or (
dataset.white_background and iteration == opt.densify_from_iter
):
gaussians.reset_opacity()
# Optimizer step
if iteration < opt.iterations:
gaussians.exposure_optimizer.step()
gaussians.exposure_optimizer.zero_grad(set_to_none = True)
if use_sparse_adam:
visible = radii > 0
gaussians.optimizer.step(visible, radii.shape[0])
gaussians.optimizer.zero_grad(set_to_none = True)
else:
gaussians.optimizer.step()
gaussians.optimizer.zero_grad(set_to_none = True)
if (iteration in checkpoint_iterations):
print("\n[ITER {}] Saving Checkpoint".format(iteration))
torch.save((gaussians.capture(), iteration), scene.model_path + "/chkpnt" + str(iteration) + ".pth")
def prepare_output_and_logger(args):
if not args.model_path:
if os.getenv('OAR_JOB_ID'):
unique_str=os.getenv('OAR_JOB_ID')
else:
unique_str = str(uuid.uuid4())
args.model_path = os.path.join("./output/", unique_str[0:10])
# Set up output folder
print("Output folder: {}".format(args.model_path))
os.makedirs(args.model_path, exist_ok = True)
with open(os.path.join(args.model_path, "cfg_args"), 'w') as cfg_log_f:
cfg_log_f.write(str(Namespace(**vars(args))))
# Create Tensorboard writer
tb_writer = None
if TENSORBOARD_FOUND:
tb_writer = SummaryWriter(args.model_path)
else:
print("Tensorboard not available: not logging progress")
return tb_writer
def training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs, train_test_exp, lpips_fn):
if tb_writer:
tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration)
tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration)
tb_writer.add_scalar('iter_time', elapsed, iteration)
# Report test and samples of training set
if iteration in testing_iterations:
torch.cuda.empty_cache()
validation_configs = (
{'name': 'test', 'cameras': scene.getTestCameras()},
{'name': 'train', 'cameras': [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]}
)
for config in validation_configs:
if config['cameras'] and len(config['cameras']) > 0:
l1_test = 0.0
psnr_test = 0.0
ssim_test = 0.0
lpips_test = 0.0
for idx, viewpoint in enumerate(config['cameras']):
image = torch.clamp(
renderFunc(viewpoint, scene.gaussians, *renderArgs)["render"],
0.0, 1.0
)
gt_image = torch.clamp(
viewpoint.original_image.to("cuda"),
0.0, 1.0
)
if train_test_exp:
image = image[..., image.shape[-1] // 2:]
gt_image = gt_image[..., gt_image.shape[-1] // 2:]
if tb_writer and (idx < 5):
tb_writer.add_images(
config['name'] + "_view_{}/render".format(viewpoint.image_name),
image[None],
global_step=iteration
)
if iteration == testing_iterations[0]:
tb_writer.add_images(
config['name'] + "_view_{}/ground_truth".format(viewpoint.image_name),
gt_image[None],
global_step=iteration
)
l1_test += l1_loss(image, gt_image).mean().double()
psnr_test += psnr(image, gt_image).mean().double()
ssim_val = ssim_metric(
image.unsqueeze(0),
gt_image.unsqueeze(0),
data_range=1.0
)
ssim_test += ssim_val.mean().double()
lpips_val = lpips_fn(
image.unsqueeze(0) * 2 - 1,
gt_image.unsqueeze(0) * 2 - 1
)
lpips_test += lpips_val.mean().double()
num_views = len(config['cameras'])
l1_test /= num_views
psnr_test /= num_views
ssim_test /= num_views
lpips_test /= num_views
print(
"\n[ITER {}] Evaluating {}: L1 {} PSNR {} SSIM {} LPIPS {}".format(
iteration,
config['name'],
l1_test,
psnr_test,
ssim_test,
lpips_test
)
)
if tb_writer:
tb_writer.add_scalar(
config['name'] + '/loss_viewpoint - l1_loss',
l1_test,
iteration
)
tb_writer.add_scalar(
config['name'] + '/loss_viewpoint - psnr',
psnr_test,
iteration
)
tb_writer.add_scalar(
config['name'] + '/loss_viewpoint - ssim',
ssim_test,
iteration
)
tb_writer.add_scalar(
config['name'] + '/loss_viewpoint - lpips',
lpips_test,
iteration
)
if tb_writer:
tb_writer.add_histogram(
"scene/opacity_histogram",
scene.gaussians.get_opacity,
iteration
)
tb_writer.add_scalar(
'total_points',
scene.gaussians.get_xyz.shape[0],
iteration
)
torch.cuda.empty_cache()
if __name__ == "__main__":
# Set up command line argument parser
parser = ArgumentParser(description="Training script parameters")
lp = ModelParams(parser)
op = OptimizationParams(parser)
pp = PipelineParams(parser)
parser.add_argument('--ip', type=str, default="127.0.0.1")
parser.add_argument('--port', type=int, default=6009)
parser.add_argument('--debug_from', type=int, default=-1)
parser.add_argument('--detect_anomaly', action='store_true', default=False)
parser.add_argument("--test_iterations", nargs="+", type=int, default=[7_000, 30_000])
parser.add_argument("--save_iterations", nargs="+", type=int, default=[7_000, 30_000])
parser.add_argument("--quiet", action="store_true")
parser.add_argument('--disable_viewer', action='store_true', default=False)
parser.add_argument("--checkpoint_iterations", nargs="+", type=int, default=[])
parser.add_argument("--start_checkpoint", type=str, default = None)
args = parser.parse_args(sys.argv[1:])
args.save_iterations.append(args.iterations)
print("Optimizing " + args.model_path)
# Initialize system state (RNG)
safe_state(args.quiet)
# Start GUI server, configure and run training
if not args.disable_viewer:
network_gui.init(args.ip, args.port)
torch.autograd.set_detect_anomaly(args.detect_anomaly)
training(lp.extract(args), op.extract(args), pp.extract(args), args.test_iterations, args.save_iterations, args.checkpoint_iterations, args.start_checkpoint, args.debug_from)
# All done
print("\nTraining complete.")