mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-06 07:48:50 +08:00
Pipeline v2 (#258)
* Model class done, pipeline class still needs more visualization stuffs * Renaming the BaseDataContainer to DataloaderOutputs and adding documentation * Pushing more documentation, removing some trivial functions * Updating dict typing * Removing config dicts for collider * Passing tests * Pushing shell new dataloader * Saving work, need to fix NGP model's get_loss_dict and Pipeline * V1 of the ngp pipeline should be done. Need train script and debugging * Updating with latest instant-ngp code * Syntax updates from latest ngp graph code * Linter, removing unneeded code in new NGP graph code * Style * Should be good now. Linter is happy and the code is verbatum current instant-ngp * Everything done except novel view testing code * Fixing some nitpicks * Debugging dataloader * merged master * WOP. integrating pipeline with configs and notebook demo * removing model folder * a lot of name changing from Graph to Model * in progress... changing trainer to use pipeline... broken right now * pipeline code runs * switched to val dataset * makes run_eval.py work * updated configs for pipeline change * fixing test_run_train script * fixing black and linting * fix docs * small updates to trainer Co-authored-by: Jake Austin <jake-austin@berkeley.edu>
This commit is contained in:
1 parent
670c2a01db
commit
0b042be956
55 files changed
+8595
-8263
No files matched your search
@@ -0,0 +1,182 @@
|
||||
# Copyright 2022 The Plenoptix Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
Implementation of Instant NGP.
|
||||
"""
|
||||
|
||||
from typing import Dict, List
|
||||
|
||||
import torch
|
||||
from torch.nn import Parameter
|
||||
from torchmetrics import PeakSignalNoiseRatio
|
||||
from torchmetrics.functional import structural_similarity_index_measure
|
||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||
|
||||
import nerfactory.cuda as nerfactory_cuda
|
||||
from nerfactory.cameras.rays import RayBundle
|
||||
from nerfactory.fields.instant_ngp_field import field_implementation_to_class
|
||||
from nerfactory.fields.modules.field_heads import FieldHeadNames
|
||||
from nerfactory.models.base import Model
|
||||
from nerfactory.models.modules.ray_sampler import NGPSpacedSampler
|
||||
from nerfactory.optimizers.loss import MSELoss
|
||||
from nerfactory.utils import colors, misc, visualization, writer
|
||||
from nerfactory.utils.callbacks import Callback
|
||||
|
||||
|
||||
class NGPModel(Model):
|
||||
"""Instant NGP model
|
||||
|
||||
Args:
|
||||
field_implementation (str): one of "torch" or "tcnn", or other fields in 'field_implementation_to_class'
|
||||
kwargs: additional params to pass up to the parent class model
|
||||
"""
|
||||
|
||||
def __init__(self, field_implementation="torch", **kwargs) -> None:
|
||||
assert field_implementation in field_implementation_to_class
|
||||
self.field_implementation = field_implementation
|
||||
self.field = None
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def get_training_callbacks(self) -> List[Callback]:
|
||||
assert self.density_field is not None
|
||||
return [
|
||||
Callback(
|
||||
update_every_num_iters=self.density_field.update_every_num_iters,
|
||||
func=self.density_field.update_density_grid,
|
||||
density_eval_func=self.field.density_fn, # type: ignore
|
||||
)
|
||||
]
|
||||
|
||||
def populate_fields(self):
|
||||
"""Set the fields."""
|
||||
# torch or tiny-cuda-nn version
|
||||
self.field = field_implementation_to_class[self.field_implementation](self.scene_bounds.aabb)
|
||||
|
||||
def populate_misc_modules(self):
|
||||
# samplers
|
||||
self.sampler = NGPSpacedSampler(num_samples=1024, density_field=self.density_field)
|
||||
|
||||
# losses
|
||||
self.rgb_loss = MSELoss()
|
||||
|
||||
# metrics
|
||||
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
|
||||
self.ssim = structural_similarity_index_measure
|
||||
self.lpips = LearnedPerceptualImagePatchSimilarity()
|
||||
|
||||
def get_param_groups(self) -> Dict[str, List[Parameter]]:
|
||||
param_groups = {}
|
||||
if self.field is None:
|
||||
raise ValueError("populate_fields() must be called before get_param_groups")
|
||||
param_groups["fields"] = list(self.field.parameters())
|
||||
return param_groups
|
||||
|
||||
@torch.cuda.amp.autocast()
|
||||
def get_outputs(self, ray_bundle: RayBundle):
|
||||
# TODO(ruilongli)
|
||||
# - train test difference
|
||||
# - visualize "depth_density_grid"
|
||||
num_rays = len(ray_bundle)
|
||||
device = ray_bundle.origins.device
|
||||
|
||||
if self.field is None:
|
||||
raise ValueError("populate_fields() must be called before get_outputs")
|
||||
ray_samples, packed_info, t_min, t_max = self.sampler(ray_bundle, self.field.aabb)
|
||||
|
||||
field_outputs = self.field.forward(ray_samples)
|
||||
rgbs = field_outputs[FieldHeadNames.RGB]
|
||||
sigmas = field_outputs[FieldHeadNames.DENSITY]
|
||||
|
||||
# accumulate all the rays start from zero opacity
|
||||
opacities = torch.zeros((num_rays, 1), device=device)
|
||||
(
|
||||
accumulated_weight,
|
||||
accumulated_depth,
|
||||
accumulated_color,
|
||||
alive_ray_mask,
|
||||
) = nerfactory_cuda.VolumeRenderer.apply(
|
||||
packed_info,
|
||||
ray_samples.frustums.starts,
|
||||
ray_samples.frustums.ends,
|
||||
sigmas.contiguous(),
|
||||
rgbs.contiguous(),
|
||||
opacities,
|
||||
)
|
||||
accumulated_depth = torch.clip(accumulated_depth, t_min[:, None], t_max[:, None])
|
||||
accumulated_color = accumulated_color + colors.WHITE.to(accumulated_color) * (1.0 - accumulated_weight)
|
||||
|
||||
outputs = {
|
||||
"rgb": accumulated_color,
|
||||
"accumulation": accumulated_weight,
|
||||
"depth": accumulated_depth,
|
||||
"alive_ray_mask": alive_ray_mask, # the rays we kept from sampler
|
||||
}
|
||||
return outputs
|
||||
|
||||
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients):
|
||||
device = self.device
|
||||
image = batch["image"].to(device)
|
||||
if "alive_ray_mask" in outputs:
|
||||
mask = outputs["alive_ray_mask"]
|
||||
rgb_loss = self.rgb_loss(image[mask], outputs["rgb"][mask])
|
||||
else:
|
||||
rgb_loss = self.rgb_loss(image, outputs["rgb"])
|
||||
loss_dict = {"rgb_loss": rgb_loss}
|
||||
loss_dict = misc.scale_dict(loss_dict, loss_coefficients)
|
||||
return loss_dict
|
||||
|
||||
def process_outputs_as_images(self, outputs): # pylint:disable=no-self-use
|
||||
"""Do preprocessing to make images valid"""
|
||||
# TODO: make log_test_image_outputs use this directly
|
||||
# TODO: implement across all the different model implementations
|
||||
outputs["accumulation"] = visualization.apply_colormap(outputs["accumulation"])
|
||||
outputs["depth"] = visualization.apply_depth_colormap(
|
||||
outputs["depth"],
|
||||
accumulation=outputs["accumulation"],
|
||||
)
|
||||
outputs["alive_ray_mask"] = visualization.apply_boolean_colormap(outputs["alive_ray_mask"])
|
||||
|
||||
def log_test_image_outputs(self, image_idx, step, batch, outputs):
|
||||
image = batch["image"]
|
||||
rgb = outputs["rgb"]
|
||||
acc = visualization.apply_colormap(outputs["accumulation"])
|
||||
depth = visualization.apply_depth_colormap(
|
||||
outputs["depth"],
|
||||
accumulation=outputs["accumulation"],
|
||||
)
|
||||
|
||||
combined_rgb = torch.cat([image, rgb], dim=1)
|
||||
combined_acc = torch.cat([acc], dim=1)
|
||||
combined_depth = torch.cat([depth], dim=1)
|
||||
|
||||
writer.put_image(name=f"img/image_idx_{image_idx}", image=combined_rgb, step=step)
|
||||
writer.put_image(name=f"accumulation/image_idx_{image_idx}", image=combined_acc, step=step)
|
||||
writer.put_image(name=f"depth/image_idx_{image_idx}", image=combined_depth, step=step)
|
||||
|
||||
# Switch images from [H, W, C] to [1, C, H, W] for metrics computations
|
||||
image = torch.moveaxis(image, -1, 0)[None, ...]
|
||||
rgb = torch.moveaxis(rgb, -1, 0)[None, ...]
|
||||
|
||||
psnr = self.psnr(image, rgb)
|
||||
ssim = self.ssim(image, rgb)
|
||||
lpips = self.lpips(image, rgb)
|
||||
|
||||
writer.put_scalar(name=f"psnr/val_{image_idx}-fine", scalar=float(psnr), step=step)
|
||||
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(ssim), step=step) # type: ignore
|
||||
writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(lpips), step=step)
|
||||
|
||||
writer.put_scalar(name=writer.EventName.CURR_TEST_PSNR, scalar=float(psnr), step=step)
|
||||
|
||||
return psnr.item()
|
||||
Reference in new issue
Block a user