mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-02 05:48:57 +08:00
Restructure into field modules
This commit is contained in:
1 parent
28a66dac72
commit
5e24cbf6fe
13 files changed
+21
-23
No files matched your search
@@ -0,0 +1,4 @@
|
||||
"""init field modules"""
|
||||
from .encoding import Encoding, ScalingAndOffset
|
||||
from .mlp import MLP
|
||||
from .base import FieldModule
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
The field module baseclass.
|
||||
"""
|
||||
from abc import abstractmethod
|
||||
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
|
||||
class FieldModule(nn.Module):
|
||||
"""Field modules that can be combined to store and compute the fields."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Default initialization of module"""
|
||||
super().__init__()
|
||||
self.in_dim = 0
|
||||
self.out_dim = 0
|
||||
|
||||
def build_nn_modules(self) -> None:
|
||||
"""Function instantiates any torch.nn members within the module.
|
||||
If none exist, do nothing."""
|
||||
|
||||
def set_in_dim(self, in_dim: int) -> None:
|
||||
"""Sets input dimension of encoding
|
||||
|
||||
Args:
|
||||
in_dim (int): input dimension
|
||||
"""
|
||||
if in_dim <= 0:
|
||||
raise ValueError("Input dimension should be greater than zero")
|
||||
self.in_dim = in_dim
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
"""Calculates output dimension of encoding.
|
||||
|
||||
Returns:
|
||||
int: output dimension
|
||||
"""
|
||||
if not hasattr(self, "out_dim"):
|
||||
raise ValueError("Output dimension has not been set")
|
||||
if self.out_dim <= 0:
|
||||
raise ValueError("Output dimension should be greater than zero")
|
||||
return self.out_dim
|
||||
|
||||
@abstractmethod
|
||||
def forward(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
"""_summary_
|
||||
|
||||
Args:
|
||||
x (TensorType[..., "input_dim"]): Input tensor to be encoded
|
||||
|
||||
Raises:
|
||||
NotImplementedError: _description_
|
||||
|
||||
Returns:
|
||||
TensorType[..., "output_dim"]: A encoded input tensor
|
||||
"""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
Encoding functions
|
||||
"""
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
from mattport.nerf.field_modules.base import FieldModule
|
||||
|
||||
|
||||
class Encoding(FieldModule):
|
||||
"""Encode an input tensor. Intended to be subclassed"""
|
||||
|
||||
def __init__(self, in_dim: int) -> None:
|
||||
"""
|
||||
Args:
|
||||
in_dim (int): Input dimension of tensor
|
||||
"""
|
||||
super().__init__()
|
||||
if in_dim <= 0:
|
||||
raise ValueError("Input dimension should be greater than zero")
|
||||
self.in_dim = in_dim
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
"""Encodes an input tensor.
|
||||
|
||||
Args:
|
||||
x (TensorType[..., "input_dim"]): Input tensor to be encoded
|
||||
|
||||
Returns:
|
||||
TensorType[..., "output_dim"]: A encoded input tensor
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def forward(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
"""Call forward"""
|
||||
return self.encode(in_tensor)
|
||||
|
||||
|
||||
class ScalingAndOffset(Encoding):
|
||||
"""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:
|
||||
in_dim (int): Input dimension of tensor
|
||||
scaling (float, optional): Scaling applied to tensor. Defaults to 1.0.
|
||||
offset (float, optional): Offset applied to tensor. Defaults to 0.0.
|
||||
"""
|
||||
super().__init__(in_dim)
|
||||
|
||||
self.scaling = scaling
|
||||
self.offset = offset
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.in_dim
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
return self.scaling * in_tensor + self.offset
|
||||
|
||||
|
||||
class NeRFEncoding(Encoding):
|
||||
"""Multi-scale sinousoidal encoding proposed in the original NeRF paper"""
|
||||
|
||||
def __init__(self, in_dim: int, num_frequencies: int, min_freq_exp: float, max_freq_exp: float) -> None:
|
||||
"""Each axis is encoded with frequencies ranging from 2^min_freq_exp to 2^max_freq_exp.
|
||||
|
||||
Args:
|
||||
in_dim (int): Input dimension of tensor
|
||||
num_frequencies (int): Number of encoded frequencies per axis
|
||||
min_freq_exp (float): Minimum frequency exponent
|
||||
max_freq_exp (float): Maximum frequency exponent
|
||||
"""
|
||||
super().__init__(in_dim)
|
||||
|
||||
self.num_frequencies = num_frequencies
|
||||
self.min_freq = min_freq_exp
|
||||
self.max_freq = max_freq_exp
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.in_dim * self.num_frequencies * 2
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
"""
|
||||
Args:
|
||||
in_tensor (TensorType[..., "input_dim"]): For best performance, the input tensor should be between 0 and 1.
|
||||
|
||||
Returns:
|
||||
TensorType[..., "output_dim"]: Output values will be between -1 and 1
|
||||
"""
|
||||
freqs = 2 ** torch.linspace(self.min_freq, self.max_freq, self.num_frequencies)
|
||||
scaled_inputs = 2 * torch.pi * in_tensor[..., None] * freqs # [..., "input_dim", "num_scales"]
|
||||
scaled_inputs = scaled_inputs.view(*scaled_inputs.shape[:-2], -1) # [..., "input_dim" * "num_scales"]
|
||||
encoded_inputs = torch.cat([torch.sin(scaled_inputs), torch.cos(scaled_inputs)], axis=-1)
|
||||
return encoded_inputs
|
||||
|
||||
|
||||
class RFFEncoding(Encoding):
|
||||
"""Random Fourier Feature encoding"""
|
||||
|
||||
def __init__(self, in_dim: int, num_frequencies: int, scale: float) -> None:
|
||||
"""
|
||||
|
||||
Args:
|
||||
in_dim (int): Input dimension of tensor
|
||||
num_frequencies (int): Number of encoding frequencies
|
||||
scale (float): Std of Gaussian to sample frequencies. Must be greater than zero
|
||||
"""
|
||||
super().__init__(in_dim)
|
||||
|
||||
self.num_frequencies = num_frequencies
|
||||
if not scale > 0:
|
||||
raise ValueError("RFF encoding scale should be greater than zero")
|
||||
self.scale = scale
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.num_frequencies * 2
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
"""
|
||||
Args:
|
||||
in_tensor (TensorType[..., "input_dim"]): For best performance, the input tensor should be between 0 and 1.
|
||||
|
||||
Returns:
|
||||
TensorType[..., "output_dim"]: Output values will be between -1 and 1
|
||||
"""
|
||||
b_matrix = torch.normal(mean=0, std=self.scale, size=(self.in_dim, self.num_frequencies))
|
||||
scaled_inputs = in_tensor @ b_matrix # [..., "num_frequencies"]
|
||||
encoded_inputs = torch.cat([torch.sin(scaled_inputs), torch.cos(scaled_inputs)], axis=-1)
|
||||
return encoded_inputs
|
||||
|
||||
|
||||
class HashEncoding(Encoding):
|
||||
"""Hash encoding"""
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
"""Encodes an input tensor.
|
||||
|
||||
Args:
|
||||
x (TensorType[..., "input_dim"]): Input tensor to be encoded
|
||||
|
||||
Returns:
|
||||
TensorType[..., "output_dim"]: A encoded input tensor
|
||||
"""
|
||||
raise NotImplementedError
|
||||
Whitespace-only changes.
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
Multi Layer Perceptron
|
||||
"""
|
||||
from typing import Optional
|
||||
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
from mattport.nerf.field_modules.base import FieldModule
|
||||
|
||||
|
||||
class MLP(FieldModule):
|
||||
"""Multilayer perceptron"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_dim: int,
|
||||
out_dim: int,
|
||||
num_layers: int,
|
||||
layer_width: int,
|
||||
activation: Optional[nn.Module] = None,
|
||||
out_activation: Optional[nn.Module] = None,
|
||||
) -> None:
|
||||
"""Initialize parameters of mulilayer perceptron.
|
||||
|
||||
Args:
|
||||
in_dim (int): Input layer dimension
|
||||
out_dim (int): Ouput layer dimension
|
||||
num_layers (int): Number of network layers
|
||||
layer_width (int): Width of each MLP layer
|
||||
activation (Optional[nn.Module], optional): intermediate layer activation function. Defaults to nn.ReLU.
|
||||
out_activation (Optional[nn.Module], optional): output activation function. Defaults to None.
|
||||
"""
|
||||
super().__init__()
|
||||
self.in_dim = in_dim
|
||||
self.out_dim = out_dim
|
||||
self.num_layers = num_layers
|
||||
self.layer_width = layer_width
|
||||
self.activation = activation
|
||||
self.out_activation = out_activation
|
||||
self.net = None
|
||||
|
||||
def build_model(self) -> None:
|
||||
"""Initialize mulilayer perceptron."""
|
||||
layers = []
|
||||
for i in range(self.num_layers):
|
||||
if i == 0:
|
||||
layers.append(nn.Linear(self.in_dim, self.layer_width))
|
||||
else:
|
||||
layers.append(nn.Linear(self.layer_width, self.layer_width))
|
||||
if self.activation is not None:
|
||||
layers.append(self.activation)
|
||||
layers.append(nn.Linear(self.layer_width, self.out_dim))
|
||||
if self.out_activation is not None:
|
||||
layers.append(self.out_activation)
|
||||
|
||||
self.net = nn.Sequential(*layers)
|
||||
|
||||
def forward(self, in_tensor: TensorType[..., "in_dim"]) -> TensorType[..., "out_dim"]:
|
||||
"""Process input with a multilayer perceptron.
|
||||
|
||||
Args:
|
||||
in_tensor (TensorType[..., "in_dim]): Network input
|
||||
|
||||
Returns:
|
||||
TensorType[..., "out_dim"]: Network output
|
||||
"""
|
||||
|
||||
return self.net(in_tensor)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
Ray generator.
|
||||
"""
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
from mattport.structures.rays import RayBundle
|
||||
from mattport.structures.cameras import get_camera_model
|
||||
|
||||
|
||||
class RayGenerator(nn.Module):
|
||||
"""torch.nn Module for generating rays.
|
||||
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:
|
||||
intrinsics (TensorType["num_cameras", "num_intrinsics_params"]):
|
||||
The intrinsics parameters.
|
||||
camera_to_world (TensorType["num_cameras", 3, 4]): Camera to world transformation matrix.
|
||||
"""
|
||||
super().__init__()
|
||||
self.num_cameras, self.num_intrinsics_params = intrinsics.shape
|
||||
assert self.num_cameras >= 0
|
||||
self.intrinsics = nn.Parameter(intrinsics, requires_grad=False)
|
||||
self.camera_to_world = nn.Parameter(camera_to_world, requires_grad=False)
|
||||
# TODO(ethan): add learnable parameters that are deltas on the intrinsics and camera_to_world parameters
|
||||
|
||||
def forward(self, ray_indices: TensorType["num_rays", 3]) -> RayBundle:
|
||||
"""Index into the cameras to generate the rays.
|
||||
|
||||
Args:
|
||||
x (_type_): _description_
|
||||
"""
|
||||
c = ray_indices[:, 0] # camera indices
|
||||
i = ray_indices[:, 1] # row indices
|
||||
j = ray_indices[:, 2] # col indices
|
||||
intrinsics = self.intrinsics[c]
|
||||
camera_to_world = self.camera_to_world[c]
|
||||
# NOTE(ethan): we currently assume all images have the same height and width
|
||||
camera_index = 0
|
||||
camera_class = get_camera_model(self.num_intrinsics_params)
|
||||
camera = camera_class(*self.intrinsics[camera_index].tolist())
|
||||
image_coords = camera.get_image_coords()
|
||||
coords = image_coords[i, j]
|
||||
|
||||
ray_bundle = camera_class.generate_rays(intrinsics=intrinsics, camera_to_world=camera_to_world, coords=coords)
|
||||
ray_bundle.camera_indices = c
|
||||
return ray_bundle
|
||||
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
Collection of render heads
|
||||
"""
|
||||
from typing import Optional
|
||||
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from mattport.nerf.field_modules.base import FieldModule
|
||||
|
||||
|
||||
class RenderHead(FieldModule):
|
||||
"""Base Render head"""
|
||||
|
||||
def __init__(self, in_dim: int, out_dim: int, activation: Optional[nn.Module] = None) -> None:
|
||||
"""
|
||||
Args:
|
||||
in_dim (int): input dimension
|
||||
out_dim (int): output dimension for renderer
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
super().__init__()
|
||||
self.in_dim = in_dim
|
||||
self.out_dim = out_dim
|
||||
self.activation = activation
|
||||
|
||||
self.net = None
|
||||
|
||||
def build_nn_modules(self) -> None:
|
||||
layers = [nn.Linear(self.in_dim, self.out_dim)]
|
||||
if self.activation:
|
||||
layers.append(self.activation)
|
||||
print(layers)
|
||||
self.net = nn.Sequential(*layers)
|
||||
|
||||
def forward(self, in_tensor: TensorType[..., "in_dim"]) -> TensorType[..., "out_dim"]:
|
||||
"""Process network output for renderer
|
||||
|
||||
Args:
|
||||
in_tensor (TensorType[..., "in_dim]): Network input
|
||||
|
||||
Returns:
|
||||
TensorType[..., "out_dim"]: Render head output
|
||||
"""
|
||||
if not self.net:
|
||||
raise SystemError("Render head network not initialized. build_nn_modules() should be called.")
|
||||
return self.net(in_tensor)
|
||||
|
||||
|
||||
class DensityHead(RenderHead):
|
||||
"""Density head"""
|
||||
|
||||
def __init__(self, in_dim: int, activation: Optional[nn.Module] = nn.Softplus()) -> None:
|
||||
super().__init__(in_dim, 1, activation)
|
||||
|
||||
|
||||
class RGBHead(RenderHead):
|
||||
"""RGB head"""
|
||||
|
||||
def __init__(self, in_dim: int, activation: Optional[nn.Module] = nn.Sigmoid()) -> None:
|
||||
super().__init__(in_dim, 3, activation)
|
||||
Reference in new issue
Block a user