mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-05 15:28:49 +08:00
SDS loss added to dreamfusion
This commit is contained in:
1 parent
5de6e5041b
commit
cbb50314b1
8 files changed
+39
-31
No files matched your search
@@ -339,7 +339,7 @@ class Cameras(TensorDataclass):
|
|||||||
When coords == None (ie: when we render out the whole image associated with this camera), we run into problems
|
When coords == None (ie: when we render out the whole image associated with this camera), we run into problems
|
||||||
since there's no way to stack each coordinate map as all coordinate maps are all different shapes. In this case,
|
since there's no way to stack each coordinate map as all coordinate maps are all different shapes. In this case,
|
||||||
we will need to flatten each individual coordinate map and concatenate them, giving us only one batch dimension,
|
we will need to flatten each individual coordinate map and concatenate them, giving us only one batch dimension,
|
||||||
regaurdless of the number of prepended extra batch dimensions in the camera_indices tensor.
|
regardless of the number of prepended extra batch dimensions in the camera_indices tensor.
|
||||||
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ from nerfstudio.configs.base_config import (
|
|||||||
ViewerConfig,
|
ViewerConfig,
|
||||||
)
|
)
|
||||||
from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManagerConfig
|
from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManagerConfig
|
||||||
|
from nerfstudio.data.datamanagers.dreamfusion_datamanager import (
|
||||||
|
DreamFusionDataManagerConfig,
|
||||||
|
)
|
||||||
from nerfstudio.data.datamanagers.semantic_datamanager import SemanticDataManagerConfig
|
from nerfstudio.data.datamanagers.semantic_datamanager import SemanticDataManagerConfig
|
||||||
from nerfstudio.data.datamanagers.variable_res_datamanager import (
|
from nerfstudio.data.datamanagers.variable_res_datamanager import (
|
||||||
VariableResDataManagerConfig,
|
VariableResDataManagerConfig,
|
||||||
@@ -259,7 +262,7 @@ method_configs["dreamfusion"] = Config(
|
|||||||
steps_per_eval_batch=500, steps_per_save=2000, max_num_iterations=30000, mixed_precision=True
|
steps_per_eval_batch=500, steps_per_save=2000, max_num_iterations=30000, mixed_precision=True
|
||||||
),
|
),
|
||||||
pipeline=VanillaPipelineConfig(
|
pipeline=VanillaPipelineConfig(
|
||||||
datamanager=VanillaDataManagerConfig(
|
datamanager=DreamFusionDataManagerConfig(
|
||||||
dataparser=NerfstudioDataParserConfig(),
|
dataparser=NerfstudioDataParserConfig(),
|
||||||
train_num_rays_per_batch=4096,
|
train_num_rays_per_batch=4096,
|
||||||
eval_num_rays_per_batch=4096,
|
eval_num_rays_per_batch=4096,
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ def random_train_pose(
|
|||||||
origins = torch.stack([torch.tensor([0, 0, 1])] * size, dim=0)
|
origins = torch.stack([torch.tensor([0, 0, 1])] * size, dim=0)
|
||||||
origins = (origins * radius_mean) + (origins * (torch.randn((origins.shape)) * radius_std))
|
origins = (origins * radius_mean) + (origins * (torch.randn((origins.shape)) * radius_std))
|
||||||
R = torch.bmm(rot_z, rot_x) # Want to have Rx @ Ry @ origin
|
R = torch.bmm(rot_z, rot_x) # Want to have Rx @ Ry @ origin
|
||||||
print(torch.bmm(R, origins.unsqueeze(-1)).shape, (torch.randn((size, 3, 1)) * jitter_std).shape)
|
# print(torch.bmm(R, origins.unsqueeze(-1)).shape, (torch.randn((size, 3, 1)) * jitter_std).shape)
|
||||||
t = torch.bmm(R, origins.unsqueeze(-1)) + torch.randn((size, 3, 1)) * jitter_std
|
t = torch.bmm(R, origins.unsqueeze(-1)) + torch.randn((size, 3, 1)) * jitter_std
|
||||||
camera_to_worlds = torch.cat([R, t], dim=-1)
|
camera_to_worlds = torch.cat([R, t], dim=-1)
|
||||||
|
|
||||||
@@ -191,7 +191,7 @@ class DreamFusionDataManagerConfig(VanillaDataManagerConfig):
|
|||||||
_target: Type = field(default_factory=lambda: DreamFusionDataManager)
|
_target: Type = field(default_factory=lambda: DreamFusionDataManager)
|
||||||
train_resolution: int = 64
|
train_resolution: int = 64
|
||||||
"""Training resolution"""
|
"""Training resolution"""
|
||||||
eval_resolution: int = 256
|
eval_resolution: int = 64
|
||||||
"""Evaluation resolution"""
|
"""Evaluation resolution"""
|
||||||
num_eval_angles: int = 256
|
num_eval_angles: int = 256
|
||||||
"""Number of evaluation angles"""
|
"""Number of evaluation angles"""
|
||||||
@@ -199,8 +199,6 @@ class DreamFusionDataManagerConfig(VanillaDataManagerConfig):
|
|||||||
"""Number of images per batch for training"""
|
"""Number of images per batch for training"""
|
||||||
eval_images_per_batch: int = 1
|
eval_images_per_batch: int = 1
|
||||||
"""Number of images per batch for evaluation"""
|
"""Number of images per batch for evaluation"""
|
||||||
prompt: str = "A surfer sitting on a surfboard in the sky watching the sunset."
|
|
||||||
"""Prompt to optimize for."""
|
|
||||||
|
|
||||||
|
|
||||||
class DreamFusionDataManager(VanillaDataManager): # pylint: disable=abstract-method
|
class DreamFusionDataManager(VanillaDataManager): # pylint: disable=abstract-method
|
||||||
@@ -276,7 +274,7 @@ class DreamFusionDataManager(VanillaDataManager): # pylint: disable=abstract-me
|
|||||||
vertical_rotation_range=[-180, 180],
|
vertical_rotation_range=[-180, 180],
|
||||||
jitter_std=0,
|
jitter_std=0,
|
||||||
)
|
)
|
||||||
ray_bundle = cameras.generate_rays(torch.tensor([[i] for i in range(self.config.train_images_per_batch)]))
|
ray_bundle = cameras.generate_rays(torch.tensor(list(range(self.config.train_images_per_batch)))).flatten()
|
||||||
|
|
||||||
return ray_bundle, {"vertical": vertical_rotation, "central": central_rotation, "initialization": True}
|
return ray_bundle, {"vertical": vertical_rotation, "central": central_rotation, "initialization": True}
|
||||||
|
|
||||||
|
|||||||
@@ -314,9 +314,9 @@ class Trainer:
|
|||||||
with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision):
|
with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision):
|
||||||
_, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step)
|
_, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step)
|
||||||
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)
|
||||||
self.grad_scaler.update()
|
# self.grad_scaler.update()
|
||||||
self.optimizers.scheduler_step_all(step)
|
self.optimizers.scheduler_step_all(step)
|
||||||
|
|
||||||
# Merging loss and metrics dict into a single output.
|
# Merging loss and metrics dict into a single output.
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
|
|
||||||
# From https://github.com/ashawkey/stable-dreamfusion/blob/main/nerf/sd.py
|
# From https://github.com/ashawkey/stable-dreamfusion/blob/main/nerf/sd.py
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
import torch
|
import torch
|
||||||
|
import torch.nn.functional as F
|
||||||
from diffusers import AutoencoderKL, PNDMScheduler, UNet2DConditionModel
|
from diffusers import AutoencoderKL, PNDMScheduler, UNet2DConditionModel
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from torch import nn
|
from torch import nn
|
||||||
@@ -71,15 +73,13 @@ class StableDiffusion(nn.Module):
|
|||||||
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
||||||
return text_embeddings
|
return text_embeddings
|
||||||
|
|
||||||
|
def sds_loss(self, text_embeddings, nerf_output, guidance_scale=100):
|
||||||
|
|
||||||
def train_step(self, text_embeddings, pred_nerf, guidance_scale=100):
|
plt.imsave('nerf_output.png', nerf_output.view(3, 64, 64).permute(1, 2, 0).detach().cpu().numpy())
|
||||||
|
nerf_output = F.interpolate(nerf_output, (IMG_DIM, IMG_DIM), mode='bilinear')
|
||||||
# Upscale NeRF render for Stable Diffusion
|
|
||||||
pred_nerf = F.interpolate(pred_nerf, (IMG_DIM, IMG_DIM), mode='bilinear')
|
|
||||||
|
|
||||||
t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device)
|
t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device)
|
||||||
latents = self.imgs_to_latent(pred_nerf)
|
latents = self.imgs_to_latent(nerf_output)
|
||||||
|
|
||||||
# predict the noise residual with unet, NO grad!
|
# predict the noise residual with unet, NO grad!
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
# add noise
|
# add noise
|
||||||
@@ -105,9 +105,10 @@ class StableDiffusion(nn.Module):
|
|||||||
# manually backward, since we omitted an item in grad and cannot simply autodiff.
|
# manually backward, since we omitted an item in grad and cannot simply autodiff.
|
||||||
# _t = time.time()
|
# _t = time.time()
|
||||||
latents.backward(gradient=grad, retain_graph=True)
|
latents.backward(gradient=grad, retain_graph=True)
|
||||||
# torch.cuda.synchronize(); print(f'[TIME] guiding: backward {time.time() - _t:.4f}s')
|
|
||||||
|
|
||||||
return 0 # dummy loss value
|
rgb_loss = torch.square(noise_pred - noise)
|
||||||
|
|
||||||
|
return rgb_loss
|
||||||
|
|
||||||
def produce_latents(self, text_embeddings, height=IMG_DIM, width=IMG_DIM, num_inference_steps=50, guidance_scale=7.5, latents=None):
|
def produce_latents(self, text_embeddings, height=IMG_DIM, width=IMG_DIM, num_inference_steps=50, guidance_scale=7.5, latents=None):
|
||||||
|
|
||||||
@@ -147,7 +148,6 @@ class StableDiffusion(nn.Module):
|
|||||||
|
|
||||||
def imgs_to_latent(self, imgs):
|
def imgs_to_latent(self, imgs):
|
||||||
# imgs: [B, 3, H, W]
|
# imgs: [B, 3, H, W]
|
||||||
|
|
||||||
imgs = 2 * imgs - 1
|
imgs = 2 * imgs - 1
|
||||||
|
|
||||||
posterior = self.auto_encoder.encode(imgs).latent_dist
|
posterior = self.auto_encoder.encode(imgs).latent_dist
|
||||||
@@ -176,8 +176,6 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
import matplotlib.pyplot as plt
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument('prompt', type=str)
|
parser.add_argument('prompt', type=str)
|
||||||
parser.add_argument('--negative', default='', type=str)
|
parser.add_argument('--negative', default='', type=str)
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ class AABBBoxCollider(SceneCollider):
|
|||||||
self.near_plane = near_plane
|
self.near_plane = near_plane
|
||||||
|
|
||||||
def _intersect_with_aabb(
|
def _intersect_with_aabb(
|
||||||
self, rays_o: TensorType["num_rays", 3], rays_d: TensorType["num_rays", 3], aabb: TensorType[2, 3]
|
self, rays_o: TensorType["num_rays":..., 3], rays_d: TensorType["num_rays":..., 3], aabb: TensorType[2, 3]
|
||||||
):
|
):
|
||||||
"""Returns collection of valid rays within a specified near/far bounding box along with a mask
|
"""Returns collection of valid rays within a specified near/far bounding box along with a mask
|
||||||
specifying which rays are valid
|
specifying which rays are valid
|
||||||
@@ -71,14 +71,14 @@ class AABBBoxCollider(SceneCollider):
|
|||||||
dir_fraction = 1.0 / (rays_d + 1e-6)
|
dir_fraction = 1.0 / (rays_d + 1e-6)
|
||||||
|
|
||||||
# x
|
# x
|
||||||
t1 = (aabb[0, 0] - rays_o[:, 0:1]) * dir_fraction[:, 0:1]
|
t1 = (aabb[0, 0] - rays_o[..., 0:1]) * dir_fraction[..., 0:1]
|
||||||
t2 = (aabb[1, 0] - rays_o[:, 0:1]) * dir_fraction[:, 0:1]
|
t2 = (aabb[1, 0] - rays_o[..., 0:1]) * dir_fraction[..., 0:1]
|
||||||
# y
|
# y
|
||||||
t3 = (aabb[0, 1] - rays_o[:, 1:2]) * dir_fraction[:, 1:2]
|
t3 = (aabb[0, 1] - rays_o[..., 1:2]) * dir_fraction[..., 1:2]
|
||||||
t4 = (aabb[1, 1] - rays_o[:, 1:2]) * dir_fraction[:, 1:2]
|
t4 = (aabb[1, 1] - rays_o[..., 1:2]) * dir_fraction[..., 1:2]
|
||||||
# z
|
# z
|
||||||
t5 = (aabb[0, 2] - rays_o[:, 2:3]) * dir_fraction[:, 2:3]
|
t5 = (aabb[0, 2] - rays_o[..., 2:3]) * dir_fraction[..., 2:3]
|
||||||
t6 = (aabb[1, 2] - rays_o[:, 2:3]) * dir_fraction[:, 2:3]
|
t6 = (aabb[1, 2] - rays_o[..., 2:3]) * dir_fraction[..., 2:3]
|
||||||
|
|
||||||
nears = torch.max(
|
nears = torch.max(
|
||||||
torch.cat([torch.minimum(t1, t2), torch.minimum(t3, t4), torch.minimum(t5, t6)], dim=1), dim=1
|
torch.cat([torch.minimum(t1, t2), torch.minimum(t3, t4), torch.minimum(t5, t6)], dim=1), dim=1
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ from nerfstudio.engine.callbacks import (
|
|||||||
# from nerfstudio.field_components.encodings import NeRFEncoding,
|
# from nerfstudio.field_components.encodings import NeRFEncoding,
|
||||||
from nerfstudio.field_components.field_heads import FieldHeadNames
|
from nerfstudio.field_components.field_heads import FieldHeadNames
|
||||||
from nerfstudio.fields.dreamfusion_field import DreamFusionField
|
from nerfstudio.fields.dreamfusion_field import DreamFusionField
|
||||||
|
from nerfstudio.generative.stable_diffusion import StableDiffusion
|
||||||
from nerfstudio.model_components.losses import (
|
from nerfstudio.model_components.losses import (
|
||||||
MSELoss,
|
MSELoss,
|
||||||
orientation_loss,
|
orientation_loss,
|
||||||
@@ -72,6 +73,8 @@ class DreamFusionModelConfig(ModelConfig):
|
|||||||
"""Randomizes light source per output."""
|
"""Randomizes light source per output."""
|
||||||
initialize_density: bool = True
|
initialize_density: bool = True
|
||||||
"""Initialize density in center of scene."""
|
"""Initialize density in center of scene."""
|
||||||
|
prompt: str = "A high quality photo of a pineaple."
|
||||||
|
"""Text prompt to optimize scene for."""
|
||||||
|
|
||||||
|
|
||||||
class DreamFusionModel(Model):
|
class DreamFusionModel(Model):
|
||||||
@@ -92,6 +95,8 @@ class DreamFusionModel(Model):
|
|||||||
self.initialize_density = config.initialize_density
|
self.initialize_density = config.initialize_density
|
||||||
self.train_normals = False
|
self.train_normals = False
|
||||||
super().__init__(config=config, **kwargs)
|
super().__init__(config=config, **kwargs)
|
||||||
|
self.sd = StableDiffusion(kwargs['device'])
|
||||||
|
self.text_embedding = self.sd.get_text_embeds(config.prompt, "")
|
||||||
|
|
||||||
def get_training_callbacks(
|
def get_training_callbacks(
|
||||||
self, training_callback_attributes: TrainingCallbackAttributes
|
self, training_callback_attributes: TrainingCallbackAttributes
|
||||||
@@ -193,7 +198,8 @@ class DreamFusionModel(Model):
|
|||||||
light_d = math.safe_normalize(light_d)
|
light_d = math.safe_normalize(light_d)
|
||||||
|
|
||||||
ratio = 0.1
|
ratio = 0.1
|
||||||
lambertian = ratio + (1 - ratio) * (pred_normals @ light_d).clamp(min=0) # [N,]
|
lambertian = ratio + (1 - ratio) * (normals @ light_d).clamp(min=0)
|
||||||
|
# lambertian = ratio + (1 - ratio) * (pred_normals @ light_d).clamp(min=0) # [N,]
|
||||||
|
|
||||||
shaded = lambertian.unsqueeze(-1).repeat(1, 3)
|
shaded = lambertian.unsqueeze(-1).repeat(1, 3)
|
||||||
shaded_albedo = rgb * lambertian.unsqueeze(-1)
|
shaded_albedo = rgb * lambertian.unsqueeze(-1)
|
||||||
@@ -221,9 +227,11 @@ class DreamFusionModel(Model):
|
|||||||
# TODO: modify to not take in data images, need to get diffusion loss here
|
# TODO: modify to not take in data images, need to get diffusion loss here
|
||||||
# Scaling metrics by coefficients to create the losses.
|
# Scaling metrics by coefficients to create the losses.
|
||||||
device = outputs["rgb"].device
|
device = outputs["rgb"].device
|
||||||
image = batch["image"].to(device)
|
|
||||||
|
|
||||||
rgb_loss = self.rgb_loss(image, outputs["rgb"])
|
# change to key 'shaded_albedo'
|
||||||
|
albedo_output = outputs["rgb"].view(1, 64, 64, 3).permute(0, 3, 1, 2)
|
||||||
|
|
||||||
|
rgb_loss = self.sd.sds_loss(self.text_embedding, albedo_output)
|
||||||
|
|
||||||
loss_dict = {"rgb_loss": rgb_loss}
|
loss_dict = {"rgb_loss": rgb_loss}
|
||||||
loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients)
|
loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients)
|
||||||
|
|||||||
@@ -229,6 +229,7 @@ class VanillaPipeline(Pipeline):
|
|||||||
scene_box=self.datamanager.train_dataset.scene_box,
|
scene_box=self.datamanager.train_dataset.scene_box,
|
||||||
num_train_data=len(self.datamanager.train_dataset),
|
num_train_data=len(self.datamanager.train_dataset),
|
||||||
metadata=self.datamanager.train_dataset.metadata,
|
metadata=self.datamanager.train_dataset.metadata,
|
||||||
|
device=device
|
||||||
)
|
)
|
||||||
self.model.to(device)
|
self.model.to(device)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user