mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-02 05:48:57 +08:00
most code for nerf running
This commit is contained in:
1 parent
c2f3c06b6c
commit
be6fbe799e
16 files changed
+223
-168
No files matched your search
+43
-37
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
The Graph module contains all trainable parameters.
|
||||
"""
|
||||
from abc import abstractmethod
|
||||
import importlib
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Optional, Set
|
||||
@@ -9,6 +10,8 @@ from omegaconf import DictConfig
|
||||
|
||||
from torch import nn
|
||||
|
||||
from mattport.nerf.dataset.utils import DatasetInputs
|
||||
|
||||
|
||||
@dataclass
|
||||
class GraphInputs:
|
||||
@@ -34,27 +37,38 @@ class Node:
|
||||
class Graph(nn.ModuleDict):
|
||||
"""_summary_"""
|
||||
|
||||
def __init__(self, modules_config: DictConfig) -> None:
|
||||
def __init__(self, intrinsics=None, camera_to_world=None) -> None:
|
||||
super().__init__()
|
||||
self.modules_config = modules_config
|
||||
# create graph and get ordering
|
||||
self.roots = self.construct_graph()
|
||||
self.module_order = self.get_module_order()
|
||||
self.intrinsics = intrinsics
|
||||
self.camera_to_world = camera_to_world
|
||||
|
||||
# initialize graph with known input dimensions; set default in_dim to 0
|
||||
for module_name, module_dict in modules_config.items():
|
||||
module = getattr(importlib.import_module("mattport.nerf.field_modules"), module_dict.class_name)
|
||||
if not module_dict.meta_data.in_dim:
|
||||
module_dict.meta_data.in_dim = 0
|
||||
self[module_name] = module(**module_dict.meta_data)
|
||||
self.modules = None # NOTE(ethan): I'm turning off these features for now
|
||||
if self.modules is not None:
|
||||
# create graph and get ordering
|
||||
self.roots = self.construct_graph()
|
||||
self.module_order = self.get_module_order()
|
||||
|
||||
# calculate input dimensions based on module dependencies
|
||||
for root in self.roots:
|
||||
self.get_in_dim(root)
|
||||
# initialize graph with known input dimensions; set default in_dim to 0
|
||||
for module_name, module_dict in self.modules.items():
|
||||
module = getattr(importlib.import_module("mattport.nerf.field_modules"), module_dict.class_name)
|
||||
if not module_dict.meta_data.in_dim:
|
||||
module_dict.meta_data.in_dim = 0
|
||||
self[module_name] = module(**module_dict.meta_data)
|
||||
|
||||
# instantiate torch.nn members of network
|
||||
for _, module in self.items():
|
||||
module.build_nn_modules()
|
||||
# calculate input dimensions based on module dependencies
|
||||
for root in self.roots:
|
||||
self.get_in_dim(root)
|
||||
|
||||
# instantiate torch.nn members of network
|
||||
for _, module in self.items():
|
||||
module.build_nn_modules()
|
||||
|
||||
self.populate_modules() # populate the modules
|
||||
|
||||
@abstractmethod
|
||||
def populate_modules(self):
|
||||
"""Initializes the modules that are part of the network."""
|
||||
pass
|
||||
|
||||
def get_in_dim(self, curr_node: Node) -> None:
|
||||
"""Dynamically calculates and sets the input dimensions of the modules based on dependency graph
|
||||
@@ -68,7 +82,7 @@ class Graph(nn.ModuleDict):
|
||||
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_config[curr_node.name].meta_data.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:
|
||||
@@ -78,14 +92,14 @@ class Graph(nn.ModuleDict):
|
||||
"""Constructs a dependency graph given the module configuration
|
||||
|
||||
Args:
|
||||
modules_config (dict): module definitions that make up the network
|
||||
config (dict): module definitions that make up the network
|
||||
|
||||
Returns:
|
||||
set: all root nodes of the constructed dependency graph
|
||||
"""
|
||||
processed_modules = {}
|
||||
roots = set()
|
||||
for module_name, module_dict in self.modules_config.items():
|
||||
for module_name, module_dict in self.modules.items():
|
||||
if not module_name in processed_modules:
|
||||
curr_module = Node(name=module_name, children={}, parents={})
|
||||
processed_modules[module_name] = curr_module
|
||||
@@ -125,7 +139,7 @@ class Graph(nn.ModuleDict):
|
||||
"""Generates a graph and determines order of module operations using topological sorting
|
||||
|
||||
Args:
|
||||
modules_config (dict): module definitions that make up the network
|
||||
config (dict): module definitions that make up the network
|
||||
|
||||
Returns:
|
||||
list: ordering of the module names that should be executed
|
||||
@@ -137,20 +151,12 @@ class Graph(nn.ModuleDict):
|
||||
self.topological_sort(root, ordering_stack)
|
||||
return ordering_stack[::-1]
|
||||
|
||||
def forward(self, x):
|
||||
"""_summary_
|
||||
@abstractmethod
|
||||
def forward(self):
|
||||
"""Forward function that needs to be overridden."""
|
||||
pass
|
||||
|
||||
Args:
|
||||
x (_type_): _description_
|
||||
"""
|
||||
# for name in self.module_order:
|
||||
# x = self.modules[name](x)
|
||||
|
||||
## can index into previous results using dictionary
|
||||
# raise NotImplementedError
|
||||
for inputs, node_name, out_name in priority_queue:
|
||||
self.outputs[out_name] = self.modules[node_name](inputs)
|
||||
|
||||
# possibly delete things from output if no longer needed
|
||||
for old_name in :
|
||||
del self.outputs[old_name]
|
||||
@abstractmethod
|
||||
def get_losses(self):
|
||||
"""Computes and returns the losses."""
|
||||
pass
|
||||
+43
-41
@@ -3,42 +3,40 @@ Implementation of vanilla nerf.
|
||||
"""
|
||||
|
||||
|
||||
import logging
|
||||
|
||||
import torch
|
||||
from omegaconf import DictConfig
|
||||
from torch import TensorType, nn
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from mattport.nerf.dataset.utils import DatasetInputs, get_dataset_inputs
|
||||
from mattport.nerf.field.nerf import NeRFField
|
||||
from mattport.nerf.field_modules.encoding import NeRFEncoding
|
||||
from mattport.nerf.field_modules.field_outputs import DensityFieldOutput, RGBFieldOutput
|
||||
from mattport.nerf.field_modules.mlp import MLP
|
||||
from mattport.nerf.field.nerf import NeRFField
|
||||
from mattport.nerf.field_modules.ray_generator import RayGenerator
|
||||
from mattport.nerf.graph.base import Graph
|
||||
from mattport.nerf.loss import MSELoss
|
||||
from mattport.nerf.renderers import RGBRenderer
|
||||
from mattport.nerf.sampler import UniformSampler
|
||||
from mattport.structures.cameras import Rays
|
||||
from mattport.nerf.dataset.utils import DatasetInputs
|
||||
|
||||
|
||||
class NeRFGraph(Graph):
|
||||
def __init__(self, modules_config: DictConfig, dataset_inputs: DatasetInputs) -> None:
|
||||
super().__init__(modules_config)
|
||||
|
||||
self.populate_modules(dataset_inputs=dataset_inputs)
|
||||
# TODO(ethan): build all modules here instead of in the code below
|
||||
|
||||
def populate_modules(self, dataset_inputs: DatasetInputs):
|
||||
def __init__(self, intrinsics=None, camera_to_world=None) -> None:
|
||||
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world)
|
||||
|
||||
def populate_modules(self):
|
||||
# ray generator
|
||||
self.ray_generator = RayGenerator(dataset_inputs.intrinsics, dataset_inputs.camera_to_world)
|
||||
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
|
||||
|
||||
# samplers
|
||||
self.sampler_uniform = UniformSampler(near_plane=0.1, far_plane=4.0, num_samples=64)
|
||||
self.sampler_pdf = UniformSampler(near_plane=0.1, far_plane=4.0, num_samples=64)
|
||||
|
||||
# field
|
||||
self.coarse = NeRFField()
|
||||
self.fine = NeRFField()
|
||||
self.field_coarse = NeRFField()
|
||||
self.field_fine = NeRFField()
|
||||
|
||||
# renderers
|
||||
self.renderer_rgb = RGBRenderer()
|
||||
@@ -46,34 +44,38 @@ class NeRFGraph(Graph):
|
||||
# losses
|
||||
self.rgb_loss = MSELoss()
|
||||
|
||||
def forward(self, batch_indices: TensorType["num_rays", 3]):
|
||||
def forward(self, ray_indices: TensorType["num_rays", 3]):
|
||||
"""Takes in the ray indices and renders out values."""
|
||||
|
||||
ray_bundle = self.ray_generator.forward(batch_indices)
|
||||
rays = Rays(origin=ray_bundle.origins, direction=ray_bundle.directions) # TODO(ethan): consolidate this
|
||||
ray_samples = self.sampler_uniform(rays)
|
||||
ray_bundle = self.ray_generator.forward(ray_indices)
|
||||
ray_samples = self.sampler_uniform(ray_bundle)
|
||||
|
||||
xyz = ray_samples.locations
|
||||
deltas = ray_samples.deltas
|
||||
xyz = ray_samples.get_positions(ray_bundle) # (num_rays, num_samples, 3)
|
||||
num_rays, num_samples = xyz.shape[:2]
|
||||
xyz = xyz.view(-1, 3)
|
||||
dirs = (
|
||||
ray_bundle.directions.unsqueeze(1).repeat(1, num_samples, 1).view(num_rays * num_samples, 3)
|
||||
) # (num_rays, 3)
|
||||
|
||||
field_output_rgb, field_output_density = self.field_coarse(xyz=xyz, dirs=dirs)
|
||||
# move these back to the correct shape
|
||||
field_output_rgb = field_output_rgb.view(num_rays, num_samples, 3)
|
||||
field_output_density = field_output_density.view(num_rays, num_samples)
|
||||
|
||||
encoded_xyz = self.encoding_xyz(xyz)
|
||||
encoded_dir = self.encoding_dir(rays.direction)
|
||||
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)
|
||||
rgb_coarse = self.renderer_rgb(rgb=field_rgb_output, density=field_density_out, deltas=deltas)
|
||||
deltas = ray_samples.get_deltas()
|
||||
rgb_coarse = self.renderer_rgb(rgb=field_output_rgb, density=field_output_density, deltas=deltas)
|
||||
|
||||
print(field_output_rgb)
|
||||
print(field_output_density)
|
||||
outputs = {
|
||||
"rgb_coarse": rgb_coarse
|
||||
}
|
||||
return outputs
|
||||
|
||||
xyz_pdf = self.sampler_pdf(rays) # TODO(ethan): implement pdf
|
||||
encoded_xyz_pdf = self.encoding_xyz(xyz_pdf)
|
||||
base_mlp_out = self.mlp_base(encoded_xyz_pdf)
|
||||
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)
|
||||
rgb_fine = self.renderer_rgb(rgb=field_rgb_output, density=field_density_out, deltas=deltas)
|
||||
|
||||
return {"rgb_coarse": rgb_coarse, "rgb_fine": rgb_fine}
|
||||
|
||||
def get_loss(self, batch, render_outputs):
|
||||
rgb_loss_coarse = self.rgb_loss(batch.rgb, render_outputs["rgb_coarse"])
|
||||
rgb_loss_fine = self.rgb_loss(batch.rgb, render_outputs["rgb_fine"])
|
||||
return {"rgb_loss_coarse": rgb_loss_coarse, "rgb_loss_fine": rgb_loss_fine}
|
||||
def get_losses(self, batch, graph_outputs):
|
||||
# batch.pixels # (num_rays, 3)
|
||||
losses = {}
|
||||
# rgb_loss_coarse = self.rgb_loss(batch.pixels, graph_outputs["rgb_coarse"])
|
||||
# rgb_loss_fine = self.rgb_loss(batch.pixels, graph_outputs["rgb_fine"])
|
||||
# losses = {"rgb_loss_coarse": rgb_loss_coarse, "rgb_loss_fine": rgb_loss_fine}
|
||||
return losses
|
||||
Reference in new issue
Block a user