From ac3b1704bf85a5620b76a04da8502a77b8279717 Mon Sep 17 00:00:00 2001 From: terrance Date: Thu, 27 Apr 2023 18:40:45 +0000 Subject: [PATCH] dreamngp works but no normals --- nerfstudio/configs/method_configs.py | 118 +++++- .../datamanagers/iterative_datamanager.py | 51 ++- nerfstudio/engine/trainer.py | 11 +- nerfstudio/fields/dreamngp_field.py | 146 +++++++ nerfstudio/generative/stable_diffusion.py | 33 ++ .../generative/stable_diffusion_img2img.py | 73 ++-- .../model_components/scene_colliders.py | 13 +- nerfstudio/models/dreamembedding.py | 26 +- nerfstudio/models/dreamfusion.py | 27 +- nerfstudio/models/dreamfusion_ngp.py | 400 ++++++++++++++++++ nerfstudio/models/dreamfusion_rgb.py | 208 +++++++++ nerfstudio/models/dreamfusion_tensor.py | 397 +++++++++++++++++ nerfstudio/pipelines/base_pipeline.py | 11 + nerfstudio/pipelines/iterative_pipeline.py | 167 ++++++-- .../viewer/server/render_state_machine.py | 3 + 15 files changed, 1552 insertions(+), 132 deletions(-) create mode 100644 nerfstudio/fields/dreamngp_field.py create mode 100644 nerfstudio/models/dreamfusion_ngp.py create mode 100644 nerfstudio/models/dreamfusion_rgb.py create mode 100644 nerfstudio/models/dreamfusion_tensor.py diff --git a/nerfstudio/configs/method_configs.py b/nerfstudio/configs/method_configs.py index 5aa3563dc..5eb448a81 100644 --- a/nerfstudio/configs/method_configs.py +++ b/nerfstudio/configs/method_configs.py @@ -54,9 +54,11 @@ from nerfstudio.engine.schedulers import ( from nerfstudio.engine.trainer import TrainerConfig from nerfstudio.field_components.temporal_distortions import TemporalDistortionKind from nerfstudio.fields.sdf_field import SDFFieldConfig +from nerfstudio.models.dreamfusion_rgb import DreamfusionRGBModelConfig from nerfstudio.models.depth_nerfacto import DepthNerfactoModelConfig from nerfstudio.models.dreamembedding import DreamEmbeddingModelConfig from nerfstudio.models.dreamfusion import DreamFusionModelConfig +from nerfstudio.models.dreamfusion_ngp import DreamfusionNGPModelConfig from nerfstudio.models.iterative_dreamfusion import DreamFusionIterativeModelConfig from nerfstudio.models.instant_ngp import InstantNGPModelConfig from nerfstudio.models.mipnerf import MipNerfModel @@ -449,7 +451,7 @@ method_configs["dreamfusion"] = TrainerConfig( pipeline=VanillaPipelineConfig( generative=True, datamanager=DreamFusionDataManagerConfig( - horizontal_rotation_warmup=4000, + horizontal_rotation_warmup=2000, ), model=DreamFusionModelConfig( eval_num_rays_per_chunk=1 << 15, @@ -458,7 +460,7 @@ method_configs["dreamfusion"] = TrainerConfig( orientation_loss_mult=0.1, max_res=256, sphere_collider=True, - initialize_density=False, + initialize_density=True, random_background=True, proposal_warmup=500, proposal_update_every=0, @@ -477,6 +479,7 @@ method_configs["dreamfusion"] = TrainerConfig( }, "fields": { "optimizer": AdamOptimizerConfig(lr=1e-3, eps=1e-15), + # "scheduler": None, "scheduler": ExponentialDecaySchedulerConfig( warmup_steps=2000, lr_final=1e-6, max_steps=20000, ramp="linear" ), @@ -486,6 +489,97 @@ method_configs["dreamfusion"] = TrainerConfig( vis="viewer", ) +method_configs["dreamngp"] = TrainerConfig( + method_name="dreamngp", + experiment_name="dreamngp", + steps_per_eval_batch=50, + steps_per_eval_image=50, + steps_per_save=200, + max_num_iterations=20000, + mixed_precision=True, + pipeline=VanillaPipelineConfig( + generative=True, + datamanager=DreamFusionDataManagerConfig( + horizontal_rotation_warmup=0, + ), + model=DreamfusionNGPModelConfig( + eval_num_rays_per_chunk=8192, + contraction_type=ContractionType.AABB, + render_step_size=0.001, + max_num_samples_per_ray=48, + orientation_loss_mult=1.0, + sphere_collider=True, + initialize_density=True, + proposal_warmup=500, + proposal_update_every=0, + proposal_weights_anneal_max_num_iters=100, + opacity_loss_mult=1, + positional_prompting="discrete", + guidance_scale=50, + ), + ), + optimizers={ + "proposal_networks": { + "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": None, + }, + "fields": { + "optimizer": AdamOptimizerConfig(lr=1e-3, eps=1e-15), + # "scheduler": None, + "scheduler": ExponentialDecaySchedulerConfig( + warmup_steps=2000, lr_final=1e-6, max_steps=20000, ramp="linear" + ), + }, + }, + viewer=ViewerConfig(num_rays_per_chunk=32000), + vis="viewer", +) + +method_configs["dreamrgb"] = TrainerConfig( + method_name="dreamrgb", + experiment_name="dreamrgb", + steps_per_eval_batch=50, + steps_per_eval_image=50, + steps_per_save=200, + max_num_iterations=20000, + mixed_precision=True, + pipeline=VanillaPipelineConfig( + generative=True, + datamanager=DreamFusionDataManagerConfig( + horizontal_rotation_warmup=0, + ), + model=DreamfusionRGBModelConfig( + eval_num_rays_per_chunk=1 << 15, + distortion_loss_mult=0.1, + interlevel_loss_mult=100.0, + orientation_loss_mult=1.0, + max_res=128, + sphere_collider=True, + initialize_density=False, + proposal_warmup=500, + proposal_update_every=0, + proposal_weights_anneal_max_num_iters=100, + opacity_loss_mult=1, + positional_prompting="discrete", + guidance_scale=50, + ), + ), + optimizers={ + "proposal_networks": { + "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": None, + }, + "fields": { + "optimizer": AdamOptimizerConfig(lr=1e-3, eps=1e-15), + "scheduler": ExponentialDecaySchedulerConfig( + warmup_steps=1000, lr_final=1e-6, max_steps=20000, ramp="linear" + ), + }, + }, + viewer=ViewerConfig(num_rays_per_chunk=1 << 15), + vis="viewer", +) + method_configs["iter_test"] = TrainerConfig( method_name="iter_test", experiment_name="iter_test", @@ -496,9 +590,27 @@ method_configs["iter_test"] = TrainerConfig( mixed_precision=True, pipeline=IterativePipelineConfig( generative=True, + datamanager2=DreamFusionDataManagerConfig( + horizontal_rotation_warmup=0, + ), datamanager=IterativeDataManagerConfig( ), - model=DreamFusionIterativeModelConfig(), + model=DreamEmbeddingModelConfig( + eval_num_rays_per_chunk=1 << 15, + distortion_loss_mult=0.1, + interlevel_loss_mult=100.0, + orientation_loss_mult=1.0, + max_res=128, + sphere_collider=True, + initialize_density=False, + proposal_warmup=500, + proposal_update_every=0, + proposal_weights_anneal_max_num_iters=100, + opacity_loss_mult=1, + positional_prompting="discrete", + guidance_scale=50, + ), + model2=DreamFusionIterativeModelConfig(), ), optimizers={ "proposal_networks": { diff --git a/nerfstudio/data/datamanagers/iterative_datamanager.py b/nerfstudio/data/datamanagers/iterative_datamanager.py index 516405912..7498a773a 100644 --- a/nerfstudio/data/datamanagers/iterative_datamanager.py +++ b/nerfstudio/data/datamanagers/iterative_datamanager.py @@ -19,31 +19,28 @@ Data manager for dreamfusion from __future__ import annotations import sys -from dataclasses import dataclass, field -from typing import Dict, List, Tuple, Type, Union, Optional -from pathlib import Path from copy import deepcopy +from dataclasses import dataclass, field from pathlib import Path, PurePath +from typing import Dict, List, Optional, Tuple, Type, Union import torch from rich.progress import Console from torch.nn import Parameter from typing_extensions import Literal + from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig - -from nerfstudio.data.dataparsers.base_dataparser import DataparserOutputs -from nerfstudio.data.utils.nerfstudio_collate import nerfstudio_collate -from nerfstudio.model_components.ray_generators import RayGenerator - from nerfstudio.cameras.cameras import Cameras from nerfstudio.cameras.rays import RayBundle from nerfstudio.configs.config_utils import to_immutable_dict from nerfstudio.data.datamanagers.base_datamanager import DataManager, DataManagerConfig +from nerfstudio.data.dataparsers.base_dataparser import DataparserOutputs from nerfstudio.data.datasets.base_dataset import InputDataset -from nerfstudio.data.scene_box import SceneBox -from nerfstudio.data.utils.dataloaders import RandIndicesEvalDataloader, CacheDataloader - from nerfstudio.data.pixel_samplers import PixelSampler +from nerfstudio.data.scene_box import SceneBox +from nerfstudio.data.utils.dataloaders import CacheDataloader, RandIndicesEvalDataloader +from nerfstudio.data.utils.nerfstudio_collate import nerfstudio_collate +from nerfstudio.model_components.ray_generators import RayGenerator CONSOLE = Console(width=120) @@ -81,6 +78,8 @@ def random_train_pose( focal_range: Tuple[float, float] = (0.75, 1.35), jitter_std: float = 0.01, center: Tuple[float, float, float] = (0, 0, 0), + vertical_rotation_given=None, + central_rotation_given=None, ): """generate random poses from an orbit camera Args: @@ -110,6 +109,11 @@ def random_train_pose( torch.rand(size) * (central_rotation_range[1] - central_rotation_range[0]) + central_rotation_range[0] ) + if vertical_rotation_given is not None: + vertical_rotation = torch.deg2rad(vertical_rotation_given) + if central_rotation_given is not None: + central_rotation = torch.deg2rad(central_rotation_given) + c_cos = torch.cos(central_rotation) c_sin = torch.sin(central_rotation) v_cos = torch.cos(vertical_rotation) @@ -191,7 +195,7 @@ class IterativeDataManagerConfig(DataManagerConfig): """Std of radius of camera orbit""" focal_range: Tuple[float, float] = (0.6, 1.2) """Range of focal length""" - vertical_rotation_range: Tuple[float, float] = (-90, 0) + vertical_rotation_range: Tuple[float, float] = (-100, 0) """Range of vertical rotation""" jitter_std: float = 0.05 """Std of camera direction jitter, so we don't just point the cameras towards the center every time""" @@ -240,6 +244,8 @@ class IterativeDataManager(DataManager): # pylint: disable=abstract-method center=self.config.center, ) + self.camera_angles = [] + self.train_dataset = TrivialDataset(cameras) self.eval_dataset = TrivialDataset(cameras) @@ -284,26 +290,31 @@ class IterativeDataManager(DataManager): # pylint: disable=abstract-method self.train_camera_optimizer, ) - def random_train_views(self, step: int, resolution:int, num_views: int) -> InputDataset: + def random_train_views(self, step: int, resolution: int, num_views: int, + vertical_rotation_given=None, + central_rotation_given=None, + cameras_only=False) -> InputDataset: """eawoijfaw""" cameras, vertical_rotation, central_rotation = random_train_pose( size=num_views, resolution=resolution, - device= self.device, + device=self.device, radius_mean=self.config.radius_mean, radius_std=self.config.radius_std, focal_range=self.config.focal_range, - central_rotation_range=(0, 360), + central_rotation_range=(-180, 180), vertical_rotation_range=self.config.vertical_rotation_range, jitter_std=self.config.jitter_std, center=self.config.center, + vertical_rotation_given=vertical_rotation_given, + central_rotation_given=central_rotation_given, ) + if cameras_only: + return cameras - ray_bundle = cameras.generate_rays( - torch.tensor([[i] for i in range(num_views)]) - ) + ray_bundle = cameras.generate_rays(torch.tensor([[i] for i in range(num_views)])) - return ray_bundle, cameras, list(zip(vertical_rotation, central_rotation)) + return ray_bundle, cameras, vertical_rotation, central_rotation def next_train(self, step: int) -> Tuple[RayBundle, Dict]: """Returns the next batch of data from the train dataloader.""" @@ -348,7 +359,7 @@ class IterativeDataManager(DataManager): # pylint: disable=abstract-method def get_eval_rays_per_batch(self) -> int: return self.config.eval_resolution**2 - + def get_datapath(self) -> Optional[Path]: # pylint:disable=no-self-use """Returns the path to the data. This is used to determine where to save camera paths.""" if self.temp_save_path is None: diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py index 8425cc1a3..bd34c965d 100644 --- a/nerfstudio/engine/trainer.py +++ b/nerfstudio/engine/trainer.py @@ -143,7 +143,8 @@ class Trainer: 'inference': does not load any dataset into memory """ self.pipeline = self.config.pipeline.setup( - device=self.device, test_mode=test_mode, world_size=self.world_size, local_rank=self.local_rank + device=self.device, test_mode=test_mode, world_size=self.world_size, local_rank=self.local_rank, + grad_scaler=self.grad_scaler, ) self.optimizers = self.setup_optimizers() @@ -165,14 +166,6 @@ class Trainer: banner_messages = [f"Viewer at: {self.viewer_state.viewer_url}"] self._check_viewer_warnings() - self.pipeline = self.config.pipeline.setup( - device=self.device, - test_mode=test_mode, - world_size=self.world_size, - local_rank=self.local_rank, - grad_scaler=self.grad_scaler, - ) - self.optimizers = self.setup_optimizers() self._load_checkpoint() diff --git a/nerfstudio/fields/dreamngp_field.py b/nerfstudio/fields/dreamngp_field.py new file mode 100644 index 000000000..1743dd69b --- /dev/null +++ b/nerfstudio/fields/dreamngp_field.py @@ -0,0 +1,146 @@ +# Copyright 2022 The Nerfstudio Team. 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. + +""" +DreamNGP field implementations using tiny-cuda-nn, torch, .... +""" + + +from typing import Dict, Optional, Tuple + +import numpy as np +import torch +from nerfacc import ContractionType, contract +from torch.nn.parameter import Parameter +from torchtyping import TensorType + +from nerfstudio.cameras.rays import RayBundle, 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.field_heads import FieldHeadNames +from nerfstudio.fields.base_field import Field, shift_directions_for_tcnn +from nerfstudio.fields.instant_ngp_field import TCNNInstantNGPField +try: + import tinycudann as tcnn +except ImportError: + # tinycudann module doesn't exist + pass + +def get_normalized_directions(directions: TensorType["bs":..., 3]): + """SH encoding must be in the range [0, 1] + + Args: + directions: batch of directions + """ + return (directions + 1.0) / 2.0 + + +class DreamNGPField(TCNNInstantNGPField): + """TCNN implementation of the Instant-NGP field. + + Args: + aabb: parameters of scene aabb bounds + num_layers: number of hidden layers + hidden_dim: dimension of hidden layers + geo_feat_dim: output geo feat dimensions + num_layers_color: number of hidden layers for color network + hidden_dim_color: dimension of hidden layers for color network + use_appearance_embedding: whether to use appearance embedding + num_images: number of images, required if use_appearance_embedding is True + appearance_embedding_dim: dimension of appearance embedding + contraction_type: type of contraction + num_levels: number of levels of the hashmap for the base mlp + log2_hashmap_size: size of the hashmap for the base mlp + max_res: maximum resolution of the hashmap for the base mlp + """ + + def __init__( + self, + aabb: TensorType, + num_layers: int = 2, + hidden_dim: int = 64, + geo_feat_dim: int = 15, + num_layers_color: int = 3, + hidden_dim_color: int = 64, + use_appearance_embedding: Optional[bool] = False, + num_images: Optional[int] = None, + appearance_embedding_dim: int = 32, + contraction_type: ContractionType = ContractionType.UN_BOUNDED_SPHERE, + num_levels: int = 16, + log2_hashmap_size: int = 19, + max_res: int = 2048, + ) -> None: + super().__init__( + aabb, + num_layers, + hidden_dim, + geo_feat_dim, + num_layers_color, + hidden_dim_color, + use_appearance_embedding, + num_images, + appearance_embedding_dim, + contraction_type, + num_levels, + log2_hashmap_size, + max_res + ) + self.mlp_background_color = tcnn.Network( + n_input_dims=self.direction_encoding.n_output_dims, + n_output_dims=3, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "Sigmoid", + "n_neurons": 32, + "n_hidden_layers": 1, + }, + ) + + def get_density(self, ray_samples: RaySamples): + """Computes and returns the densities""" + positions = ray_samples.frustums.get_positions() + # positions = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) + positions_flat = positions.view(-1, 3) + positions_flat = contract(x=positions_flat, roi=self.aabb, type=self.contraction_type) + + self._sample_locations = positions_flat + if not self._sample_locations.requires_grad: + self._sample_locations.requires_grad = True + + 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 + + # import pdb + # pdb.set_trace() + + # 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)) + return density, base_mlp_out + + + + def get_background_rgb(self, ray_bundle: RayBundle): + """Predicts background colors at infinity.""" + directions = get_normalized_directions(ray_bundle.directions) + + outputs_shape = ray_bundle.directions.shape[:-1] + directions_flat = self.direction_encoding(directions.view(-1, 3)) + background_rgb = self.mlp_background_color(directions_flat).view(*outputs_shape, -1).to(directions) + + return background_rgb \ No newline at end of file diff --git a/nerfstudio/generative/stable_diffusion.py b/nerfstudio/generative/stable_diffusion.py index 908f1a2a4..ce030e677 100644 --- a/nerfstudio/generative/stable_diffusion.py +++ b/nerfstudio/generative/stable_diffusion.py @@ -187,6 +187,39 @@ class StableDiffusion(nn.Module): text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) return text_embeddings + + @torch.no_grad() + def sds_rgb(self, + text_embeddings: TensorType["N", "max_length", "embed_dim"], + image: TensorType["BS", 3, "H", "W"], + guidance_scale: float = 100.0, + grad_scaler: Optional[GradScaler] = None, + ) -> torch.Tensor: + + with torch.autocast(device_type="cuda", enabled=False): + image = F.interpolate(image.half(), (IMG_DIM, IMG_DIM), mode="bilinear") + t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device) + + latents = self.imgs_to_latent(image) + # add noise + noise = torch.randn_like(latents) + latents_noisy = self.scheduler.add_noise(latents, noise, t) # type: ignore + # pred noise + latent_model_input = torch.cat([latents_noisy] * 2) + noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample + + # perform guidance + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond) + + # latents_unnoised = self.scheduler.step(noise_pred, t, latents)["prev_sample"] + latents_unnoised = latents_noisy - noise_pred + pred_rgb = self.latents_to_img(latents_unnoised) + + pred_rgb = F.interpolate(pred_rgb, (64, 64), mode="bilinear") + + return pred_rgb + def sds_loss_latent( self, diff --git a/nerfstudio/generative/stable_diffusion_img2img.py b/nerfstudio/generative/stable_diffusion_img2img.py index 82a8ed880..d65388d06 100644 --- a/nerfstudio/generative/stable_diffusion_img2img.py +++ b/nerfstudio/generative/stable_diffusion_img2img.py @@ -27,16 +27,20 @@ import numpy as np import torch import torch.nn.functional as F import tyro +from PIL import Image from rich.console import Console from torch import nn from torch.cuda.amp import custom_bwd, custom_fwd from torch.cuda.amp.grad_scaler import GradScaler from torchtyping import TensorType -from PIL import Image - try: - from diffusers import PNDMScheduler, StableDiffusionPipeline, DDIMScheduler, DDPMScheduler + from diffusers import ( + DDIMScheduler, + DDPMScheduler, + PNDMScheduler, + StableDiffusionPipeline, + ) from transformers import logging SD_AVAILABLE = True @@ -85,6 +89,7 @@ class StableDiffusionImg2Img(nn.Module): self.min_step = int(self.num_train_timesteps * 0.02) self.max_step = int(self.num_train_timesteps * 0.98) + # might need to change scheduler here? self.scheduler = PNDMScheduler( skip_prk_steps=True, beta_start=0.00085, @@ -96,7 +101,7 @@ class StableDiffusionImg2Img(nn.Module): sd_id = SD_IDENTIFIERS[version] pipe = StableDiffusionPipeline.from_pretrained(sd_id, torch_dtype=torch.float16) - print('SD Pipe Loaded') + print("SD Pipe Loaded") assert pipe is not None pipe = pipe.to(self.device) @@ -135,7 +140,7 @@ class StableDiffusionImg2Img(nn.Module): self.tokenizer = pipe.tokenizer self.text_encoder = pipe.text_encoder self.auto_encoder = pipe.vae - + CONSOLE.print("Stable Diffusion loaded!") def get_text_embeds( @@ -306,7 +311,7 @@ class StableDiffusionImg2Img(nn.Module): cur_img = self.latents_to_img(latents.half()) cur_img = cur_img.detach().cpu().permute(0, 2, 3, 1).numpy() - cur_img = (cur_img * 255).round().astype("uint8")[0] # might delete this indexing + cur_img = (cur_img * 255).round().astype("uint8")[0] # might delete this indexing save_path = Path(f"normal_diffusion_image_steps/{i}.png") mediapy.write_image(str(save_path), cur_img) @@ -343,7 +348,7 @@ class StableDiffusionImg2Img(nn.Module): latents = posterior.sample() * CONST_SCALE return latents - + def search_updates(self, text_embedding, image): self.scheduler.set_timesteps(50) # type: ignore guidance_scale = 7.5 @@ -351,7 +356,7 @@ class StableDiffusionImg2Img(nn.Module): print(self.scheduler.timesteps) print(len(self.scheduler.timesteps)) - noise_strength = .8 + noise_strength = 0.8 # for noise_strength in (1.0, .95, .9, 0.8, 0.7, 0.5, .4, .3, .25, 0.2, .1): # for noise_strength in reversed([1.0, .95, .9, 0.8, 0.7, 0.5, .4, .3, .25, 0.2, .1]): @@ -359,7 +364,7 @@ class StableDiffusionImg2Img(nn.Module): latent = self.imgs_to_latent(image.half()) # t = torch.randint(0, 1, [1], dtype=torch.long) # t = torch.randint(12, 13, [1], dtype=torch.long) - t = torch.randint(a, a+1, [1], dtype=torch.long) + t = torch.randint(a, a + 1, [1], dtype=torch.long) new_steps = self.scheduler.timesteps[t:] new_steps = torch.round(new_steps * noise_strength).type(torch.long) @@ -369,7 +374,7 @@ class StableDiffusionImg2Img(nn.Module): noise = torch.randn_like(latent) latent = self.scheduler.add_noise(latent, noise, t_noise) # type: ignore - + for j, time in enumerate(new_steps): # predict the noise residual latent_model_input = torch.cat([latent] * 2) @@ -377,38 +382,38 @@ class StableDiffusionImg2Img(nn.Module): with torch.no_grad(): noise_pred = self.unet( latent_model_input, time.to(self.device), encoder_hidden_states=text_embedding - ).sample + ).sample # perform guidance noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond) - + latent = self.scheduler.step(noise_pred, time, latent)["prev_sample"] # type: ignore diffused_img = self.latents_to_img(latent.half()) diffused_img = diffused_img.detach().cpu().permute(0, 2, 3, 1).numpy() - diffused_img = (diffused_img * 255).round().astype("uint8")[0] # might delete this indexing + diffused_img = (diffused_img * 255).round().astype("uint8")[0] # might delete this indexing - mediapy.write_image(f'/home/terrance/nerfactory/nerfstudio/generative/img2img/7/newsched_test{a}.png', diffused_img) + mediapy.write_image( + f"/home/terrance/nerfactory/nerfstudio/generative/img2img/7/newsched_test{a}.png", diffused_img + ) return diffused_img - def update_img(self, text_embedding, image, step=0): guidance_scale = 7.5 noise_strength = 1.0 - min_step = int(self.num_train_timesteps * 0.4) + min_step = int(self.num_train_timesteps * 0.7) max_step = int(self.num_train_timesteps * 0.98) # t = torch.randint(min_step, max_step, [1], dtype=torch.long, device=self.device) - # self.scheduler.config.num_train_timesteps = t.item() + # self.scheduler.config.num_train_timesteps = t.item() # self.scheduler.set_timesteps(20) # type: ignore latent = self.imgs_to_latent(image.half()) - # t = torch.randint(10, 11, [1], dtype=torch.long) # t = torch.randint(5, 6, [1], dtype=torch.long) @@ -417,13 +422,15 @@ class StableDiffusionImg2Img(nn.Module): noise_strength = 1.0 else: t = torch.randint(min_step, max_step, [1], dtype=torch.long, device=self.device) - - - self.scheduler.config.num_train_timesteps = t.item() - self.scheduler.set_timesteps(20) # type: ignore + noise_strength = 0.7 + + t = torch.round(t * noise_strength).type(torch.long) + + self.scheduler.config.num_train_timesteps = t.item() + self.scheduler.set_timesteps(50) # type: ignore # self.scheduler.set_timesteps(50) # type: ignore - # t = torch.randint(34, 35, [1], dtype=torch.long) + # t = torch.randint(34, 35, [1], dtype=torch.long) # noise_strength = 0.8 # new_steps = self.scheduler.timesteps[t:] @@ -436,27 +443,26 @@ class StableDiffusionImg2Img(nn.Module): latent = self.scheduler.add_noise(latent, noise, t) # type: ignore for i, time in enumerate(self.scheduler.timesteps): - # for i, time in enumerate(new_steps): + # for i, time in enumerate(new_steps): # predict the noise residual latent_model_input = torch.cat([latent] * 2) with torch.no_grad(): noise_pred = self.unet( latent_model_input, time.to(self.device), encoder_hidden_states=text_embedding - ).sample + ).sample # perform guidance noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond) - + latent = self.scheduler.step(noise_pred, time, latent)["prev_sample"] # type: ignore with torch.no_grad(): diffused_img = self.latents_to_img(latent.half()) diffused_img = diffused_img.detach().cpu().permute(0, 2, 3, 1).numpy() - diffused_img = (diffused_img * 255).round().astype("uint8")[0] # might delete this indexing - + diffused_img = (diffused_img * 255).round().astype("uint8")[0] return diffused_img def prompt_to_img( @@ -513,7 +519,12 @@ class StableDiffusionImg2Img(nn.Module): def generate_image( - prompt: str, negative: str = "", image_path: str = "", seed: int = 0, steps: int = 50, save_path: Path = Path("test_sd.png") + prompt: str, + negative: str = "", + image_path: str = "", + seed: int = 0, + steps: int = 50, + save_path: Path = Path("test_sd.png"), ): """Generate an image from a prompt using Stable Diffusion. Args: @@ -532,10 +543,10 @@ def generate_image( image = np.array(pil_image, dtype="uint8") # shape is (h, w) or (h, w, 3 or 4) image = torch.from_numpy(image.astype("float32") / 255.0) image = image[None, :, :, :3].permute(0, 3, 1, 2).to(cuda_device) - + text_embedding = sd.get_text_embeds(prompt, "") - num_steps=20 + num_steps = 20 imgs = sd.search_updates(text_embedding, image) # imgs = sd.update_img(text_embedding, image) # # imgs = sd.prompt_to_img(prompt, negative) diff --git a/nerfstudio/model_components/scene_colliders.py b/nerfstudio/model_components/scene_colliders.py index a36edfb38..aa5e9cd05 100644 --- a/nerfstudio/model_components/scene_colliders.py +++ b/nerfstudio/model_components/scene_colliders.py @@ -112,8 +112,12 @@ class AABBBoxCollider(SceneCollider): def _intersect_with_sphere( rays_o: torch.Tensor, rays_d: torch.Tensor, center: torch.Tensor, radius: float = 1.0, near_plane: float = 0.0 ): - a = (rays_d * rays_d).sum(dim=-1, keepdim=True) - b = 2 * (rays_o - center) * rays_d + # a = (rays_d * rays_d).sum(dim=-1, keepdim=True) + # b = 2 * (rays_o - center) * rays_d + dir = rays_d - rays_o + a = (dir * dir).sum(dim=-1, keepdim=True) + b = 2 * (rays_o - center) * dir + b = b.sum(dim=-1, keepdim=True) c = (rays_o - center) * (rays_o - center) c = c.sum(dim=-1, keepdim=True) - radius**2 @@ -162,7 +166,10 @@ class SphereCollider(SceneCollider): radius=self.radius, near_plane=near_plane, ) - ray_bundle.nears = nears + if not self.training: + ray_bundle.nears = torch.ones_like(ray_bundle.origins[..., 0:1]) * 0 + else: + ray_bundle.nears = nears ray_bundle.fars = fars return ray_bundle diff --git a/nerfstudio/models/dreamembedding.py b/nerfstudio/models/dreamembedding.py index be9c76928..e8b41599d 100644 --- a/nerfstudio/models/dreamembedding.py +++ b/nerfstudio/models/dreamembedding.py @@ -51,7 +51,7 @@ class DreamEmbeddingModelConfig(DreamFusionModelConfig): _target: Type = field(default_factory=lambda: DreamEmbeddingModel) """target class to instantiate""" - prompt: str = "A high quality photo of a rubber ducky" + prompt: str = "A high quality zoomed out photo of a teddy bear" """prompt for stable dreamfusion""" orientation_loss_mult: float = 0.0001 @@ -178,8 +178,10 @@ class DreamEmbeddingModel(DreamFusionModel): if self.initialize_density: pos = ray_samples.frustums.get_positions() - density_blob = self.density_strength * torch.exp(-torch.norm(pos, dim=-1) / (2 * 0.04))[..., None] - density = density + density_blob + # density_blob = self.density_strength * torch.exp(-torch.norm(pos, dim=-1) / (2 * 0.04))[..., None] + # density = density + density_blob + density_blob = (-torch.exp(torch.norm(pos, dim=-1) / 0.6) + 2)[..., None] + density = torch.max(density + density_blob, torch.tensor([0.], device=self.device)) weights = ray_samples.get_weights(density) weights_list.append(weights) @@ -208,16 +210,10 @@ class DreamEmbeddingModel(DreamFusionModel): if ray_dims: height = ray_dims[0] width = ray_dims[1] - # print(height, width) latents_input = latents.view(1, height, width, 4).half() - # latents_input = features.view(1, height, width, 4).half() latents_input = latents_input.permute(0, 3, 1, 2) - # latents_input = torch.nn.functional.interpolate(latents_input, size=(latents_input.shape[2] // 8, latents_input.shape[3] // 8), mode='bilinear') - rgb = self.sd.latents_to_img(latents_input) # .permute(0, 2, 3, 1)[0] - # rgb = torch.nn.functional.interpolate( - # rgb, size=(height, width), mode="bilinear" - # ) + rgb = self._sd.latents_to_img(latents_input) # ADD WHITE BG TO RGB white_bg = torch.tensor([1.0, 1.0, 1.0], device=self.device) @@ -302,7 +298,7 @@ class DreamEmbeddingModel(DreamFusionModel): .permute(0, 3, 1, 2) ) - sds_loss = self.sd.sds_loss_latent( + sds_loss = self._sd.sds_loss_latent( text_embedding.to(self.sd_device), latents.to(self.sd_device), guidance_scale=int(self.guidance_scale), @@ -355,16 +351,14 @@ class DreamEmbeddingModel(DreamFusionModel): outputs_lists[output_name].append(output) outputs = {} for output_name, outputs_list in outputs_lists.items(): - if not torch.is_tensor(outputs_list[0]): - # TODO: handle lists of tensors as well - continue if output_name == "rgb": outputs[output_name] = torch.cat(outputs_list).view(image_height * 8, image_width * 8, -1) # type: ignore + elif output_name in ["latents", "feature_only", "background_feature", "background"]: + continue else: outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore # outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore # print(output_name, outputs[output_name].shape) - return outputs def get_image_metrics_and_images( @@ -388,7 +382,7 @@ class DreamEmbeddingModel(DreamFusionModel): latents_input = outputs["latents"].view(1, size, size, 4).half() latents_input = latents_input.permute(0, 3, 1, 2) - rgb = self.sd.latents_to_img(latents_input) + rgb = self._sd.latents_to_img(latents_input) rgb = rgb.permute(0, 2, 3, 1)[0].reshape(512, 512, 3).cpu().to(torch.float32) metrics_dict = {} diff --git a/nerfstudio/models/dreamfusion.py b/nerfstudio/models/dreamfusion.py index 4dd4b6b1f..62c9d9d47 100644 --- a/nerfstudio/models/dreamfusion.py +++ b/nerfstudio/models/dreamfusion.py @@ -66,7 +66,8 @@ class DreamFusionModelConfig(ModelConfig): _target: Type = field(default_factory=lambda: DreamFusionModel) """target class to instantiate""" - prompt: str = "A high-quality photo of a tree frog on a stump" + prompt: str = "A high-quality photo of a realistic pineapple with green leaves" + # prompt: str = "a high-quality photo of a banana" """prompt for stable dreamfusion""" orientation_loss_mult: float = 0.0001 @@ -77,7 +78,7 @@ class DreamFusionModelConfig(ModelConfig): """Randomizes light source per output.""" initialize_density: bool = True """Initialize density in center of scene.""" - taper_range: Tuple[int, int] = (0, 1000) + taper_range: Tuple[int, int] = (0, 500) """Range of step values for the density tapering""" taper_strength: Tuple[float, float] = (1.0, 0.0) """Strength schedule of center density""" @@ -198,14 +199,14 @@ class DreamFusionModel(Model): """Set the fields and modules""" super().populate_modules() - self.sd = StableDiffusion(self.sd_device, version=self.sd_version) + self._sd = StableDiffusion(self.sd_device, version=self.sd_version) self.text_embeddings = PositionalTextEmbeddings( base_prompt=self.cur_prompt, top_prompt=self.cur_prompt + self.top_prompt, side_prompt=self.cur_prompt + self.side_prompt, back_prompt=self.cur_prompt + self.back_prompt, front_prompt=self.cur_prompt + self.front_prompt, - stable_diffusion=self.sd, + stable_diffusion=self._sd, positional_prompting=self.positional_prompting, ) @@ -256,10 +257,12 @@ class DreamFusionModel(Model): self.rgb_loss = MSELoss() # colliders - if self.config.sphere_collider: - self.collider = SphereCollider(torch.Tensor([0, 0, 0]), 1.0) - else: - self.collider = AABBBoxCollider(scene_box=self.scene_box) + # if self.config.sphere_collider: + # self.collider = SphereCollider(torch.Tensor([0, 0, 0]), 1.0) + # # else: + # # self.collider = AABBBoxCollider(scene_box=self.scene_box) + self.collider = AABBBoxCollider(scene_box=self.scene_box) + def get_training_callbacks( self, training_callback_attributes: TrainingCallbackAttributes @@ -353,8 +356,10 @@ class DreamFusionModel(Model): if self.initialize_density: pos = ray_samples.frustums.get_positions() - density_blob = self.density_strength * torch.exp(-torch.norm(pos, dim=-1) / (2 * 0.04))[..., None] - density = density + density_blob + # density_blob = self.density_strength * torch.exp(-torch.norm(pos, dim=-1) / (2 * 0.04))[..., None] + # density = density + density_blob + density_blob = (-0.05 * torch.exp(5 * torch.norm(pos, dim=-1)) + 0.2)[..., None] + density = torch.max(density + density_blob, torch.tensor([0.], device=self.device)) weights = ray_samples.get_weights(density) weights_list.append(weights) @@ -480,7 +485,7 @@ class DreamFusionModel(Model): .permute(0, 3, 1, 2) ) - sds_loss = self.sd.sds_loss( + sds_loss = self._sd.sds_loss( text_embedding.to(self.sd_device), train_output.to(self.sd_device), guidance_scale=int(self.guidance_scale), diff --git a/nerfstudio/models/dreamfusion_ngp.py b/nerfstudio/models/dreamfusion_ngp.py new file mode 100644 index 000000000..3811e8ea0 --- /dev/null +++ b/nerfstudio/models/dreamfusion_ngp.py @@ -0,0 +1,400 @@ +# Copyright 2022 The Nerfstudio Team. 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. + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple, Type + +import nerfacc +import torch +import numpy as np +import torch.nn.functional as F +from nerfacc import ContractionType +from torch.nn import Parameter + +from typing_extensions import Literal +from nerfstudio.models.dreamfusion import DreamFusionModel, DreamFusionModelConfig + +from nerfstudio.cameras.rays import RayBundle +from nerfstudio.engine.callbacks import ( + TrainingCallback, + TrainingCallbackAttributes, + TrainingCallbackLocation, +) + +from nerfstudio.fields.dreamngp_field import DreamNGPField +from nerfstudio.fields.instant_ngp_field import TCNNInstantNGPField +from nerfstudio.field_components.field_heads import FieldHeadNames +from nerfstudio.fields.density_fields import HashMLPDensityField +from nerfstudio.fields.dreamfusion_field import DreamFusionField +from nerfstudio.generative.stable_diffusion import StableDiffusion +from nerfstudio.generative.stable_diffusion_utils import PositionalTextEmbeddings +from nerfstudio.model_components.losses import ( + MSELoss, + distortion_loss, + interlevel_loss, + orientation_loss, + pred_normal_loss, +) +from nerfstudio.model_components.ray_samplers import ( + ProposalNetworkSampler, + UniformSampler, +) +from nerfstudio.model_components.ray_samplers import VolumetricSampler + +from nerfstudio.model_components.renderers import ( + AccumulationRenderer, + DepthRenderer, + NormalsRenderer, + RGBRenderer, +) +from nerfstudio.model_components.scene_colliders import AABBBoxCollider, SphereCollider +from nerfstudio.model_components.shaders import LambertianShader, NormalsShader +from nerfstudio.models.base_model import Model, ModelConfig +from nerfstudio.utils import colormaps, colors, math, misc + + +@dataclass +class DreamfusionNGPModelConfig(DreamFusionModelConfig): + """DreamFusion model config""" + + _target: Type = field(default_factory=lambda: DreamfusionNGPModel) + """target class to instantiate""" + # prompt: str = "A high quality zoomed out photo of a teddy bear" + prompt: str = "A high-quality photo of a pineapple" + """prompt for stable dreamfusion""" + + orientation_loss_mult: float = 0.0001 + """Orientation loss multipier on computed normals.""" + pred_normal_loss_mult: float = 0.001 + """Predicted normal loss multiplier.""" + random_light_source: bool = True + """Randomizes light source per output.""" + initialize_density: bool = True + """Initialize density in center of scene.""" + taper_range: Tuple[int, int] = (0, 1000) + """Range of step values for the density tapering""" + taper_strength: Tuple[float, float] = (1.0, 0.0) + """Strength schedule of center density""" + sphere_collider: bool = True + """Use spherical collider instead of box""" + target_transmittance_start: float = 0.4 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the start of training""" + target_transmittance_end: float = 0.7 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the end of training""" + transmittance_end_schedule: int = 1500 + """number of iterations to reach target_transmittance_end""" + + contraction_type: ContractionType = ContractionType.UN_BOUNDED_SPHERE + """Contraction type used for spatial deformation of the field.""" + + grid_resolution: int = 64 + """Resolution of the grid used for the field.""" + # max_res: int = 2048 + max_res = 256 + """Maximum resolution of the hashmap for the base mlp.""" + log2_hashmap_size: int = 19 + """Size of the hashmap for the base mlp""" + cone_angle: float = 0.0 + """Should be set to 0.0 for blender scenes but 1./256 for real scenes.""" + render_step_size: float = 0.01 + """Minimum step size for rendering.""" + near_plane: float = 0.05 + """How far along ray to start sampling.""" + far_plane: float = 1e3 + """How far along ray to stop sampling.""" + max_num_samples_per_ray: int = 24 + + + start_normals_training: int = 1000 + """Start training normals after this many iterations""" + start_lambertian_training: int = 1000 + """start training with lambertian shading after this many iterations""" + opacity_penalty: bool = False + """enables penalty to encourage sparse weights (penalizing for uniform density along ray)""" + opacity_loss_mult: float = 1 + """scale for opacity penalty""" + + + +class DreamfusionNGPModel(DreamFusionModel): + """DreamEmbeddingModel Model + + Args: + config: DreamFusion configuration to instantiate model + """ + + config: DreamfusionNGPModel + + def __init__( + self, + config: DreamfusionNGPModelConfig, + **kwargs, + ) -> None: + super().__init__(config=config, **kwargs) + + def populate_modules(self): + """Set the fields and modules""" + super().populate_modules() + + # setting up fields + self.field = DreamNGPField( + aabb=self.scene_box.aabb, + contraction_type=self.config.contraction_type, + use_appearance_embedding=False, + num_images=self.num_train_data, + log2_hashmap_size=self.config.log2_hashmap_size, + max_res=self.config.max_res, + ) + self.initialize_density=self.config.initialize_density + self.scene_aabb = Parameter(self.scene_box.aabb.flatten(), requires_grad=False) + + # Occupancy Grid + self.occupancy_grid = nerfacc.OccupancyGrid( + roi_aabb=self.scene_aabb, + resolution=self.config.grid_resolution, + contraction_type=self.config.contraction_type, + ) + + # samplers + self.sampler = VolumetricSampler( + scene_aabb=self.scene_box.aabb, + occupancy_grid=self.occupancy_grid, + density_fn=self.field.density_fn, + ) + + # renderers + self.renderer_rgb = RGBRenderer(background_color=colors.WHITE) + self.renderer_accumulation = AccumulationRenderer() + self.renderer_depth = DepthRenderer(method="expected") + self.renderer_normals = NormalsRenderer() + + # shaders + self.shader_lambertian = LambertianShader() + self.shader_normals = NormalsShader() + + # losses + self.rgb_loss = MSELoss() + + # colliders + # if self.config.sphere_collider: + # self.collider = SphereCollider(torch.Tensor([0, 0, 0]), 1.0) + # # else: + # # self.collider = AABBBoxCollider(scene_box=self.scene_box) + self.collider = AABBBoxCollider(scene_box=self.scene_box) + + def get_training_callbacks( + self, training_callback_attributes: TrainingCallbackAttributes + ) -> List[TrainingCallback]: + def update_occupancy_grid(step: int): + # TODO: needs to get access to the sampler, on how the step size is determinated at each x. See + # https://github.com/KAIR-BAIR/nerfacc/blob/127223b11401125a9fce5ce269bb0546ee4de6e8/examples/train_ngp_nerf.py#L190-L213 + self.occupancy_grid.every_n_step( + step=step, + occ_eval_fn=lambda x: self.field.get_opacity(x, self.config.render_step_size), + ) + + def start_training_normals( + self, training_callback_attributes: TrainingCallbackAttributes, step: int # pylint: disable=unused-argument + ): + self.train_normals = True + + def taper_density( + self, training_callback_attributes: TrainingCallbackAttributes, step: int # pylint: disable=unused-argument + ): + self.density_strength = np.interp(step, self.config.taper_range, self.config.taper_strength) + + return [ + TrainingCallback( + where_to_run=[TrainingCallbackLocation.BEFORE_TRAIN_ITERATION], + update_every_num_iters=1, + func=update_occupancy_grid, + ), + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + iters=(self.config.start_normals_training,), + func=start_training_normals, + args=[self, training_callback_attributes], + ), + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + func=taper_density, + update_every_num_iters=1, + args=[self, training_callback_attributes], + ), + ] + + def get_param_groups(self) -> Dict[str, List[Parameter]]: + param_groups = {} + param_groups["fields"] = list(self.field.parameters()) + return param_groups + + + def get_outputs(self, ray_bundle: RayBundle): + num_rays = len(ray_bundle) + + with torch.no_grad(): + ray_samples, ray_indices = self.sampler( + ray_bundle=ray_bundle, + near_plane=self.config.near_plane, + far_plane=self.config.far_plane, + render_step_size=self.config.render_step_size, + cone_angle=self.config.cone_angle, + ) + # field_outputs = self.field(ray_samples, compute_normals=True) + field_outputs = self.field(ray_samples, compute_normals=False) + + density = field_outputs[FieldHeadNames.DENSITY] + + if self.initialize_density: + pos = ray_samples.frustums.get_positions() + density_blob = (-0.05 * torch.exp(5 * torch.norm(pos, dim=-1)) + 0.5)[..., None] + density = torch.max(density + density_blob, torch.tensor([0.], device=self.device)) + + packed_info = nerfacc.pack_info(ray_indices, num_rays) + weights = nerfacc.render_weight_from_density( + packed_info=packed_info, + sigmas=density, + t_starts=ray_samples.frustums.starts, + t_ends=ray_samples.frustums.ends, + ) + + rgb = self.renderer_rgb( + rgb=field_outputs[FieldHeadNames.RGB], + weights=weights, + ray_indices=ray_indices, + num_rays=num_rays, + ) + + background_rgb = self.field.get_background_rgb(ray_bundle) + + depth = self.renderer_depth( + weights=weights, ray_samples=ray_samples, ray_indices=ray_indices, num_rays=num_rays + ) + accumulation = self.renderer_accumulation(weights=weights, ray_indices=ray_indices, num_rays=num_rays) + alive_ray_mask = accumulation.squeeze(-1) > 0 + + accum_mask = torch.clamp((torch.nan_to_num(accumulation, nan=0.0)), min=0.0, max=1.0) + accum_mask_inv = 1.0 - accum_mask + + background = accum_mask_inv * background_rgb + + outputs = { + "rgb_only": rgb, + "background_rgb": background_rgb, + "background": background, + "accumulation": accum_mask, + "depth": depth, + "rgb": accum_mask * rgb + background + } + + normals = self.renderer_normals(normals=field_outputs[FieldHeadNames.NORMALS], weights=weights) + outputs["normals"] = self.shader_normals(normals, weights=accum_mask) + + # lambertian shading + if self.config.random_light_source: # and self.training: + light_d = ray_bundle.origins[0] + torch.randn(3, dtype=torch.float).to(normals) + else: + light_d = ray_bundle.origins[0] + light_d = math.safe_normalize(light_d) + + if (self.train_shaded and np.random.random_sample() > 0.75) or not self.training: + shading_weight = 0.9 + else: + shading_weight = 0.0 + + shaded, shaded_albedo = self.shader_lambertian( + rgb=rgb, normals=normals, light_direction=light_d, shading_weight=shading_weight, detach_normals=False + ) + + outputs["shaded"] = accum_mask * shaded + + if shading_weight > 0: + samp = np.random.random_sample() + if samp > 0.5 and not self.training: + outputs["train_output"] = outputs["shaded"] + elif samp < 0.2 and self.random_background: + rand_bg = torch.ones_like(background) * torch.rand(3, device=self.device) + outputs["train_output"] = accum_mask * shaded_albedo + rand_bg * accum_mask_inv + else: + outputs["train_output"] = accum_mask * shaded_albedo + background + else: + outputs["train_output"] = outputs["rgb"] + + # print(outputs["rgb"].shape) + # outputs["train_output"] = outputs["rgb"] + + + outputs["rendered_orientation_loss"] = orientation_loss( + weights.detach(), + field_outputs[FieldHeadNames.NORMALS], + ray_bundle.directions, + ) + + assert weights.shape[-1] == 1 + if self.config.opacity_penalty: + outputs["opacity_loss"] = torch.sqrt(torch.sum(weights, dim=-2) ** 2 + 0.01) * self.config.opacity_loss_mult + + return outputs + + def get_loss_dict(self, outputs, batch, metrics_dict=None) -> Dict[str, torch.Tensor]: + # Scaling metrics by coefficients to create the losses. + + loss_dict = {} + loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients) + if self.train_normals: + # orientation loss for computed normals + loss_dict["orientation_loss"] = self.config.orientation_loss_mult * torch.mean( + outputs["rendered_orientation_loss"] + ) + else: + loss_dict["orientation_loss"] = 0 + + if self.config.opacity_penalty: + loss_dict["opacity_loss"] = self.config.opacity_loss_mult * outputs["opacity_loss"].mean() + + if self.prompt != self.cur_prompt: + self.cur_prompt = self.prompt + self.text_embeddings.update_prompt( + base_prompt=self.cur_prompt, + top_prompt=self.cur_prompt + self.top_prompt, + side_prompt=self.cur_prompt + self.side_prompt, + back_prompt=self.cur_prompt + self.back_prompt, + front_prompt=self.cur_prompt + self.front_prompt, + ) + + text_embedding = self.text_embeddings.get_text_embedding( + vertical_angle=batch["vertical"], horizontal_angle=batch["central"] + ) + + train_output = ( + outputs["train_output"] + .view(1, int(outputs["train_output"].shape[0] ** 0.5), int(outputs["train_output"].shape[0] ** 0.5), 3) + .permute(0, 3, 1, 2) + ) + + sds_loss = self._sd.sds_loss( + text_embedding.to(self.sd_device), + train_output.to(self.sd_device), + guidance_scale=int(self.guidance_scale), + grad_scaler=self.grad_scaler, + ) + + loss_dict["sds_loss"] = sds_loss.to(self.device) + return loss_dict + \ No newline at end of file diff --git a/nerfstudio/models/dreamfusion_rgb.py b/nerfstudio/models/dreamfusion_rgb.py new file mode 100644 index 000000000..2d7ef02ce --- /dev/null +++ b/nerfstudio/models/dreamfusion_rgb.py @@ -0,0 +1,208 @@ +# Copyright 2022 The Nerfstudio Team. 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. + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple, Type + +import imageio +import torch +import torch.nn.functional as F +from typing_extensions import Literal + +from nerfstudio.cameras.rays import RayBundle +from nerfstudio.engine.callbacks import ( + TrainingCallback, + TrainingCallbackAttributes, + TrainingCallbackLocation, +) +from nerfstudio.field_components.field_heads import FieldHeadNames +from nerfstudio.fields.density_fields import HashMLPDensityField +from nerfstudio.fields.dreamembedding_field import DreamEmbeddingField +from nerfstudio.generative.stable_diffusion import StableDiffusion +from nerfstudio.generative.stable_diffusion_utils import PositionalTextEmbeddings +from nerfstudio.model_components.losses import ( + MSELoss, + distortion_loss, + interlevel_loss, + orientation_loss, +) +from nerfstudio.model_components.renderers import FeatureRenderer +from nerfstudio.models.dreamfusion import DreamFusionModel, DreamFusionModelConfig +from nerfstudio.utils import colormaps, colors, math, misc + + +@dataclass +class DreamfusionRGBModelConfig(DreamFusionModelConfig): + """DreamFusionRGB model config""" + + _target: Type = field(default_factory=lambda: DreamfusionRGBModel) + """target class to instantiate""" + prompt: str = "A high quality zoomed out photo of a teddy bear" + """prompt for stable dreamfusion""" + + orientation_loss_mult: float = 0.0001 + """Orientation loss multipier on computed normals.""" + pred_normal_loss_mult: float = 0.001 + """Predicted normal loss multiplier.""" + random_light_source: bool = True + """Randomizes light source per output.""" + initialize_density: bool = True + """Initialize density in center of scene.""" + taper_range: Tuple[int, int] = (0, 1000) + """Range of step values for the density tapering""" + taper_strength: Tuple[float, float] = (1.0, 0.0) + """Strength schedule of center density""" + sphere_collider: bool = True + """Use spherical collider instead of box""" + target_transmittance_start: float = 0.4 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the start of training""" + target_transmittance_end: float = 0.7 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the end of training""" + transmittance_end_schedule: int = 1500 + """number of iterations to reach target_transmittance_end""" + num_proposal_samples_per_ray: Tuple[int, ...] = (96, 48) + """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": 64, + }, + { + "hidden_dim": 16, + "log2_hashmap_size": 17, + "num_levels": 5, + "max_res": 128, + }, + ] + ) + """Arguments for the proposal density fields.""" + proposal_weights_anneal_slope: float = 10.0 + """Slope of the annealing function for the proposal weights.""" + proposal_weights_anneal_max_num_iters: int = 500 + """Max num iterations for the annealing function.""" + use_single_jitter: bool = True + """Whether use single jitter or not for the proposal networks.""" + interlevel_loss_mult: float = 1.0 + """Proposal loss multiplier.""" + distortion_loss_mult: float = 1.0 + """Distortion loss multiplier.""" + start_lambertian_training: int = 1000 + """start training with lambertian shading after this many iterations""" + opacity_penalty: bool = True + """enables penalty to encourage sparse weights (penalizing for uniform density along ray)""" + opacity_loss_mult: float = 1 + """scale for opacity penalty""" + max_res: int = 256 + """Maximum resolution of the density field.""" + + +class DreamfusionRGBModel(DreamFusionModel): + """DreamEmbeddingModel Model + + Args: + config: DreamFusion configuration to instantiate model + """ + + config: DreamfusionRGBModelConfig + + def __init__( + self, + config: DreamfusionRGBModelConfig, + **kwargs, + ) -> None: + super().__init__(config=config, **kwargs) + self.rgb_loss = MSELoss() + + + def get_loss_dict(self, outputs, batch, metrics_dict=None) -> Dict[str, torch.Tensor]: + # Scaling metrics by coefficients to create the losses. + + loss_dict = {} + loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients) + if self.train_normals: + # orientation loss for computed normals + loss_dict["orientation_loss"] = self.config.orientation_loss_mult * torch.mean( + outputs["rendered_orientation_loss"] + ) + else: + loss_dict["orientation_loss"] = 0 + + if self.config.opacity_penalty: + loss_dict["opacity_loss"] = self.config.opacity_loss_mult * outputs["opacity_loss"].mean() + + if self.prompt != self.cur_prompt: + self.cur_prompt = self.prompt + self.text_embeddings.update_prompt( + base_prompt=self.cur_prompt, + top_prompt=self.cur_prompt + self.top_prompt, + side_prompt=self.cur_prompt + self.side_prompt, + back_prompt=self.cur_prompt + self.back_prompt, + front_prompt=self.cur_prompt + self.front_prompt, + ) + + text_embedding = self.text_embeddings.get_text_embedding( + vertical_angle=batch["vertical"], horizontal_angle=batch["central"] + ) + + train_output = ( + outputs["train_output"] + .view(1, int(outputs["train_output"].shape[0] ** 0.5), int(outputs["train_output"].shape[0] ** 0.5), 3) + .permute(0, 3, 1, 2) + ) + + sds_loss = self._sd.sds_loss( + text_embedding.to(self.sd_device), + train_output.to(self.sd_device), + guidance_scale=int(self.guidance_scale), + grad_scaler=self.grad_scaler, + ) + + sds_output = self._sd.sds_rgb( + text_embedding.to(self.sd_device), + train_output.to(self.sd_device), + guidance_scale=int(self.guidance_scale), + grad_scaler=self.grad_scaler, + ) + + # import pdb + # pdb.set_trace() + loss_dict["sds_rgb_loss"] = self.rgb_loss(sds_output, train_output) + + if self.training: + loss_dict["distortion_loss"] = self.config.distortion_loss_mult * distortion_loss( + outputs["weights_list"], outputs["ray_samples_list"] + ) + loss_dict["interlevel_loss"] = self.config.interlevel_loss_mult * interlevel_loss( + outputs["weights_list"], outputs["ray_samples_list"] + ) + + return loss_dict \ No newline at end of file diff --git a/nerfstudio/models/dreamfusion_tensor.py b/nerfstudio/models/dreamfusion_tensor.py new file mode 100644 index 000000000..e8b41599d --- /dev/null +++ b/nerfstudio/models/dreamfusion_tensor.py @@ -0,0 +1,397 @@ +# Copyright 2022 The Nerfstudio Team. 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. + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple, Type + +import imageio +import torch +import torch.nn.functional as F +from typing_extensions import Literal + +from nerfstudio.cameras.rays import RayBundle +from nerfstudio.engine.callbacks import ( + TrainingCallback, + TrainingCallbackAttributes, + TrainingCallbackLocation, +) +from nerfstudio.field_components.field_heads import FieldHeadNames +from nerfstudio.fields.density_fields import HashMLPDensityField +from nerfstudio.fields.dreamembedding_field import DreamEmbeddingField +from nerfstudio.generative.stable_diffusion import StableDiffusion +from nerfstudio.generative.stable_diffusion_utils import PositionalTextEmbeddings +from nerfstudio.model_components.losses import ( + MSELoss, + distortion_loss, + interlevel_loss, + orientation_loss, +) +from nerfstudio.model_components.renderers import FeatureRenderer +from nerfstudio.models.dreamfusion import DreamFusionModel, DreamFusionModelConfig +from nerfstudio.utils import colormaps, colors, math, misc + + +@dataclass +class DreamEmbeddingModelConfig(DreamFusionModelConfig): + """DreamFusion model config""" + + _target: Type = field(default_factory=lambda: DreamEmbeddingModel) + """target class to instantiate""" + prompt: str = "A high quality zoomed out photo of a teddy bear" + """prompt for stable dreamfusion""" + + orientation_loss_mult: float = 0.0001 + """Orientation loss multipier on computed normals.""" + pred_normal_loss_mult: float = 0.001 + """Predicted normal loss multiplier.""" + random_light_source: bool = True + """Randomizes light source per output.""" + initialize_density: bool = True + """Initialize density in center of scene.""" + taper_range: Tuple[int, int] = (0, 1000) + """Range of step values for the density tapering""" + taper_strength: Tuple[float, float] = (1.0, 0.0) + """Strength schedule of center density""" + sphere_collider: bool = True + """Use spherical collider instead of box""" + target_transmittance_start: float = 0.4 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the start of training""" + target_transmittance_end: float = 0.7 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the end of training""" + transmittance_end_schedule: int = 1500 + """number of iterations to reach target_transmittance_end""" + num_proposal_samples_per_ray: Tuple[int, ...] = (96, 48) + """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": 64, + }, + { + "hidden_dim": 16, + "log2_hashmap_size": 17, + "num_levels": 5, + "max_res": 128, + }, + ] + ) + """Arguments for the proposal density fields.""" + proposal_weights_anneal_slope: float = 10.0 + """Slope of the annealing function for the proposal weights.""" + proposal_weights_anneal_max_num_iters: int = 500 + """Max num iterations for the annealing function.""" + use_single_jitter: bool = True + """Whether use single jitter or not for the proposal networks.""" + interlevel_loss_mult: float = 1.0 + """Proposal loss multiplier.""" + distortion_loss_mult: float = 1.0 + """Distortion loss multiplier.""" + start_lambertian_training: int = 1000 + """start training with lambertian shading after this many iterations""" + opacity_penalty: bool = True + """enables penalty to encourage sparse weights (penalizing for uniform density along ray)""" + opacity_loss_mult: float = 1 + """scale for opacity penalty""" + max_res: int = 256 + """Maximum resolution of the density field.""" + + location_based_prompting: bool = True + """enables location based prompting""" + interpolated_prompting: bool = False + """enables interpolated location prompting""" + positional_prompting: Literal["discrete", "interpolated", "off"] = "discrete" + """ how to incorporate position into prompt""" + top_prompt: str = ", overhead view" + """appended to prompt for overhead view""" + side_prompt: str = ", side view" + """appended to prompt for side view""" + front_prompt: str = ", front view" + """appended to prompt for front view""" + back_prompt: str = ", back view" + """appended to prompt for back view""" + guidance_scale: float = 100 + """guidance scale for sds loss""" + stablediffusion_device: Optional[str] = None + """device for stable diffusion""" + sd_version: str = "1-5" + + +class DreamEmbeddingModel(DreamFusionModel): + """DreamEmbeddingModel Model + + Args: + config: DreamFusion configuration to instantiate model + """ + + config: DreamEmbeddingModelConfig + + def __init__( + self, + config: DreamEmbeddingModelConfig, + **kwargs, + ) -> None: + super().__init__(config=config, **kwargs) + + def populate_modules(self): + """Set the fields and modules""" + super().populate_modules() + + # setting up fields + self.field = DreamEmbeddingField(self.scene_box.aabb, max_res=self.config.max_res) + self.renderer_feature = FeatureRenderer() + + def get_outputs(self, ray_bundle: RayBundle, ray_dims: Tuple): + # uniform sampling + background_feature = self.field.get_background_feature(ray_bundle) + ray_samples, weights_list, ray_samples_list = self.proposal_sampler(ray_bundle, density_fns=self.density_fns) + field_outputs = self.field(ray_samples, compute_normals=True) + density = field_outputs[FieldHeadNames.DENSITY] + + if self.initialize_density: + pos = ray_samples.frustums.get_positions() + # density_blob = self.density_strength * torch.exp(-torch.norm(pos, dim=-1) / (2 * 0.04))[..., None] + # density = density + density_blob + density_blob = (-torch.exp(torch.norm(pos, dim=-1) / 0.6) + 2)[..., None] + density = torch.max(density + density_blob, torch.tensor([0.], device=self.device)) + + weights = ray_samples.get_weights(density) + weights_list.append(weights) + ray_samples_list.append(ray_samples) + + accumulation = self.renderer_accumulation(weights) + depth = self.renderer_depth(weights, ray_samples) + features = self.renderer_feature(features=field_outputs[FieldHeadNames.FEATURE], weights=weights) + + accum_mask = torch.clamp((torch.nan_to_num(accumulation, nan=0.0)), min=0.0, max=1.0) + accum_mask_inv = 1.0 - accum_mask + + background = accum_mask_inv * background_feature + + outputs = { + "feature_only": features, + "background_feature": background_feature, + "background": background, + "accumulation": accum_mask, + "depth": depth, + } + + latents = accum_mask * features + background + outputs["latents"] = latents + + if ray_dims: + height = ray_dims[0] + width = ray_dims[1] + + latents_input = latents.view(1, height, width, 4).half() + latents_input = latents_input.permute(0, 3, 1, 2) + rgb = self._sd.latents_to_img(latents_input) + + # ADD WHITE BG TO RGB + white_bg = torch.tensor([1.0, 1.0, 1.0], device=self.device) + + a_mask = accum_mask.reshape(1, 1, height, width) + + a_mask = torch.nn.functional.interpolate(a_mask, size=(height * 8, width * 8), mode="bilinear") + + a_mask = torch.flatten(a_mask.permute(0, 2, 3, 1), end_dim=-2) + a_mask_inv = 1 - a_mask + + rgb = rgb.permute(0, 2, 3, 1)[0] + rgb = torch.flatten(rgb, end_dim=-2) + rgb = a_mask * rgb + (a_mask_inv * white_bg) + rgb = rgb.to(torch.float32) + # print("rgb", rgb) + # print(rgb.shape) + + outputs["rgb"] = rgb + + # 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 + + 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]) + + normals = self.renderer_normals(normals=field_outputs[FieldHeadNames.NORMALS], weights=weights) + outputs["normals"] = self.shader_normals(normals, weights=accum_mask) + + outputs["rendered_orientation_loss"] = orientation_loss( + weights.detach(), + field_outputs[FieldHeadNames.NORMALS], + ray_bundle.directions, + ) + + assert weights.shape[-1] == 1 + if self.config.opacity_penalty: + outputs["opacity_loss"] = torch.sqrt(torch.sum(weights, dim=-2) ** 2 + 0.01) * self.config.opacity_loss_mult + + return outputs + + def get_loss_dict(self, outputs, batch, metrics_dict=None) -> Dict[str, torch.Tensor]: + # Scaling metrics by coefficients to create the losses. + + loss_dict = {} + loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients) + if self.train_normals: + # orientation loss for computed normals + loss_dict["orientation_loss"] = self.config.orientation_loss_mult * torch.mean( + outputs["rendered_orientation_loss"] + ) + else: + loss_dict["orientation_loss"] = 0 + + if self.config.opacity_penalty: + loss_dict["opacity_loss"] = self.config.opacity_loss_mult * outputs["opacity_loss"].mean() + + if self.prompt != self.cur_prompt: + self.cur_prompt = self.prompt + self.text_embeddings.update_prompt( + base_prompt=self.cur_prompt, + top_prompt=self.cur_prompt + self.top_prompt, + side_prompt=self.cur_prompt + self.side_prompt, + back_prompt=self.cur_prompt + self.back_prompt, + front_prompt=self.cur_prompt + self.front_prompt, + ) + + text_embedding = self.text_embeddings.get_text_embedding( + vertical_angle=batch["vertical"], horizontal_angle=batch["central"] + ) + + latents = ( + outputs["latents"] + .view( + 1, + int(outputs["latents"].shape[0] ** 0.5), + int(outputs["latents"].shape[0] ** 0.5), + 4, + ) + .permute(0, 3, 1, 2) + ) + + sds_loss = self._sd.sds_loss_latent( + text_embedding.to(self.sd_device), + latents.to(self.sd_device), + guidance_scale=int(self.guidance_scale), + grad_scaler=self.grad_scaler, + ) + + loss_dict["sds_loss"] = sds_loss.to(self.device) + + if self.training: + loss_dict["distortion_loss"] = self.config.distortion_loss_mult * distortion_loss( + outputs["weights_list"], outputs["ray_samples_list"] + ) + loss_dict["interlevel_loss"] = self.config.interlevel_loss_mult * interlevel_loss( + outputs["weights_list"], outputs["ray_samples_list"] + ) + # if 45 < batch["central"] <= 135: + # loss_dict["input_latent_loss"] = self.l2_loss(self.input_latent.detach(), outputs["latents"]) + return loss_dict + + def forward(self, ray_bundle: RayBundle, ray_dims: Tuple = ()) -> Dict[str, torch.Tensor]: + """Run forward starting with a ray bundle. This outputs different things depending on the configuration + of the model and whether or not the batch is provided (whether or not we are training basically) + + Args: + ray_bundle: containing all the information needed to render that ray latents included + """ + + if self.collider is not None: + ray_bundle = self.collider(ray_bundle) + + return self.get_outputs(ray_bundle, ray_dims) + + @torch.no_grad() + def get_outputs_for_camera_ray_bundle(self, camera_ray_bundle: RayBundle) -> Dict[str, torch.Tensor]: + """Takes in camera parameters and computes the output of the model. + + Args: + camera_ray_bundle: ray bundle to calculate outputs over + """ + num_rays_per_chunk = self.config.eval_num_rays_per_chunk + image_height, image_width = camera_ray_bundle.origins.shape[:2] + num_rays = len(camera_ray_bundle) + outputs_lists = defaultdict(list) + for i in range(0, num_rays, num_rays_per_chunk): + start_idx = i + end_idx = i + num_rays_per_chunk + ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx) + outputs = self.forward(ray_bundle=ray_bundle, ray_dims=(image_height, image_width)) + for output_name, output in outputs.items(): # type: ignore + outputs_lists[output_name].append(output) + outputs = {} + for output_name, outputs_list in outputs_lists.items(): + if output_name == "rgb": + outputs[output_name] = torch.cat(outputs_list).view(image_height * 8, image_width * 8, -1) # type: ignore + elif output_name in ["latents", "feature_only", "background_feature", "background"]: + continue + else: + outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore + # outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore + # print(output_name, outputs[output_name].shape) + return outputs + + 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]]: + acc = colormaps.apply_colormap(outputs["accumulation"]) + depth = colormaps.apply_depth_colormap( + outputs["depth"], + accumulation=outputs["accumulation"], + ) + prop_depth_0 = colormaps.apply_depth_colormap( + outputs["prop_depth_0"], + accumulation=outputs["accumulation"], + ) + prop_depth_1 = colormaps.apply_depth_colormap( + outputs["prop_depth_1"], + accumulation=outputs["accumulation"], + ) + + size = outputs["latents"].shape[0] + + latents_input = outputs["latents"].view(1, size, size, 4).half() + latents_input = latents_input.permute(0, 3, 1, 2) + rgb = self._sd.latents_to_img(latents_input) + rgb = rgb.permute(0, 2, 3, 1)[0].reshape(512, 512, 3).cpu().to(torch.float32) + + metrics_dict = {} + images_dict = { + "img": rgb, + "accumulation": acc, + "depth": depth, + "prop_depth_0": prop_depth_0, + "prop_depth_1": prop_depth_1, + "normals": outputs["normals"], + } + return metrics_dict, images_dict diff --git a/nerfstudio/pipelines/base_pipeline.py b/nerfstudio/pipelines/base_pipeline.py index 9c97a88ce..1f8a9e5b5 100644 --- a/nerfstudio/pipelines/base_pipeline.py +++ b/nerfstudio/pipelines/base_pipeline.py @@ -23,6 +23,7 @@ from dataclasses import dataclass, field from time import time from typing import Any, Dict, List, Mapping, Optional, Type, Union, cast +import mediapy import torch import torch.distributed as dist from rich.progress import ( @@ -284,6 +285,16 @@ class VanillaPipeline(Pipeline): """ ray_bundle, batch = self.datamanager.next_train(step) model_outputs = self.model(ray_bundle) + + if step % 100 == 0: + image = model_outputs["rgb"] + image = image.view(int(image.shape[0] ** 0.5), int(image.shape[0] ** 0.5), 3) + image = image.detach().cpu().numpy() + image = (image * 255).round().astype("uint8") + mediapy.write_image(str('dreamngp.png'), image) + # mediapy.write_image(str('dreamfusion.png'), image) + + metrics_dict = self.model.get_metrics_dict(model_outputs, batch) if self.config.datamanager.camera_optimizer is not None: diff --git a/nerfstudio/pipelines/iterative_pipeline.py b/nerfstudio/pipelines/iterative_pipeline.py index f2afe4799..440693cb6 100644 --- a/nerfstudio/pipelines/iterative_pipeline.py +++ b/nerfstudio/pipelines/iterative_pipeline.py @@ -16,52 +16,55 @@ A pipeline that saves outputs from the nerf to iteratively apply SD on . """ -from dataclasses import dataclass, field -from typing import Any, Dict, List, Mapping, Optional, Type, cast -from pathlib import Path, PurePath - import os +import tracemalloc +from dataclasses import dataclass, field +from pathlib import Path, PurePath +from typing import Any, Dict, List, Mapping, Optional, Type, cast + +import mediapy import torch +import torch.distributed as dist from torch.cuda.amp.grad_scaler import GradScaler from typing_extensions import Literal -import torch.distributed as dist -import mediapy -from nerfstudio.generative.stable_diffusion_utils import PositionalTextEmbeddings - -from nerfstudio.data.datamanagers.base_datamanager import ( - DataManager, - DataManagerConfig, +from nerfstudio.data.datamanagers.base_datamanager import DataManager, DataManagerConfig +from nerfstudio.data.datamanagers.iterative_datamanager import ( + IterativeDataManager, + IterativeDataManagerConfig, +) +from nerfstudio.data.datamanagers.dreamfusion_datamanager import ( + DreamFusionDataManagerConfig, ) from nerfstudio.generative.stable_diffusion_img2img import StableDiffusionImg2Img - -from nerfstudio.data.datamanagers.iterative_datamanager import IterativeDataManager, IterativeDataManagerConfig +from nerfstudio.generative.stable_diffusion_utils import PositionalTextEmbeddings from nerfstudio.models.base_model import Model, ModelConfig - from nerfstudio.pipelines.base_pipeline import VanillaPipeline, VanillaPipelineConfig from nerfstudio.utils import profiler -import tracemalloc tracemalloc.start() + @dataclass class IterativePipelineConfig(VanillaPipelineConfig): """Iterative Pipeline Config""" _target: Type = field(default_factory=lambda: IterativePipeline) """target class to instantiate""" - datamanager: DataManagerConfig = IterativeDataManagerConfig() + datamanager2: DataManagerConfig = DreamFusionDataManagerConfig() """specifies the datamanager config""" + datamanager: DataManagerConfig = IterativeDataManagerConfig() model: ModelConfig = ModelConfig() """specifies the model config""" + model2: ModelConfig=ModelConfig() generative: bool = True """specifies whether the pipeline is for generative models""" temp_save_path: str = "iterative_assets" """save path for generated dataset""" - prompt: str="a photo of a pineapple" + prompt: str = "a photo of a pineapple" class IterativePipeline(VanillaPipeline): - """Pipeline with logic for saving outputs from nerf for use as training images.""" + """Pipeline with logic for saving outputs from nerf for use as training images.""" def __init__( self, @@ -77,14 +80,14 @@ class IterativePipeline(VanillaPipeline): self.datamanager.temp_save_path = self.temp_save_path sd_version = "1-5" - self.sd = StableDiffusionImg2Img(self.device, version=sd_version) + self._sd = StableDiffusionImg2Img(self.device, version=sd_version) self.text_embeddings = PositionalTextEmbeddings( base_prompt=config.prompt, top_prompt=config.prompt + ", overhead view", side_prompt=config.prompt + ", side view", back_prompt=config.prompt + ", back view", front_prompt=config.prompt + ", front view", - stable_diffusion=self.sd, + stable_diffusion=self._sd, positional_prompting="discrete", ) @@ -93,32 +96,68 @@ class IterativePipeline(VanillaPipeline): Path.mkdir(Path(self.temp_save_path) / "rendered_images") Path.mkdir(Path(self.temp_save_path) / "generated_images") + def init_first_model(): + return + def init_second_model(): + return + def forward(self): """Blank forward method This is an nn.Module, and so requires a forward() method normally, although in our case we do not need a forward() method""" raise NotImplementedError + + @torch.no_grad() + def save_images_and_cameras(self, step: int): + num_images = 3 + resolution = 64 + + ray_bundles, cameras_small, vertical_rotation, central_rotation = self.datamanager.random_train_views(step, resolution=resolution, num_views=num_images) + + train_img_paths = [] + temp_path = "/home/terrance/nerfactory/iterative_assets/latent_nerf_images" + self.model.eval() + + for i in range(num_images): + cur_bundle = ray_bundles[:, :, i] + rgb = self.model.get_outputs_for_camera_ray_bundle(cur_bundle)["rgb"] + + img = rgb.detach().cpu().numpy() # something + save_path = PurePath(temp_path, f"img_{i}.png") + train_img_paths.append(str(save_path)) + mediapy.write_image(str(save_path), img) + + torch.save(train_img_paths, str(PurePath(temp_path, 'img_paths.pt'))) + torch.save(cameras_small, str(PurePath(temp_path, 'cameras_small.pt'))) + camera_angles = list(zip(vertical_rotation, central_rotation)) + torch.save(camera_angles, str(PurePath(temp_path, 'camera_angles.pt'))) + + del ray_bundles + cameras = self.datamanager.random_train_views(step, resolution * 8, num_images, + vertical_rotation, central_rotation, cameras_only=True) + torch.save(cameras, str(PurePath(temp_path, 'cameras.pt'))) + + @torch.no_grad() def save_new_train_images(self, step: int): print("saving training images") - num_images_per_train = 5 + num_images_per_train = 25 resolution = 512 - ray_bundles, cameras, camera_angles = self.datamanager.random_train_views(step, resolution=resolution, num_views=num_images_per_train) + ray_bundles, cameras, camera_angles = self.datamanager.random_train_views( + step, resolution=resolution, num_views=num_images_per_train + ) train_img_paths = [] - # no grad - for i in range(num_images_per_train): cur_bundle = ray_bundles[:, :, i] - rgb = self.model.get_outputs_for_camera_ray_bundle(cur_bundle)['rgb'] - - img = rgb.detach().cpu().numpy() # something + rgb = self.model.get_outputs_for_camera_ray_bundle(cur_bundle)["rgb"] + + img = rgb.detach().cpu().numpy() # something save_path = PurePath(self.temp_save_path, "rendered_images", f"img_{i}.png") train_img_paths.append(str(save_path)) mediapy.write_image(str(save_path), img) - self.datamanager.create_train_dataset(train_img_paths, cameras, camera_angles) @@ -131,8 +170,8 @@ class IterativePipeline(VanillaPipeline): camera_angles = self.datamanager.camera_angles[i] text_embedding = self.text_embeddings.get_text_embedding(camera_angles[0], camera_angles[1]) - image = self.datamanager.train_dataset.get_image(i)[None, :, :, :].permute(0, 3, 1, 2).to(self.sd.device) - image = self.sd.update_img(text_embedding, image, step) + image = self.datamanager.train_dataset.get_image(i)[None, :, :, :].permute(0, 3, 1, 2).to(self._sd.device) + image = self._sd.update_img(text_embedding, image, step) save_path = PurePath(self.temp_save_path, "generated_images", f"img_{i}.png") generated_img_paths.append(str(save_path)) mediapy.write_image(str(save_path), image) @@ -140,20 +179,70 @@ class IterativePipeline(VanillaPipeline): cameras = self.datamanager.train_dataset.cameras self.datamanager.create_train_dataset(generated_img_paths, cameras, self.datamanager.camera_angles) - + + def update_single_image(self, step: int): + + to_update_idx = torch.rand(1) * len(self.datamanager.train_dataset) + to_update_idx = int(torch.floor(to_update_idx)) + print(to_update_idx) + + # re render image + cur_cam = self.datamanager.train_dataset.cameras[to_update_idx] + ray_bundle = cur_cam.generate_rays(0)[:, :, None] + + # replace image with new image + cur_bundle = ray_bundle[:, :, 0] + rgb = self.model.get_outputs_for_camera_ray_bundle(cur_bundle)["rgb"] + + rendered = rgb.detach().cpu().numpy() # something + save_path = PurePath(self.temp_save_path, "rendered_images", f"img_{to_update_idx}.png") + mediapy.write_image(str(save_path), rendered) + + # run sd on image + camera_angles = self.datamanager.camera_angles[to_update_idx] + text_embedding = self.text_embeddings.get_text_embedding(camera_angles[0], camera_angles[1]) + img = rgb[None, :, :, :].permute(0, 3, 1, 2).to(self._sd.device) + img = self._sd.update_img(text_embedding, img, step) + + # recreate dataset + save_path = PurePath(self.temp_save_path, "generated_images", f"img_{to_update_idx}.png") + mediapy.write_image(str(save_path), img) + + img_paths = self.datamanager.train_dataset.image_filenames + self.datamanager.create_train_dataset( + img_paths, self.datamanager.train_dataset.cameras, self.datamanager.camera_angles + ) + + def load_images(self): + temp_path = "/home/terrance/nerfactory/iterative_assets/latent_nerf_images" + + train_img_paths = torch.load(str(PurePath(temp_path, 'img_paths.pt'))) + cameras = torch.load(str(PurePath(temp_path, 'cameras.pt'))) + camera_angles = torch.load(str(PurePath(temp_path, 'camera_angles.pt'))) + + self.datamanager.create_train_dataset(train_img_paths, cameras, camera_angles) + @profiler.time_function def get_train_loss_dict(self, step: int): - # create train dataset - # for every X iterations, apply SD to all train images - # use a data loader that allows for multiview supervision each train step - # rerender train dataset every Y iterations + # new plan + # start with sds loss / dreamfusion + # at 6k iters? switch to this iterative process with small updates - update_steps = [0, 2000, 4000, 6000, 10000, 15000] + # print('saving images') + # self.save_images_and_cameras(step) + # raise Exception - if step in update_steps: - self.save_new_train_images(step) - self.update_train_images(step) + # update_steps = [0, 2000, 4000, 6000, 10000, 15000] + + # if step in (0, 2000): + # self.save_new_train_images(step) + # self.update_train_images(step) + # elif step > 2000 and step % 250 == 0: + # self.update_single_image(step) + + if step == 0: + self.load_images() if self.world_size > 1 and step: assert self.datamanager.train_sampler is not None diff --git a/nerfstudio/viewer/server/render_state_machine.py b/nerfstudio/viewer/server/render_state_machine.py index 9a955e42b..835181782 100644 --- a/nerfstudio/viewer/server/render_state_machine.py +++ b/nerfstudio/viewer/server/render_state_machine.py @@ -123,6 +123,8 @@ class RenderStateMachine(threading.Thread): ) image_height, image_width = self._calculate_image_res(cam_msg.aspect) + # image_height, image_width = self._calculate_image_res(1.0) + intrinsics_matrix, camera_to_world_h = get_intrinsics_matrix_and_camera_to_world_h( cam_msg, image_height=image_height, image_width=image_width @@ -251,6 +253,7 @@ class RenderStateMachine(threading.Thread): image_width: the maximum image width that can be rendered in the time budget """ max_res = self.viewer.control_panel.max_res + # max_res = 128 if self.state == "high": # high res is always static image_height = max_res