mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-07 00:09:14 +08:00
Update docstrings
This commit is contained in:
1 parent
cc79708df7
commit
37a3692b45
11 files changed
+165
-98
No files matched your search
+43
-16
@@ -24,6 +24,7 @@ import torch
|
|||||||
import torch.distributed as dist
|
import torch.distributed as dist
|
||||||
from omegaconf import DictConfig
|
from omegaconf import DictConfig
|
||||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||||
|
from torchtyping import TensorType
|
||||||
|
|
||||||
from pyrad.cameras.rays import RayBundle
|
from pyrad.cameras.rays import RayBundle
|
||||||
from pyrad.data.dataloader import EvalDataloader, TrainDataloader
|
from pyrad.data.dataloader import EvalDataloader, TrainDataloader
|
||||||
@@ -38,10 +39,7 @@ logging.getLogger("PIL").setLevel(logging.WARNING)
|
|||||||
|
|
||||||
|
|
||||||
class Trainer:
|
class Trainer:
|
||||||
"""Training class"""
|
"""Training class
|
||||||
|
|
||||||
def __init__(self, config: DictConfig, local_rank: int = 0, world_size: int = 1):
|
|
||||||
"""_summary_
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
config (DictConfig): _description_
|
config (DictConfig): _description_
|
||||||
@@ -49,6 +47,8 @@ class Trainer:
|
|||||||
world_size (int, optional): _description_. Defaults to 1.
|
world_size (int, optional): _description_. Defaults to 1.
|
||||||
cpu (bool, optional): Whether or not to use the CPU.
|
cpu (bool, optional): Whether or not to use the CPU.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, config: DictConfig, local_rank: int = 0, world_size: int = 1):
|
||||||
self.config = config
|
self.config = config
|
||||||
self.local_rank = local_rank
|
self.local_rank = local_rank
|
||||||
self.world_size = world_size
|
self.world_size = world_size
|
||||||
@@ -133,7 +133,7 @@ class Trainer:
|
|||||||
"""Load the checkpoint from the given path
|
"""Load the checkpoint from the given path
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
load_path (str): path from which to load the model
|
load_config (DictConfig): Configuration for loading a model.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
int: step iteration associated with the loaded checkpoint
|
int: step iteration associated with the loaded checkpoint
|
||||||
@@ -154,8 +154,6 @@ class Trainer:
|
|||||||
Args:
|
Args:
|
||||||
output_dir (str): directory to save the checkpoint
|
output_dir (str): directory to save the checkpoint
|
||||||
step (int): number of steps in training for given checkpoint
|
step (int): number of steps in training for given checkpoint
|
||||||
model (Graph): Graph model to be saved
|
|
||||||
optimizers (Optimizers): Optimizers to be saved
|
|
||||||
"""
|
"""
|
||||||
if not os.path.exists(output_dir):
|
if not os.path.exists(output_dir):
|
||||||
os.makedirs(output_dir)
|
os.makedirs(output_dir)
|
||||||
@@ -181,7 +179,7 @@ class Trainer:
|
|||||||
return loss_sum
|
return loss_sum
|
||||||
|
|
||||||
def train(self) -> None:
|
def train(self) -> None:
|
||||||
"""_summary_"""
|
"""Main training loop."""
|
||||||
train_start = time()
|
train_start = time()
|
||||||
num_iterations = self.config.graph.max_num_iterations
|
num_iterations = self.config.graph.max_num_iterations
|
||||||
iter_dataloader_train = iter(self.dataloader_train)
|
iter_dataloader_train = iter(self.dataloader_train)
|
||||||
@@ -227,8 +225,12 @@ class Trainer:
|
|||||||
)
|
)
|
||||||
self._write_out_storage(num_iterations)
|
self._write_out_storage(num_iterations)
|
||||||
|
|
||||||
def _write_out_storage(self, step):
|
def _write_out_storage(self, step: int) -> None:
|
||||||
"""Perform writes only during appropriate time steps"""
|
"""Perform writes only during appropriate time steps
|
||||||
|
|
||||||
|
Args:
|
||||||
|
step (int): Current training step.
|
||||||
|
"""
|
||||||
if (
|
if (
|
||||||
step % self.config.logging.steps_per_log == 0
|
step % self.config.logging.steps_per_log == 0
|
||||||
or (self.config.graph.steps_per_save and step % self.config.graph.steps_per_save == 0)
|
or (self.config.graph.steps_per_save and step % self.config.graph.steps_per_save == 0)
|
||||||
@@ -238,8 +240,19 @@ class Trainer:
|
|||||||
writer.write_out_storage()
|
writer.write_out_storage()
|
||||||
|
|
||||||
@profiler.time_function
|
@profiler.time_function
|
||||||
def train_iteration(self, ray_indices, batch: dict, step: int, _callback: List[Callable] = None):
|
def train_iteration(
|
||||||
"""Run one iteration with a batch of inputs."""
|
self, ray_indices: TensorType["num_rays", 3], batch: dict, step: int, _callback: List[Callable] = None
|
||||||
|
) -> Dict[str, float]:
|
||||||
|
"""Run one iteration with a batch of inputs.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ray_indices (TensorType["num_rays", 3]): Contains camera, row, and col indicies for target rays.
|
||||||
|
batch (dict): Batch of training data.
|
||||||
|
step (int): Current training step.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, float]: Dictionary of model losses.
|
||||||
|
"""
|
||||||
_, loss_dict = self.graph.forward(ray_indices, batch=batch)
|
_, loss_dict = self.graph.forward(ray_indices, batch=batch)
|
||||||
loss = loss_dict["aggregated_loss"]
|
loss = loss_dict["aggregated_loss"]
|
||||||
self.optimizers.zero_grad_all()
|
self.optimizers.zero_grad_all()
|
||||||
@@ -252,8 +265,17 @@ class Trainer:
|
|||||||
return loss_dict
|
return loss_dict
|
||||||
|
|
||||||
@profiler.time_function
|
@profiler.time_function
|
||||||
def test_image(self, camera_ray_bundle: RayBundle, batch: dict, step: int = None):
|
def test_image(self, camera_ray_bundle: RayBundle, batch: dict, step: int = None) -> float:
|
||||||
"""Test a specific image."""
|
"""Test a specific image.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
camera_ray_bundle (RayBundle): Bundle of test rays.
|
||||||
|
batch (dict): Batch of data.
|
||||||
|
step (int): Current training step.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
float: PSNR
|
||||||
|
"""
|
||||||
self.graph.eval()
|
self.graph.eval()
|
||||||
image_idx = int(camera_ray_bundle.camera_indices[0, 0])
|
image_idx = int(camera_ray_bundle.camera_indices[0, 0])
|
||||||
outputs = self.graph.get_outputs_for_camera_ray_bundle(camera_ray_bundle)
|
outputs = self.graph.get_outputs_for_camera_ray_bundle(camera_ray_bundle)
|
||||||
@@ -261,7 +283,12 @@ class Trainer:
|
|||||||
self.graph.train()
|
self.graph.train()
|
||||||
return psnr
|
return psnr
|
||||||
|
|
||||||
def eval_with_dataloader(self, dataloader: EvalDataloader, step: int = None):
|
def eval_with_dataloader(self, dataloader: EvalDataloader, step: int = None) -> None:
|
||||||
"""Run evaluation with a given dataloader."""
|
"""Run evaluation with a given dataloader.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
dataloader (EvalDataLoader): Evaluation dataloader.
|
||||||
|
step (int): Current training iteration.
|
||||||
|
"""
|
||||||
for camera_ray_bundle, batch in dataloader:
|
for camera_ray_bundle, batch in dataloader:
|
||||||
self.test_image(camera_ray_bundle, batch, step=step)
|
self.test_image(camera_ray_bundle, batch, step=step)
|
||||||
@@ -72,7 +72,11 @@ class Field(nn.Module):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def forward(self, point_samples: PointSamples):
|
def forward(self, point_samples: PointSamples):
|
||||||
"""Evaluates the field at points along the ray."""
|
"""Evaluates the field at points along the ray.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
point_samples (PointSamples): Samples to evaluate field on.
|
||||||
|
"""
|
||||||
valid_mask = point_samples.valid_mask
|
valid_mask = point_samples.valid_mask
|
||||||
|
|
||||||
if is_not_none(valid_mask):
|
if is_not_none(valid_mask):
|
||||||
|
|||||||
@@ -22,10 +22,14 @@ from torchtyping import TensorType
|
|||||||
|
|
||||||
|
|
||||||
class FieldModule(nn.Module):
|
class FieldModule(nn.Module):
|
||||||
"""Field modules that can be combined to store and compute the fields."""
|
"""Field modules that can be combined to store and compute the fields.
|
||||||
|
|
||||||
def __init__(self, in_dim=None, out_dim=None) -> None:
|
Args:
|
||||||
"""Default initialization of module"""
|
in_dim (int, optional): Input dimension to module.
|
||||||
|
out_dim (int, optional): Ouput dimension to module.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, in_dim: int = None, out_dim: int = None) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.in_dim = in_dim
|
self.in_dim = in_dim
|
||||||
self.out_dim = out_dim
|
self.out_dim = out_dim
|
||||||
|
|||||||
@@ -25,14 +25,13 @@ from pyrad.fields.modules.base import FieldModule
|
|||||||
class Embedding(FieldModule):
|
class Embedding(FieldModule):
|
||||||
"""Index into embeddings.
|
"""Index into embeddings.
|
||||||
# TODO: add different types of initializations
|
# TODO: add different types of initializations
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, in_dim: int, out_dim: int) -> None:
|
|
||||||
"""
|
|
||||||
Args:
|
Args:
|
||||||
in_dim (int): Number of embeddings
|
in_dim (int): Number of embeddings
|
||||||
out_dim (int): Dimension of the embedding vectors
|
out_dim (int): Dimension of the embedding vectors
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, in_dim: int, out_dim: int) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.in_dim = in_dim
|
self.in_dim = in_dim
|
||||||
self.out_dim = out_dim
|
self.out_dim = out_dim
|
||||||
|
|||||||
@@ -29,13 +29,13 @@ from pyrad.utils.math import components_from_spherical_harmonics, expected_sin
|
|||||||
|
|
||||||
|
|
||||||
class Encoding(FieldModule):
|
class Encoding(FieldModule):
|
||||||
"""Encode an input tensor. Intended to be subclassed"""
|
"""Encode an input tensor. Intended to be subclassed
|
||||||
|
|
||||||
def __init__(self, in_dim: int) -> None:
|
|
||||||
"""
|
|
||||||
Args:
|
Args:
|
||||||
in_dim (int): Input dimension of tensor
|
in_dim (int): Input dimension of tensor
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, in_dim: int) -> None:
|
||||||
if in_dim <= 0:
|
if in_dim <= 0:
|
||||||
raise ValueError("Input dimension should be greater than zero")
|
raise ValueError("Input dimension should be greater than zero")
|
||||||
super().__init__(in_dim=in_dim)
|
super().__init__(in_dim=in_dim)
|
||||||
@@ -56,16 +56,15 @@ class Identity(Encoding):
|
|||||||
|
|
||||||
|
|
||||||
class ScalingAndOffset(Encoding):
|
class ScalingAndOffset(Encoding):
|
||||||
"""Simple scaling and offet to input"""
|
"""Simple scaling and offet to input
|
||||||
|
|
||||||
def __init__(self, in_dim: int, scaling: float = 1.0, offset: float = 0.0) -> None:
|
|
||||||
"""Each input is scaled then offset
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
in_dim (int): Input dimension of tensor
|
in_dim (int): Input dimension of tensor
|
||||||
scaling (float, optional): Scaling applied to tensor. Defaults to 1.0.
|
scaling (float, optional): Scaling applied to tensor. Defaults to 1.0.
|
||||||
offset (float, optional): Offset applied to tensor. Defaults to 0.0.
|
offset (float, optional): Offset applied to tensor. Defaults to 0.0.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, in_dim: int, scaling: float = 1.0, offset: float = 0.0) -> None:
|
||||||
super().__init__(in_dim)
|
super().__init__(in_dim)
|
||||||
|
|
||||||
self.scaling = scaling
|
self.scaling = scaling
|
||||||
@@ -79,12 +78,8 @@ class ScalingAndOffset(Encoding):
|
|||||||
|
|
||||||
|
|
||||||
class NeRFEncoding(Encoding):
|
class NeRFEncoding(Encoding):
|
||||||
"""Multi-scale sinousoidal encodings. Support ``integrated positional encodings`` if covariances are provided."""
|
"""Multi-scale sinousoidal encodings. Support ``integrated positional encodings`` if covariances are provided.
|
||||||
|
Each axis is encoded with frequencies ranging from 2^min_freq_exp to 2^max_freq_exp.
|
||||||
def __init__(
|
|
||||||
self, in_dim: int, num_frequencies: int, min_freq_exp: float, max_freq_exp: float, include_input: bool = False
|
|
||||||
) -> None:
|
|
||||||
"""Each axis is encoded with frequencies ranging from 2^min_freq_exp to 2^max_freq_exp.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
in_dim (int): Input dimension of tensor
|
in_dim (int): Input dimension of tensor
|
||||||
@@ -93,6 +88,10 @@ class NeRFEncoding(Encoding):
|
|||||||
max_freq_exp (float): Maximum frequency exponent
|
max_freq_exp (float): Maximum frequency exponent
|
||||||
include_input (float): Append the input coordinate to the encoding
|
include_input (float): Append the input coordinate to the encoding
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, in_dim: int, num_frequencies: int, min_freq_exp: float, max_freq_exp: float, include_input: bool = False
|
||||||
|
) -> None:
|
||||||
super().__init__(in_dim)
|
super().__init__(in_dim)
|
||||||
|
|
||||||
self.num_frequencies = num_frequencies
|
self.num_frequencies = num_frequencies
|
||||||
@@ -138,10 +137,7 @@ class NeRFEncoding(Encoding):
|
|||||||
|
|
||||||
|
|
||||||
class RFFEncoding(Encoding):
|
class RFFEncoding(Encoding):
|
||||||
"""Random Fourier Feature encoding. Supports integrated encodings."""
|
"""Random Fourier Feature encoding. Supports integrated encodings.
|
||||||
|
|
||||||
def __init__(self, in_dim: int, num_frequencies: int, scale: float, include_input: bool = False) -> None:
|
|
||||||
"""
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
in_dim (int): Input dimension of tensor
|
in_dim (int): Input dimension of tensor
|
||||||
@@ -149,6 +145,8 @@ class RFFEncoding(Encoding):
|
|||||||
scale (float): Std of Gaussian to sample frequencies. Must be greater than zero
|
scale (float): Std of Gaussian to sample frequencies. Must be greater than zero
|
||||||
include_input (float): Append the input coordinate to the encoding
|
include_input (float): Append the input coordinate to the encoding
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, in_dim: int, num_frequencies: int, scale: float, include_input: bool = False) -> None:
|
||||||
super().__init__(in_dim)
|
super().__init__(in_dim)
|
||||||
|
|
||||||
self.num_frequencies = num_frequencies
|
self.num_frequencies = num_frequencies
|
||||||
@@ -193,7 +191,16 @@ class RFFEncoding(Encoding):
|
|||||||
|
|
||||||
|
|
||||||
class HashEncoding(Encoding):
|
class HashEncoding(Encoding):
|
||||||
"""Hash encoding"""
|
"""Hash encoding
|
||||||
|
|
||||||
|
Args:
|
||||||
|
num_levels (int, optional): Number of feature grids. Defaults to 16.
|
||||||
|
min_res (int, optional): Resolution of smallest feature grid. Defaults to 16.
|
||||||
|
max_res (int, optional): Resolution of largest feature grid. Defaults to 1024.
|
||||||
|
hash_table_size (int, optional): Size of hash table. Defaults to 2**19.
|
||||||
|
features_per_level (int, optional): Number of features per level. Defaults to 2.
|
||||||
|
hash_init_scale (float, optional): Value to initialize hash grid. Defaults to 0.001.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -204,16 +211,7 @@ class HashEncoding(Encoding):
|
|||||||
features_per_level: int = 2,
|
features_per_level: int = 2,
|
||||||
hash_init_scale: float = 0.001,
|
hash_init_scale: float = 0.001,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""_summary_
|
|
||||||
|
|
||||||
Args:
|
|
||||||
num_levels (int, optional): Number of feature grids. Defaults to 16.
|
|
||||||
min_res (int, optional): Resolution of smallest feature grid. Defaults to 16.
|
|
||||||
max_res (int, optional): Resolution of largest feature grid. Defaults to 1024.
|
|
||||||
hash_table_size (int, optional): Size of hash table. Defaults to 2**19.
|
|
||||||
features_per_level (int, optional): Number of features per level. Defaults to 2.
|
|
||||||
hash_init_scale (float, optional): Value to initialize hash grid. Defaults to 0.001.
|
|
||||||
"""
|
|
||||||
super().__init__(in_dim=3)
|
super().__init__(in_dim=3)
|
||||||
self.num_levels = num_levels
|
self.num_levels = num_levels
|
||||||
self.features_per_level = features_per_level
|
self.features_per_level = features_per_level
|
||||||
@@ -297,15 +295,15 @@ class HashEncoding(Encoding):
|
|||||||
|
|
||||||
|
|
||||||
class TensorCPEncoding(Encoding):
|
class TensorCPEncoding(Encoding):
|
||||||
"""Learned CANDECOMP/PARFAC (CP) decomposition encoding used in TensoRF"""
|
"""Learned CANDECOMP/PARFAC (CP) decomposition encoding used in TensoRF
|
||||||
|
|
||||||
def __init__(self, resolution: int = 256, num_components: int = 24, init_scale: float = 0.1) -> None:
|
|
||||||
"""
|
|
||||||
Args:
|
Args:
|
||||||
resolution (int, optional): Resolution of grid. Defaults to 256.
|
resolution (int, optional): Resolution of grid. Defaults to 256.
|
||||||
num_components (int, optional): Number of components per dimension. Defaults to 24.
|
num_components (int, optional): Number of components per dimension. Defaults to 24.
|
||||||
init_scale (float, optional): Initialization scale. Defaults to 0.1.
|
init_scale (float, optional): Initialization scale. Defaults to 0.1.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, resolution: int = 256, num_components: int = 24, init_scale: float = 0.1) -> None:
|
||||||
super().__init__(in_dim=3)
|
super().__init__(in_dim=3)
|
||||||
|
|
||||||
self.resolution = resolution
|
self.resolution = resolution
|
||||||
@@ -347,15 +345,15 @@ class TensorCPEncoding(Encoding):
|
|||||||
|
|
||||||
|
|
||||||
class TensorVMEncoding(Encoding):
|
class TensorVMEncoding(Encoding):
|
||||||
"""Learned vector-matrix encoding proposed by TensoRF"""
|
"""Learned vector-matrix encoding proposed by TensoRF
|
||||||
|
|
||||||
def __init__(self, resolution: int = 256, num_components: int = 24, init_scale: float = 0.1) -> None:
|
|
||||||
"""
|
|
||||||
Args:
|
Args:
|
||||||
resolution (int, optional): Resolution of grid. Defaults to 256.
|
resolution (int, optional): Resolution of grid. Defaults to 256.
|
||||||
num_components (int, optional): Number of components per dimension. Defaults to 24.
|
num_components (int, optional): Number of components per dimension. Defaults to 24.
|
||||||
init_scale (float, optional): Initialization scale. Defaults to 0.1.
|
init_scale (float, optional): Initialization scale. Defaults to 0.1.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, resolution: int = 256, num_components: int = 24, init_scale: float = 0.1) -> None:
|
||||||
super().__init__(in_dim=3)
|
super().__init__(in_dim=3)
|
||||||
|
|
||||||
self.resolution = resolution
|
self.resolution = resolution
|
||||||
@@ -405,13 +403,13 @@ class TensorVMEncoding(Encoding):
|
|||||||
|
|
||||||
|
|
||||||
class SHEncoding(Encoding):
|
class SHEncoding(Encoding):
|
||||||
"""Spherical harmonic encoding"""
|
"""Spherical harmonic encoding
|
||||||
|
|
||||||
def __init__(self, levels: int = 4) -> None:
|
|
||||||
"""
|
|
||||||
Args:
|
Args:
|
||||||
levels (int, optional): Number of spherical hamonic levels to encode. Defaults to 4.
|
levels (int, optional): Number of spherical hamonic levels to encode. Defaults to 4.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, levels: int = 4) -> None:
|
||||||
super().__init__(in_dim=3)
|
super().__init__(in_dim=3)
|
||||||
|
|
||||||
if levels <= 0 or levels > 4:
|
if levels <= 0 or levels > 4:
|
||||||
|
|||||||
+12
-15
@@ -29,7 +29,18 @@ from pyrad.cameras.rays import PointSamples
|
|||||||
|
|
||||||
|
|
||||||
class NeRFField(Field):
|
class NeRFField(Field):
|
||||||
"""NeRF Field"""
|
"""NeRF Field
|
||||||
|
|
||||||
|
Args:
|
||||||
|
position_encoding (Encoding, optional): Position encoder. Defaults to Identity(in_dim=3).
|
||||||
|
direction_encoding (Encoding, optional): Direction encoder. Defaults to Identity(in_dim=3).
|
||||||
|
base_mlp_num_layers (int, optional): Number of layers for base MLP. Defaults to 8.
|
||||||
|
base_mlp_layer_width (int, optional): Width of base MLP layers. Defaults to 256.
|
||||||
|
head_mlp_num_layers (int, optional): Number of layer for ourput head MLP. Defaults to 2.
|
||||||
|
head_mlp_layer_width (int, optional): Width of output head MLP layers. Defaults to 128.
|
||||||
|
skip_connections (Tuple, optional): Where to add skip connection in base MLP. Defaults to (4,).
|
||||||
|
use_integrated_encoding (bool, optional): Used integrated samples as encoding input, Defaults to False.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -43,18 +54,6 @@ class NeRFField(Field):
|
|||||||
field_heads: Tuple[FieldHead] = (RGBFieldHead(),),
|
field_heads: Tuple[FieldHead] = (RGBFieldHead(),),
|
||||||
use_integrated_encoding: bool = False,
|
use_integrated_encoding: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Create boilerplate NeRF field.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
position_encoding (Encoding, optional): Position encoder. Defaults to Identity(in_dim=3).
|
|
||||||
direction_encoding (Encoding, optional): Direction encoder. Defaults to Identity(in_dim=3).
|
|
||||||
base_mlp_num_layers (int, optional): Number of layers for base MLP. Defaults to 8.
|
|
||||||
base_mlp_layer_width (int, optional): Width of base MLP layers. Defaults to 256.
|
|
||||||
head_mlp_num_layers (int, optional): Number of layer for ourput head MLP. Defaults to 2.
|
|
||||||
head_mlp_layer_width (int, optional): Width of output head MLP layers. Defaults to 128.
|
|
||||||
skip_connections (Tuple, optional): Where to add skip connection in base MLP. Defaults to (4,).
|
|
||||||
use_integrated_encoding (bool, optional): Used integrated samples as encoding input, Defaults to False.
|
|
||||||
"""
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.position_encoding = position_encoding
|
self.position_encoding = position_encoding
|
||||||
self.direction_encoding = direction_encoding
|
self.direction_encoding = direction_encoding
|
||||||
@@ -79,7 +78,6 @@ class NeRFField(Field):
|
|||||||
field_head.set_in_dim(self.mlp_head.get_out_dim())
|
field_head.set_in_dim(self.mlp_head.get_out_dim())
|
||||||
|
|
||||||
def get_density(self, point_samples: PointSamples):
|
def get_density(self, point_samples: PointSamples):
|
||||||
"""Computes and returns the densities."""
|
|
||||||
if self.use_integrated_encoding:
|
if self.use_integrated_encoding:
|
||||||
gaussian_samples = point_samples.frustums.get_gaussian_blob()
|
gaussian_samples = point_samples.frustums.get_gaussian_blob()
|
||||||
encoded_xyz = self.position_encoding(gaussian_samples.mean, covs=gaussian_samples.cov)
|
encoded_xyz = self.position_encoding(gaussian_samples.mean, covs=gaussian_samples.cov)
|
||||||
@@ -92,7 +90,6 @@ class NeRFField(Field):
|
|||||||
def get_outputs(
|
def get_outputs(
|
||||||
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
|
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
|
||||||
) -> Dict[FieldHeadNames, TensorType]:
|
) -> Dict[FieldHeadNames, TensorType]:
|
||||||
"""Computes and returns the outputs."""
|
|
||||||
outputs = {}
|
outputs = {}
|
||||||
for field_head in self.field_heads:
|
for field_head in self.field_heads:
|
||||||
encoded_dir = self.direction_encoding(point_samples.frustums.directions)
|
encoded_dir = self.direction_encoding(point_samples.frustums.directions)
|
||||||
|
|||||||
@@ -36,7 +36,20 @@ from pyrad.cameras.rays import PointSamples
|
|||||||
|
|
||||||
|
|
||||||
class VanillaNerfWField(Field):
|
class VanillaNerfWField(Field):
|
||||||
"""The NeRF-W field which has appearance and transient conditioning."""
|
"""The NeRF-W field which has appearance and transient conditioning.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
num_images (int): How many images exist in the dataset.
|
||||||
|
position_encoding (Encoding, optional): Position encoder. Defaults to Identity(in_dim=3).
|
||||||
|
direction_encoding (Encoding, optional): Direction encoder. Defaults to Identity(in_dim=3).
|
||||||
|
base_mlp_num_layers (int, optional): Number of layers for base MLP. Defaults to 8.
|
||||||
|
base_mlp_layer_width (int, optional): Width of base MLP layers. Defaults to 256.
|
||||||
|
head_mlp_num_layers (int, optional): Number of layer for ourput head MLP. Defaults to 2.
|
||||||
|
head_mlp_layer_width (int, optional): Width of output head MLP layers. Defaults to 128.
|
||||||
|
appearance_embedding_dim: (int, optional): Dimension of appearance embedding. Defaults to 48.
|
||||||
|
transient_embedding_dim: (int, optional): Dimension of transient embedding. Defaults to 16.
|
||||||
|
skip_connections (Tuple, optional): Where to add skip connection in base MLP. Defaults to (4,).
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ class OccupancyGrid(nn.Module):
|
|||||||
"""Module to keep track of the density and occupancy."""
|
"""Module to keep track of the density and occupancy."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self, num_cascades=1, resolution=128, aabb=None, density_fn=None, update_every_num_iters: int = 16
|
self, num_cascades: int = 1, resolution: int = 128, aabb=None, density_fn=None, update_every_num_iters: int = 16
|
||||||
) -> None:
|
) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
assert is_not_none(aabb), "The axis-aligned bounding box aabb is not defined!"
|
assert is_not_none(aabb), "The axis-aligned bounding box aabb is not defined!"
|
||||||
|
|||||||
+23
-6
@@ -50,14 +50,24 @@ class AbstractGraph(nn.Module):
|
|||||||
|
|
||||||
|
|
||||||
class Graph(AbstractGraph):
|
class Graph(AbstractGraph):
|
||||||
"""_summary_"""
|
"""Where everything (Fields, Optimizers, Samplers, Visualization, etc) is linked together. This should be
|
||||||
|
subclassed for custom NeRF model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
intrinsics (torch.Tensor): Camera intrinsics.
|
||||||
|
camera_to_world (torch.Tensor): Camera to world transformation.
|
||||||
|
loss_coefficients (DictConfig): Loss specific weights.
|
||||||
|
steps_per_occupancy_grid_update (int): How often to update occupancy grid.
|
||||||
|
scene_bounds (SceneBounds): Bounds of target scene.
|
||||||
|
collider_config (DictConfig): Configuration of scene collider.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
intrinsics=None,
|
intrinsics: torch.Tensor = None,
|
||||||
camera_to_world=None,
|
camera_to_world: torch.Tensor = None,
|
||||||
loss_coefficients: DictConfig = None,
|
loss_coefficients: DictConfig = None,
|
||||||
steps_per_occupancy_grid_update=16,
|
steps_per_occupancy_grid_update: int = 16,
|
||||||
scene_bounds: SceneBounds = None,
|
scene_bounds: SceneBounds = None,
|
||||||
collider_config: DictConfig = None,
|
collider_config: DictConfig = None,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
@@ -94,8 +104,15 @@ class Graph(AbstractGraph):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_outputs(self, ray_bundle: RayBundle):
|
def get_outputs(self, ray_bundle: RayBundle) -> dict:
|
||||||
"""Takes in a Ray Bundle and returns a dictionary of outputs."""
|
"""Takes in a Ray Bundle and returns a dictionary of outputs.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ray_bundle (RayBundle): Input bundle of rays.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Outputs of graph. (ie. rendered colors)
|
||||||
|
"""
|
||||||
|
|
||||||
def forward_after_ray_generator(self, ray_bundle: RayBundle, batch: Union[str, Dict[str, torch.tensor]] = None):
|
def forward_after_ray_generator(self, ray_bundle: RayBundle, batch: Union[str, Dict[str, torch.tensor]] = None):
|
||||||
"""Run forward starting with a ray bundle."""
|
"""Run forward starting with a ray bundle."""
|
||||||
|
|||||||
@@ -23,20 +23,19 @@ from pyrad.cameras.cameras import get_camera_model
|
|||||||
|
|
||||||
class RayGenerator(nn.Module):
|
class RayGenerator(nn.Module):
|
||||||
"""torch.nn Module for generating rays.
|
"""torch.nn Module for generating rays.
|
||||||
This class will store the intrinsics and extrinsics parameters of the cameras."""
|
This class will store the intrinsics and extrinsics parameters of the cameras.
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
intrinsics: TensorType["num_cameras", "num_intrinsics_params"],
|
|
||||||
camera_to_world: TensorType["num_cameras", 3, 4],
|
|
||||||
) -> None:
|
|
||||||
"""_summary_
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
intrinsics (TensorType["num_cameras", "num_intrinsics_params"]):
|
intrinsics (TensorType["num_cameras", "num_intrinsics_params"]):
|
||||||
The intrinsics parameters.
|
The intrinsics parameters.
|
||||||
camera_to_world (TensorType["num_cameras", 3, 4]): Camera to world transformation matrix.
|
camera_to_world (TensorType["num_cameras", 3, 4]): Camera to world transformation matrix.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
intrinsics: TensorType["num_cameras", "num_intrinsics_params"],
|
||||||
|
camera_to_world: TensorType["num_cameras", 3, 4],
|
||||||
|
) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.num_cameras, self.num_intrinsics_params = intrinsics.shape
|
self.num_cameras, self.num_intrinsics_params = intrinsics.shape
|
||||||
assert self.num_cameras >= 0
|
assert self.num_cameras >= 0
|
||||||
@@ -54,7 +53,7 @@ class RayGenerator(nn.Module):
|
|||||||
"""Index into the cameras to generate the rays.
|
"""Index into the cameras to generate the rays.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
x (_type_): _description_
|
ray_indices (TensorType["num_rays", 3]): Contains camera, row, and col indicies for target rays.
|
||||||
"""
|
"""
|
||||||
c = ray_indices[:, 0] # camera indices
|
c = ray_indices[:, 0] # camera indices
|
||||||
y = ray_indices[:, 1] # row indices
|
y = ray_indices[:, 1] # row indices
|
||||||
|
|||||||
@@ -37,16 +37,25 @@ from pyrad.utils import visualization, writer
|
|||||||
|
|
||||||
|
|
||||||
class NeRFGraph(Graph):
|
class NeRFGraph(Graph):
|
||||||
"""Vanilla NeRF graph"""
|
"""Vanilla NeRF graph
|
||||||
|
|
||||||
|
Args:
|
||||||
|
intrinsics (torch.Tensor): Camera intrinsics.
|
||||||
|
camera_to_world (torch.Tensor): Camera to world transformation.
|
||||||
|
near_plane (float, optional): Where to start sampling points. Defaults to a distance of 2,
|
||||||
|
far_plane (float, optional): Where to stop sampling points. Defaults to a distance of 6,
|
||||||
|
num_coarse_samples (int, optional): Number of samples in coarse field evaluation. Defaults to 64,
|
||||||
|
num_importance_samples(int, optional): Number of samples in fine field evaluation. Defaults to 64,
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
intrinsics=None,
|
intrinsics: torch.Tensor = None,
|
||||||
camera_to_world=None,
|
camera_to_world: torch.Tensor = None,
|
||||||
near_plane=2.0,
|
near_plane: float = 2.0,
|
||||||
far_plane=6.0,
|
far_plane: float = 6.0,
|
||||||
num_coarse_samples=64,
|
num_coarse_samples: int = 64,
|
||||||
num_importance_samples=128,
|
num_importance_samples: int = 128,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.near_plane = near_plane
|
self.near_plane = near_plane
|
||||||
|
|||||||
Reference in new issue
Block a user