mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-06 15:59:16 +08:00
Refactoring (data loading, semantic-nerf/nerf-w fixes, ...) (#8)
* in progress. camera_indices broken * faster dataloader. starting on pixel sampler logic * imagesampler and pixelsampler * lint and black * continuing merge * pytest working * fixed docs * docs * minor changes
This commit is contained in:
1 parent
1f189b3e54
commit
146332cfb6
50 files changed
+914
-831
No files matched your search
+13
-16
@@ -13,11 +13,9 @@ 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
|
||||
from pyrad.utils.misc import get_masked_dict, instantiate_from_dict_config, is_not_none
|
||||
|
||||
|
||||
class AbstractGraph(nn.Module):
|
||||
@@ -52,6 +50,7 @@ class Graph(AbstractGraph):
|
||||
loss_coefficients: DictConfig = None,
|
||||
steps_per_occupancy_grid_update=16,
|
||||
scene_bounds: SceneBounds = None,
|
||||
collider_config: DictConfig = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
@@ -59,6 +58,7 @@ class Graph(AbstractGraph):
|
||||
self.intrinsics = intrinsics
|
||||
self.camera_to_world = camera_to_world
|
||||
self.scene_bounds = scene_bounds
|
||||
self.collider_config = collider_config
|
||||
self.loss_coefficients = loss_coefficients
|
||||
self.steps_per_occupancy_grid_update = steps_per_occupancy_grid_update
|
||||
self.kwargs = kwargs
|
||||
@@ -70,7 +70,7 @@ class Graph(AbstractGraph):
|
||||
|
||||
def populate_collider(self):
|
||||
"""Set the scene bounds collider to use."""
|
||||
self.collider = AABBBoxCollider(self.scene_bounds)
|
||||
self.collider = instantiate_from_dict_config(self.collider_config, scene_bounds=self.scene_bounds)
|
||||
|
||||
@abstractmethod
|
||||
def populate_misc_modules(self):
|
||||
@@ -110,39 +110,36 @@ class Graph(AbstractGraph):
|
||||
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
|
||||
aggregated_loss_dict = self.get_aggregated_loss_dict(loss_dict)
|
||||
return outputs, aggregated_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):
|
||||
def get_aggregated_loss_dict(self, loss_dict):
|
||||
"""Computes the aggregated loss from the loss_dict and the coefficients specified."""
|
||||
aggregated_loss = 0.0
|
||||
aggregated_loss_dict = {}
|
||||
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
|
||||
aggregated_loss_dict[loss_name] = loss_coefficient * loss_value
|
||||
aggregated_loss_dict["aggregated_loss"] = sum(loss_dict.values())
|
||||
return aggregated_loss_dict
|
||||
|
||||
@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()
|
||||
camera_ray_bundle = camera.generate_camera_rays(device=self.get_device())
|
||||
# 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):
|
||||
@@ -158,5 +155,5 @@ class Graph(AbstractGraph):
|
||||
return outputs
|
||||
|
||||
@abstractmethod
|
||||
def log_test_image_outputs(self, image_idx, step, image, mask, outputs):
|
||||
def log_test_image_outputs(self, image_idx, step, batch, outputs):
|
||||
"""Writes the test image outputs."""
|
||||
@@ -16,7 +16,7 @@ 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.nerf.ray_sampler import PDFSampler, UniformSampler
|
||||
from pyrad.structures import colors
|
||||
from pyrad.structures.rays import RayBundle
|
||||
from pyrad.utils import visualization, writer
|
||||
@@ -115,10 +115,10 @@ class NGPGraph(Graph):
|
||||
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):
|
||||
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(
|
||||
|
||||
+109
-127
@@ -1,163 +1,142 @@
|
||||
"""
|
||||
NeRF-W (NeRF in the wild) implementation.
|
||||
TODO:
|
||||
"""
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchmetrics import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
|
||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||
|
||||
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.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.fields.nerfw_field import VanillaNerfWField
|
||||
from pyrad.nerf.graph.base import Graph
|
||||
from pyrad.nerf.loss import MSELoss
|
||||
from pyrad.nerf.ray_sampler import PDFSampler, UniformSampler
|
||||
from pyrad.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer, UncertaintyRenderer
|
||||
from pyrad.structures import colors
|
||||
from pyrad.structures.rays import RayBundle
|
||||
from pyrad.utils import visualization, writer
|
||||
|
||||
|
||||
class NerfWField(Field):
|
||||
"""The NeRF-W field which has appearance and transient conditioning."""
|
||||
class NerfWGraph(Graph):
|
||||
"""NeRF-W graph"""
|
||||
|
||||
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(),),
|
||||
intrinsics=None,
|
||||
camera_to_world=None,
|
||||
near_plane=2.0,
|
||||
far_plane=6.0,
|
||||
num_coarse_samples=64,
|
||||
num_importance_samples=128,
|
||||
**kwargs,
|
||||
) -> 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.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
|
||||
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(
|
||||
|
||||
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 = VanillaNerfWField(
|
||||
num_images=self.num_images,
|
||||
position_encoding=position_encoding,
|
||||
direction_encoding=direction_encoding,
|
||||
appearance_embedding_dim=self.appearance_embedding_dim,
|
||||
transient_embedding_dim=self.transient_embedding_dim,
|
||||
)
|
||||
|
||||
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.BLACK)
|
||||
self.renderer_accumulation = AccumulationRenderer()
|
||||
self.renderer_depth = DepthRenderer()
|
||||
self.renderer_uncertainty = UncertaintyRenderer()
|
||||
|
||||
# losses
|
||||
self.rgb_loss = MSELoss()
|
||||
|
||||
# metrics
|
||||
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
|
||||
self.ssim = StructuralSimilarityIndexMeasure()
|
||||
self.lpips = LearnedPerceptualImagePatchSimilarity()
|
||||
|
||||
def get_param_groups(self):
|
||||
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):
|
||||
# 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])
|
||||
# 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=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]
|
||||
rgb=field_outputs_coarse[FieldHeadNames.RGB],
|
||||
weights=weights_coarse,
|
||||
)
|
||||
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])
|
||||
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())
|
||||
|
||||
# fine weights
|
||||
weights_fine = ray_samples_pdf.get_weights(
|
||||
field_outputs_fine[FieldHeadNames.DENSITY] + field_outputs_fine[FieldHeadNames.TRANSIENT_DENSITY]
|
||||
)
|
||||
weights_fine_static = ray_samples_pdf.get_weights(field_outputs_fine[FieldHeadNames.DENSITY])
|
||||
weights_fine_transient = ray_samples_pdf.get_weights(field_outputs_fine[FieldHeadNames.TRANSIENT_DENSITY])
|
||||
|
||||
# rgb
|
||||
rgb_fine_static_component = self.renderer_rgb(
|
||||
rgb=fine_field_outputs[FieldHeadNames.RGB],
|
||||
weights=fine_weights,
|
||||
).rgb
|
||||
rgb=field_outputs_fine[FieldHeadNames.RGB],
|
||||
weights=weights_fine,
|
||||
)
|
||||
rgb_fine_transient_component = self.renderer_rgb(
|
||||
rgb=fine_field_outputs[FieldHeadNames.TRANSIENT_RGB],
|
||||
weights=fine_weights,
|
||||
).rgb
|
||||
rgb=field_outputs_fine[FieldHeadNames.TRANSIENT_RGB],
|
||||
weights=weights_fine,
|
||||
)
|
||||
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
|
||||
rgb=field_outputs_fine[FieldHeadNames.RGB],
|
||||
weights=weights_fine_static,
|
||||
)
|
||||
|
||||
# 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
|
||||
density_transient = field_outputs_fine[FieldHeadNames.TRANSIENT_DENSITY]
|
||||
|
||||
density_transient = fine_field_outputs[FieldHeadNames.TRANSIENT_DENSITY]
|
||||
# depth
|
||||
depth_fine = self.renderer_depth(weights_fine, ray_samples_pdf.ts)
|
||||
depth_fine_static = self.renderer_depth(weights_fine_static, ray_samples_pdf.ts)
|
||||
|
||||
# uncertainty
|
||||
uncertainty = self.renderer_uncertainty(field_outputs_fine[FieldHeadNames.UNCERTAINTY], weights_fine_transient)
|
||||
|
||||
# outputs:
|
||||
outputs = {
|
||||
"rgb_coarse": rgb_coarse, # (num_rays, 3)
|
||||
"rgb_fine": rgb_fine,
|
||||
@@ -188,10 +167,10 @@ class NerfWGraph(NeRFGraph):
|
||||
"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):
|
||||
def log_test_image_outputs(self, image_idx, step, batch, outputs):
|
||||
image = batch["image"]
|
||||
rgb_coarse = outputs["rgb_coarse"]
|
||||
rgb_fine = outputs["rgb_fine"]
|
||||
rgb_fine_static = outputs["rgb_fine_static"]
|
||||
@@ -210,4 +189,7 @@ class NerfWGraph(NeRFGraph):
|
||||
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)
|
||||
writer.put_image(name=f"img/image_idx_{image_idx}-nerfw", image=combined_image, step=step)
|
||||
|
||||
mask = batch["mask"].repeat(1, 1, 3)
|
||||
writer.put_image(name=f"mask/image_idx_{image_idx}", image=mask, step=step)
|
||||
+118
-103
@@ -2,157 +2,172 @@
|
||||
Semantic NeRF implementation.
|
||||
"""
|
||||
|
||||
from typing import Tuple
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from pyrad.nerf.field_modules.field_heads import FieldHeadNames, SemanticStuffHead
|
||||
from pyrad.nerf.field_modules.encoding import Encoding, Identity, NeRFEncoding
|
||||
from pyrad.nerf.field_modules.field_heads import DensityFieldHead, FieldHeadNames, RGBFieldHead, SemanticFieldHead
|
||||
from pyrad.nerf.field_modules.mlp import MLP
|
||||
from pyrad.nerf.graph.vanilla_nerf import NeRFField, NeRFGraph
|
||||
from pyrad.nerf.fields.base import Field
|
||||
from pyrad.nerf.fields.nerf_field import NeRFField
|
||||
from pyrad.nerf.graph.vanilla_nerf import NeRFGraph
|
||||
from pyrad.nerf.renderers import SemanticRenderer
|
||||
from pyrad.structures.rays import RayBundle, RaySamples
|
||||
from pyrad.utils import visualization, writer
|
||||
from pyrad.structures.rays import PointSamples, RayBundle
|
||||
from pyrad.utils import writer
|
||||
|
||||
|
||||
class SemanticNerfField(NeRFField):
|
||||
class SemanticNerfField(Field):
|
||||
"""Semantic-NeRF field"""
|
||||
|
||||
def __init__(
|
||||
self, num_layers=8, layer_width=256, skip_connections: Tuple = (4,), num_stuff_classes: int = None
|
||||
self,
|
||||
num_semantic_classes: int,
|
||||
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,),
|
||||
) -> 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,
|
||||
super().__init__()
|
||||
self.num_semantic_classes = num_semantic_classes
|
||||
self.position_encoding = position_encoding
|
||||
self.direction_encoding = direction_encoding
|
||||
self.mlp_base = MLP(
|
||||
in_dim=self.position_encoding.get_out_dim(),
|
||||
num_layers=base_mlp_num_layers,
|
||||
layer_width=base_mlp_layer_width,
|
||||
skip_connections=skip_connections,
|
||||
)
|
||||
self.mlp_head = MLP(
|
||||
in_dim=self.mlp_base.get_out_dim() + self.direction_encoding.get_out_dim(),
|
||||
num_layers=head_mlp_num_layers,
|
||||
layer_width=head_mlp_layer_width,
|
||||
)
|
||||
self.mlp_semantic = MLP(
|
||||
in_dim=self.mlp_head.get_out_dim(),
|
||||
layer_width=self.mlp_head.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.field_head_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
|
||||
self.field_head_rgb = RGBFieldHead(in_dim=self.mlp_head.get_out_dim())
|
||||
self.field_head_semantic = SemanticFieldHead(
|
||||
in_dim=self.mlp_semantic.get_out_dim(), num_classes=self.num_semantic_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)
|
||||
def get_density(self, point_samples: PointSamples):
|
||||
encoded_xyz = self.position_encoding(point_samples.positions)
|
||||
base_mlp_out = self.mlp_base(encoded_xyz)
|
||||
rgb_mlp_out = self.mlp_rgb(torch.cat([encoded_dir, base_mlp_out], dim=-1))
|
||||
density = self.field_head_density(base_mlp_out)
|
||||
return density, base_mlp_out
|
||||
|
||||
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
|
||||
def get_outputs(
|
||||
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
|
||||
) -> Dict[FieldHeadNames, TensorType]:
|
||||
encoded_dir = self.direction_encoding(point_samples.directions)
|
||||
mlp_out = self.mlp_head(torch.cat([encoded_dir, density_embedding], dim=-1))
|
||||
outputs = {}
|
||||
# rgb
|
||||
outputs[self.field_head_rgb.field_head_name] = self.field_head_rgb(mlp_out)
|
||||
# semantic
|
||||
mlp_out_sem = self.mlp_semantic(mlp_out)
|
||||
outputs[self.field_head_semantic.field_head_name] = self.field_head_semantic(mlp_out_sem)
|
||||
return outputs
|
||||
|
||||
|
||||
class SemanticNerfGraph(NeRFGraph):
|
||||
"""Semantic-NeRF graph"""
|
||||
|
||||
def __init__(self, intrinsics=None, camera_to_world=None, stuff_classes: int = None, **kwargs) -> None:
|
||||
def __init__(self, intrinsics=None, camera_to_world=None, stuff_classes=None, stuff_colors=None, **kwargs) -> None:
|
||||
assert stuff_classes is not None
|
||||
self.stuff_classes = stuff_classes
|
||||
self.stuff_colors = stuff_colors
|
||||
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))
|
||||
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)
|
||||
|
||||
num_semantic_classes = len(self.stuff_classes)
|
||||
self.field_fine = SemanticNerfField(
|
||||
num_semantic_classes, position_encoding=position_encoding, direction_encoding=direction_encoding
|
||||
)
|
||||
|
||||
def populate_misc_modules(self):
|
||||
super().populate_misc_modules()
|
||||
self.renderer_semantic = SemanticRenderer()
|
||||
self.cross_entropy_loss = nn.CrossEntropyLoss(reduction="mean")
|
||||
|
||||
def get_outputs(self, ray_bundle: RayBundle):
|
||||
# coarse network:
|
||||
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
|
||||
# uniform sampling
|
||||
ray_samples_uniform = self.sampler_uniform(ray_bundle)
|
||||
|
||||
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,
|
||||
# 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,
|
||||
)
|
||||
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,
|
||||
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,
|
||||
)
|
||||
coarse_renderer_accumulation = visualization.apply_colormap(coarse_renderer_accumulation.accumulation)
|
||||
fine_renderer_accumulation = visualization.apply_colormap(fine_renderer_accumulation.accumulation)
|
||||
accumulation_fine = self.renderer_accumulation(weights_fine)
|
||||
depth_fine = self.renderer_depth(weights_fine, ray_samples_pdf.ts)
|
||||
semantic_fine = self.renderer_semantic(field_outputs_fine[FieldHeadNames.SEMANTICS], weights=weights_fine)
|
||||
|
||||
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,
|
||||
"rgb_coarse": rgb_coarse,
|
||||
"rgb_fine": rgb_fine,
|
||||
"accumulation_coarse": accumulation_coarse,
|
||||
"accumulation_fine": accumulation_fine,
|
||||
"depth_coarse": depth_coarse,
|
||||
"depth_fine": depth_fine,
|
||||
"semantic_fine": semantic_fine,
|
||||
}
|
||||
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)
|
||||
pixels = batch["pixels"]
|
||||
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_logits = outputs["semantic_fine"]
|
||||
semantic_classes = batch["semantics"][..., 0].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)
|
||||
def log_test_image_outputs(self, image_idx, step, batch, outputs):
|
||||
super().log_test_image_outputs(image_idx, step, batch, outputs)
|
||||
semantic_logits = outputs["semantic_fine"]
|
||||
semantic_labels = torch.argmax(torch.nn.functional.softmax(semantic_logits, dim=-1), dim=-1)
|
||||
semantic_labels_image = self.stuff_colors[semantic_labels]
|
||||
writer.put_image(name=f"semantics/image_idx_{image_idx}", image=semantic_labels_image, step=step)
|
||||
|
||||
mask = batch["mask"].repeat(1, 1, 3)
|
||||
writer.put_image(name=f"mask/image_idx_{image_idx}", image=mask, step=step)
|
||||
@@ -9,17 +9,16 @@ 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.ray_sampler import PDFSampler, UniformSampler
|
||||
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
|
||||
|
||||
|
||||
@@ -44,9 +43,6 @@ class NeRFGraph(Graph):
|
||||
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."""
|
||||
|
||||
@@ -126,10 +122,10 @@ class NeRFGraph(Graph):
|
||||
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):
|
||||
def log_test_image_outputs(self, image_idx, step, batch, outputs):
|
||||
image = batch["image"]
|
||||
rgb_coarse = outputs["rgb_coarse"]
|
||||
rgb_fine = outputs["rgb_fine"]
|
||||
acc_coarse = visualization.apply_colormap(outputs["accumulation_coarse"])
|
||||
@@ -150,12 +146,10 @@ class NeRFGraph(Graph):
|
||||
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, ...]
|
||||
|
||||
Reference in new issue
Block a user