mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-11-14 03:44:02 +08:00
Added hdr-nerfacto from nerfacto
This commit is contained in:
1 parent
d89d988c81
commit
1af1958062
2 files changed
+702
No files matched your search
@@ -0,0 +1,301 @@
|
||||
# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
Field for compound nerf model, adds scene contraction and image embeddings to instant ngp
|
||||
"""
|
||||
|
||||
|
||||
from typing import Dict, Literal, Optional, Tuple
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
|
||||
from nerfstudio.cameras.rays import RaySamples
|
||||
from nerfstudio.data.scene_box import SceneBox
|
||||
from nerfstudio.field_components.activations import trunc_exp
|
||||
from nerfstudio.field_components.embedding import Embedding
|
||||
from nerfstudio.field_components.encodings import HashEncoding, NeRFEncoding, SHEncoding
|
||||
from nerfstudio.field_components.field_heads import (
|
||||
FieldHeadNames,
|
||||
PredNormalsFieldHead,
|
||||
SemanticFieldHead,
|
||||
TransientDensityFieldHead,
|
||||
TransientRGBFieldHead,
|
||||
UncertaintyFieldHead,
|
||||
)
|
||||
from nerfstudio.field_components.mlp import MLP
|
||||
from nerfstudio.field_components.spatial_distortions import SpatialDistortion
|
||||
from nerfstudio.fields.base_field import Field, get_normalized_directions
|
||||
|
||||
|
||||
class NerfactoField(Field):
|
||||
"""Compound Field that uses TCNN
|
||||
|
||||
Args:
|
||||
aabb: parameters of scene aabb bounds
|
||||
num_images: number of images in the dataset
|
||||
num_layers: number of hidden layers
|
||||
hidden_dim: dimension of hidden layers
|
||||
geo_feat_dim: output geo feat dimensions
|
||||
num_levels: number of levels of the hashmap for the base mlp
|
||||
base_res: base resolution of the hashmap for the base mlp
|
||||
max_res: maximum resolution of the hashmap for the base mlp
|
||||
log2_hashmap_size: size of the hashmap for the base mlp
|
||||
num_layers_color: number of hidden layers for color network
|
||||
num_layers_transient: number of hidden layers for transient network
|
||||
features_per_level: number of features per level for the hashgrid
|
||||
hidden_dim_color: dimension of hidden layers for color network
|
||||
hidden_dim_transient: dimension of hidden layers for transient network
|
||||
appearance_embedding_dim: dimension of appearance embedding
|
||||
transient_embedding_dim: dimension of transient embedding
|
||||
use_transient_embedding: whether to use transient embedding
|
||||
use_semantics: whether to use semantic segmentation
|
||||
num_semantic_classes: number of semantic classes
|
||||
use_pred_normals: whether to use predicted normals
|
||||
use_average_appearance_embedding: whether to use average appearance embedding or zeros for inference
|
||||
spatial_distortion: spatial distortion to apply to the scene
|
||||
"""
|
||||
|
||||
aabb: Tensor
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
aabb: Tensor,
|
||||
num_images: int,
|
||||
num_layers: int = 2,
|
||||
hidden_dim: int = 64,
|
||||
geo_feat_dim: int = 15,
|
||||
num_levels: int = 16,
|
||||
base_res: int = 16,
|
||||
max_res: int = 2048,
|
||||
log2_hashmap_size: int = 19,
|
||||
num_layers_color: int = 3,
|
||||
num_layers_transient: int = 2,
|
||||
features_per_level: int = 2,
|
||||
hidden_dim_color: int = 64,
|
||||
hidden_dim_transient: int = 64,
|
||||
appearance_embedding_dim: int = 32,
|
||||
transient_embedding_dim: int = 16,
|
||||
use_transient_embedding: bool = False,
|
||||
use_semantics: bool = False,
|
||||
num_semantic_classes: int = 100,
|
||||
pass_semantic_gradients: bool = False,
|
||||
use_pred_normals: bool = False,
|
||||
use_average_appearance_embedding: bool = False,
|
||||
spatial_distortion: Optional[SpatialDistortion] = None,
|
||||
implementation: Literal["tcnn", "torch"] = "tcnn",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.register_buffer("aabb", aabb)
|
||||
self.geo_feat_dim = geo_feat_dim
|
||||
|
||||
self.register_buffer("max_res", torch.tensor(max_res))
|
||||
self.register_buffer("num_levels", torch.tensor(num_levels))
|
||||
self.register_buffer("log2_hashmap_size", torch.tensor(log2_hashmap_size))
|
||||
|
||||
self.spatial_distortion = spatial_distortion
|
||||
self.num_images = num_images
|
||||
self.appearance_embedding_dim = appearance_embedding_dim
|
||||
self.embedding_appearance = Embedding(self.num_images, self.appearance_embedding_dim)
|
||||
self.use_average_appearance_embedding = use_average_appearance_embedding
|
||||
self.use_transient_embedding = use_transient_embedding
|
||||
self.use_semantics = use_semantics
|
||||
self.use_pred_normals = use_pred_normals
|
||||
self.pass_semantic_gradients = pass_semantic_gradients
|
||||
self.base_res = base_res
|
||||
|
||||
self.direction_encoding = SHEncoding(
|
||||
levels=4,
|
||||
implementation=implementation,
|
||||
)
|
||||
|
||||
self.position_encoding = NeRFEncoding(
|
||||
in_dim=3, num_frequencies=2, min_freq_exp=0, max_freq_exp=2 - 1, implementation=implementation
|
||||
)
|
||||
|
||||
self.mlp_base_grid = HashEncoding(
|
||||
num_levels=num_levels,
|
||||
min_res=base_res,
|
||||
max_res=max_res,
|
||||
log2_hashmap_size=log2_hashmap_size,
|
||||
features_per_level=features_per_level,
|
||||
implementation=implementation,
|
||||
)
|
||||
self.mlp_base_mlp = MLP(
|
||||
in_dim=self.mlp_base_grid.get_out_dim(),
|
||||
num_layers=num_layers,
|
||||
layer_width=hidden_dim,
|
||||
out_dim=1 + self.geo_feat_dim,
|
||||
activation=nn.ReLU(),
|
||||
out_activation=None,
|
||||
implementation=implementation,
|
||||
)
|
||||
self.mlp_base = torch.nn.Sequential(self.mlp_base_grid, self.mlp_base_mlp)
|
||||
|
||||
# transients
|
||||
if self.use_transient_embedding:
|
||||
self.transient_embedding_dim = transient_embedding_dim
|
||||
self.embedding_transient = Embedding(self.num_images, self.transient_embedding_dim)
|
||||
self.mlp_transient = MLP(
|
||||
in_dim=self.geo_feat_dim + self.transient_embedding_dim,
|
||||
num_layers=num_layers_transient,
|
||||
layer_width=hidden_dim_transient,
|
||||
out_dim=hidden_dim_transient,
|
||||
activation=nn.ReLU(),
|
||||
out_activation=None,
|
||||
implementation=implementation,
|
||||
)
|
||||
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())
|
||||
|
||||
# semantics
|
||||
if self.use_semantics:
|
||||
self.mlp_semantics = MLP(
|
||||
in_dim=self.geo_feat_dim,
|
||||
num_layers=2,
|
||||
layer_width=64,
|
||||
out_dim=hidden_dim_transient,
|
||||
activation=nn.ReLU(),
|
||||
out_activation=None,
|
||||
implementation=implementation,
|
||||
)
|
||||
self.field_head_semantics = SemanticFieldHead(
|
||||
in_dim=self.mlp_semantics.get_out_dim(), num_classes=num_semantic_classes
|
||||
)
|
||||
|
||||
# predicted normals
|
||||
if self.use_pred_normals:
|
||||
self.mlp_pred_normals = MLP(
|
||||
in_dim=self.geo_feat_dim + self.position_encoding.get_out_dim(),
|
||||
num_layers=3,
|
||||
layer_width=64,
|
||||
out_dim=hidden_dim_transient,
|
||||
activation=nn.ReLU(),
|
||||
out_activation=None,
|
||||
implementation=implementation,
|
||||
)
|
||||
self.field_head_pred_normals = PredNormalsFieldHead(in_dim=self.mlp_pred_normals.get_out_dim())
|
||||
|
||||
self.mlp_head = MLP(
|
||||
in_dim=self.direction_encoding.get_out_dim() + self.geo_feat_dim + self.appearance_embedding_dim,
|
||||
num_layers=num_layers_color,
|
||||
layer_width=hidden_dim_color,
|
||||
out_dim=3,
|
||||
activation=nn.ReLU(),
|
||||
out_activation=nn.Sigmoid(),
|
||||
implementation=implementation,
|
||||
)
|
||||
|
||||
def get_density(self, ray_samples: RaySamples) -> Tuple[Tensor, Tensor]:
|
||||
"""Computes and returns the densities."""
|
||||
if self.spatial_distortion is not None:
|
||||
positions = ray_samples.frustums.get_positions()
|
||||
positions = self.spatial_distortion(positions)
|
||||
positions = (positions + 2.0) / 4.0
|
||||
else:
|
||||
positions = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb)
|
||||
# Make sure the tcnn gets inputs between 0 and 1.
|
||||
selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1)
|
||||
positions = positions * selector[..., None]
|
||||
self._sample_locations = positions
|
||||
if not self._sample_locations.requires_grad:
|
||||
self._sample_locations.requires_grad = True
|
||||
positions_flat = positions.view(-1, 3)
|
||||
h = self.mlp_base(positions_flat).view(*ray_samples.frustums.shape, -1)
|
||||
density_before_activation, base_mlp_out = torch.split(h, [1, self.geo_feat_dim], dim=-1)
|
||||
self._density_before_activation = density_before_activation
|
||||
|
||||
# Rectifying the density with an exponential is much more stable than a ReLU or
|
||||
# softplus, because it enables high post-activation (float32) density outputs
|
||||
# from smaller internal (float16) parameters.
|
||||
density = trunc_exp(density_before_activation.to(positions))
|
||||
density = density * selector[..., None]
|
||||
return density, base_mlp_out
|
||||
|
||||
def get_outputs(
|
||||
self, ray_samples: RaySamples, density_embedding: Optional[Tensor] = None
|
||||
) -> Dict[FieldHeadNames, Tensor]:
|
||||
assert density_embedding is not None
|
||||
outputs = {}
|
||||
if ray_samples.camera_indices is None:
|
||||
raise AttributeError("Camera indices are not provided.")
|
||||
camera_indices = ray_samples.camera_indices.squeeze()
|
||||
directions = get_normalized_directions(ray_samples.frustums.directions)
|
||||
directions_flat = directions.view(-1, 3)
|
||||
d = self.direction_encoding(directions_flat)
|
||||
|
||||
outputs_shape = ray_samples.frustums.directions.shape[:-1]
|
||||
|
||||
# appearance
|
||||
if self.training:
|
||||
embedded_appearance = self.embedding_appearance(camera_indices)
|
||||
else:
|
||||
if self.use_average_appearance_embedding:
|
||||
embedded_appearance = torch.ones(
|
||||
(*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device
|
||||
) * self.embedding_appearance.mean(dim=0)
|
||||
else:
|
||||
embedded_appearance = torch.zeros(
|
||||
(*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device
|
||||
)
|
||||
|
||||
# transients
|
||||
if self.use_transient_embedding and self.training:
|
||||
embedded_transient = self.embedding_transient(camera_indices)
|
||||
transient_input = torch.cat(
|
||||
[
|
||||
density_embedding.view(-1, self.geo_feat_dim),
|
||||
embedded_transient.view(-1, self.transient_embedding_dim),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
x = self.mlp_transient(transient_input).view(*outputs_shape, -1).to(directions)
|
||||
outputs[FieldHeadNames.UNCERTAINTY] = self.field_head_transient_uncertainty(x)
|
||||
outputs[FieldHeadNames.TRANSIENT_RGB] = self.field_head_transient_rgb(x)
|
||||
outputs[FieldHeadNames.TRANSIENT_DENSITY] = self.field_head_transient_density(x)
|
||||
|
||||
# semantics
|
||||
if self.use_semantics:
|
||||
semantics_input = density_embedding.view(-1, self.geo_feat_dim)
|
||||
if not self.pass_semantic_gradients:
|
||||
semantics_input = semantics_input.detach()
|
||||
|
||||
x = self.mlp_semantics(semantics_input).view(*outputs_shape, -1).to(directions)
|
||||
outputs[FieldHeadNames.SEMANTICS] = self.field_head_semantics(x)
|
||||
|
||||
# predicted normals
|
||||
if self.use_pred_normals:
|
||||
positions = ray_samples.frustums.get_positions()
|
||||
|
||||
positions_flat = self.position_encoding(positions.view(-1, 3))
|
||||
pred_normals_inp = torch.cat([positions_flat, density_embedding.view(-1, self.geo_feat_dim)], dim=-1)
|
||||
|
||||
x = self.mlp_pred_normals(pred_normals_inp).view(*outputs_shape, -1).to(directions)
|
||||
outputs[FieldHeadNames.PRED_NORMALS] = self.field_head_pred_normals(x)
|
||||
|
||||
h = torch.cat(
|
||||
[
|
||||
d,
|
||||
density_embedding.view(-1, self.geo_feat_dim),
|
||||
embedded_appearance.view(-1, self.appearance_embedding_dim),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
rgb = self.mlp_head(h).view(*outputs_shape, -1).to(directions)
|
||||
outputs.update({FieldHeadNames.RGB: rgb})
|
||||
|
||||
return outputs
|
||||
@@ -0,0 +1,401 @@
|
||||
# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
NeRF implementation that combines many recent advancements.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Literal, Tuple, Type
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch.nn import Parameter
|
||||
from torchmetrics.functional import structural_similarity_index_measure
|
||||
from torchmetrics.image import PeakSignalNoiseRatio
|
||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||
|
||||
from nerfstudio.cameras.rays import RayBundle, RaySamples
|
||||
from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes, TrainingCallbackLocation
|
||||
from nerfstudio.field_components.field_heads import FieldHeadNames
|
||||
from nerfstudio.field_components.spatial_distortions import SceneContraction
|
||||
from nerfstudio.fields.density_fields import HashMLPDensityField
|
||||
from nerfstudio.fields.nerfacto_field import NerfactoField
|
||||
from nerfstudio.model_components.losses import (
|
||||
MSELoss,
|
||||
distortion_loss,
|
||||
interlevel_loss,
|
||||
orientation_loss,
|
||||
pred_normal_loss,
|
||||
scale_gradients_by_distance_squared,
|
||||
)
|
||||
from nerfstudio.model_components.ray_samplers import ProposalNetworkSampler, UniformSampler
|
||||
from nerfstudio.model_components.renderers import AccumulationRenderer, DepthRenderer, NormalsRenderer, RGBRenderer
|
||||
from nerfstudio.model_components.scene_colliders import NearFarCollider
|
||||
from nerfstudio.model_components.shaders import NormalsShader
|
||||
from nerfstudio.models.base_model import Model, ModelConfig
|
||||
from nerfstudio.utils import colormaps
|
||||
|
||||
|
||||
@dataclass
|
||||
class NerfactoModelConfig(ModelConfig):
|
||||
"""Nerfacto Model Config"""
|
||||
|
||||
_target: Type = field(default_factory=lambda: NerfactoModel)
|
||||
near_plane: float = 0.05
|
||||
"""How far along the ray to start sampling."""
|
||||
far_plane: float = 1000.0
|
||||
"""How far along the ray to stop sampling."""
|
||||
background_color: Literal["random", "last_sample", "black", "white"] = "last_sample"
|
||||
"""Whether to randomize the background color."""
|
||||
hidden_dim: int = 64
|
||||
"""Dimension of hidden layers"""
|
||||
hidden_dim_color: int = 64
|
||||
"""Dimension of hidden layers for color network"""
|
||||
hidden_dim_transient: int = 64
|
||||
"""Dimension of hidden layers for transient network"""
|
||||
num_levels: int = 16
|
||||
"""Number of levels of the hashmap for the base mlp."""
|
||||
base_res: int = 16
|
||||
"""Resolution of the base grid for the hashgrid."""
|
||||
max_res: int = 2048
|
||||
"""Maximum resolution of the hashmap for the base mlp."""
|
||||
log2_hashmap_size: int = 19
|
||||
"""Size of the hashmap for the base mlp"""
|
||||
features_per_level: int = 2
|
||||
"""How many hashgrid features per level"""
|
||||
num_proposal_samples_per_ray: Tuple[int, ...] = (256, 96)
|
||||
"""Number of samples per ray for each proposal network."""
|
||||
num_nerf_samples_per_ray: int = 48
|
||||
"""Number of samples per ray for the nerf network."""
|
||||
proposal_update_every: int = 5
|
||||
"""Sample every n steps after the warmup"""
|
||||
proposal_warmup: int = 5000
|
||||
"""Scales n from 1 to proposal_update_every over this many steps"""
|
||||
num_proposal_iterations: int = 2
|
||||
"""Number of proposal network iterations."""
|
||||
use_same_proposal_network: bool = False
|
||||
"""Use the same proposal network. Otherwise use different ones."""
|
||||
proposal_net_args_list: List[Dict] = field(
|
||||
default_factory=lambda: [
|
||||
{"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 128, "use_linear": False},
|
||||
{"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 256, "use_linear": False},
|
||||
]
|
||||
)
|
||||
"""Arguments for the proposal density fields."""
|
||||
proposal_initial_sampler: Literal["piecewise", "uniform"] = "piecewise"
|
||||
"""Initial sampler for the proposal network. Piecewise is preferred for unbounded scenes."""
|
||||
interlevel_loss_mult: float = 1.0
|
||||
"""Proposal loss multiplier."""
|
||||
distortion_loss_mult: float = 0.002
|
||||
"""Distortion loss multiplier."""
|
||||
orientation_loss_mult: float = 0.0001
|
||||
"""Orientation loss multiplier on computed normals."""
|
||||
pred_normal_loss_mult: float = 0.001
|
||||
"""Predicted normal loss multiplier."""
|
||||
use_proposal_weight_anneal: bool = True
|
||||
"""Whether to use proposal weight annealing."""
|
||||
use_average_appearance_embedding: bool = True
|
||||
"""Whether to use average appearance embedding or zeros for inference."""
|
||||
proposal_weights_anneal_slope: float = 10.0
|
||||
"""Slope of the annealing function for the proposal weights."""
|
||||
proposal_weights_anneal_max_num_iters: int = 1000
|
||||
"""Max num iterations for the annealing function."""
|
||||
use_single_jitter: bool = True
|
||||
"""Whether use single jitter or not for the proposal networks."""
|
||||
predict_normals: bool = False
|
||||
"""Whether to predict normals or not."""
|
||||
disable_scene_contraction: bool = False
|
||||
"""Whether to disable scene contraction or not."""
|
||||
use_gradient_scaling: bool = False
|
||||
"""Use gradient scaler where the gradients are lower for points closer to the camera."""
|
||||
implementation: Literal["tcnn", "torch"] = "tcnn"
|
||||
"""Which implementation to use for the model."""
|
||||
appearance_embed_dim: int = 32
|
||||
"""Dimension of the appearance embedding."""
|
||||
|
||||
|
||||
class NerfactoModel(Model):
|
||||
"""Nerfacto model
|
||||
|
||||
Args:
|
||||
config: Nerfacto configuration to instantiate model
|
||||
"""
|
||||
|
||||
config: NerfactoModelConfig
|
||||
|
||||
def populate_modules(self):
|
||||
"""Set the fields and modules."""
|
||||
super().populate_modules()
|
||||
|
||||
if self.config.disable_scene_contraction:
|
||||
scene_contraction = None
|
||||
else:
|
||||
scene_contraction = SceneContraction(order=float("inf"))
|
||||
|
||||
# Fields
|
||||
self.field = NerfactoField(
|
||||
self.scene_box.aabb,
|
||||
hidden_dim=self.config.hidden_dim,
|
||||
num_levels=self.config.num_levels,
|
||||
max_res=self.config.max_res,
|
||||
base_res=self.config.base_res,
|
||||
features_per_level=self.config.features_per_level,
|
||||
log2_hashmap_size=self.config.log2_hashmap_size,
|
||||
hidden_dim_color=self.config.hidden_dim_color,
|
||||
hidden_dim_transient=self.config.hidden_dim_transient,
|
||||
spatial_distortion=scene_contraction,
|
||||
num_images=self.num_train_data,
|
||||
use_pred_normals=self.config.predict_normals,
|
||||
use_average_appearance_embedding=self.config.use_average_appearance_embedding,
|
||||
appearance_embedding_dim=self.config.appearance_embed_dim,
|
||||
implementation=self.config.implementation,
|
||||
)
|
||||
|
||||
self.density_fns = []
|
||||
num_prop_nets = self.config.num_proposal_iterations
|
||||
# Build the proposal network(s)
|
||||
self.proposal_networks = torch.nn.ModuleList()
|
||||
if self.config.use_same_proposal_network:
|
||||
assert len(self.config.proposal_net_args_list) == 1, "Only one proposal network is allowed."
|
||||
prop_net_args = self.config.proposal_net_args_list[0]
|
||||
network = HashMLPDensityField(
|
||||
self.scene_box.aabb,
|
||||
spatial_distortion=scene_contraction,
|
||||
**prop_net_args,
|
||||
implementation=self.config.implementation,
|
||||
)
|
||||
self.proposal_networks.append(network)
|
||||
self.density_fns.extend([network.density_fn for _ in range(num_prop_nets)])
|
||||
else:
|
||||
for i in range(num_prop_nets):
|
||||
prop_net_args = self.config.proposal_net_args_list[min(i, len(self.config.proposal_net_args_list) - 1)]
|
||||
network = HashMLPDensityField(
|
||||
self.scene_box.aabb,
|
||||
spatial_distortion=scene_contraction,
|
||||
**prop_net_args,
|
||||
implementation=self.config.implementation,
|
||||
)
|
||||
self.proposal_networks.append(network)
|
||||
self.density_fns.extend([network.density_fn for network in self.proposal_networks])
|
||||
|
||||
# Samplers
|
||||
def update_schedule(step):
|
||||
return np.clip(
|
||||
np.interp(step, [0, self.config.proposal_warmup], [0, self.config.proposal_update_every]),
|
||||
1,
|
||||
self.config.proposal_update_every,
|
||||
)
|
||||
|
||||
# Change proposal network initial sampler if uniform
|
||||
initial_sampler = None # None is for piecewise as default (see ProposalNetworkSampler)
|
||||
if self.config.proposal_initial_sampler == "uniform":
|
||||
initial_sampler = UniformSampler(single_jitter=self.config.use_single_jitter)
|
||||
|
||||
self.proposal_sampler = ProposalNetworkSampler(
|
||||
num_nerf_samples_per_ray=self.config.num_nerf_samples_per_ray,
|
||||
num_proposal_samples_per_ray=self.config.num_proposal_samples_per_ray,
|
||||
num_proposal_network_iterations=self.config.num_proposal_iterations,
|
||||
single_jitter=self.config.use_single_jitter,
|
||||
update_sched=update_schedule,
|
||||
initial_sampler=initial_sampler,
|
||||
)
|
||||
|
||||
# Collider
|
||||
self.collider = NearFarCollider(near_plane=self.config.near_plane, far_plane=self.config.far_plane)
|
||||
|
||||
# renderers
|
||||
self.renderer_rgb = RGBRenderer(background_color=self.config.background_color)
|
||||
self.renderer_accumulation = AccumulationRenderer()
|
||||
self.renderer_depth = DepthRenderer()
|
||||
self.renderer_normals = NormalsRenderer()
|
||||
|
||||
# shaders
|
||||
self.normals_shader = NormalsShader()
|
||||
|
||||
# losses
|
||||
self.rgb_loss = MSELoss()
|
||||
|
||||
# metrics
|
||||
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
|
||||
self.ssim = structural_similarity_index_measure
|
||||
self.lpips = LearnedPerceptualImagePatchSimilarity(normalize=True)
|
||||
|
||||
def get_param_groups(self) -> Dict[str, List[Parameter]]:
|
||||
param_groups = {}
|
||||
param_groups["proposal_networks"] = list(self.proposal_networks.parameters())
|
||||
param_groups["fields"] = list(self.field.parameters())
|
||||
return param_groups
|
||||
|
||||
def get_training_callbacks(
|
||||
self, training_callback_attributes: TrainingCallbackAttributes
|
||||
) -> List[TrainingCallback]:
|
||||
callbacks = []
|
||||
if self.config.use_proposal_weight_anneal:
|
||||
# anneal the weights of the proposal network before doing PDF sampling
|
||||
N = self.config.proposal_weights_anneal_max_num_iters
|
||||
|
||||
def set_anneal(step):
|
||||
# https://arxiv.org/pdf/2111.12077.pdf eq. 18
|
||||
train_frac = np.clip(step / N, 0, 1)
|
||||
|
||||
def bias(x, b):
|
||||
return b * x / ((b - 1) * x + 1)
|
||||
|
||||
anneal = bias(train_frac, self.config.proposal_weights_anneal_slope)
|
||||
self.proposal_sampler.set_anneal(anneal)
|
||||
|
||||
callbacks.append(
|
||||
TrainingCallback(
|
||||
where_to_run=[TrainingCallbackLocation.BEFORE_TRAIN_ITERATION],
|
||||
update_every_num_iters=1,
|
||||
func=set_anneal,
|
||||
)
|
||||
)
|
||||
callbacks.append(
|
||||
TrainingCallback(
|
||||
where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION],
|
||||
update_every_num_iters=1,
|
||||
func=self.proposal_sampler.step_cb,
|
||||
)
|
||||
)
|
||||
return callbacks
|
||||
|
||||
def get_outputs(self, ray_bundle: RayBundle):
|
||||
ray_samples: RaySamples
|
||||
ray_samples, weights_list, ray_samples_list = self.proposal_sampler(ray_bundle, density_fns=self.density_fns)
|
||||
field_outputs = self.field.forward(ray_samples, compute_normals=self.config.predict_normals)
|
||||
if self.config.use_gradient_scaling:
|
||||
field_outputs = scale_gradients_by_distance_squared(field_outputs, ray_samples)
|
||||
|
||||
weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY])
|
||||
weights_list.append(weights)
|
||||
ray_samples_list.append(ray_samples)
|
||||
|
||||
rgb = self.renderer_rgb(rgb=field_outputs[FieldHeadNames.RGB], weights=weights)
|
||||
depth = self.renderer_depth(weights=weights, ray_samples=ray_samples)
|
||||
accumulation = self.renderer_accumulation(weights=weights)
|
||||
|
||||
outputs = {
|
||||
"rgb": rgb,
|
||||
"accumulation": accumulation,
|
||||
"depth": depth,
|
||||
}
|
||||
|
||||
if self.config.predict_normals:
|
||||
normals = self.renderer_normals(normals=field_outputs[FieldHeadNames.NORMALS], weights=weights)
|
||||
pred_normals = self.renderer_normals(field_outputs[FieldHeadNames.PRED_NORMALS], weights=weights)
|
||||
outputs["normals"] = self.normals_shader(normals)
|
||||
outputs["pred_normals"] = self.normals_shader(pred_normals)
|
||||
# These use a lot of GPU memory, so we avoid storing them for eval.
|
||||
if self.training:
|
||||
outputs["weights_list"] = weights_list
|
||||
outputs["ray_samples_list"] = ray_samples_list
|
||||
|
||||
if self.training and self.config.predict_normals:
|
||||
outputs["rendered_orientation_loss"] = orientation_loss(
|
||||
weights.detach(), field_outputs[FieldHeadNames.NORMALS], ray_bundle.directions
|
||||
)
|
||||
|
||||
outputs["rendered_pred_normal_loss"] = pred_normal_loss(
|
||||
weights.detach(),
|
||||
field_outputs[FieldHeadNames.NORMALS].detach(),
|
||||
field_outputs[FieldHeadNames.PRED_NORMALS],
|
||||
)
|
||||
|
||||
for i in range(self.config.num_proposal_iterations):
|
||||
outputs[f"prop_depth_{i}"] = self.renderer_depth(weights=weights_list[i], ray_samples=ray_samples_list[i])
|
||||
|
||||
return outputs
|
||||
|
||||
def get_metrics_dict(self, outputs, batch):
|
||||
metrics_dict = {}
|
||||
gt_rgb = batch["image"].to(self.device) # RGB or RGBA image
|
||||
gt_rgb = self.renderer_rgb.blend_background(gt_rgb) # Blend if RGBA
|
||||
predicted_rgb = outputs["rgb"]
|
||||
metrics_dict["psnr"] = self.psnr(predicted_rgb, gt_rgb)
|
||||
|
||||
if self.training:
|
||||
metrics_dict["distortion"] = distortion_loss(outputs["weights_list"], outputs["ray_samples_list"])
|
||||
return metrics_dict
|
||||
|
||||
def get_loss_dict(self, outputs, batch, metrics_dict=None):
|
||||
loss_dict = {}
|
||||
image = batch["image"].to(self.device)
|
||||
pred_rgb, gt_rgb = self.renderer_rgb.blend_background_for_loss_computation(
|
||||
pred_image=outputs["rgb"],
|
||||
pred_accumulation=outputs["accumulation"],
|
||||
gt_image=image,
|
||||
)
|
||||
|
||||
loss_dict["rgb_loss"] = self.rgb_loss(gt_rgb, pred_rgb)
|
||||
if self.training:
|
||||
loss_dict["interlevel_loss"] = self.config.interlevel_loss_mult * interlevel_loss(
|
||||
outputs["weights_list"], outputs["ray_samples_list"]
|
||||
)
|
||||
assert metrics_dict is not None and "distortion" in metrics_dict
|
||||
loss_dict["distortion_loss"] = self.config.distortion_loss_mult * metrics_dict["distortion"]
|
||||
if self.config.predict_normals:
|
||||
# orientation loss for computed normals
|
||||
loss_dict["orientation_loss"] = self.config.orientation_loss_mult * torch.mean(
|
||||
outputs["rendered_orientation_loss"]
|
||||
)
|
||||
|
||||
# ground truth supervision for normals
|
||||
loss_dict["pred_normal_loss"] = self.config.pred_normal_loss_mult * torch.mean(
|
||||
outputs["rendered_pred_normal_loss"]
|
||||
)
|
||||
return loss_dict
|
||||
|
||||
def get_image_metrics_and_images(
|
||||
self, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor]
|
||||
) -> Tuple[Dict[str, float], Dict[str, torch.Tensor]]:
|
||||
gt_rgb = batch["image"].to(self.device)
|
||||
predicted_rgb = outputs["rgb"] # Blended with background (black if random background)
|
||||
gt_rgb = self.renderer_rgb.blend_background(gt_rgb)
|
||||
acc = colormaps.apply_colormap(outputs["accumulation"])
|
||||
depth = colormaps.apply_depth_colormap(
|
||||
outputs["depth"],
|
||||
accumulation=outputs["accumulation"],
|
||||
)
|
||||
|
||||
combined_rgb = torch.cat([gt_rgb, predicted_rgb], dim=1)
|
||||
combined_acc = torch.cat([acc], dim=1)
|
||||
combined_depth = torch.cat([depth], dim=1)
|
||||
|
||||
# Switch images from [H, W, C] to [1, C, H, W] for metrics computations
|
||||
gt_rgb = torch.moveaxis(gt_rgb, -1, 0)[None, ...]
|
||||
predicted_rgb = torch.moveaxis(predicted_rgb, -1, 0)[None, ...]
|
||||
|
||||
psnr = self.psnr(gt_rgb, predicted_rgb)
|
||||
ssim = self.ssim(gt_rgb, predicted_rgb)
|
||||
lpips = self.lpips(torch.clamp(gt_rgb, 0, 1), torch.clamp(predicted_rgb, 0, 1))
|
||||
|
||||
# all of these metrics will be logged as scalars
|
||||
metrics_dict = {"psnr": float(psnr.item()), "ssim": float(ssim)} # type: ignore
|
||||
metrics_dict["lpips"] = float(lpips)
|
||||
|
||||
images_dict = {"img": combined_rgb, "accumulation": combined_acc, "depth": combined_depth}
|
||||
|
||||
for i in range(self.config.num_proposal_iterations):
|
||||
key = f"prop_depth_{i}"
|
||||
prop_depth_i = colormaps.apply_depth_colormap(
|
||||
outputs[key],
|
||||
accumulation=outputs["accumulation"],
|
||||
)
|
||||
images_dict[key] = prop_depth_i
|
||||
|
||||
return metrics_dict, images_dict
|
||||
Reference in new issue
Block a user