mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-11-23 08:05:28 +08:00
Adios mattport
This commit is contained in:
1 parent
9d2b34ab60
commit
b26408eb7a
86 files changed
+176
-176
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
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 radiance.nerf.field_modules.field_heads import FieldHeadNames
|
||||
|
||||
from radiance.structures.rays import PointSamples
|
||||
from radiance.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."""
|
||||
point_samples = PointSamples(positions=positions)
|
||||
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(
|
||||
positions=point_samples.positions[0, :], directions=point_samples.directions[0, :]
|
||||
)
|
||||
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,152 @@
|
||||
"""
|
||||
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 radiance.nerf.field_modules.encoding import Encoding, HashEncoding, SHEncoding
|
||||
from radiance.nerf.field_modules.field_heads import FieldHeadNames
|
||||
from radiance.nerf.fields.base import Field
|
||||
from radiance.nerf.fields.nerf_field import NeRFField
|
||||
from radiance.structures.rays import PointSamples
|
||||
from radiance.utils.misc import is_not_none
|
||||
|
||||
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
|
||||
|
||||
|
||||
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__()
|
||||
|
||||
# TODO: make this a parameter that is put to the correct device
|
||||
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."""
|
||||
# TODO: add valid_mask masking!
|
||||
# remap positions to range 0 to 1 based on the aabb
|
||||
positions = get_normalized_positions(point_samples.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.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!
|
||||
assert is_not_none(density_embedding)
|
||||
directions = point_samples.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.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.positions, self.aabb)
|
||||
return super().get_density(normalized_point_samples)
|
||||
|
||||
|
||||
field_implementation_to_class = {"tcnn": TCNNInstantNGPField, "torch": TorchInstantNGPField}
|
||||
@@ -0,0 +1,80 @@
|
||||
""" Classic NeRF field"""
|
||||
|
||||
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
|
||||
from radiance.nerf.field_modules.encoding import Encoding, Identity
|
||||
from radiance.nerf.field_modules.field_heads import DensityFieldHead, FieldHead, FieldHeadNames, RGBFieldHead
|
||||
from radiance.nerf.field_modules.mlp import MLP
|
||||
from radiance.nerf.fields.base import Field
|
||||
from radiance.structures.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.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.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
|
||||
Reference in new issue
Block a user