mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-05 15:28:49 +08:00
dataloader logic, new folder structure, flatter configs (#26)
* renaming dataloader to data. adding some dataloader classes * restructuring configs * fixed instant ngp tcnn direction rescaling * working through test cases * black and lint and tests
This commit is contained in:
1 parent
24c1c77ef1
commit
457788d689
105 files changed
+8828
-682
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
Base class for the graphs.
|
||||
"""
|
||||
|
||||
from abc import abstractmethod
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
from torch import nn
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
from pyrad.fields.modules.field_heads import FieldHeadNames
|
||||
|
||||
from pyrad.cameras.rays import Frustums, PointSamples
|
||||
from pyrad.utils.misc import is_not_none
|
||||
|
||||
|
||||
class Field(nn.Module):
|
||||
"""Base class for fields."""
|
||||
|
||||
def density_fn(self, positions):
|
||||
"""Returns only the density. Used primarily with the occupancy grid."""
|
||||
# Need to figure out a better way to descibe positions with a ray.
|
||||
point_samples = PointSamples(
|
||||
frustums=Frustums(
|
||||
origins=positions,
|
||||
directions=torch.ones_like(positions),
|
||||
frustum_starts=torch.zeros((*positions.shape[:-1], 1)),
|
||||
frustum_ends=torch.zeros((*positions.shape[:-1], 1)),
|
||||
pixel_area=torch.ones((*positions.shape[:-1], 1)),
|
||||
)
|
||||
)
|
||||
density, _ = self.get_density(point_samples)
|
||||
return density
|
||||
|
||||
@abstractmethod
|
||||
def get_density(self, point_samples: PointSamples) -> Tuple[TensorType[..., 1], TensorType[..., "num_features"]]:
|
||||
"""Computes and returns the densities.
|
||||
|
||||
Args:
|
||||
point_samples (PointSamples): Samples locations to compute density.
|
||||
|
||||
Returns:
|
||||
Tuple[TensorType[...,1], TensorType[...,"num_features"]]: A tensor of densities and a tensor of features.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_outputs(
|
||||
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
|
||||
) -> Dict[FieldHeadNames, TensorType]:
|
||||
"""Computes and returns the colors.
|
||||
|
||||
Args:
|
||||
point_samples (PointSamples): Samples locations to compute outputs.
|
||||
density_embedding (TensorType, optional): Density embeddings to condition on.
|
||||
|
||||
Returns:
|
||||
Dict[FieldHeadNames, TensorType]: Output field values.
|
||||
"""
|
||||
|
||||
def forward(self, point_samples: PointSamples):
|
||||
"""Evaluates the field at points along the ray."""
|
||||
valid_mask = point_samples.valid_mask
|
||||
|
||||
if is_not_none(valid_mask):
|
||||
# Hacky handling of empty masks. Tests on a single ray but doesn't use results
|
||||
if not valid_mask.any():
|
||||
point_samples = PointSamples(frustums=Frustums.get_mock_frustum())
|
||||
else:
|
||||
point_samples = point_samples.apply_masks()
|
||||
density_masked, density_embedding_masked = self.get_density(point_samples)
|
||||
field_outputs_masked = self.get_outputs(point_samples, density_embedding=density_embedding_masked)
|
||||
|
||||
field_outputs = {}
|
||||
for k, value in field_outputs_masked.items():
|
||||
zeros = torch.zeros(*valid_mask.shape, value.shape[-1], dtype=torch.float32, device=valid_mask.device)
|
||||
if valid_mask.any():
|
||||
zeros[valid_mask] = value
|
||||
else:
|
||||
zeros[0, :] = value
|
||||
field_outputs[k] = zeros
|
||||
density = torch.zeros(*valid_mask.shape, 1, dtype=torch.float32, device=valid_mask.device)
|
||||
if valid_mask.any():
|
||||
density[valid_mask] = density_masked
|
||||
else:
|
||||
density, density_embedding = self.get_density(point_samples)
|
||||
field_outputs = self.get_outputs(point_samples, density_embedding=density_embedding)
|
||||
|
||||
field_outputs[FieldHeadNames.DENSITY] = density
|
||||
return field_outputs
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
Instant-NGP field implementations using tiny-cuda-nn, torch, ....
|
||||
"""
|
||||
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch.nn.parameter import Parameter
|
||||
|
||||
from pyrad.fields.modules.encoding import Encoding, HashEncoding, SHEncoding
|
||||
from pyrad.fields.modules.field_heads import FieldHeadNames
|
||||
from pyrad.fields.base import Field
|
||||
from pyrad.fields.nerf_field import NeRFField
|
||||
from pyrad.cameras.rays import PointSamples
|
||||
|
||||
try:
|
||||
import tinycudann as tcnn
|
||||
except ImportError as e:
|
||||
# tinycudann module doesn't exist
|
||||
pass
|
||||
|
||||
|
||||
def get_normalized_positions(positions, aabb):
|
||||
"""Return normalized positions in range [0, 1] based on the aabb axis-aligned bounding box."""
|
||||
aabb_lengths = aabb[1] - aabb[0]
|
||||
positions = (positions - aabb[0]) / aabb_lengths
|
||||
return positions
|
||||
|
||||
|
||||
def get_normalized_directions(directions):
|
||||
"""SH encoding must be in the range [0, 1]"""
|
||||
return (directions + 1.0) / 2.0
|
||||
|
||||
|
||||
class TCNNInstantNGPField(Field):
|
||||
"""NeRF Field"""
|
||||
|
||||
def __init__(
|
||||
self, aabb, num_layers=2, hidden_dim=64, geo_feat_dim=15, num_layers_color=3, hidden_dim_color=64
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.aabb = Parameter(aabb, requires_grad=False)
|
||||
|
||||
self.geo_feat_dim = geo_feat_dim
|
||||
|
||||
# TODO: set this properly based on the aabb
|
||||
per_level_scale = 1.4472692012786865
|
||||
|
||||
self.position_encoding = tcnn.Encoding(
|
||||
n_input_dims=3,
|
||||
encoding_config={
|
||||
"otype": "HashGrid",
|
||||
"n_levels": 16,
|
||||
"n_features_per_level": 2,
|
||||
"log2_hashmap_size": 19,
|
||||
"base_resolution": 16,
|
||||
"per_level_scale": per_level_scale,
|
||||
},
|
||||
)
|
||||
|
||||
self.direction_encoding = tcnn.Encoding(
|
||||
n_input_dims=3,
|
||||
encoding_config={
|
||||
"otype": "SphericalHarmonics",
|
||||
"degree": 4,
|
||||
},
|
||||
)
|
||||
|
||||
self.mlp_base = tcnn.Network(
|
||||
n_input_dims=32,
|
||||
n_output_dims=1 + self.geo_feat_dim,
|
||||
network_config={
|
||||
"otype": "FullyFusedMLP",
|
||||
"activation": "ReLU",
|
||||
"output_activation": "None",
|
||||
"n_neurons": hidden_dim,
|
||||
"n_hidden_layers": num_layers - 1,
|
||||
},
|
||||
)
|
||||
|
||||
self.mlp_head = tcnn.Network(
|
||||
n_input_dims=self.direction_encoding.n_output_dims + self.geo_feat_dim,
|
||||
n_output_dims=3,
|
||||
network_config={
|
||||
"otype": "FullyFusedMLP",
|
||||
"activation": "ReLU",
|
||||
"output_activation": "None",
|
||||
"n_neurons": hidden_dim_color,
|
||||
"n_hidden_layers": num_layers_color - 1,
|
||||
},
|
||||
)
|
||||
|
||||
def get_density(self, point_samples: PointSamples):
|
||||
"""Computes and returns the densities."""
|
||||
positions = get_normalized_positions(point_samples.frustums.get_positions(), self.aabb)
|
||||
positions_flat = positions.view(-1, 3)
|
||||
dtype = positions_flat.dtype
|
||||
x = self.position_encoding(positions_flat)
|
||||
h = self.mlp_base(x).view(*point_samples.frustums.get_positions().shape[:-1], -1).to(dtype)
|
||||
density_before_activation, base_mlp_out = torch.split(h, [1, self.geo_feat_dim], dim=-1)
|
||||
density = F.softplus(density_before_activation)
|
||||
return density, base_mlp_out
|
||||
|
||||
def get_outputs(self, point_samples: PointSamples, density_embedding=None):
|
||||
# TODO: add valid_mask masking!
|
||||
# tcnn requires directions in the range [0,1]
|
||||
directions = get_normalized_directions(point_samples.frustums.directions)
|
||||
directions_flat = directions.view(-1, 3)
|
||||
dtype = directions_flat.dtype
|
||||
d = self.direction_encoding(directions_flat)
|
||||
h = torch.cat([d, density_embedding.view(-1, self.geo_feat_dim)], dim=-1)
|
||||
h = self.mlp_head(h).view(*point_samples.frustums.directions.shape[:-1], -1).to(dtype)
|
||||
rgb = torch.sigmoid(h)
|
||||
return {FieldHeadNames.RGB: rgb}
|
||||
|
||||
|
||||
class TorchInstantNGPField(NeRFField):
|
||||
"""
|
||||
PyTorch implementation of the instant-ngp field.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
aabb,
|
||||
position_encoding: Encoding = HashEncoding(),
|
||||
direction_encoding: Encoding = SHEncoding(),
|
||||
base_mlp_num_layers: int = 3,
|
||||
base_mlp_layer_width: int = 64,
|
||||
head_mlp_num_layers: int = 2,
|
||||
head_mlp_layer_width: int = 32,
|
||||
skip_connections: Tuple = (4,),
|
||||
) -> None:
|
||||
super().__init__(
|
||||
position_encoding,
|
||||
direction_encoding,
|
||||
base_mlp_num_layers,
|
||||
base_mlp_layer_width,
|
||||
head_mlp_num_layers,
|
||||
head_mlp_layer_width,
|
||||
skip_connections,
|
||||
)
|
||||
self.aabb = Parameter(aabb, requires_grad=False)
|
||||
|
||||
def get_density(self, point_samples: PointSamples):
|
||||
normalized_point_samples = point_samples
|
||||
normalized_point_samples.positions = get_normalized_positions(
|
||||
normalized_point_samples.frustums.get_positions(), self.aabb
|
||||
)
|
||||
return super().get_density(normalized_point_samples)
|
||||
|
||||
|
||||
field_implementation_to_class = {"tcnn": TCNNInstantNGPField, "torch": TorchInstantNGPField}
|
||||
@@ -0,0 +1,4 @@
|
||||
"""init field modules"""
|
||||
from .encoding import Encoding, ScalingAndOffset
|
||||
from .mlp import MLP
|
||||
from .base import FieldModule
|
||||
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
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"]:
|
||||
"""
|
||||
Args:
|
||||
in_tensor (TensorType[..., "input_dim"]): Input tensor to process
|
||||
|
||||
Returns:
|
||||
TensorType[..., "output_dim"]: Processed tensor
|
||||
"""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
Code for embeddings.
|
||||
"""
|
||||
|
||||
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
from pyrad.fields.modules.base import FieldModule
|
||||
|
||||
|
||||
class Embedding(FieldModule):
|
||||
"""Index into embeddings.
|
||||
# TODO: add different types of initializations
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: int, out_dim: int) -> None:
|
||||
"""
|
||||
Args:
|
||||
in_dim (int): Number of embeddings
|
||||
out_dim (int): Dimension of the embedding vectors
|
||||
"""
|
||||
super().__init__()
|
||||
self.in_dim = in_dim
|
||||
self.out_dim = out_dim
|
||||
self.build_nn_modules()
|
||||
|
||||
def build_nn_modules(self) -> None:
|
||||
self.embedding = torch.nn.Embedding(self.in_dim, self.out_dim)
|
||||
|
||||
def forward(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
"""Call forward"""
|
||||
return self.embedding(in_tensor)
|
||||
@@ -0,0 +1,393 @@
|
||||
"""
|
||||
Encoding functions
|
||||
"""
|
||||
|
||||
from abc import abstractmethod
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from pyrad.fields.modules.base import FieldModule
|
||||
from pyrad.utils.math import components_from_spherical_harmonics
|
||||
|
||||
|
||||
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
|
||||
|
||||
@abstractmethod
|
||||
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 Identity(Encoding):
|
||||
"""Identity encoding (Does not modify input)"""
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.in_dim
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
return 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, include_input: bool = False
|
||||
) -> 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
|
||||
include_input (float): Append the input coordinate to the encoding
|
||||
"""
|
||||
super().__init__(in_dim)
|
||||
|
||||
self.num_frequencies = num_frequencies
|
||||
self.min_freq = min_freq_exp
|
||||
self.max_freq = max_freq_exp
|
||||
self.include_input = include_input
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
out_dim = self.in_dim * self.num_frequencies * 2
|
||||
if self.include_input:
|
||||
out_dim += self.in_dim
|
||||
return out_dim
|
||||
|
||||
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).to(in_tensor.device)
|
||||
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)
|
||||
if self.include_input:
|
||||
encoded_inputs = torch.cat([encoded_inputs, in_tensor], 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
|
||||
b_matrix = torch.normal(mean=0, std=self.scale, size=(self.in_dim, self.num_frequencies))
|
||||
self.register_buffer(name="b_matrix", tensor=b_matrix)
|
||||
|
||||
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
|
||||
"""
|
||||
scaled_inputs = in_tensor @ self.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 __init__(
|
||||
self,
|
||||
num_levels: int = 16,
|
||||
min_res: int = 16,
|
||||
max_res: int = 1024,
|
||||
hash_table_size: int = 2**19,
|
||||
features_per_level: int = 2,
|
||||
hash_init_scale: float = 0.001,
|
||||
) -> 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)
|
||||
self.num_levels = num_levels
|
||||
self.features_per_level = features_per_level
|
||||
self.hash_table_size = hash_table_size
|
||||
|
||||
levels = torch.arange(num_levels)
|
||||
growth_factor = np.exp((np.log(max_res) - np.log(min_res)) / (num_levels - 1))
|
||||
self.scalings = torch.floor(min_res * growth_factor**levels)
|
||||
|
||||
self.hash_offset = levels * hash_table_size
|
||||
self.hash_table = torch.rand(size=(hash_table_size * num_levels, features_per_level)) * 2 - 1
|
||||
self.hash_table *= hash_init_scale
|
||||
self.hash_table = nn.Parameter(self.hash_table)
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.num_levels * self.features_per_level
|
||||
|
||||
def hash_fn(self, in_tensor: TensorType[..., "num_levels", 3]) -> TensorType[..., "num_levels"]:
|
||||
"""Hash tensor using method described in Instant-NGP
|
||||
|
||||
Args:
|
||||
in_tensor (TensorType[..., "num_levels", 3]): Tensor to be hashed
|
||||
|
||||
Returns:
|
||||
TensorType[..., "num_levels"]: Hashed tensor
|
||||
"""
|
||||
|
||||
# min_val = torch.min(in_tensor)
|
||||
# max_val = torch.max(in_tensor)
|
||||
# assert min_val >= 0.0
|
||||
# assert max_val <= 1.0
|
||||
|
||||
in_tensor = in_tensor * torch.tensor([1, 2654435761, 805459861]).to(in_tensor.device)
|
||||
x = torch.bitwise_xor(in_tensor[..., 0], in_tensor[..., 1])
|
||||
x = torch.bitwise_xor(x, in_tensor[..., 2])
|
||||
x %= self.hash_table_size
|
||||
x += self.hash_offset.to(x.device)
|
||||
return x
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
assert in_tensor.shape[-1] == 3
|
||||
|
||||
in_tensor = in_tensor[..., None, :] # [..., 1, 3]
|
||||
scaled = in_tensor * self.scalings.view(-1, 1).to(in_tensor.device) # [..., L, 3]
|
||||
scaled_c = torch.ceil(scaled).type(torch.int32)
|
||||
scaled_f = torch.floor(scaled).type(torch.int32)
|
||||
|
||||
offset = scaled - scaled_f
|
||||
|
||||
hashed_0 = self.hash_fn(scaled_c) # [..., num_levels]
|
||||
hashed_1 = self.hash_fn(torch.cat([scaled_c[..., 0:1], scaled_f[..., 1:2], scaled_c[..., 2:3]], dim=-1))
|
||||
hashed_2 = self.hash_fn(torch.cat([scaled_f[..., 0:1], scaled_f[..., 1:2], scaled_c[..., 2:3]], dim=-1))
|
||||
hashed_3 = self.hash_fn(torch.cat([scaled_f[..., 0:1], scaled_c[..., 1:2], scaled_c[..., 2:3]], dim=-1))
|
||||
hashed_4 = self.hash_fn(torch.cat([scaled_c[..., 0:1], scaled_c[..., 1:2], scaled_f[..., 2:3]], dim=-1))
|
||||
hashed_5 = self.hash_fn(torch.cat([scaled_c[..., 0:1], scaled_f[..., 1:2], scaled_f[..., 2:3]], dim=-1))
|
||||
hashed_6 = self.hash_fn(scaled_f)
|
||||
hashed_7 = self.hash_fn(torch.cat([scaled_f[..., 0:1], scaled_c[..., 1:2], scaled_f[..., 2:3]], dim=-1))
|
||||
|
||||
f_0 = self.hash_table[hashed_0] # [..., num_levels, features_per_level]
|
||||
f_1 = self.hash_table[hashed_1]
|
||||
f_2 = self.hash_table[hashed_2]
|
||||
f_3 = self.hash_table[hashed_3]
|
||||
f_4 = self.hash_table[hashed_4]
|
||||
f_5 = self.hash_table[hashed_5]
|
||||
f_6 = self.hash_table[hashed_6]
|
||||
f_7 = self.hash_table[hashed_7]
|
||||
|
||||
f_03 = f_0 * offset[..., 0:1] + f_3 * (1 - offset[..., 0:1])
|
||||
f_12 = f_1 * offset[..., 0:1] + f_2 * (1 - offset[..., 0:1])
|
||||
f_56 = f_5 * offset[..., 0:1] + f_6 * (1 - offset[..., 0:1])
|
||||
f_47 = f_4 * offset[..., 0:1] + f_7 * (1 - offset[..., 0:1])
|
||||
|
||||
f0312 = f_03 * offset[..., 1:2] + f_12 * (1 - offset[..., 1:2])
|
||||
f4756 = f_47 * offset[..., 1:2] + f_56 * (1 - offset[..., 1:2])
|
||||
|
||||
encoded_value = f0312 * offset[..., 2:3] + f4756 * (
|
||||
1 - offset[..., 2:3]
|
||||
) # [..., num_levels, features_per_level]
|
||||
|
||||
return torch.flatten(encoded_value, start_dim=-2, end_dim=-1) # [..., num_levels * features_per_level]
|
||||
|
||||
|
||||
class TensorCPEncoding(Encoding):
|
||||
"""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:
|
||||
resolution (int, optional): Resolution of grid. Defaults to 256.
|
||||
num_components (int, optional): Number of components per dimension. Defaults to 24.
|
||||
init_scale (float, optional): Initialization scale. Defaults to 0.1.
|
||||
"""
|
||||
super().__init__(in_dim=3)
|
||||
|
||||
self.resolution = resolution
|
||||
self.num_components = num_components
|
||||
|
||||
# TODO Learning rates should be different for these
|
||||
self.line_coef = nn.Parameter(init_scale * torch.randn((3, num_components, resolution, 1)))
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.num_components
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
in_tensor = in_tensor / 4.0 + 0.5
|
||||
line_coord = torch.stack([in_tensor[..., 2], in_tensor[..., 1], in_tensor[..., 0]]) # [3, ...]
|
||||
line_coord = torch.stack([torch.zeros_like(line_coord), line_coord], dim=-1) # [3, ...., 2]
|
||||
|
||||
# Stop gradients from going to sampler
|
||||
line_coord = line_coord.view(3, -1, 1, 2).detach()
|
||||
|
||||
line_features = F.grid_sample(self.line_coef, line_coord, align_corners=True) # [3, Components, -1, 1]
|
||||
|
||||
features = torch.prod(line_features, dim=0)
|
||||
features = torch.moveaxis(features.view(self.num_components, *in_tensor.shape[:-1]), 0, -1)
|
||||
|
||||
return features # [..., Components]
|
||||
|
||||
@torch.no_grad()
|
||||
def upsample_grid(self, resolution: int) -> None:
|
||||
"""Upsamples underyling feature grid
|
||||
|
||||
Args:
|
||||
resolution (int): Target resolution.
|
||||
"""
|
||||
|
||||
self.line_coef.data = F.interpolate(
|
||||
self.line_coef.data, size=(resolution, 1), mode="bilinear", align_corners=True
|
||||
)
|
||||
|
||||
self.resolution = resolution
|
||||
|
||||
|
||||
class TensorVMEncoding(Encoding):
|
||||
"""Learned vector-matrix encoding proposed by TensoRF"""
|
||||
|
||||
def __init__(self, resolution: int = 256, num_components: int = 24, init_scale: float = 0.1) -> None:
|
||||
"""
|
||||
Args:
|
||||
resolution (int, optional): Resolution of grid. Defaults to 256.
|
||||
num_components (int, optional): Number of components per dimension. Defaults to 24.
|
||||
init_scale (float, optional): Initialization scale. Defaults to 0.1.
|
||||
"""
|
||||
super().__init__(in_dim=3)
|
||||
|
||||
self.resolution = resolution
|
||||
self.num_components = num_components
|
||||
|
||||
# TODO Learning rates should be different for these
|
||||
self.plane_coef = nn.Parameter(init_scale * torch.randn((3, num_components, resolution, resolution)))
|
||||
self.line_coef = nn.Parameter(init_scale * torch.randn((3, num_components, resolution, 1)))
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.num_components * 3
|
||||
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
in_tensor = in_tensor / 4.0 + 0.5
|
||||
plane_coord = torch.stack([in_tensor[..., [0, 1]], in_tensor[..., [0, 2]], in_tensor[..., [1, 2]]]) # [3,...,2]
|
||||
line_coord = torch.stack([in_tensor[..., 2], in_tensor[..., 1], in_tensor[..., 0]]) # [3, ...]
|
||||
line_coord = torch.stack([torch.zeros_like(line_coord), line_coord], dim=-1) # [3, ...., 2]
|
||||
|
||||
# Stop gradients from going to sampler
|
||||
plane_coord = plane_coord.view(3, -1, 1, 2).detach()
|
||||
line_coord = line_coord.view(3, -1, 1, 2).detach()
|
||||
|
||||
plane_features = F.grid_sample(self.plane_coef, plane_coord, align_corners=True) # [3, Components, -1, 1]
|
||||
line_features = F.grid_sample(self.line_coef, line_coord, align_corners=True) # [3, Components, -1, 1]
|
||||
|
||||
features = plane_features * line_features # [3, Components, -1, 1]
|
||||
features = torch.moveaxis(features.view(3 * self.num_components, *in_tensor.shape[:-1]), 0, -1)
|
||||
|
||||
return features # [..., 3 * Components]
|
||||
|
||||
@torch.no_grad()
|
||||
def upsample_grid(self, resolution: int) -> None:
|
||||
"""Upsamples underyling feature grid
|
||||
|
||||
Args:
|
||||
resolution (int): Target resolution.
|
||||
"""
|
||||
|
||||
self.plane_coef.data = F.interpolate(
|
||||
self.plane_coef.data, size=(resolution, resolution), mode="bilinear", align_corners=True
|
||||
)
|
||||
self.line_coef.data = F.interpolate(
|
||||
self.line_coef.data, size=(resolution, 1), mode="bilinear", align_corners=True
|
||||
)
|
||||
|
||||
self.resolution = resolution
|
||||
|
||||
|
||||
class SHEncoding(Encoding):
|
||||
"""Spherical harmonic encoding"""
|
||||
|
||||
def __init__(self, levels: int = 4) -> None:
|
||||
"""
|
||||
Args:
|
||||
levels (int, optional): Number of spherical hamonic levels to encode. Defaults to 4.
|
||||
"""
|
||||
super().__init__(in_dim=3)
|
||||
|
||||
if levels <= 0 or levels > 4:
|
||||
raise ValueError(f"Spherical harmonic encoding only suports 1 to 4 levels, requested {levels}")
|
||||
|
||||
self.levels = levels
|
||||
|
||||
def get_out_dim(self) -> int:
|
||||
return self.levels**2
|
||||
|
||||
@torch.no_grad()
|
||||
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
|
||||
return components_from_spherical_harmonics(levels=self.levels, directions=in_tensor)
|
||||
@@ -0,0 +1,168 @@
|
||||
"""
|
||||
Collection of render heads
|
||||
"""
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from pyrad.fields.modules.base import FieldModule
|
||||
|
||||
|
||||
class FieldHeadNames(Enum):
|
||||
"""Possible field outputs"""
|
||||
|
||||
RGB = "rgb"
|
||||
SH = "sh"
|
||||
DENSITY = "density"
|
||||
UNCERTAINTY = "uncertainty"
|
||||
TRANSIENT_RGB = "transient_rgb"
|
||||
TRANSIENT_DENSITY = "transient_density"
|
||||
SEMANTICS = "semantics"
|
||||
|
||||
|
||||
class FieldHead(FieldModule):
|
||||
"""Base field output
|
||||
|
||||
Args:
|
||||
out_dim (int): output dimension for renderer
|
||||
field_head_name (FieldHeadNames): Field type
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
out_dim: int,
|
||||
field_head_name: FieldHeadNames,
|
||||
in_dim: Optional[int] = None,
|
||||
activation: Optional[nn.Module] = None,
|
||||
) -> None:
|
||||
|
||||
super().__init__()
|
||||
self.out_dim = out_dim
|
||||
self.activation = activation
|
||||
self.field_head_name = field_head_name
|
||||
self.net = None
|
||||
if in_dim is not None:
|
||||
self.in_dim = in_dim
|
||||
self._construct_net()
|
||||
|
||||
def set_in_dim(self, in_dim: int) -> None:
|
||||
"""Set input dimension of Field Head"""
|
||||
self.in_dim = in_dim
|
||||
self._construct_net()
|
||||
|
||||
def _construct_net(self):
|
||||
layers = [nn.Linear(self.in_dim, self.out_dim)]
|
||||
if self.activation:
|
||||
layers.append(self.activation)
|
||||
self.net = nn.Sequential(*layers)
|
||||
|
||||
def forward(self, in_tensor: TensorType[..., "in_dim"]) -> TensorType:
|
||||
"""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("in_dim not set. Must be provided to construtor, or set_in_dim() should be called.")
|
||||
out_tensor = self.net(in_tensor)
|
||||
return out_tensor
|
||||
|
||||
|
||||
class DensityFieldHead(FieldHead):
|
||||
"""Density output
|
||||
|
||||
Args:
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Softplus()) -> None:
|
||||
super().__init__(in_dim=in_dim, out_dim=1, field_head_name=FieldHeadNames.DENSITY, activation=activation)
|
||||
|
||||
|
||||
class RGBFieldHead(FieldHead):
|
||||
"""RGB output
|
||||
|
||||
Args:
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Sigmoid()) -> None:
|
||||
super().__init__(in_dim=in_dim, out_dim=3, field_head_name=FieldHeadNames.RGB, activation=activation)
|
||||
|
||||
|
||||
class SHFieldHead(FieldHead):
|
||||
"""Spherical harmonics output
|
||||
|
||||
Args:
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
levels (int, optional): Number of spherical harmonics layers. Defaults to 3.
|
||||
channels (int, optional): Number of channels. Defaults to 3 (ie RGB).
|
||||
activation (Optional[nn.Module], optional): Output activation. Defaults to None.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, in_dim: Optional[int] = None, levels: int = 3, channels: int = 3, activation: Optional[nn.Module] = None
|
||||
) -> None:
|
||||
|
||||
out_dim = channels * levels**2
|
||||
super().__init__(in_dim=in_dim, out_dim=out_dim, field_head_name=FieldHeadNames.SH, activation=activation)
|
||||
|
||||
|
||||
class UncertaintyFieldHead(FieldHead):
|
||||
"""Uncertainty output
|
||||
|
||||
Args:
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Softplus()) -> None:
|
||||
super().__init__(in_dim=in_dim, out_dim=1, field_head_name=FieldHeadNames.UNCERTAINTY, activation=activation)
|
||||
|
||||
|
||||
class TransientRGBFieldHead(FieldHead):
|
||||
"""Transient RGB output
|
||||
|
||||
Args:
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Sigmoid()) -> None:
|
||||
super().__init__(in_dim=in_dim, out_dim=3, field_head_name=FieldHeadNames.TRANSIENT_RGB, activation=activation)
|
||||
|
||||
|
||||
class TransientDensityFieldHead(FieldHead):
|
||||
"""Transient density output
|
||||
|
||||
Args:
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Softplus()) -> None:
|
||||
super().__init__(
|
||||
in_dim=in_dim, out_dim=1, field_head_name=FieldHeadNames.TRANSIENT_DENSITY, activation=activation
|
||||
)
|
||||
|
||||
|
||||
class SemanticFieldHead(FieldHead):
|
||||
"""Semantic stuff output
|
||||
|
||||
Args:
|
||||
num_classes (int): Number of semantic classes
|
||||
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
|
||||
activation (Optional[nn.Module]): output head activation
|
||||
"""
|
||||
|
||||
def __init__(self, num_classes: int, in_dim: Optional[int] = None) -> None:
|
||||
super().__init__(in_dim=in_dim, out_dim=num_classes, field_head_name=FieldHeadNames.SEMANTICS, activation=None)
|
||||
Whitespace-only changes.
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
Multi Layer Perceptron
|
||||
"""
|
||||
from typing import Tuple, Optional
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from pyrad.fields.modules.base import FieldModule
|
||||
|
||||
|
||||
class MLP(FieldModule):
|
||||
"""Multilayer perceptron
|
||||
|
||||
Args:
|
||||
in_dim (int): Input layer dimension
|
||||
num_layers (int): Number of network layers
|
||||
layer_width (int): Width of each MLP layer
|
||||
out_dim (int, optional): Ouput layer dimension. Defaults to layer_width
|
||||
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.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_dim: int,
|
||||
num_layers: int,
|
||||
layer_width: int,
|
||||
out_dim: Optional[int] = None,
|
||||
skip_connections: Tuple[int] = (),
|
||||
activation: Optional[nn.Module] = nn.ReLU(),
|
||||
out_activation: Optional[nn.Module] = None,
|
||||
) -> None:
|
||||
|
||||
super().__init__()
|
||||
self.in_dim = in_dim
|
||||
assert self.in_dim > 0
|
||||
self.out_dim = out_dim if out_dim is not None else layer_width
|
||||
self.num_layers = num_layers
|
||||
self.layer_width = layer_width
|
||||
self.skip_connections = skip_connections
|
||||
self.activation = activation
|
||||
self.out_activation = out_activation
|
||||
self.net = None
|
||||
self.build_nn_modules()
|
||||
|
||||
def build_nn_modules(self) -> None:
|
||||
"""Initialize multi-layer perceptron."""
|
||||
layers = []
|
||||
if self.num_layers == 1:
|
||||
layers.append(nn.Linear(self.in_dim, self.out_dim))
|
||||
else:
|
||||
for i in range(self.num_layers - 1):
|
||||
if i == 0:
|
||||
assert i not in list(self.skip_connections), "Skip connection at layer 0 doesn't make sense."
|
||||
layers.append(nn.Linear(self.in_dim, self.layer_width))
|
||||
elif i in self.skip_connections:
|
||||
layers.append(nn.Linear(self.layer_width + self.in_dim, self.layer_width))
|
||||
else:
|
||||
layers.append(nn.Linear(self.layer_width, self.layer_width))
|
||||
layers.append(nn.Linear(self.layer_width, self.out_dim))
|
||||
self.layers = nn.ModuleList(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"]: MLP network output
|
||||
"""
|
||||
x = in_tensor
|
||||
for i, layer in enumerate(self.layers):
|
||||
if i in self.skip_connections:
|
||||
x = torch.cat([in_tensor, x], -1)
|
||||
x = layer(x)
|
||||
if self.activation:
|
||||
x = self.activation(x)
|
||||
return x
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Classic NeRF field"""
|
||||
|
||||
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from pyrad.fields.modules.encoding import Encoding, Identity
|
||||
from pyrad.fields.modules.field_heads import DensityFieldHead, FieldHead, FieldHeadNames, RGBFieldHead
|
||||
from pyrad.fields.modules.mlp import MLP
|
||||
from pyrad.fields.base import Field
|
||||
from pyrad.cameras.rays import PointSamples
|
||||
|
||||
|
||||
class NeRFField(Field):
|
||||
"""NeRF Field"""
|
||||
|
||||
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(),),
|
||||
) -> 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,).
|
||||
"""
|
||||
super().__init__()
|
||||
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.field_output_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
|
||||
self.field_heads = nn.ModuleList(field_heads)
|
||||
for field_head in self.field_heads:
|
||||
field_head.set_in_dim(self.mlp_head.get_out_dim())
|
||||
|
||||
def get_density(self, point_samples: PointSamples):
|
||||
"""Computes and returns the densities."""
|
||||
encoded_xyz = self.position_encoding(point_samples.frustums.get_positions())
|
||||
base_mlp_out = self.mlp_base(encoded_xyz)
|
||||
density = self.field_output_density(base_mlp_out)
|
||||
return density, base_mlp_out
|
||||
|
||||
def get_outputs(
|
||||
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
|
||||
) -> Dict[FieldHeadNames, TensorType]:
|
||||
"""Computes and returns the outputs."""
|
||||
outputs = {}
|
||||
for field_head in self.field_heads:
|
||||
encoded_dir = self.direction_encoding(point_samples.frustums.directions)
|
||||
mlp_out = self.mlp_head(torch.cat([encoded_dir, density_embedding], dim=-1))
|
||||
outputs[field_head.field_head_name] = field_head(mlp_out)
|
||||
return outputs
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Fields for nerf-w"""
|
||||
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from pyrad.fields.modules.embedding import Embedding
|
||||
from pyrad.fields.modules.encoding import Encoding, Identity
|
||||
from pyrad.fields.modules.field_heads import (
|
||||
DensityFieldHead,
|
||||
FieldHeadNames,
|
||||
RGBFieldHead,
|
||||
TransientDensityFieldHead,
|
||||
TransientRGBFieldHead,
|
||||
UncertaintyFieldHead,
|
||||
)
|
||||
from pyrad.fields.modules.mlp import MLP
|
||||
from pyrad.fields.base import Field
|
||||
from pyrad.cameras.rays import PointSamples
|
||||
|
||||
|
||||
class VanillaNerfWField(Field):
|
||||
"""The NeRF-W field which has appearance and transient conditioning."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_images: 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,
|
||||
appearance_embedding_dim: int = 48,
|
||||
transient_embedding_dim: int = 16,
|
||||
skip_connections: Tuple[int] = (4,),
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.num_images = num_images
|
||||
self.position_encoding = position_encoding
|
||||
self.direction_encoding = direction_encoding
|
||||
self.base_mlp_num_layers = base_mlp_num_layers
|
||||
self.base_mlp_layer_width = base_mlp_layer_width
|
||||
self.head_mlp_num_layers = head_mlp_num_layers
|
||||
self.head_mlp_layer_width = head_mlp_layer_width
|
||||
self.appearance_embedding_dim = appearance_embedding_dim
|
||||
self.transient_embedding_dim = transient_embedding_dim
|
||||
|
||||
self.embedding_appearance = Embedding(self.num_images, self.appearance_embedding_dim)
|
||||
self.embedding_transient = Embedding(self.num_images, self.transient_embedding_dim)
|
||||
|
||||
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_transient = MLP(
|
||||
in_dim=self.mlp_base.get_out_dim() + self.embedding_transient.get_out_dim(),
|
||||
out_dim=base_mlp_layer_width // 2,
|
||||
num_layers=4,
|
||||
layer_width=base_mlp_layer_width,
|
||||
activation=nn.ReLU(),
|
||||
)
|
||||
self.mlp_head = MLP(
|
||||
in_dim=self.mlp_base.get_out_dim()
|
||||
+ self.direction_encoding.get_out_dim()
|
||||
+ self.embedding_appearance.get_out_dim(),
|
||||
num_layers=head_mlp_num_layers,
|
||||
layer_width=head_mlp_layer_width,
|
||||
)
|
||||
|
||||
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_transient_uncertainty = UncertaintyFieldHead(in_dim=self.mlp_transient.get_out_dim())
|
||||
self.field_head_transient_rgb = TransientRGBFieldHead(in_dim=self.mlp_transient.get_out_dim())
|
||||
self.field_head_transient_density = TransientDensityFieldHead(in_dim=self.mlp_transient.get_out_dim())
|
||||
|
||||
def get_density(self, point_samples: PointSamples):
|
||||
"""Computes and returns the densities."""
|
||||
encoded_xyz = self.position_encoding(point_samples.frustums.positions())
|
||||
base_mlp_out = self.mlp_base(encoded_xyz)
|
||||
density = self.field_head_density(base_mlp_out)
|
||||
return density, base_mlp_out
|
||||
|
||||
def get_outputs(
|
||||
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
|
||||
) -> Dict[FieldHeadNames, TensorType]:
|
||||
outputs = {}
|
||||
encoded_dir = self.direction_encoding(point_samples.directions)
|
||||
embedded_appearance = self.embedding_appearance(point_samples.camera_indices)
|
||||
mlp_head_out = self.mlp_head(torch.cat([density_embedding, encoded_dir, embedded_appearance], dim=-1))
|
||||
outputs[self.field_head_rgb.field_head_name] = self.field_head_rgb(mlp_head_out) # static rgb
|
||||
embedded_transient = self.embedding_transient(point_samples.camera_indices)
|
||||
transient_mlp_out = self.mlp_transient(torch.cat([density_embedding, embedded_transient], dim=-1))
|
||||
outputs[self.field_head_transient_uncertainty.field_head_name] = self.field_head_transient_uncertainty(
|
||||
transient_mlp_out
|
||||
) # uncertainty
|
||||
outputs[self.field_head_transient_rgb.field_head_name] = self.field_head_transient_rgb(
|
||||
transient_mlp_out
|
||||
) # transient rgb
|
||||
outputs[self.field_head_transient_density.field_head_name] = self.field_head_transient_density(
|
||||
transient_mlp_out
|
||||
) # transient density
|
||||
return outputs
|
||||
Whitespace-only changes.
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
Code to implement the density grid.
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from pyrad.utils.misc import is_not_none
|
||||
|
||||
|
||||
class OccupancyGrid(nn.Module):
|
||||
"""Module to keep track of the density and occupancy."""
|
||||
|
||||
def __init__(
|
||||
self, num_cascades=1, resolution=128, aabb=None, density_fn=None, update_every_num_iters: int = 16
|
||||
) -> None:
|
||||
super().__init__()
|
||||
assert is_not_none(aabb), "The axis-aligned bounding box aabb is not defined!"
|
||||
self.num_cascades = num_cascades # the number of levels (i.e, cascades)
|
||||
self.resolution = resolution
|
||||
self.register_buffer("aabb", aabb) # axis-aligned bounding box
|
||||
occupancy_grid = torch.ones(
|
||||
[self.num_cascades] + [self.resolution] * 3
|
||||
) # (num_cascades, x_resolution, y_resolution, z_resolution)
|
||||
# not a module parameter, but it still should be saved and part of `state_dict`
|
||||
self.register_buffer("occupancy_grid", occupancy_grid)
|
||||
self.mean_density = 0.0
|
||||
|
||||
self.density_fn = density_fn
|
||||
self.update_every_num_iters = update_every_num_iters
|
||||
self.iteration_count = 0
|
||||
|
||||
def reset(self):
|
||||
"""Zero out the occupancy grid."""
|
||||
self.occupancy_grid.zero_()
|
||||
|
||||
@torch.no_grad()
|
||||
def mark_untrained_grid(self):
|
||||
"""Marks the locations in the density grid that are never seen by training views."""
|
||||
# TODO: only query points that are covered by the training cameras viewing frustrum
|
||||
# We'll need to pass in the camera poses and intrinsics to this function
|
||||
raise NotImplementedError()
|
||||
|
||||
@torch.no_grad()
|
||||
def update_occupancy_grid(self, density_fn, decay=0.95, split_size=64):
|
||||
"""Update the occupancy grid with density values.
|
||||
|
||||
Args:
|
||||
density_fn: Function from takes points in the shape (..., 3) and
|
||||
returns a tensor of densities of shape (..., 1).
|
||||
"""
|
||||
# TODO(ethan): remove this pylint disable
|
||||
# pylint: disable=invalid-name
|
||||
|
||||
device = self.occupancy_grid.device
|
||||
|
||||
assert self.num_cascades == 1, "Still need to implement code for multiple cascades."
|
||||
temp_occupancy_grid = torch.zeros_like(self.occupancy_grid)
|
||||
|
||||
X_length, Y_length, Z_length = self.aabb[1] - self.aabb[0]
|
||||
X_half_voxel_length = 0.5 * X_length / self.resolution
|
||||
Y_half_voxel_length = 0.5 * Y_length / self.resolution
|
||||
Z_half_voxel_length = 0.5 * Z_length / self.resolution
|
||||
half_voxel_lengths = torch.tensor(
|
||||
[X_half_voxel_length, Y_half_voxel_length, Z_half_voxel_length], device=device
|
||||
)
|
||||
X = torch.linspace(
|
||||
self.aabb[0][0] + X_half_voxel_length, self.aabb[1][0] - X_half_voxel_length, self.resolution, device=device
|
||||
).split(split_size)
|
||||
Y = torch.linspace(
|
||||
self.aabb[0][1] + Y_half_voxel_length, self.aabb[1][1] - Y_half_voxel_length, self.resolution, device=device
|
||||
).split(split_size)
|
||||
Z = torch.linspace(
|
||||
self.aabb[0][2] + Z_half_voxel_length, self.aabb[1][2] - Z_half_voxel_length, self.resolution, device=device
|
||||
).split(split_size)
|
||||
for x_index, xs in enumerate(X):
|
||||
for y_index, ys in enumerate(Y):
|
||||
for z_index, zs in enumerate(Z):
|
||||
x_len, y_len, z_len = len(xs), len(ys), len(zs)
|
||||
grid_x, grid_y, grid_z = torch.meshgrid(xs, ys, zs, indexing="ij")
|
||||
xyzs = torch.stack([grid_x, grid_y, grid_z], dim=-1) # (resolution, resolution,, resolution, 3)
|
||||
# add noise to the points
|
||||
xyzs_rand = (
|
||||
torch.rand_like(xyzs) * half_voxel_lengths
|
||||
) # range [-half_voxel_length, half_voxel_length] for each dimension
|
||||
xyzs += xyzs_rand
|
||||
densities = density_fn(xyzs)
|
||||
assert densities.shape[-1] == 1
|
||||
temp_occupancy_grid[
|
||||
0,
|
||||
x_index * split_size : x_index * split_size + x_len,
|
||||
y_index * split_size : y_index * split_size + y_len,
|
||||
z_index * split_size : z_index * split_size + z_len,
|
||||
] = densities[..., 0]
|
||||
|
||||
# exponential moving average update
|
||||
valid_mask = self.occupancy_grid >= 0.0
|
||||
self.occupancy_grid[valid_mask] = torch.maximum(
|
||||
self.occupancy_grid[valid_mask] * decay, temp_occupancy_grid[valid_mask]
|
||||
)
|
||||
self.mean_density = torch.mean(self.occupancy_grid[valid_mask]).item()
|
||||
|
||||
@torch.no_grad()
|
||||
def get_densities(self, xyzs: TensorType[..., 3]) -> TensorType[..., 1]:
|
||||
"""Trilinear interpolation to get the density values.
|
||||
|
||||
Args:
|
||||
xyzs (TensorType[..., 3]): 3D querry coordinate
|
||||
|
||||
Returns:
|
||||
TensorType[..., 1]: Density values
|
||||
"""
|
||||
occupancy_grid = self.occupancy_grid[None, ...] # shape (1, num_cascades, X_res, Y_res, Z_res)
|
||||
xyzs_shape = xyzs.shape
|
||||
xyzs_reshaped = xyzs.view(1, -1, 1, 1, 3)
|
||||
voxel_lengths = self.aabb[1] - self.aabb[0]
|
||||
xyzs_reshaped_normalized = ((xyzs_reshaped - self.aabb[0]) / voxel_lengths) * 2.0 - 1.0
|
||||
densities = F.grid_sample(
|
||||
occupancy_grid.permute(
|
||||
0, 1, 4, 3, 2
|
||||
), # (xyz to zyx) for grid sample useage because the xyzs have xyz ordering
|
||||
xyzs_reshaped_normalized,
|
||||
align_corners=True,
|
||||
padding_mode="zeros",
|
||||
)
|
||||
densities = densities.view(*xyzs_shape[:-1], 1)
|
||||
return densities
|
||||
|
||||
def forward(self, x):
|
||||
"""Not implemented."""
|
||||
raise NotImplementedError()
|
||||
Reference in new issue
Block a user