shuinb's picture
Upload STB code utilities
b004d6f verified
Raw
History Blame Contribute Delete
19.7 kB
import math
import os
import configargparse
import numpy as np
import pandas as pd
import scipy.io as sio
import torch
import torch.multiprocessing as mp
import tqdm
from nerfacc.estimators.occ_grid import OccGridEstimator
from torch.utils.tensorboard import SummaryWriter
from misc.summary import write_summary_histogram
from misc.transient_volrend import torch_laser_kernel
from radiance_fields.ngp import NGPRadianceField
from utils import (
load_args,
make_save_folder,
make_save_folder_final,
render_transient,
set_random_seed,
)
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method("spawn")
def load_args_ours():
parser = configargparse.ArgumentParser()
parser.add_argument(
"--irf_path",
type=str,
default="",
help="Path to IRF file. Supports .csv/.npy/.mat/.pt. If empty, fallback to --pulse_path.",
)
parser.add_argument(
"--irf_column",
type=str,
default="irf",
help="CSV column name for IRF values.",
)
parser.add_argument(
"--irf_half_window",
type=int,
default=50,
help="Half window size for cropping around IRF peak. Set <=0 to disable crop.",
)
parser.add_argument(
"--no_irf_reverse",
action="store_true",
help="Disable reverse before Conv1d kernel creation.",
)
parser.add_argument(
"--measurement_root",
type=str,
default="",
help="Optional root directory of measurement files (.npz/.txt/.pt/.h5).",
)
parser.add_argument(
"--data_exts",
type=str,
default=".npz,.txt,.pt,.h5,.hdf5",
help="Comma-separated measurement extensions lookup order.",
)
parser.add_argument(
"--bin_width_s_loader",
type=float,
default=None,
help="Bin width in seconds for shift resampling. If empty, derived from exposure_time / c.",
)
parser.add_argument(
"--img_height",
type=int,
default=None,
help="Training image height. If empty, use --img_shape.",
)
parser.add_argument(
"--img_width",
type=int,
default=None,
help="Training image width. If empty, use --img_shape.",
)
parser.add_argument(
"--img_height_test",
type=int,
default=None,
help="Test image height. If empty, use --img_shape_test.",
)
parser.add_argument(
"--img_width_test",
type=int,
default=None,
help="Test image width. If empty, use --img_shape_test.",
)
parser.add_argument(
"--meas_peak_min",
type=float,
default=100.0,
help=(
"Minimum raw histogram peak per pixel to keep it in photometric loss. "
"<=0 disables this mask. Threshold is interpreted in pre-normalization measurement scale."
),
)
parser.add_argument(
"--invalid_mask_path",
type=str,
default="",
help=(
"Path to offset map used to build valid-pixel mask. "
"Pixels with offset > invalid_mask_invalid_gt are excluded from training/eval."
),
)
parser.add_argument(
"--invalid_mask_invalid_gt",
type=float,
default=10.0,
help="Offset threshold for invalid pixels in invalid_mask_path.",
)
return load_args(eval=True, parser=parser)
def _to_numpy(x):
if isinstance(x, np.ndarray):
return x
if isinstance(x, torch.Tensor):
return x.detach().cpu().numpy()
return np.asarray(x)
def _load_irf_series(path: str, column: str) -> np.ndarray:
ext = os.path.splitext(path)[1].lower()
if ext == ".csv":
df = pd.read_csv(path, sep=",")
if column in df.columns:
arr = df[column].to_numpy(dtype=np.float64)
else:
numeric_cols = [c for c in df.columns if np.issubdtype(df[c].dtype, np.number)]
if not numeric_cols:
raise ValueError(f"No numeric columns found in IRF CSV: {path}")
arr = df[numeric_cols[0]].to_numpy(dtype=np.float64)
return arr.squeeze()
if ext == ".npy":
return np.load(path).astype(np.float64).squeeze()
if ext == ".mat":
mat = sio.loadmat(path)
if "out" in mat:
return _to_numpy(mat["out"]).astype(np.float64).squeeze()
for value in mat.values():
if isinstance(value, np.ndarray) and value.ndim >= 1 and value.size > 1:
return _to_numpy(value).astype(np.float64).squeeze()
raise ValueError(f"Cannot find valid IRF series in mat file: {path}")
if ext == ".pt":
return _to_numpy(torch.load(path, map_location="cpu")).astype(np.float64).squeeze()
raise ValueError(f"Unsupported IRF extension: {ext}")
def build_irf_kernel(args, device):
irf_path = args.irf_path if args.irf_path else args.pulse_path
if not irf_path:
raise ValueError("IRF path is empty. Set --irf_path or --pulse_path.")
irf = _load_irf_series(irf_path, args.irf_column)
if irf.ndim != 1:
irf = irf.reshape(-1)
if irf.size == 0:
raise ValueError(f"Loaded empty IRF from: {irf_path}")
peak_idx = int(np.argmax(irf))
if args.irf_half_window and args.irf_half_window > 0:
lo = max(0, peak_idx - int(args.irf_half_window))
hi = min(len(irf), peak_idx + int(args.irf_half_window) + 1)
irf = irf[lo:hi]
irf = irf / (irf.sum() + 1e-8)
if not args.no_irf_reverse:
irf = irf[::-1].copy()
laser = torch.tensor(irf, dtype=torch.float32, device=device)
return torch_laser_kernel(laser, device=device)
def run():
args = load_args_ours()
device = torch.device(args.device)
args.device = str(device)
if device.type == "cuda":
if not torch.cuda.is_available():
raise RuntimeError(f"CUDA device requested but CUDA is unavailable: {device}")
torch.cuda.set_device(device)
torch.cuda.empty_cache()
set_random_seed(args.seed)
train_h = int(args.img_height) if args.img_height is not None else int(args.img_shape)
train_w = int(args.img_width) if args.img_width is not None else int(args.img_shape)
test_h = int(args.img_height_test) if args.img_height_test is not None else int(args.img_shape_test)
test_w = int(args.img_width_test) if args.img_width_test is not None else int(args.img_shape_test)
img_shape = (train_h, train_w)
img_shape_test = (test_h, test_w)
aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
train_dataset_kwargs = {}
test_dataset_kwargs = {}
rfilter_sigma = args.rfilter_sigma
max_steps = args.max_steps
sample_as_per_distribution = args.sample_as_per_distribution
target_sample_batch_size = 1 << 16
if args.version == "simulated":
from loaders.loader_synthetic import SubjectLoaderTransient as SubjectLoader
test_dataset_kwargs = {
"img_shape": img_shape_test,
"have_images": True,
"n_bins": args.n_bins,
"color_bkgd_aug": "black",
"rfilter_sigma": rfilter_sigma,
"sample_as_per_distribution": sample_as_per_distribution,
}
train_dataset_kwargs = {
"img_shape": img_shape,
"n_bins": args.n_bins,
"color_bkgd_aug": "black",
"rfilter_sigma": rfilter_sigma,
"sample_as_per_distribution": sample_as_per_distribution,
}
train_dataset = SubjectLoader(
root_fp=args.data_root_fp,
subject_id=args.exp_name,
split="train",
num_rays=target_sample_batch_size // args.render_n_samples,
**train_dataset_kwargs,
num_views=args.num_views,
)
train_dataset.camtoworlds = train_dataset.camtoworlds.to(device)
train_dataset.K = train_dataset.K.to(device)
test_dataset = SubjectLoader(
root_fp=args.data_root_fp,
subject_id=args.exp_name,
split="test",
num_rays=None,
**test_dataset_kwargs,
)
if test_dataset_kwargs["have_images"]:
test_dataset.images = test_dataset.images.to(device)
test_dataset.camtoworlds = test_dataset.camtoworlds.to(device)
test_dataset.K = test_dataset.K.to(device)
else:
from loaders.loader_captured_ours import LearnRays, SubjectLoaderTransientRealOurs as SubjectLoader
params = np.load(args.intrinsics, allow_pickle=True)[()]
shift = _to_numpy(params["shift"])
rays = _to_numpy(params["rays"])
source_img_shape = (int(rays.shape[0]), int(rays.shape[1]))
measurement_root = args.measurement_root.strip() or None
invalid_mask_path = args.invalid_mask_path.strip() or None
data_exts = tuple(e.strip() for e in args.data_exts.split(",") if e.strip())
if args.bin_width_s_loader is not None:
bin_width_s_loader = float(args.bin_width_s_loader)
else:
bin_width_s_loader = float(args.exposure_time) / 299792458.0
test_dataset_kwargs = {
"img_shape": img_shape_test,
"have_images": True,
"n_bins": args.n_bins,
"color_bkgd_aug": "black",
"rfilter_sigma": rfilter_sigma,
"sample_as_per_distribution": sample_as_per_distribution,
"shift": shift,
"measurement_root": measurement_root,
"data_exts": data_exts,
"bin_width_s": bin_width_s_loader,
"source_img_shape": source_img_shape,
"invalid_mask_path": invalid_mask_path,
"invalid_mask_invalid_gt": float(args.invalid_mask_invalid_gt),
}
train_dataset_kwargs = {
"img_shape": img_shape,
"n_bins": args.n_bins,
"color_bkgd_aug": "black",
"rfilter_sigma": rfilter_sigma,
"sample_as_per_distribution": sample_as_per_distribution,
"shift": shift,
"measurement_root": measurement_root,
"data_exts": data_exts,
"bin_width_s": bin_width_s_loader,
"source_img_shape": source_img_shape,
"invalid_mask_path": invalid_mask_path,
"invalid_mask_invalid_gt": float(args.invalid_mask_invalid_gt),
}
train_dataset = SubjectLoader(
root_fp=args.data_root_fp,
subject_id=args.exp_name,
split="train",
num_rays=target_sample_batch_size // args.render_n_samples,
**train_dataset_kwargs,
)
train_dataset.camtoworlds = train_dataset.camtoworlds.to(device)
train_dataset.K = LearnRays(rays, device=device, img_shape=img_shape).to(device)
test_dataset = SubjectLoader(
root_fp=args.data_root_fp,
subject_id=args.exp_name,
split="test",
num_rays=None,
**test_dataset_kwargs,
)
if test_dataset_kwargs["have_images"]:
test_dataset.images = test_dataset.images.to(device)
test_dataset.camtoworlds = test_dataset.camtoworlds.to(device)
test_dataset.K = LearnRays(rays, device=device, img_shape=img_shape_test).to(device)
args.laser_kernel = build_irf_kernel(args, device=device)
train_dataset_scale = float(_to_numpy(train_dataset.max).reshape(-1)[0])
if train_dataset_scale <= 0:
train_dataset_scale = 1.0
scene_aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
render_step_size = ((scene_aabb[3:] - scene_aabb[:3]).max() * math.sqrt(3) / args.render_n_samples).item()
grad_scaler = torch.cuda.amp.GradScaler(2**10)
radiance_field = NGPRadianceField(
use_viewdirs=True,
aabb=args.aabb,
unbounded=False,
radiance_activation=torch.exp,
args=args,
).to(device)
optimizer = torch.optim.Adam(radiance_field.parameters(), lr=args.lr, eps=1e-15)
scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer,
milestones=[max_steps // 2, max_steps * 3 // 4, max_steps * 9 // 10],
gamma=0.33,
)
occupancy_grid = OccGridEstimator(
roi_aabb=aabb,
resolution=args.grid_resolution,
levels=args.grid_nlvl,
).to(device)
if args.final:
writer, step, outpath = make_save_folder_final(
args,
optimizer,
scheduler,
radiance_field,
occupancy_grid,
)
args.outpath = outpath
else:
outpath = make_save_folder(args)
args.outpath = outpath
writer = SummaryWriter(log_dir=outpath)
step = 0
# When resuming (final=True), show progress from resumed step.
pbar = tqdm.tqdm(total=args.max_steps, initial=min(step, args.max_steps))
zero_sample_streak = 0
while step < max_steps:
pbar.update(1)
if args.version == "simulated" and step % 1000 == 0:
if train_dataset.rep < 30:
train_dataset.rep += 2
radiance_field.train()
i = torch.randint(0, len(train_dataset), (1,)).item()
data = train_dataset[i]
rays = data["rays"]
num_base_rays = int(rays.origins.shape[0] / train_dataset.rep)
pixs = torch.reshape(
data["pixels"][:num_base_rays],
(-1, args.n_bins, 3),
)
data_valid_mask = data.get("valid_mask")
if data_valid_mask is not None:
data_valid_mask = data_valid_mask.to(device=device, dtype=torch.bool).reshape(-1)
if data_valid_mask.numel() < num_base_rays:
raise ValueError(
f"valid_mask has too few elements: {data_valid_mask.numel()} < base rays {num_base_rays}"
)
data_valid_mask = data_valid_mask[:num_base_rays]
else:
data_valid_mask = torch.ones(pixs.shape[0], dtype=torch.bool, device=device)
# Use measurement peak (pre-log) to exclude low-signal / out-of-range pixels.
if args.version == "captured" and float(args.meas_peak_min) > 0:
peak_thre_norm = float(args.meas_peak_min) / float(train_dataset_scale)
meas_peak = torch.amax(pixs[..., 0], dim=-1)
meas_valid_mask = meas_peak >= peak_thre_norm
else:
meas_valid_mask = torch.ones(pixs.shape[0], dtype=torch.bool, device=pixs.device)
def occ_eval_fn(x):
density = radiance_field.query_density(x)
density = torch.nan_to_num(density, nan=0.0, posinf=0.0, neginf=0.0)
return density.squeeze(-1) * render_step_size
base_occ_thre = float(args.occ_thre)
if args.version == "captured":
warmup_steps = int(args.thold_warmup) if int(args.thold_warmup) > 0 else 10000
occ_thre = min(base_occ_thre, 1e-6) if step < warmup_steps else base_occ_thre
else:
occ_thre = base_occ_thre
try:
occupancy_grid.update_every_n_steps(step=step, occ_eval_fn=occ_eval_fn, occ_thre=occ_thre)
except RuntimeError as ex:
if "invalid configuration argument" in str(ex).lower():
raise RuntimeError(
"CUDA invalid configuration argument during occupancy update. "
"This is often an async CUDA error from an earlier kernel. "
"Rerun with CUDA_LAUNCH_BLOCKING=1 to get the first failing op."
) from ex
raise
out = render_transient(
radiance_field,
occupancy_grid,
rays,
near_plane=args.near_plane,
far_plane=args.far_plane,
render_step_size=render_step_size,
cone_angle=args.cone_angle,
alpha_thre=args.alpha_thre,
use_normals=False,
args=args,
)
rgb, acc, n_rendering_samples, comp_weights = [
out[key] for key in ["colors", "opacities", "n_rendering_samples", "comp_weights"]
]
del out
if n_rendering_samples == 0:
# Avoid infinite loops where step never advances.
zero_sample_streak += 1
if zero_sample_streak % 100 == 0:
print(
f"[WARN] n_rendering_samples==0 streak={zero_sample_streak} "
f"at step={step}. Try lowering occ_thre (current={occ_thre})."
)
step += 1
continue
zero_sample_streak = 0
train_dataset.update_num_rays(args.num_rays_per_batch)
alive_ray_mask = acc.squeeze(-1) > 0
alive_ray_mask = alive_ray_mask.reshape(train_dataset.rep, -1)
alive_ray_mask = alive_ray_mask.sum(0).bool()
supervised_mask = alive_ray_mask & meas_valid_mask & data_valid_mask
rgba = torch.reshape(rgb, (-1, args.n_bins, 3)) * data["weights"][:, None, None]
carve_mask = pixs.sum(-1).repeat(train_dataset.rep, 1) < 1e-7
valid_mask_flat = data_valid_mask.repeat(train_dataset.rep)[:, None]
carve_mask = carve_mask & valid_mask_flat.expand(-1, args.n_bins)
carve_vals = comp_weights[carve_mask]
if carve_vals.numel() > 0:
comp_weights = carve_vals.mean()
else:
comp_weights = torch.tensor(0.0, device=device, dtype=rgba.dtype)
rgb = torch.zeros((int(rgba.shape[0] / train_dataset.rep), args.n_bins, 3), device=device)
index = (
torch.arange(int(rgba.shape[0] / train_dataset.rep), device=device)
.repeat(train_dataset.rep)[:, None, None]
.expand(-1, args.n_bins, 3)
)
rgb.scatter_add_(0, index.type(torch.int64), rgba)
pixs = torch.log(pixs + 1)
rgb = torch.log(rgb + 1)
if supervised_mask.any():
photometric_loss = torch.nn.functional.l1_loss(rgb[supervised_mask], pixs[supervised_mask])
else:
photometric_loss = torch.tensor(0.0, device=device)
loss = photometric_loss + comp_weights * args.space_carving
optimizer.zero_grad()
grad_scaler.scale(loss).backward()
optimizer.step()
scheduler.step()
writer.add_scalar("Loss/train", loss.detach().cpu().numpy(), step)
writer.add_scalar("Loss/photometric", photometric_loss.detach().cpu().numpy(), step)
writer.add_scalar("Mask/supervised_ratio", supervised_mask.float().mean().detach().cpu().numpy(), step)
if not step % args.steps_til_checkpoint:
path = os.path.join(outpath, "radiance_field_{:04d}.pth".format(step))
torch.save(radiance_field.state_dict(), path)
path = os.path.join(outpath, "occupancy_grid_{:04d}.pth".format(step))
torch.save(occupancy_grid.state_dict(), path)
path = os.path.join(outpath, "optimizer_{:04d}.pth".format(step))
torch.save(optimizer.state_dict(), path)
path = os.path.join(outpath, "scheduler_{:04d}.pth".format(step))
torch.save(scheduler.state_dict(), path)
torch.save({"step": step, "rays_per_pixel": train_dataset.rep}, os.path.join(outpath, "variables.pth"))
if test_dataset_kwargs["have_images"]:
write_summary_histogram(
radiance_field,
occupancy_grid,
writer,
test_dataset,
step,
render_step_size,
args,
)
step += 1
if __name__ == "__main__":
run()