mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-06 07:48:50 +08:00
Merge branch 'generative' of https://github.com/plenoptix/nerfactory into generative
This commit is contained in:
commit
5d91d32402
7 files changed
+88
-14
No files matched your search
@@ -18,7 +18,7 @@ Optimizers class.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any, Dict, List, Type
|
from typing import Any, Dict, List, Optional, Type
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
from torch.cuda.amp.grad_scaler import GradScaler
|
from torch.cuda.amp.grad_scaler import GradScaler
|
||||||
@@ -34,8 +34,13 @@ class OptimizerConfig(base_config.PrintableConfig):
|
|||||||
"""Basic optimizer config with RAdam"""
|
"""Basic optimizer config with RAdam"""
|
||||||
|
|
||||||
_target: Type = torch.optim.Adam
|
_target: Type = torch.optim.Adam
|
||||||
|
"""The optimizer class to use."""
|
||||||
lr: float = 0.0005
|
lr: float = 0.0005
|
||||||
|
"""The learning rate to use."""
|
||||||
eps: float = 1e-08
|
eps: float = 1e-08
|
||||||
|
"""The epsilon value to use."""
|
||||||
|
max_norm: Optional[float] = None
|
||||||
|
"""The max norm to use for gradient clipping."""
|
||||||
|
|
||||||
# TODO: somehow make this more generic. i dont like the idea of overriding the setup function
|
# TODO: somehow make this more generic. i dont like the idea of overriding the setup function
|
||||||
# but also not sure how to go about passing things into predefined torch objects.
|
# but also not sure how to go about passing things into predefined torch objects.
|
||||||
@@ -43,6 +48,7 @@ class OptimizerConfig(base_config.PrintableConfig):
|
|||||||
"""Returns the instantiated object using the config."""
|
"""Returns the instantiated object using the config."""
|
||||||
kwargs = vars(self).copy()
|
kwargs = vars(self).copy()
|
||||||
kwargs.pop("_target")
|
kwargs.pop("_target")
|
||||||
|
kwargs.pop("max_norm")
|
||||||
return self._target(params, **kwargs)
|
return self._target(params, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
@@ -52,6 +58,7 @@ class AdamOptimizerConfig(OptimizerConfig):
|
|||||||
|
|
||||||
_target: Type = torch.optim.Adam
|
_target: Type = torch.optim.Adam
|
||||||
weight_decay: float = 0
|
weight_decay: float = 0
|
||||||
|
"""The weight decay to use."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -73,9 +80,11 @@ class Optimizers:
|
|||||||
self.config = config
|
self.config = config
|
||||||
self.optimizers = {}
|
self.optimizers = {}
|
||||||
self.schedulers = {}
|
self.schedulers = {}
|
||||||
|
self.parameters = {}
|
||||||
for param_group_name, params in param_groups.items():
|
for param_group_name, params in param_groups.items():
|
||||||
lr_init = config[param_group_name]["optimizer"].lr
|
lr_init = config[param_group_name]["optimizer"].lr
|
||||||
self.optimizers[param_group_name] = config[param_group_name]["optimizer"].setup(params=params)
|
self.optimizers[param_group_name] = config[param_group_name]["optimizer"].setup(params=params)
|
||||||
|
self.parameters[param_group_name] = params
|
||||||
if config[param_group_name]["scheduler"]:
|
if config[param_group_name]["scheduler"]:
|
||||||
self.schedulers[param_group_name] = config[param_group_name]["scheduler"].setup(
|
self.schedulers[param_group_name] = config[param_group_name]["scheduler"].setup(
|
||||||
optimizer=self.optimizers[param_group_name], lr_init=lr_init
|
optimizer=self.optimizers[param_group_name], lr_init=lr_init
|
||||||
@@ -109,13 +118,20 @@ class Optimizers:
|
|||||||
Args:
|
Args:
|
||||||
grad_scaler: GradScaler to use
|
grad_scaler: GradScaler to use
|
||||||
"""
|
"""
|
||||||
for _, optimizer in self.optimizers.items():
|
for param_group, optimizer in self.optimizers.items():
|
||||||
|
max_norm = self.config[param_group]["optimizer"].max_norm
|
||||||
|
if max_norm is not None:
|
||||||
|
grad_scaler.unscale_(optimizer)
|
||||||
|
torch.nn.utils.clip_grad_norm_(self.parameters[param_group], max_norm)
|
||||||
grad_scaler.step(optimizer)
|
grad_scaler.step(optimizer)
|
||||||
|
|
||||||
def optimizer_step_all(self):
|
def optimizer_step_all(self):
|
||||||
"""Run step for all optimizers."""
|
"""Run step for all optimizers."""
|
||||||
for _, optimizer in self.optimizers.items():
|
for param_group, optimizer in self.optimizers.items():
|
||||||
# note that they key is the parameter name
|
# note that they key is the parameter name
|
||||||
|
max_norm = self.config[param_group]["optimizer"].max_norm
|
||||||
|
if max_norm is not None:
|
||||||
|
torch.nn.utils.clip_grad_norm_(self.parameters[param_group], max_norm)
|
||||||
optimizer.step()
|
optimizer.step()
|
||||||
|
|
||||||
def scheduler_step_all(self, step: int) -> None:
|
def scheduler_step_all(self, step: int) -> None:
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ class TrainerConfig(ExperimentConfig):
|
|||||||
load_step: Optional[int] = None
|
load_step: Optional[int] = None
|
||||||
"""Optionally specify model step to load from; if none, will find most recent model in load_dir."""
|
"""Optionally specify model step to load from; if none, will find most recent model in load_dir."""
|
||||||
load_config: Optional[Path] = None
|
load_config: Optional[Path] = None
|
||||||
|
"""Optionally log gradients during training"""
|
||||||
|
log_gradients: bool = False
|
||||||
|
|
||||||
|
|
||||||
class Trainer:
|
class Trainer:
|
||||||
@@ -189,7 +191,6 @@ class Trainer:
|
|||||||
step = 0
|
step = 0
|
||||||
for step in range(self._start_step, self._start_step + num_iterations):
|
for step in range(self._start_step, self._start_step + num_iterations):
|
||||||
with TimeWriter(writer, EventName.ITER_TRAIN_TIME, step=step) as train_t:
|
with TimeWriter(writer, EventName.ITER_TRAIN_TIME, step=step) as train_t:
|
||||||
|
|
||||||
self.pipeline.train()
|
self.pipeline.train()
|
||||||
|
|
||||||
# training callbacks before the training iteration
|
# training callbacks before the training iteration
|
||||||
@@ -371,6 +372,18 @@ class Trainer:
|
|||||||
loss = functools.reduce(torch.add, loss_dict.values())
|
loss = functools.reduce(torch.add, loss_dict.values())
|
||||||
self.grad_scaler.scale(loss).backward() # type: ignore
|
self.grad_scaler.scale(loss).backward() # type: ignore
|
||||||
self.optimizers.optimizer_scaler_step_all(self.grad_scaler)
|
self.optimizers.optimizer_scaler_step_all(self.grad_scaler)
|
||||||
|
|
||||||
|
if self.config.log_gradients:
|
||||||
|
total_grad = 0
|
||||||
|
for tag, value in self.pipeline.model.named_parameters():
|
||||||
|
assert tag != "Total"
|
||||||
|
if value.grad is not None:
|
||||||
|
grad = value.grad.norm()
|
||||||
|
metrics_dict[f"Gradients/{tag}"] = grad
|
||||||
|
total_grad += grad
|
||||||
|
|
||||||
|
metrics_dict["Gradients/Total"] = total_grad
|
||||||
|
|
||||||
self.grad_scaler.update()
|
self.grad_scaler.update()
|
||||||
self.optimizers.scheduler_step_all(step)
|
self.optimizers.scheduler_step_all(step)
|
||||||
|
|
||||||
|
|||||||
@@ -332,3 +332,37 @@ class NormalsRenderer(nn.Module):
|
|||||||
"""Calculate normals along the ray."""
|
"""Calculate normals along the ray."""
|
||||||
n = torch.sum(weights * normals, dim=-2)
|
n = torch.sum(weights * normals, dim=-2)
|
||||||
return n
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
class LambertianShadingRenderer(nn.Module):
|
||||||
|
"""Calculate Lambertian shading."""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def forward(
|
||||||
|
cls,
|
||||||
|
rgb: TensorType["bs":..., 3],
|
||||||
|
normals: TensorType["bs":..., 3],
|
||||||
|
light_direction: TensorType["bs":..., 3],
|
||||||
|
shading_weight: float = 1.0,
|
||||||
|
detach_normals=True,
|
||||||
|
):
|
||||||
|
"""Calculate Lambertian shading.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
rgb: Accumulated rgb along a ray.
|
||||||
|
normals: Accumulated normals along a ray.
|
||||||
|
light_direction: Direction of light source.
|
||||||
|
shading_weight: Lambertian shading (1.0) vs. ambient lighting (0.0) ratio
|
||||||
|
detach_normals: Detach normals from the computation graph when computing shading.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Textureless Lambertian shading, Lambertian shading
|
||||||
|
"""
|
||||||
|
if detach_normals:
|
||||||
|
normals = normals.detach()
|
||||||
|
|
||||||
|
lambertian = (1 - shading_weight) + shading_weight * (normals @ light_direction).clamp(min=0)
|
||||||
|
shaded = lambertian.unsqueeze(-1).repeat(1, 3)
|
||||||
|
shaded_albedo = rgb * lambertian.unsqueeze(-1)
|
||||||
|
|
||||||
|
return shaded, shaded_albedo
|
||||||
@@ -47,6 +47,7 @@ from nerfstudio.model_components.ray_samplers import UniformSampler
|
|||||||
from nerfstudio.model_components.renderers import (
|
from nerfstudio.model_components.renderers import (
|
||||||
AccumulationRenderer,
|
AccumulationRenderer,
|
||||||
DepthRenderer,
|
DepthRenderer,
|
||||||
|
LambertianShadingRenderer,
|
||||||
NormalsRenderer,
|
NormalsRenderer,
|
||||||
RGBRenderer,
|
RGBRenderer,
|
||||||
)
|
)
|
||||||
@@ -180,6 +181,7 @@ class DreamFusionModel(Model):
|
|||||||
self.renderer_accumulation = AccumulationRenderer()
|
self.renderer_accumulation = AccumulationRenderer()
|
||||||
self.renderer_depth = DepthRenderer()
|
self.renderer_depth = DepthRenderer()
|
||||||
self.renderer_normals = NormalsRenderer()
|
self.renderer_normals = NormalsRenderer()
|
||||||
|
self.renderer_lambertian = LambertianShadingRenderer()
|
||||||
|
|
||||||
# losses
|
# losses
|
||||||
self.rgb_loss = MSELoss()
|
self.rgb_loss = MSELoss()
|
||||||
@@ -248,13 +250,13 @@ class DreamFusionModel(Model):
|
|||||||
light_d = math.safe_normalize(light_d)
|
light_d = math.safe_normalize(light_d)
|
||||||
|
|
||||||
if self.train_shaded and np.random.random_sample() > 0.75:
|
if self.train_shaded and np.random.random_sample() > 0.75:
|
||||||
ratio = 0.1
|
shading_weight = 0.9
|
||||||
else:
|
else:
|
||||||
ratio = 0.0
|
shading_weight = 0.0
|
||||||
# with torch.no_grad():
|
|
||||||
lambertian = ratio + (1 - ratio) * (pred_normals.detach() @ light_d).clamp(min=0)
|
shaded, shaded_albedo = self.renderer_lambertian(
|
||||||
shaded = lambertian.unsqueeze(-1).repeat(1, 3)
|
rgb=rgb, normals=pred_normals, light_direction=light_d, shading_weight=shading_weight, detach_normals=True
|
||||||
shaded_albedo = rgb * lambertian.unsqueeze(-1)
|
)
|
||||||
|
|
||||||
outputs["normals"] = normals
|
outputs["normals"] = normals
|
||||||
outputs["pred_normals"] = pred_normals
|
outputs["pred_normals"] = pred_normals
|
||||||
@@ -262,7 +264,7 @@ class DreamFusionModel(Model):
|
|||||||
outputs["shaded_albedo"] = shaded_albedo
|
outputs["shaded_albedo"] = shaded_albedo
|
||||||
outputs["render"] = accum_mask * rgb + background
|
outputs["render"] = accum_mask * rgb + background
|
||||||
|
|
||||||
if ratio > 0:
|
if shading_weight < 0:
|
||||||
if np.random.random_sample() > 0.5:
|
if np.random.random_sample() > 0.5:
|
||||||
outputs["train_output"] = shaded
|
outputs["train_output"] = shaded
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -39,3 +39,11 @@ def check_colmap_installed():
|
|||||||
CONSOLE.print("[bold red]Could not find COLMAP. Please install COLMAP.")
|
CONSOLE.print("[bold red]Could not find COLMAP. Please install COLMAP.")
|
||||||
print("See https://colmap.github.io/install.html for installation instructions.")
|
print("See https://colmap.github.io/install.html for installation instructions.")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def check_curl_installed():
|
||||||
|
"""Checks if curl is installed."""
|
||||||
|
curl_path = shutil.which("curl")
|
||||||
|
if curl_path is None:
|
||||||
|
CONSOLE.print("[bold red]Could not find [yellow]curl[red], Please install [yellow]curl")
|
||||||
|
sys.exit(1)
|
||||||
@@ -48,7 +48,6 @@ from nerfstudio.models.base_model import Model
|
|||||||
from nerfstudio.utils import colormaps, profiler, writer
|
from nerfstudio.utils import colormaps, profiler, writer
|
||||||
from nerfstudio.utils.decorators import check_main_thread, decorate_all
|
from nerfstudio.utils.decorators import check_main_thread, decorate_all
|
||||||
from nerfstudio.utils.io import load_from_json, write_to_json
|
from nerfstudio.utils.io import load_from_json, write_to_json
|
||||||
from nerfstudio.utils.misc import get_dict_to_torch
|
|
||||||
from nerfstudio.utils.writer import GLOBAL_BUFFER, EventName, TimeWriter
|
from nerfstudio.utils.writer import GLOBAL_BUFFER, EventName, TimeWriter
|
||||||
from nerfstudio.viewer.server.subprocess import run_viewer_bridge_server_as_subprocess
|
from nerfstudio.viewer.server.subprocess import run_viewer_bridge_server_as_subprocess
|
||||||
from nerfstudio.viewer.server.utils import (
|
from nerfstudio.viewer.server.utils import (
|
||||||
@@ -163,7 +162,6 @@ class RenderThread(threading.Thread):
|
|||||||
self.exc = e
|
self.exc = e
|
||||||
|
|
||||||
if outputs:
|
if outputs:
|
||||||
outputs = get_dict_to_torch(outputs)
|
|
||||||
self.vis_outputs = outputs
|
self.vis_outputs = outputs
|
||||||
|
|
||||||
self.state.check_done_render = True
|
self.state.check_done_render = True
|
||||||
@@ -828,7 +826,7 @@ class ViewerState:
|
|||||||
else:
|
else:
|
||||||
image_height = (num_vis_rays / aspect_ratio) ** 0.5
|
image_height = (num_vis_rays / aspect_ratio) ** 0.5
|
||||||
image_height = int(round(image_height, -1))
|
image_height = int(round(image_height, -1))
|
||||||
image_height = min(self.max_resolution, image_height)
|
image_height = max(min(self.max_resolution, image_height), 30)
|
||||||
image_width = int(image_height * aspect_ratio)
|
image_width = int(image_height * aspect_ratio)
|
||||||
if image_width > self.max_resolution:
|
if image_width > self.max_resolution:
|
||||||
image_width = self.max_resolution
|
image_width = self.max_resolution
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from rich.console import Console
|
|||||||
from typing_extensions import Annotated
|
from typing_extensions import Annotated
|
||||||
|
|
||||||
from nerfstudio.configs.base_config import PrintableConfig
|
from nerfstudio.configs.base_config import PrintableConfig
|
||||||
|
from nerfstudio.utils import install_checks
|
||||||
from nerfstudio.utils.scripts import run_command
|
from nerfstudio.utils.scripts import run_command
|
||||||
|
|
||||||
CONSOLE = Console(width=120)
|
CONSOLE = Console(width=120)
|
||||||
@@ -212,6 +213,7 @@ class DNerfDownload(DatasetDownload):
|
|||||||
"""Download the D-NeRF dataset (https://github.com/albertpumarola/D-NeRF)."""
|
"""Download the D-NeRF dataset (https://github.com/albertpumarola/D-NeRF)."""
|
||||||
# TODO: give this code the same structure as download_nerfstudio
|
# TODO: give this code the same structure as download_nerfstudio
|
||||||
|
|
||||||
|
install_checks.check_curl_installed()
|
||||||
final_path = save_dir / Path("dnerf")
|
final_path = save_dir / Path("dnerf")
|
||||||
if os.path.exists(final_path):
|
if os.path.exists(final_path):
|
||||||
shutil.rmtree(str(final_path))
|
shutil.rmtree(str(final_path))
|
||||||
@@ -253,6 +255,7 @@ class PhototourismDownload(DatasetDownload):
|
|||||||
def download(self, save_dir: Path):
|
def download(self, save_dir: Path):
|
||||||
"""Download a PhotoTourism dataset: https://www.cs.ubc.ca/~kmyi/imw2020/data.html"""
|
"""Download a PhotoTourism dataset: https://www.cs.ubc.ca/~kmyi/imw2020/data.html"""
|
||||||
|
|
||||||
|
install_checks.check_curl_installed()
|
||||||
if self.capture_name == "all":
|
if self.capture_name == "all":
|
||||||
for capture_name in phototourism_downloads:
|
for capture_name in phototourism_downloads:
|
||||||
if capture_name != "all":
|
if capture_name != "all":
|
||||||
|
|||||||
Reference in new issue
Block a user