Change name to pyrad

This commit is contained in:
Matt Tancik committed 2022-05-31 14:15:06 -07:00
1 parent ee1dcdd197
commit 1a8ad9a763
87 files changed
+186 -187

No files matched your search

+162
View File
@@ -0,0 +1,162 @@
"""
The Graph module contains all trainable parameters.
"""
from abc import abstractmethod
from collections import defaultdict
from typing import Dict, List, Union
import torch
from omegaconf import DictConfig
from torch import nn
from torch.nn import Parameter
from torchtyping import TensorType
from pyrad.nerf.dataset.structs import SceneBounds
from pyrad.nerf.ray_generator import RayGenerator
from pyrad.nerf.colliders import AABBBoxCollider
from pyrad.structures.cameras import get_camera_model
from pyrad.structures.rays import RayBundle
from pyrad.utils.misc import get_masked_dict
from pyrad.utils.misc import is_not_none
class AbstractGraph(nn.Module):
"""Highest level graph class. Somewhat useful to lift code up and out of the way."""
def __init__(self) -> None:
super().__init__()
# to keep track of which device the nn.Module is on
self.device_indicator_param = nn.Parameter(torch.empty(0))
def get_device(self):
"""Returns the device that the torch parameters are on."""
return self.device_indicator_param.device
@abstractmethod
def forward(
self,
ray_indices: TensorType["num_rays", 3],
batch: Union[str, Dict[str, torch.tensor]] = None,
step: int = None,
):
"""Process starting with ray indices. Turns them into rays, then performs volume rendering."""
class Graph(AbstractGraph):
"""_summary_"""
def __init__(
self,
intrinsics=None,
camera_to_world=None,
loss_coefficients: DictConfig = None,
steps_per_occupancy_grid_update=16,
scene_bounds: SceneBounds = None,
**kwargs,
) -> None:
super().__init__()
assert is_not_none(scene_bounds), "scene_bounds is needed to use the occupancy grid"
self.intrinsics = intrinsics
self.camera_to_world = camera_to_world
self.scene_bounds = scene_bounds
self.loss_coefficients = loss_coefficients
self.steps_per_occupancy_grid_update = steps_per_occupancy_grid_update
self.kwargs = kwargs
self.collider = None
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
self.populate_collider()
self.populate_fields()
self.populate_misc_modules() # populate the modules
def populate_collider(self):
"""Set the scene bounds collider to use."""
self.collider = AABBBoxCollider(self.scene_bounds)
@abstractmethod
def populate_misc_modules(self):
"""Initializes any additional modules that are part of the network."""
@abstractmethod
def get_param_groups(self) -> Dict[str, List[Parameter]]:
"""Obtain the parameter groups for the optimizers
Returns:
Dict[str, List[Parameter]]: Mapping of different parameter groups
"""
@abstractmethod
def get_outputs(self, ray_bundle: RayBundle):
"""Takes in a Ray Bundle and returns a dictionary of outputs."""
def forward(
self,
ray_indices: TensorType["num_rays", 3],
batch: Union[str, Dict[str, torch.tensor]] = None,
step: int = None,
):
# get the rays
original_ray_bundle = self.ray_generator.forward(ray_indices) # RayBundle
intersected_ray_bundle = self.collider(original_ray_bundle)
if isinstance(batch, type(None)):
# during inference, keep all rays
outputs = self.get_outputs(intersected_ray_bundle)
return outputs
# during training, keep only the rays that intersect the scene. discard the rest
valid_mask = intersected_ray_bundle.valid_mask
masked_intersected_ray_bundle = intersected_ray_bundle.get_masked_ray_bundle(valid_mask)
masked_batch = get_masked_dict(batch, valid_mask) # NOTE(ethan): this is really slow if on CPU!
outputs = self.get_outputs(masked_intersected_ray_bundle)
loss_dict = self.get_loss_dict(outputs=outputs, batch=masked_batch)
return outputs, loss_dict
@abstractmethod
def get_loss_dict(self, outputs, batch) -> Dict[str, torch.tensor]:
"""Computes and returns the losses."""
def get_aggregated_loss_from_loss_dict(self, loss_dict):
"""Computes the aggregated loss from the loss_dict and the coefficients specified."""
aggregated_loss = 0.0
for loss_name, loss_value in loss_dict.items():
assert loss_name in self.loss_coefficients, f"{loss_name} no in self.loss_coefficients"
loss_coefficient = self.loss_coefficients[loss_name]
aggregated_loss += loss_coefficient * loss_value
return aggregated_loss
@torch.no_grad()
def get_outputs_for_camera(self, intrinsics, camera_to_world, chunk_size=1024, training_camera_index=0):
"""Takes in camera parameters and computes the output of the graph."""
# NOTE(ethan): this function has a spike in CPU usage
device = self.get_device()
assert len(intrinsics.shape) == 1
num_intrinsics_params = len(intrinsics)
camera_class = get_camera_model(num_intrinsics_params)
camera = camera_class(*intrinsics.tolist(), camera_to_world=camera_to_world)
camera_ray_bundle = camera.generate_camera_rays()
# TODO(ethan): decide how to properly handle the image indices for validation images
camera_ray_bundle.set_camera_indices(camera_index=training_camera_index)
camera_ray_bundle.move_to_device(device)
image_height, image_width = camera_ray_bundle.origins.shape[:2]
num_rays = len(camera_ray_bundle)
outputs = {}
outputs_lists = defaultdict(list)
for i in range(0, num_rays, chunk_size):
start_idx = i
end_idx = i + chunk_size
original_ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
intersected_ray_bundle = self.collider(original_ray_bundle)
outputs = self.get_outputs(intersected_ray_bundle)
for output_name, output in outputs.items():
outputs_lists[output_name].append(output)
for output_name, outputs_list in outputs_lists.items():
outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1)
return outputs
@abstractmethod
def log_test_image_outputs(self, image_idx, step, image, mask, outputs):
"""Writes the test image outputs."""
+152
View File
@@ -0,0 +1,152 @@
"""
Implementation of Instant NGP.
"""
from typing import Dict, List
import torch
from torch.nn import Parameter
from torchmetrics import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from pyrad.nerf.colliders import AABBBoxCollider
from pyrad.nerf.field_modules.field_heads import FieldHeadNames
from pyrad.nerf.fields.instant_ngp_field import field_implementation_to_class
from pyrad.nerf.graph.base import Graph
from pyrad.nerf.loss import MSELoss
from pyrad.nerf.occupancy_grid import OccupancyGrid
from pyrad.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer
from pyrad.nerf.sampler import PDFSampler, UniformSampler
from pyrad.structures import colors
from pyrad.structures.rays import RayBundle
from pyrad.utils import visualization, writer
class NGPGraph(Graph):
"""Instant NGP graph"""
def __init__(self, field_implementation="torch", intrinsics=None, camera_to_world=None, **kwargs) -> None:
assert field_implementation in field_implementation_to_class
self.field_implementation = field_implementation
self.field = None
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
def populate_collider(self):
self.collider = AABBBoxCollider(self.scene_bounds)
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):
# occupancy grid
self.occupancy_grid = OccupancyGrid(aabb=self.scene_bounds.aabb)
# samplers
self.sampler_occupancy_grid = UniformSampler(num_samples=128, occupancy_field=self.occupancy_grid)
# NOTE(ethan): are we sure we want the include_original flag used like this?
# it could be easily forgotten that it's by default True...?
self.sampler_pdf = PDFSampler(num_samples=128, include_original=False)
# renderers
self.renderer_rgb = RGBRenderer(background_color=colors.WHITE)
self.renderer_accumulation = AccumulationRenderer()
self.renderer_depth = DepthRenderer()
# losses
self.rgb_loss = MSELoss()
# metrics
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
self.ssim = StructuralSimilarityIndexMeasure()
self.lpips = LearnedPerceptualImagePatchSimilarity()
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = {}
param_groups["fields"] = list(self.field.parameters())
return param_groups
def get_outputs(self, ray_bundle: RayBundle):
# uniform sampling
ray_samples_uniform = self.sampler_occupancy_grid(ray_bundle)
field_outputs_uniform = self.field.forward(ray_samples_uniform.to_point_samples())
weights_uniform = ray_samples_uniform.get_weights(field_outputs_uniform[FieldHeadNames.DENSITY])
# pdf sampling
ray_samples_pdf = self.sampler_pdf(ray_bundle, ray_samples_uniform, weights_uniform)
field_outputs_pdf = self.field.forward(ray_samples_pdf.to_point_samples())
ts, indices = torch.sort(torch.cat([ray_samples_uniform.ts, ray_samples_pdf.ts], -1), -1)
ray_samples = ray_bundle.get_ray_samples(ts)
field_outputs = {}
for fo_name, _ in field_outputs_pdf.items():
fo_uniform = field_outputs_uniform[fo_name]
fo_pdf = field_outputs_pdf[fo_name]
fo_uniform_pdf = torch.cat([fo_uniform, fo_pdf], 1)
index = indices.view(fo_uniform_pdf[..., :1].shape)
index = index.expand(-1, -1, fo_uniform_pdf.shape[-1]) # TODO: don't hardcode this
field_outputs[fo_name] = torch.gather(fo_uniform_pdf, dim=1, index=index)
weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY])
rgb = self.renderer_rgb(
rgb=field_outputs[FieldHeadNames.RGB],
weights=weights,
)
accumulation = self.renderer_accumulation(weights)
depth = self.renderer_depth(weights, ray_samples.ts)
densities_occupancy_grid = self.occupancy_grid.get_densities(ray_samples.positions)
weights_occupancy_grid = ray_samples.get_weights(densities_occupancy_grid)
depth_occupancy_grid = self.renderer_depth(weights_occupancy_grid, ray_samples.ts)
outputs = {
"rgb": rgb,
"accumulation": accumulation,
"depth": depth,
"depth_occupancy_grid": depth_occupancy_grid,
}
return outputs
def get_loss_dict(self, outputs, batch):
device = self.get_device()
pixels = batch["pixels"].to(device)
rgb_loss = self.rgb_loss(pixels, outputs["rgb"])
loss_dict = {"rgb_loss": rgb_loss}
loss_dict["aggregated_loss"] = self.get_aggregated_loss_from_loss_dict(loss_dict)
return loss_dict
def log_test_image_outputs(self, image_idx, step, image, mask, outputs):
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)
depth = visualization.apply_depth_colormap(outputs["depth_occupancy_grid"])
writer.put_image(name=f"depth_occupancy_grid/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)
writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(lpips), step=step)
return psnr.item()
+213
View File
@@ -0,0 +1,213 @@
"""
NeRF-W (NeRF in the wild) implementation.
TODO:
"""
from typing import Tuple
import torch
from torch import nn
from pyrad.nerf.field_modules.embedding import Embedding
from pyrad.nerf.field_modules.field_heads import (
FieldHeadNames,
TransientDensityHead,
TransientRGBHead,
UncertaintyFieldHead,
)
from pyrad.nerf.field_modules.mlp import MLP
from pyrad.nerf.graph.vanilla_nerf import NeRFField, NeRFGraph
from pyrad.nerf.renderers import UncertaintyRenderer
from pyrad.structures.rays import RayBundle, RaySamples
from pyrad.utils import visualization, writer
class NerfWField(Field):
"""The NeRF-W field which has appearance and transient conditioning."""
def __init__(
self,
position_encoding: Encoding = Identity(in_dim=3),
direction_encoding: Encoding = Identity(in_dim=3),
base_mlp_num_layers: int = 8,
base_mlp_layer_width: int = 256,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
field_heads: Tuple[FieldHead] = (RGBFieldHead(),),
) -> None:
super().__init__()
self.num_images = num_images
self.appearance_embedding_dim = 48
self.transient_embedding_dim = 16
self.embedding_appearance = Embedding(self.num_images, self.appearance_embedding_dim)
self.embedding_transient = Embedding(self.num_images, self.transient_embedding_dim)
self.mlp_transient = MLP(
in_dim=self.mlp_base.get_out_dim() + self.embedding_transient.get_out_dim(),
out_dim=self.layer_width // 2,
num_layers=4,
layer_width=self.layer_width,
activation=nn.ReLU(),
)
self.mlp_head = MLP(
in_dim=self.mlp_base.get_out_dim()
+ self.encoding_dir.get_out_dim()
+ self.embedding_appearance.get_out_dim(),
out_dim=self.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
)
def build_heads(self):
super().build_heads()
self.field_output_transient_uncertainty = UncertaintyFieldHead(in_dim=self.mlp_transient.get_out_dim())
self.field_output_transient_rgb = TransientRGBHead(in_dim=self.mlp_transient.get_out_dim())
self.field_output_transient_density = TransientDensityHead(in_dim=self.mlp_transient.get_out_dim())
def forward(self, ray_samples: RaySamples):
positions = ray_samples.positions
directions = ray_samples.directions
camera_indices = ray_samples.get_camera_indices()
encoded_xyz = self.encoding_xyz(positions)
encoded_dir = self.encoding_dir(directions)
embedded_appearance = self.embedding_appearance(camera_indices)
embedded_transient = self.embedding_transient(camera_indices)
base_mlp_out = self.mlp_base(encoded_xyz)
rgb_mlp_out = self.mlp_rgb(torch.cat([base_mlp_out, encoded_dir, embedded_appearance], dim=-1))
transient_mlp_out = self.mlp_transient(torch.cat([base_mlp_out, embedded_transient], dim=-1))
field_rgb_output = self.field_output_rgb(rgb_mlp_out)
field_density_out = self.field_output_density(base_mlp_out)
field_transient_uncertainty_out = self.field_output_transient_uncertainty(transient_mlp_out)
field_transient_rgb_out = self.field_output_transient_rgb(transient_mlp_out)
field_transient_density_out = self.field_output_transient_density(transient_mlp_out)
field_outputs = {}
field_outputs.update(field_rgb_output)
field_outputs.update(field_density_out)
field_outputs.update(field_transient_uncertainty_out)
field_outputs.update(field_transient_rgb_out)
field_outputs.update(field_transient_density_out)
return field_outputs
class NerfWGraph(NeRFGraph):
"""NeRF-W graph"""
def __init__(self, intrinsics=None, camera_to_world=None, **kwargs) -> None:
self.num_images = len(intrinsics)
self.appearance_embedding_dim = 48
self.transient_embedding_dim = 16
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
self.renderer_uncertainty = UncertaintyRenderer()
def populate_fields(self):
"""Set the fields."""
self.field_coarse = NeRFField()
self.field_fine = NerfWField(
num_images=self.num_images,
appearance_embedding_dim=self.appearance_embedding_dim,
transient_embedding_dim=self.transient_embedding_dim,
)
def get_outputs(self, ray_bundle: RayBundle):
# coarse network
uniform_ray_samples = self.sampler_uniform(ray_bundle)
coarse_field_outputs = self.field_coarse(uniform_ray_samples)
coarse_weights = uniform_ray_samples.get_weights(coarse_field_outputs[FieldHeadNames.DENSITY])
rgb_coarse = self.renderer_rgb(
rgb=coarse_field_outputs[FieldHeadNames.RGB],
weights=coarse_weights,
).rgb
depth_coarse = self.renderer_depth(coarse_weights, uniform_ray_samples.ts).depth
# fine network
pdf_ray_samples = self.sampler_pdf(uniform_ray_samples, coarse_weights)
fine_field_outputs = self.field_fine(pdf_ray_samples)
fine_weights = pdf_ray_samples.get_weights(
fine_field_outputs[FieldHeadNames.DENSITY] + fine_field_outputs[FieldHeadNames.TRANSIENT_DENSITY]
)
fine_weights_static = pdf_ray_samples.get_weights(fine_field_outputs[FieldHeadNames.DENSITY])
fine_weights_transient = pdf_ray_samples.get_weights(fine_field_outputs[FieldHeadNames.TRANSIENT_DENSITY])
rgb_fine_static_component = self.renderer_rgb(
rgb=fine_field_outputs[FieldHeadNames.RGB],
weights=fine_weights,
).rgb
rgb_fine_transient_component = self.renderer_rgb(
rgb=fine_field_outputs[FieldHeadNames.TRANSIENT_RGB],
weights=fine_weights,
).rgb
rgb_fine = rgb_fine_static_component + rgb_fine_transient_component
rgb_fine_static = self.renderer_rgb(
rgb=fine_field_outputs[FieldHeadNames.RGB],
weights=fine_weights_static,
).rgb
# fine_renderer_accumulation_static = self.renderer_accumulation(fine_weights_static)
depth_fine = self.renderer_depth(fine_weights, pdf_ray_samples.ts).depth
depth_fine_static = self.renderer_depth(fine_weights_static, pdf_ray_samples.ts).depth
uncertainty = self.renderer_uncertainty(
fine_field_outputs[FieldHeadNames.UNCERTAINTY], fine_weights_transient
).uncertainty
density_transient = fine_field_outputs[FieldHeadNames.TRANSIENT_DENSITY]
# outputs:
outputs = {
"rgb_coarse": rgb_coarse, # (num_rays, 3)
"rgb_fine": rgb_fine,
"rgb_fine_static": rgb_fine_static,
"depth_coarse": depth_coarse,
"depth_fine": depth_fine,
"depth_fine_static": depth_fine_static,
"density_transient": density_transient, # (num_rays, num_samples, 1)
"uncertainty": uncertainty, # (num_rays, 1)
}
return outputs
def get_loss_dict(self, outputs, batch):
device = outputs["rgb_coarse"].device
pixels = batch["pixels"].to(device)
rgb_coarse = outputs["rgb_coarse"]
rgb_fine = outputs["rgb_fine"]
density_transient = outputs["density_transient"]
betas = outputs["uncertainty"]
rgb_loss_coarse = 0.5 * ((pixels - rgb_coarse) ** 2).sum(-1).mean()
rgb_loss_fine = 0.5 * (((pixels - rgb_fine) ** 2).sum(-1) / (betas[..., 0] ** 2)).mean()
uncertainty_loss = 0.5 * (3 + torch.log(betas)).mean()
density_loss = density_transient.mean()
loss_dict = {
"rgb_loss_coarse": rgb_loss_coarse,
"rgb_loss_fine": rgb_loss_fine,
"uncertainty_loss": uncertainty_loss,
"density_loss": density_loss,
}
loss_dict["aggregated_loss"] = self.get_aggregated_loss_from_loss_dict(loss_dict)
return loss_dict
def log_test_image_outputs(self, image_idx, step, image, mask, outputs):
rgb_coarse = outputs["rgb_coarse"]
rgb_fine = outputs["rgb_fine"]
rgb_fine_static = outputs["rgb_fine_static"]
depth_coarse = outputs["depth_coarse"]
depth_fine = outputs["depth_fine"]
depth_fine_static = outputs["depth_fine_static"]
uncertainty = outputs["uncertainty"]
depth_coarse = visualization.apply_depth_colormap(depth_coarse)
depth_fine = visualization.apply_depth_colormap(depth_fine)
depth_fine_static = visualization.apply_depth_colormap(depth_fine_static)
uncertainty = visualization.apply_depth_colormap(uncertainty)
row0 = torch.cat([image, uncertainty, torch.ones_like(rgb_fine)], dim=-2)
row1 = torch.cat([rgb_fine, rgb_fine_static, rgb_coarse], dim=-2)
row2 = torch.cat([depth_fine, depth_fine_static, depth_coarse], dim=-2)
combined_image = torch.cat([row0, row1, row2], dim=-3)
writer.put_image(name="img/image_idx_{image_idx}-nerfw", image=combined_image, step=step)
+158
View File
@@ -0,0 +1,158 @@
"""
Semantic NeRF implementation.
"""
from typing import Tuple
import torch
from torch import nn
from pyrad.nerf.field_modules.field_heads import FieldHeadNames, SemanticStuffHead
from pyrad.nerf.field_modules.mlp import MLP
from pyrad.nerf.graph.vanilla_nerf import NeRFField, NeRFGraph
from pyrad.nerf.renderers import SemanticRenderer
from pyrad.structures.rays import RayBundle, RaySamples
from pyrad.utils import visualization, writer
class SemanticNerfField(NeRFField):
"""Semantic-NeRF field"""
def __init__(
self, num_layers=8, layer_width=256, skip_connections: Tuple = (4,), num_stuff_classes: int = None
) -> None:
assert num_stuff_classes is not None
self.num_stuff_classes = num_stuff_classes
super().__init__(num_layers=num_layers, layer_width=layer_width, skip_connections=skip_connections)
self.semantic_mlp = MLP(
in_dim=self.mlp_base.get_out_dim(),
out_dim=self.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
)
self.field_output_semantic = SemanticStuffHead(
in_dim=self.semantic_mlp.get_out_dim(), num_classes=num_stuff_classes
)
self.semantic_sequential = torch.nn.Sequential(self.semantic_mlp, self.field_output_semantic)
def forward(self, ray_samples: RaySamples):
"""Evaluates the field at points along the ray."""
positions = ray_samples.positions
directions = ray_samples.directions
encoded_xyz = self.encoding_xyz(positions)
encoded_dir = self.encoding_dir(directions)
base_mlp_out = self.mlp_base(encoded_xyz)
rgb_mlp_out = self.mlp_rgb(torch.cat([encoded_dir, base_mlp_out], dim=-1))
field_rgb_output = self.field_output_rgb(rgb_mlp_out)
field_density_out = self.field_output_density(base_mlp_out)
field_semantic_output = self.semantic_sequential(base_mlp_out)
field_outputs = {}
field_outputs.update(field_rgb_output)
field_outputs.update(field_density_out)
field_outputs.update(field_semantic_output)
return field_outputs
class SemanticNerfGraph(NeRFGraph):
"""Semantic-NeRF graph"""
def __init__(self, intrinsics=None, camera_to_world=None, stuff_classes: int = None, **kwargs) -> None:
assert stuff_classes is not None
self.stuff_classes = stuff_classes
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
self.renderer_semantic = SemanticRenderer()
self.cross_entropy_loss = nn.CrossEntropyLoss(reduction="mean")
def populate_fields(self):
"""Set the fields."""
self.field_coarse = NeRFField()
self.field_fine = SemanticNerfField(num_stuff_classes=len(self.stuff_classes))
def get_outputs(self, ray_bundle: RayBundle):
# coarse network:
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
coarse_field_outputs = self.field_coarse(uniform_ray_samples) # FieldOutputs
coarse_weights = uniform_ray_samples.get_weights(coarse_field_outputs[FieldHeadNames.DENSITY])
coarse_renderer_outputs = self.renderer_rgb(
rgb=coarse_field_outputs[FieldHeadNames.RGB],
weights=coarse_weights,
) # RendererOutputs
coarse_renderer_accumulation = self.renderer_accumulation(coarse_weights) # RendererOutputs
coarse_renderer_depth = self.renderer_depth(coarse_weights, uniform_ray_samples.ts)
# fine network:
pdf_ray_samples = self.sampler_pdf(uniform_ray_samples, coarse_weights) # RaySamples
fine_field_outputs = self.field_fine(pdf_ray_samples) # FieldOutputs
fine_weights = pdf_ray_samples.get_weights(fine_field_outputs[FieldHeadNames.DENSITY])
fine_renderer_outputs = self.renderer_rgb(
rgb=fine_field_outputs[FieldHeadNames.RGB],
weights=fine_weights,
) # RendererOutputs
fine_renderer_accumulation = self.renderer_accumulation(fine_weights) # RendererOutputs
fine_renderer_depth = self.renderer_depth(fine_weights, pdf_ray_samples.ts)
# TODO refactor this into "vis" section. Doesn't need to be run during training.
coarse_renderer_depth = visualization.apply_depth_colormap(
coarse_renderer_depth.depth,
accumulation=coarse_renderer_accumulation.accumulation,
near_plane=self.near_plane,
far_plane=self.far_plane,
)
fine_renderer_depth = visualization.apply_depth_colormap(
fine_renderer_depth.depth,
accumulation=fine_renderer_accumulation.accumulation,
near_plane=self.near_plane,
far_plane=self.far_plane,
)
coarse_renderer_accumulation = visualization.apply_colormap(coarse_renderer_accumulation.accumulation)
fine_renderer_accumulation = visualization.apply_colormap(fine_renderer_accumulation.accumulation)
semantic_logits = self.renderer_semantic(
fine_field_outputs[FieldHeadNames.SEMANTICS_STUFF], weights=fine_weights
).semantics
# outputs:
outputs = {
"rgb_coarse": coarse_renderer_outputs.rgb,
"rgb_fine": fine_renderer_outputs.rgb,
"accumulation_coarse": coarse_renderer_accumulation,
"accumulation_fine": fine_renderer_accumulation,
"depth_coarse": coarse_renderer_depth,
"depth_fine": fine_renderer_depth,
"semantic_logits": semantic_logits,
}
return outputs
def get_loss_dict(self, outputs, batch):
# TODO(ethan): batch has "stuff_image". use it
device = outputs["rgb_coarse"].device
pixels = batch["pixels"].to(device)
rgb_loss_coarse = self.rgb_loss(pixels, outputs["rgb_coarse"])
rgb_loss_fine = self.rgb_loss(pixels, outputs["rgb_fine"])
semantic_logits = outputs["semantic_logits"]
semantic_classes = batch["stuff_image"][..., 0].to(device).long()
semantic_loss_fine = self.cross_entropy_loss(semantic_logits, semantic_classes)
loss_dict = {
"rgb_loss_coarse": rgb_loss_coarse,
"rgb_loss_fine": rgb_loss_fine,
"semantic_loss_fine": semantic_loss_fine,
}
loss_dict["aggregated_loss"] = self.get_aggregated_loss_from_loss_dict(loss_dict)
return loss_dict
def log_test_image_outputs(self, image_idx, step, image, mask, outputs):
super().log_test_image_outputs(image_idx, step, image, mask, outputs)
semantic_labels = torch.argmax(torch.nn.functional.softmax(outputs["semantic_logits"], dim=-1), dim=-1) / len(
self.stuff_classes
)
semantic_labels_image = visualization.apply_colormap(semantic_labels[..., None])
writer.put_image(name="semantics/image_idx_{image_idx}", image=semantic_labels_image, step=step)
+4
View File
@@ -0,0 +1,4 @@
"""
TensorRF implementation.
TODO:
"""
+177
View File
@@ -0,0 +1,177 @@
"""
Implementation of vanilla nerf.
"""
from typing import Dict, List
import torch
from torch.nn import Parameter
from torchmetrics import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from pyrad.nerf.field_modules.encoding import NeRFEncoding
from pyrad.nerf.field_modules.field_heads import FieldHeadNames
from pyrad.nerf.fields.nerf_field import NeRFField
from pyrad.nerf.graph.base import Graph
from pyrad.nerf.loss import MSELoss
from pyrad.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer
from pyrad.nerf.sampler import PDFSampler, UniformSampler
from pyrad.structures import colors
from pyrad.structures.rays import RayBundle
from pyrad.nerf.colliders import NearFarCollider
from pyrad.utils import visualization, writer
class NeRFGraph(Graph):
"""Vanilla NeRF graph"""
def __init__(
self,
intrinsics=None,
camera_to_world=None,
near_plane=2.0,
far_plane=6.0,
num_coarse_samples=64,
num_importance_samples=128,
**kwargs,
) -> None:
self.near_plane = near_plane
self.far_plane = far_plane
self.num_coarse_samples = num_coarse_samples
self.num_importance_samples = num_importance_samples
self.field_coarse = None
self.field_fine = None
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
def populate_collider(self):
self.collider = NearFarCollider(self.near_plane, self.far_plane)
def populate_fields(self):
"""Set the fields."""
position_encoding = NeRFEncoding(
in_dim=3, num_frequencies=10, min_freq_exp=0.0, max_freq_exp=8.0, include_input=True
)
direction_encoding = NeRFEncoding(
in_dim=3, num_frequencies=4, min_freq_exp=0.0, max_freq_exp=4.0, include_input=True
)
self.field_coarse = NeRFField(position_encoding=position_encoding, direction_encoding=direction_encoding)
self.field_fine = NeRFField(position_encoding=position_encoding, direction_encoding=direction_encoding)
def populate_misc_modules(self):
# samplers
self.sampler_uniform = UniformSampler(num_samples=self.num_coarse_samples)
self.sampler_pdf = PDFSampler(num_samples=self.num_importance_samples)
# renderers
self.renderer_rgb = RGBRenderer(background_color=colors.WHITE)
self.renderer_accumulation = AccumulationRenderer()
self.renderer_depth = DepthRenderer()
# losses
self.rgb_loss = MSELoss()
# metrics
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
self.ssim = StructuralSimilarityIndexMeasure()
self.lpips = LearnedPerceptualImagePatchSimilarity()
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = {}
param_groups["fields"] = list(self.field_coarse.parameters()) + list(self.field_fine.parameters())
return param_groups
def get_outputs(self, ray_bundle: RayBundle):
# uniform sampling
ray_samples_uniform = self.sampler_uniform(ray_bundle)
# coarse field:
field_outputs_coarse = self.field_coarse.forward(ray_samples_uniform.to_point_samples())
weights_coarse = ray_samples_uniform.get_weights(field_outputs_coarse[FieldHeadNames.DENSITY])
rgb_coarse = self.renderer_rgb(
rgb=field_outputs_coarse[FieldHeadNames.RGB],
weights=weights_coarse,
)
accumulation_coarse = self.renderer_accumulation(weights_coarse)
depth_coarse = self.renderer_depth(weights_coarse, ray_samples_uniform.ts)
# pdf sampling
ray_samples_pdf = self.sampler_pdf(ray_bundle, ray_samples_uniform, weights_coarse)
# fine field:
field_outputs_fine = self.field_fine.forward(ray_samples_pdf.to_point_samples())
weights_fine = ray_samples_pdf.get_weights(field_outputs_fine[FieldHeadNames.DENSITY])
rgb_fine = self.renderer_rgb(
rgb=field_outputs_fine[FieldHeadNames.RGB],
weights=weights_fine,
)
accumulation_fine = self.renderer_accumulation(weights_fine)
depth_fine = self.renderer_depth(weights_fine, ray_samples_pdf.ts)
outputs = {
"rgb_coarse": rgb_coarse,
"rgb_fine": rgb_fine,
"accumulation_coarse": accumulation_coarse,
"accumulation_fine": accumulation_fine,
"depth_coarse": depth_coarse,
"depth_fine": depth_fine,
}
return outputs
def get_loss_dict(self, outputs, batch):
device = outputs["rgb_coarse"].device
pixels = batch["pixels"].to(device)
rgb_loss_coarse = self.rgb_loss(pixels, outputs["rgb_coarse"])
rgb_loss_fine = self.rgb_loss(pixels, outputs["rgb_fine"])
loss_dict = {"rgb_loss_coarse": rgb_loss_coarse, "rgb_loss_fine": rgb_loss_fine}
loss_dict["aggregated_loss"] = self.get_aggregated_loss_from_loss_dict(loss_dict)
return loss_dict
def log_test_image_outputs(self, image_idx, step, image, mask, outputs):
rgb_coarse = outputs["rgb_coarse"]
rgb_fine = outputs["rgb_fine"]
acc_coarse = visualization.apply_colormap(outputs["accumulation_coarse"])
acc_fine = visualization.apply_colormap(outputs["accumulation_fine"])
depth_coarse = visualization.apply_depth_colormap(
outputs["depth_coarse"],
accumulation=outputs["accumulation_coarse"],
near_plane=self.near_plane,
far_plane=self.far_plane,
)
depth_fine = visualization.apply_depth_colormap(
outputs["depth_fine"],
accumulation=outputs["accumulation_fine"],
near_plane=self.near_plane,
far_plane=self.far_plane,
)
combined_rgb = torch.cat([image, rgb_coarse, rgb_fine], dim=1)
combined_acc = torch.cat([acc_coarse, acc_fine], dim=1)
combined_depth = torch.cat([depth_coarse, depth_fine], dim=1)
mask = visualization.apply_depth_colormap(mask[..., None])
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)
writer.put_image(name=f"mask/image_idx_{image_idx}", image=mask, step=step)
# Switch images from [H, W, C] to [1, C, H, W] for metrics computations
image = torch.moveaxis(image, -1, 0)[None, ...]
rgb_coarse = torch.moveaxis(rgb_coarse, -1, 0)[None, ...]
rgb_fine = torch.moveaxis(rgb_fine, -1, 0)[None, ...]
coarse_psnr = self.psnr(image, rgb_coarse)
fine_psnr = self.psnr(image, rgb_fine)
fine_ssim = self.ssim(image, rgb_fine)
fine_lpips = self.lpips(image, rgb_fine)
writer.put_scalar(name=f"psnr/val_{image_idx}-coarse", scalar=float(coarse_psnr), step=step)
writer.put_scalar(name=f"psnr/val_{image_idx}-fine", scalar=float(fine_psnr), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(fine_ssim), step=step)
writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(fine_lpips), step=step)
writer.put_scalar(name=writer.EventName.CURR_TEST_PSNR, scalar=float(fine_psnr), step=step)
return fine_psnr.item()