File size: 17,153 Bytes
b004d6f | 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 | from datetime import datetime
import random
from typing import Optional
import ast
import configargparse
import os
import numpy as np
import torch
from loaders.utils import Rays, namedtuple_map
from nerfacc.estimators.occ_grid import OccGridEstimator
from nerfacc.grid import ray_aabb_intersect, traverse_grids
from misc.transient_volrend import (
rendering_transient_single_path)
from torch.utils.tensorboard import SummaryWriter
import shutil
def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
def render_transient(
# scene
radiance_field: torch.nn.Module,
occupancy_grid: OccGridEstimator,
rays: Rays,
# rendering options
near_plane = 0,
far_plane = 2**15,
render_step_size: float = 1e-3,
cone_angle: float = 0.0,
alpha_thre: float = 0.0,
# test options
# only useful for dnerf
chunk = 8192*128,
use_normals = False,
args = None
):
"""Render the pixels of an image."""
rays_shape = rays.origins.shape
if len(rays_shape) == 3:
height, width, _ = rays_shape
n_rays = height * width
rays = namedtuple_map(
lambda r: r.reshape([n_rays] + list(r.shape[2:])), rays
)
else:
n_rays, _ = rays_shape
results = []
def rgb_sigma_fn(t_starts, t_ends, ray_indices):
t_origins = chunk_rays.origins[ray_indices]
t_dirs = chunk_rays.viewdirs[ray_indices]
positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0
rgbs, sigmas = radiance_field(positions, t_dirs)
return rgbs, sigmas.squeeze(-1)
for i in range(0, n_rays, chunk):
chunk_rays = namedtuple_map(lambda r: r[i : i + chunk], rays)
def sigma_fn(t_starts, t_ends, ray_indices):
t_origins = chunk_rays.origins[ray_indices]
t_dirs = chunk_rays.viewdirs[ray_indices]
positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0
sigmas = radiance_field.query_density(positions)
return sigmas.squeeze(-1)
ray_indices, t_starts, t_ends = occupancy_grid.sampling(
chunk_rays.origins,
chunk_rays.viewdirs,
sigma_fn=sigma_fn,
near_plane=near_plane,
far_plane=far_plane,
render_step_size=render_step_size,
stratified=radiance_field.training,
cone_angle=cone_angle,
alpha_thre=alpha_thre,
)
rgb, opacity, depth, depth_variance, comp_weights, raw_rgbs = rendering_transient_single_path(
t_starts=t_starts,
t_ends=t_ends,
ray_indices=ray_indices,
n_rays=n_rays,
# radiance field
rgb_sigma_fn=rgb_sigma_fn,
# rendering options
render_bkgd=None,
args = args
)
chunk_results_single = [rgb, opacity, depth, depth_variance, comp_weights, raw_rgbs, len(t_starts)]
results.append(chunk_results_single)
colors_single, opacities_single, depths_single, depths_variance, densities, raw_rgbs, n_rendering_samples = [
torch.cat(r, dim=0) if isinstance(r[0], torch.Tensor) else r
for r in zip(*results)
]
normals_loss = 0
colors = torch.reshape(colors_single, (-1, args.n_bins, 3))
return {'colors': colors.view((*rays_shape[:-1], -1)),
'opacities': opacities_single.view((*rays_shape[:-1], -1)),
'depths': depths_single.view((*rays_shape[:-1], -1)),
'depths_variance' : depths_variance.view((*rays_shape[:-1], -1)),
'n_rendering_samples': sum(n_rendering_samples),
'normals_loss': normals_loss,
'comp_weights': comp_weights,
"raw_rgbs":raw_rgbs}
def parse_list(arg):
try:
return ast.literal_eval(arg)
except (SyntaxError, ValueError):
raise configargparse.ArgumentTypeError(f"Invalid list format: {arg}")
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise configargparse.ArgumentTypeError('Boolean value expected.')
def load_args(eval = False, parser= None):
# parser = configargparse.ArgumentParser()
if not eval:
parser = configargparse.ArgumentParser()
has_test_config = (
eval
and parser is not None
and hasattr(parser, "_option_string_actions")
and "--test_config" in parser._option_string_actions
)
my_config_default = None if has_test_config else "./configs/train/simulated/bench_two_views.ini"
parser.add('-c', '--my-config',
is_config_file=True,
default=my_config_default,
help='Path to config file.'
)
parser.add_argument(
'--exp_name',
type=str,
default='lego_two_views',
help='Experiment name.'
)
parser.add_argument(
"--aabb",
nargs='+',
type = lambda s: ast.literal_eval(s),
default="[-1.5,-1.5,-1.5,1.5,1.5, 1.5]",
help="AABB size.",
)
parser.add_argument(
"--test_chunk_size",
type=int,
default=512,
help="Test chunk size..",
)
parser.add_argument(
"--num_rays_per_batch",
type=int,
default=512,
help="Number of rays per batch.",
)
parser.add_argument(
"--starting_rays_per_pixel",
type=int,
default=1,
help="Starting rays per pixels.",
)
parser.add_argument(
"--tfilter_sigma",
type=int,
default=3,
help="Temporal filter standard deviation.",
)
parser.add_argument(
"--space_carving",
type=float,
default=7*1e-3,
help="Space carvig regaularization strength.",
)
# parser.add_argument(
# "--dataset_scale",
# type=int,
# default=46,
# help="Scale for all transient images.",
# )
parser.add_argument(
"--rfilter_sigma",
type=float,
default=0.15,
help="Spatial filter standard deviation.",
)
parser.add_argument(
"--exposure_time",
type=float,
default=0.01,
help="Exposure length per bin in meters.",
)
parser.add_argument(
"--lr",
type=float,
default=1e-3,
help="Learning rate.",
)
parser.add_argument(
"--steps_til_checkpoint",
type=int,
default=20000,
help="Steps per checkpoint.",
)
parser.add_argument(
"--n_bins",
type=int,
default=1200,
help="Number of bins.",
)
parser.add_argument(
"--img_shape",
type=int,
default=512,
help="Shape of training image.",
)
parser.add_argument(
"--sample_as_per_distribution",
action="store_true",
help="Sample as per distribution or uniformly.",
)
parser.add_argument(
"--render_n_samples",
type=int,
default=4096,
help="Num samples per ray.",
)
parser.add_argument(
"--exp",
type=str2bool,
default="true",
help="Use double exp.",
)
parser.add_argument(
"--max_steps",
type=int,
default=300000,
help="Max number of steps.",
)
parser.add_argument(
"--near_plane",
type=float,
default=0.0,
help="Near plane value.",
)
parser.add_argument(
"--alpha_thre",
type=float,
default=0,
)
parser.add_argument(
"--far_plane",
type=float,
default=float(2**15),
help="Far plane value.",
)
parser.add_argument(
"--version",
type=str,
default="simulated",
choices=["captured", "simulated"],
help="Dataset being trained, captured or simulated.",
)
parser.add_argument(
"--occ_thre",
type=float,
default=0.01,
help="Occupancy threshold",
)
parser.add_argument(
"--thold_warmup",
type=int,
default=-1,
help="Warmup period for the occupancy threshold.",
)
parser.add_argument(
"--final",
type=str2bool,
default="false",
help="If final version or debug mode (creates dated folder).",
)
parser.add_argument(
"--grid_resolution",
type=int,
default=128,
help="Occgrid resolution.",
)
parser.add_argument(
"--grid_nlvl",
type=int,
default=1,
help="Number of grid levels.",
)
parser.add_argument(
"--outpath",
type=str,
default="./results",
help="Path to results folder.",
)
parser.add_argument(
"--data_root_fp",
type=str,
default="./data/lego_data/lego_jsons/two_views",
help="Root of dataset directory (where the transforms directory is).",
)
parser.add_argument(
"--pulse_path",
type=str,
default="./datasets/pulse_low_flux.mat",
help="Path to pulse for captured dataset.",
)
parser.add_argument(
"--intrinsics",
type=str,
default="./data/lego_data/lego_jsons/two_views",
help="Path to intrinsics for captured dataset",
)
parser.add_argument(
"--pixels_to_plot",
nargs='+',
type = lambda s: ast.literal_eval(s),
default=[(16, 16), (20, 16), (28, 25)],
help="Pixels used for plotting in the summary.",
)
parser.add_argument(
"--img_scale",
type=int,
default=100,
help="Image scale used in summary.",
)
parser.add_argument(
"--num_views",
type=int,
default=2,
help="Number of views trained on.",
)
parser.add_argument(
"--img_shape_test",
type=int,
default=64,
help="Test image shape.",
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Seed.",
)
parser.add_argument(
"--device",
type=str,
default="cuda:7",
help="Device.",
)
parser.add_argument("--cone_angle", type=float, default=0.0)
parser.add_argument(
"--resume",
type=str,
default=None,
help="Path to a checkpoint directory to resume training from.",
)
args = parser.parse_args()
return args
def make_save_folder(args):
now = datetime.now()
now = now.strftime("%m-%d_%H:%M:%S")
exp_name = args.exp_name + "_" + now
outpath = os.path.join(args.outpath, exp_name)
os.makedirs(args.outpath, exist_ok=True)
os.mkdir(outpath)
shutil.copy(args.my_config, os.path.join(outpath, "params.txt"))
with open(os.path.join(outpath, "params_full.txt"), "w") as out_file:
param_list = []
for key, value in vars(args).items():
if type(value) == list:
value = [eval(f"{x}") for x in value]
elif type(value) != int and type(value) != float:
value = str(value)
value = f"'{value}'"
param_list.append("%s= %s" % (key, value))
out_file.write('\n'.join(param_list))
return outpath
def make_save_folder_final(args, optimizer, scheduler, radiance_field, occupancy_grid):
outpath = os.path.join(args.outpath, args.exp_name)
if not os.path.isdir(outpath):
os.makedirs(outpath, exist_ok=True)
with open(os.path.join(outpath, "params_full.txt"), "w") as out_file:
param_list = []
for key, value in vars(args).items():
if type(value) != int and type(value) != float:
value = str(value)
value = f"'{value}'"
param_list.append("%s= %s" % (key, value))
out_file.write('\n'.join(param_list))
step = 0
writer = SummaryWriter(log_dir=outpath)
else:
ckpt_path_var = os.path.join(outpath, 'variables.pth')
if not os.path.isfile(ckpt_path_var):
print(f"warning: '{ckpt_path_var}' not found; starting fresh in existing directory.")
step = 0
writer = SummaryWriter(log_dir=outpath)
return writer, step, outpath
ckpt = torch.load(ckpt_path_var, map_location="cpu")
step = int(ckpt.get('step', 0))
ckpt_path_rf = os.path.join(outpath, 'radiance_field_%04d.pth' % (step))
ckpt_path_oc = os.path.join(outpath, 'occupancy_grid_%04d.pth' % (step))
ckpt_path_opt = os.path.join(outpath, 'optimizer_%04d.pth' % (step))
ckpt_path_sch = os.path.join(outpath, 'scheduler_%04d.pth' % (step))
if not (os.path.isfile(ckpt_path_rf) and os.path.isfile(ckpt_path_oc)):
print(
"warning: model checkpoint files missing for saved step; "
"starting fresh optimizer/model state."
)
step = 0
writer = SummaryWriter(log_dir=outpath)
return writer, step, outpath
ckpt = torch.load(ckpt_path_rf, map_location=args.device)
radiance_field.load_state_dict(ckpt)
radiance_field = radiance_field.to(args.device)
ckpt = torch.load(ckpt_path_oc, map_location=args.device)
occupancy_grid.load_state_dict(ckpt)
occupancy_grid = occupancy_grid.to(args.device)
if os.path.isfile(ckpt_path_opt):
ckpt = torch.load(ckpt_path_opt, map_location=args.device)
optimizer.load_state_dict(ckpt)
else:
print(f"warning: optimizer checkpoint missing at '{ckpt_path_opt}', using fresh optimizer state.")
if os.path.isfile(ckpt_path_sch):
ckpt = torch.load(ckpt_path_sch, map_location=args.device)
scheduler.load_state_dict(ckpt)
else:
print(f"warning: scheduler checkpoint missing at '{ckpt_path_sch}', using fresh scheduler state.")
print(f"previous checkpoint loaded; current step: {step}")
writer = SummaryWriter(log_dir=outpath)
return writer, step, outpath
def resume_training(args, optimizer, scheduler, radiance_field, occupancy_grid):
"""Load a previous checkpoint and prepare writer/step/outpath."""
ckpt_dir = args.resume
if ckpt_dir is None:
raise ValueError("args.resume is None, cannot resume.")
if not os.path.isdir(ckpt_dir):
raise FileNotFoundError(f"Checkpoint directory not found: {ckpt_dir}")
variables_path = os.path.join(ckpt_dir, "variables.pth")
step = 0
rays_per_pixel = None
if os.path.isfile(variables_path):
ckpt_vars = torch.load(variables_path, map_location="cpu")
step = ckpt_vars.get("step", 0)
rays_per_pixel = ckpt_vars.get("rays_per_pixel")
else:
ckpt_steps = []
for name in os.listdir(ckpt_dir):
if name.startswith("radiance_field_") and name.endswith(".pth"):
try:
ckpt_steps.append(int(name.split("_")[-1].split(".")[0]))
except ValueError:
continue
if not ckpt_steps:
raise FileNotFoundError(
"No checkpoint files found to resume from in "
f"{ckpt_dir}. Expected radiance_field_XXXX.pth."
)
step = max(ckpt_steps)
rf_path = os.path.join(ckpt_dir, f"radiance_field_{step:04d}.pth")
oc_path = os.path.join(ckpt_dir, f"occupancy_grid_{step:04d}.pth")
opt_path = os.path.join(ckpt_dir, f"optimizer_{step:04d}.pth")
sch_path = os.path.join(ckpt_dir, f"scheduler_{step:04d}.pth")
for required_path in [rf_path, oc_path]:
if not os.path.isfile(required_path):
raise FileNotFoundError(f"Missing checkpoint file: {required_path}")
radiance_field.load_state_dict(
torch.load(rf_path, map_location=args.device)
)
radiance_field = radiance_field.to(args.device)
occupancy_grid.load_state_dict(
torch.load(oc_path, map_location=args.device)
)
occupancy_grid = occupancy_grid.to(args.device)
if os.path.isfile(opt_path):
optimizer.load_state_dict(torch.load(opt_path, map_location=args.device))
else:
print(f"warning: missing optimizer checkpoint '{opt_path}', using fresh optimizer state.")
if os.path.isfile(sch_path):
scheduler.load_state_dict(torch.load(sch_path, map_location=args.device))
else:
print(f"warning: missing scheduler checkpoint '{sch_path}', using fresh scheduler state.")
writer = SummaryWriter(log_dir=ckpt_dir)
args.outpath = ckpt_dir
return writer, step, ckpt_dir, rays_per_pixel
if __name__=="__main__":
pass
|