mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-05 23:38:42 +08:00
Occupancy grid (#79)
* occupancy grid in progress * visualizing occupancy grid. currently restructing field and renderer head outputs * black and pylint. broke nerfw and semantic nerf but it's okay * get_project_root
This commit is contained in:
1 parent
5c2d8c2a0b
commit
fb440fedf3
23 files changed
+423
-217
No files matched your search
+65
-70
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
The Graph module contains all trainable parameters.
|
||||
"""
|
||||
import logging
|
||||
from abc import abstractmethod
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Optional, Union
|
||||
from typing import Dict, List, Union
|
||||
|
||||
import torch
|
||||
from omegaconf import DictConfig
|
||||
@@ -13,57 +13,20 @@ from torch.nn import Parameter
|
||||
from torchtyping import TensorType
|
||||
|
||||
from mattport.nerf.dataset.structs import SceneBounds
|
||||
from mattport.nerf.field_modules.ray_generator import RayGenerator
|
||||
from mattport.nerf.field_modules.scene_bounds_collider import AABBBoxCollider
|
||||
from mattport.nerf.occupancy_grid import OccupancyGrid
|
||||
from mattport.nerf.ray_generator import RayGenerator
|
||||
from mattport.nerf.colliders import AABBBoxCollider
|
||||
from mattport.structures.cameras import get_camera_model
|
||||
from mattport.structures.rays import RayBundle
|
||||
from mattport.utils.misc import get_masked_dict
|
||||
from mattport.utils.misc import is_not_none
|
||||
|
||||
|
||||
@dataclass
|
||||
class GraphInputs:
|
||||
"""Datastucture to encode the inputs to the graph."""
|
||||
class AbstractGraph(nn.Module):
|
||||
"""Highest level graph class. Somewhat useful to lift code up and out of the way."""
|
||||
|
||||
points: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class Node:
|
||||
"""Node datastructure for graph composition."""
|
||||
|
||||
name: str
|
||||
children: Dict[str, "Node"]
|
||||
parents: Dict[str, "Node"]
|
||||
visited_order: Optional[bool] = False
|
||||
visited_in_dim: Optional[bool] = False
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.name)
|
||||
|
||||
|
||||
class Graph(nn.Module):
|
||||
"""_summary_"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
intrinsics=None,
|
||||
camera_to_world=None,
|
||||
loss_coefficients: DictConfig = None,
|
||||
scene_bounds: SceneBounds = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.intrinsics = intrinsics
|
||||
self.camera_to_world = camera_to_world
|
||||
self.scene_bounds = scene_bounds
|
||||
self.loss_coefficients = loss_coefficients
|
||||
# assert self.scene_bounds is not None
|
||||
self.kwargs = kwargs
|
||||
self.scene_bounds_collider = None
|
||||
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
|
||||
self.populate_collider()
|
||||
self.populate_modules() # populate the modules
|
||||
|
||||
# to keep track of which device the nn.Module is on
|
||||
self.device_indicator_param = nn.Parameter(torch.empty(0))
|
||||
|
||||
@@ -71,45 +34,77 @@ class Graph(nn.Module):
|
||||
"""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.occupancy_grid = OccupancyGrid(aabb=self.scene_bounds.aabb)
|
||||
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.scene_bounds_collider = AABBBoxCollider(self.scene_bounds)
|
||||
self.collider = AABBBoxCollider(self.scene_bounds)
|
||||
|
||||
@abstractmethod
|
||||
def populate_modules(self):
|
||||
"""Initializes the modules that are part of the network."""
|
||||
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]]:
|
||||
"""Returns the parameter groups of the network in a dictionary format"""
|
||||
"""Obtain the parameter groups for the optimizers
|
||||
|
||||
def get_in_dim(self, curr_node: Node) -> None:
|
||||
"""Dynamically calculates and sets the input dimensions of the modules based on dependency graph
|
||||
|
||||
Args:
|
||||
curr_node (Node): pointer to current node in process
|
||||
Returns:
|
||||
Dict[str, List[Parameter]]: Mapping of different parameter groups
|
||||
"""
|
||||
curr_node.visited_in_dim = True
|
||||
if len(curr_node.parents) > 0:
|
||||
in_dim = 0
|
||||
for parent_name in curr_node.parents.keys():
|
||||
in_dim += self[parent_name].get_out_dim()
|
||||
self[curr_node.name].set_in_dim(in_dim)
|
||||
self.modules[curr_node.name].meta_data.in_dim = in_dim
|
||||
|
||||
for child_node in curr_node.children.values():
|
||||
if not child_node.visited_in_dim:
|
||||
self.get_in_dim(child_node)
|
||||
|
||||
@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):
|
||||
"""Forward function that needs to be overridden."""
|
||||
def forward(
|
||||
self,
|
||||
ray_indices: TensorType["num_rays", 3],
|
||||
batch: Union[str, Dict[str, torch.tensor]] = None,
|
||||
step: int = None,
|
||||
):
|
||||
# update the occupancy grid
|
||||
if step and step % self.steps_per_occupancy_grid_update == 0:
|
||||
logging.info("Updating occupancy grid.")
|
||||
self.occupancy_grid.update_occupancy_grid(density_fn=self.field_fine.density_fn)
|
||||
|
||||
# get the rays
|
||||
original_ray_bundle = self.ray_generator.forward(ray_indices) # RayBundle
|
||||
intersected_ray_bundle = self.scene_bounds_collider(original_ray_bundle)
|
||||
intersected_ray_bundle = self.collider(original_ray_bundle)
|
||||
|
||||
if isinstance(batch, type(None)):
|
||||
# during inference, keep all rays
|
||||
@@ -159,7 +154,7 @@ class Graph(nn.Module):
|
||||
end_idx = i + chunk_size
|
||||
original_ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
|
||||
original_ray_bundle.move_to_device(device)
|
||||
intersected_ray_bundle = self.scene_bounds_collider(original_ray_bundle)
|
||||
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)
|
||||
|
||||
@@ -12,21 +12,25 @@ from torchmetrics import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
|
||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||
|
||||
from mattport.nerf.field_modules.encoding import NeRFEncoding
|
||||
from mattport.nerf.field_modules.field_heads import DensityFieldHead, FieldHeadNames, RGBFieldHead
|
||||
from mattport.nerf.field_modules.field_heads import DensityFieldHead, RGBFieldHead
|
||||
from mattport.nerf.field_modules.mlp import MLP
|
||||
from mattport.nerf.fields.base import Field
|
||||
from mattport.nerf.graph.base import Graph
|
||||
from mattport.nerf.loss import MSELoss
|
||||
from mattport.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer
|
||||
from mattport.nerf.sampler import PDFSampler, UniformSampler
|
||||
from mattport.structures import colors
|
||||
from mattport.structures.rays import RayBundle, RaySamples
|
||||
from mattport.nerf.field_modules.scene_bounds_collider import NearFarCollider
|
||||
from mattport.structures.rays import PointSamples, RayBundle
|
||||
from mattport.nerf.colliders import NearFarCollider
|
||||
from mattport.utils import stats_tracker, visualization, writer
|
||||
from mattport.utils.misc import is_not_none
|
||||
|
||||
|
||||
class NeRFField(nn.Module):
|
||||
class NeRFField(Field):
|
||||
"""NeRF module"""
|
||||
|
||||
OUTPUT_RGB = "rgb"
|
||||
|
||||
def __init__(self, num_layers=8, layer_width=256, skip_connections: Tuple = (4,)) -> None:
|
||||
super().__init__()
|
||||
self.num_layers = num_layers
|
||||
@@ -73,22 +77,35 @@ class NeRFField(nn.Module):
|
||||
self.field_output_rgb = RGBFieldHead(in_dim=self.mlp_rgb.get_out_dim())
|
||||
self.field_output_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
|
||||
|
||||
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))
|
||||
def get_density(self, point_samples: PointSamples, valid_mask=None):
|
||||
"""Computes and returns the densities."""
|
||||
positions = point_samples.positions
|
||||
if not is_not_none(valid_mask):
|
||||
valid_mask = torch.ones_like(positions[..., 0]).bool()
|
||||
# placeholders for values to return
|
||||
density = torch.zeros(*valid_mask.shape, 1, dtype=torch.float32, device=positions.device)
|
||||
base_mlp_out = torch.zeros(
|
||||
*valid_mask.shape, self.mlp_base.out_dim, dtype=torch.float32, device=positions.device
|
||||
)
|
||||
if not valid_mask.any(): # empty mask
|
||||
return density, base_mlp_out
|
||||
encoded_xyz = self.encoding_xyz(positions[valid_mask])
|
||||
base_mlp_out[valid_mask] = self.mlp_base(encoded_xyz)
|
||||
density[valid_mask] = self.field_output_density(base_mlp_out[valid_mask])
|
||||
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_outputs = {}
|
||||
field_outputs.update(field_rgb_output)
|
||||
field_outputs.update(field_density_out)
|
||||
return field_outputs
|
||||
def get_outputs(self, point_samples: PointSamples, density_embedding=None, valid_mask=None):
|
||||
directions = point_samples.directions
|
||||
if not is_not_none(valid_mask):
|
||||
valid_mask = torch.ones_like(directions[..., 0]).bool()
|
||||
# placeholders for values to return
|
||||
rgb = torch.zeros(*valid_mask.shape, 3, dtype=torch.float32, device=directions.device)
|
||||
if not valid_mask.any(): # empty mask
|
||||
return {"rgb": rgb}
|
||||
encoded_dir = self.encoding_dir(directions[valid_mask])
|
||||
rgb_mlp_out = self.mlp_rgb(torch.cat([encoded_dir, density_embedding[valid_mask]], dim=-1))
|
||||
rgb[valid_mask] = self.field_output_rgb(rgb_mlp_out)
|
||||
return {"rgb": rgb}
|
||||
|
||||
|
||||
class NeRFGraph(Graph):
|
||||
@@ -112,23 +129,20 @@ 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."""
|
||||
self.field_coarse = NeRFField()
|
||||
self.field_fine = NeRFField()
|
||||
|
||||
def populate_collider(self):
|
||||
self.scene_bounds_collider = NearFarCollider(self.near_plane, self.far_plane)
|
||||
|
||||
def populate_modules(self):
|
||||
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)
|
||||
|
||||
# field
|
||||
self.populate_fields()
|
||||
|
||||
# renderers
|
||||
self.renderer_rgb = RGBRenderer(background_color=colors.WHITE)
|
||||
self.renderer_accumulation = AccumulationRenderer()
|
||||
@@ -143,54 +157,52 @@ class NeRFGraph(Graph):
|
||||
self.lpips = LearnedPerceptualImagePatchSimilarity()
|
||||
|
||||
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
|
||||
"""
|
||||
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):
|
||||
|
||||
# TODO: set the new rays...
|
||||
# uniform sampling
|
||||
ray_samples_uniform = self.sampler_uniform(ray_bundle)
|
||||
|
||||
# coarse network:
|
||||
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
|
||||
# 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["density"])
|
||||
rgb_coarse = self.renderer_rgb(
|
||||
rgb=field_outputs_coarse["rgb"],
|
||||
weights=weights_coarse,
|
||||
)
|
||||
accumulation_coarse = self.renderer_accumulation(weights_coarse)
|
||||
depth_coarse = self.renderer_depth(weights_coarse, ray_samples_uniform.ts)
|
||||
|
||||
coarse_field_outputs = self.field_coarse(uniform_ray_samples) # FieldOutputs
|
||||
# pdf sampling
|
||||
ray_samples_pdf = self.sampler_pdf(ray_samples_uniform, weights_coarse)
|
||||
|
||||
coarse_weights = uniform_ray_samples.get_weights(coarse_field_outputs[FieldHeadNames.DENSITY])
|
||||
# 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["density"])
|
||||
rgb_fine = self.renderer_rgb(
|
||||
rgb=field_outputs_fine["rgb"],
|
||||
weights=weights_fine,
|
||||
)
|
||||
accumulation_fine = self.renderer_accumulation(weights_fine)
|
||||
depth_fine = self.renderer_depth(weights_fine, ray_samples_pdf.ts)
|
||||
|
||||
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)
|
||||
# --- occupancy grid ---
|
||||
# TODO(ethan): move this elsewhere. currently here for debugging purposes
|
||||
density_occ = self.occupancy_grid.get_densities(ray_samples_pdf.positions)
|
||||
weights_occ = ray_samples_pdf.get_weights(density_occ)
|
||||
depth_occ = self.renderer_depth(weights_occ, ray_samples_pdf.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)
|
||||
|
||||
# outputs:
|
||||
outputs = {
|
||||
"rgb_coarse": coarse_renderer_outputs.rgb,
|
||||
"rgb_fine": fine_renderer_outputs.rgb,
|
||||
"accumulation_coarse": coarse_renderer_accumulation.accumulation,
|
||||
"accumulation_fine": fine_renderer_accumulation.accumulation,
|
||||
"depth_coarse": coarse_renderer_depth.depth,
|
||||
"depth_fine": fine_renderer_depth.depth,
|
||||
"rgb_coarse": rgb_coarse,
|
||||
"rgb_fine": rgb_fine,
|
||||
"accumulation_coarse": accumulation_coarse,
|
||||
"accumulation_fine": accumulation_fine,
|
||||
"depth_coarse": depth_coarse,
|
||||
"depth_fine": depth_fine,
|
||||
"depth_occ": depth_occ,
|
||||
}
|
||||
return outputs
|
||||
|
||||
@@ -229,6 +241,9 @@ class NeRFGraph(Graph):
|
||||
writer.write_image(name=f"image_idx_{image_idx}", image=combined_acc, step=step, group="accumulation")
|
||||
writer.write_image(name=f"image_idx_{image_idx}", image=combined_depth, step=step, group="depth")
|
||||
|
||||
depth_occ = visualization.apply_depth_colormap(outputs["depth_occ"])
|
||||
writer.write_image(name=f"image_idx_{image_idx}", image=depth_occ, step=step, group="depth_occupancy_grid")
|
||||
|
||||
# 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, ...]
|
||||
|
||||
Reference in new issue
Block a user