[WIP] dreamfusion implementation (#1008)

* starting the framework for dreamfusion

* Removed view direction from RGB to calculate albedo

* Started diffusion

* Added dreamfusion to CLI, removed direction embeddings

* Normals in dreamfusion

* Lambertian shading added

* Train normals in Dreamfusion

* Stable diffusion from Stable Dreamfusion

* Fix normal orientation loss

* Configurable light direction sampling

* adding density initalization at origin

* V1 datamanager

* Don't train normals for first 1k iters

* SDS loss added to dreamfusion

* Dreamfusion pipeline

* Background MLP and SphereCollider

* Normals prediction training fixed

* Sigmoid on background, prompt in config

* Shading hyperparameter adjustements

* Shading hyperparameter tuning

* Location based prompting, density initialization fades, LR change

* Cleaned imports, more config options

* Tuning, more config changes

* remove unused sampler, normalize predicted normals from network

* change position encoding to direction encoding for background color mlp

* Updating dreamfusion to use custom trainer, fixed bug, multi-gpu support (put diffusion on one specific device), merged with main

* Hard coding less, offloading to config

* Appeasing the linter

* First pass opacity / sparsity losses

* Small patches and configs

* Accidentally pushed logs

* Removing logs for real this time

* Transmittance loss bug fix

* 12 GB Dreamfusion!

* Lint

* Remove unecissary collider changes

* Start SD cleanup

* Cleanup SD code

* adding overhead location prompting

* Use lambertian renderer

* turn grad accum off by default, decrease background mlp size, add overhead text embedding

* Cleanup

* Fix normals vis

* change uniform sampler to prediction network, add option to jit unet for faster sds_loss

* Use shaders

* cleaning up jit code

* add warning if using non jit unet

* add proposal network optimizer to config

* speed up render and cleanup code

* Clean up datamanager

* Add distortion loss

* fix wanb

* adding interpolated location sampling

* Update configs

* interpolated location prompting option, lowering init density, transmittance loss interpolation flipped

* rename alphas mult to alphas loss mult

* Mess around with normals

* add option to use random bg color + bg mlp

* Remove Dreamfusion Trainer (#1423)

* Dreamfusion trainer no longer needed

* Added typing for grad scaler

* SDS return loss

* Fix CFG

* Cleanup

* Update configs

* Fix opacity loss, use unform sampling first round of prop

* add prompt edditing to viewer

* Choose your own diffusion

* remove dreamfusion pipeline file

* merging + remove dreamfusion pipeline file

* Update configs

* add stable diff utils

* cleanup

* cleanup

* Fix test

* positional prompting bugfix

* Warmups

* tune

* lint

* Remove dataparser

* merging + text embedding bugfix

* Set data path to launch viewer for DreamFusion (#1776)

* Set data path to launch viewer for DreamFusion

* Apply formatter

* Fallback to 'base_dir' if data manager has no path

* Make if statement non-inline

* Reformat

---------

Co-authored-by: Matthew Tancik <mattt4001@gmail.com>

* add deepfloyd option first try

* merging

* merging from main

* merging

* removing comments, cleaning code, making stable diff utils usable for deepfloyd, remove deepfloyd text encoder after use

* undo chagnes in data folder

* cleaning code, removing unneccesary changes from main, removed normals prediction network

* remove old scripts files, rename generative pipeline flag to no_input_data, revert to default histogram padding in proposal sampler

* changing pipeline flag

* move no input data flag from pipeline to datamanager

* undo config and merge in deepfloyd from main

* merging grad scaler pipeline addition

* merging + setting proposal net scheduler

* revert nerfacto config change

* typing + linting

* rename dreamfusion datamanager to random camras datamanager, check datamanager typing in pipeline and trainer

* fix test import

* fix test import

* changing datamanager check in trainer, add typing in random cameras datamanager

* add Tensor to randomcamerasdatamanager

* remove old comments

* resolve tyro warning

* update fields to use tcnn

* lint

* add packages for deepfloyd

* add versions

* docs first draft

* rename to generfacto, clean docs

* fix import error

* minor changes

* fix orientation loss bug, retune params

* cleanup

* typing

* trying docs fix

* fixing generative package imports

* fix pyright

* docs fix

* merge w main

* docs minor change

* tuning + bugfixes

* remove torch.backends

---------

Co-authored-by: Abhik Ahuja <ahujaabhik@berkeley.edu>
Co-authored-by: David McAllister <davidrmc2@gmail.com>
Co-authored-by: Jake Austin <jake-austin@berkeley.edu>
Co-authored-by: Matthew Tancik <tancik@berkeley.edu>
Co-authored-by: Matt Tancik <mattt4001@gmail.com>
Co-authored-by: SeungWoo Yoo <dreamy1534@gmail.com>
Co-authored-by: ayaanzhaque <ayaanzhaque@gmail.com>
Co-authored-by: Ayaan Haque <ayaanzhaque@berkeley.edu>
This commit is contained in:
22 files changed
+1324 -99

No files matched your search

+49 -42
View File
@@ -14,21 +14,30 @@
import gc
from pathlib import Path
from typing import List, Optional, Union, cast
from typing import List, Optional, Union
import torch
import torch.nn.functional as F
import tyro
from diffusers import IFPipeline
from diffusers.pipelines.deepfloyd_if import IFPipelineOutput
from jaxtyping import Float
from PIL import Image
from torch import FloatTensor, Generator, Tensor, nn
from torch import Generator, Tensor, nn
from torch.cuda.amp.grad_scaler import GradScaler
from transformers import T5EncoderModel
from nerfstudio.generative.utils import _SDSGradient
from nerfstudio.generative.utils import CatchMissingPackages
try:
from diffusers import IFPipeline as IFOrig
from diffusers.pipelines.deepfloyd_if import IFPipelineOutput as IFOutputOrig
from diffusers import IFPipeline, DiffusionPipeline
from diffusers.pipelines.deepfloyd_if import IFPipelineOutput
from transformers import T5EncoderModel
except ImportError:
IFPipeline = IFPipelineOutput = T5EncoderModel = CatchMissingPackages()
IMG_DIM = 64
@@ -61,7 +70,7 @@ class DeepFloyd(nn.Module):
variant="fp16",
torch_dtype=torch.float16,
)
assert isinstance(self.pipe, IFPipeline)
assert isinstance(self.pipe, DiffusionPipeline)
self.pipe = self.pipe.to(self.device)
self.pipe.enable_attention_slicing(1)
@@ -96,7 +105,7 @@ class DeepFloyd(nn.Module):
variant="fp16",
torch_dtype=torch.float16,
)
assert isinstance(self.pipe, IFPipeline)
assert isinstance(self.pipe, DiffusionPipeline)
self.pipe = self.pipe.to(self.device)
self.pipe.enable_attention_slicing(1)
@@ -122,12 +131,12 @@ class DeepFloyd(nn.Module):
prompt = [prompt] if isinstance(prompt, str) else prompt
negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
assert isinstance(self.pipe, IFPipeline)
assert isinstance(self.pipe, DiffusionPipeline)
with torch.no_grad():
prompt_embeds, negative_embeds = self.pipe.encode_prompt(prompt, negative_prompt=negative_prompt)
assert isinstance(negative_embeds, FloatTensor)
assert isinstance(prompt_embeds, FloatTensor)
assert isinstance(negative_embeds, Tensor)
assert isinstance(prompt_embeds, Tensor)
return torch.cat([negative_embeds, prompt_embeds])
def sds_loss(
@@ -146,40 +155,37 @@ class DeepFloyd(nn.Module):
Returns:
The loss
"""
with torch.autocast(device_type="cuda", enabled=False):
image = F.interpolate(image.half(), (IMG_DIM, IMG_DIM), mode="bilinear", align_corners=False)
t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device)
image = F.interpolate(image.half(), (IMG_DIM, IMG_DIM), mode="bilinear", align_corners=False)
t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device)
# predict the noise residual with unet, NO grad!
with torch.no_grad():
# add noise
noise = torch.randn_like(image)
image_noisy = self.scheduler.add_noise(image, noise, t) # type: ignore
# pred noise
image_model_input = torch.cat((image_noisy,) * 2)
noise_pred = self.unet(image_model_input, t, encoder_hidden_states=text_embeddings).sample
# predict the noise residual with unet, NO grad!
with torch.no_grad():
# add noise
noise = torch.randn_like(image)
image_noisy = self.scheduler.add_noise(image, noise, t) # type: ignore
# pred noise
image_model_input = torch.cat((image_noisy,) * 2)
noise_pred = self.unet(image_model_input, t, encoder_hidden_states=text_embeddings).sample
# perform guidance
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
noise_pred_text, predicted_variance = noise_pred_text.split(3, dim=1)
noise_pred_uncond, _ = noise_pred_uncond.split(3, dim=1)
# perform guidance
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
noise_pred_text, predicted_variance = noise_pred_text.split(3, dim=1)
noise_pred_uncond, _ = noise_pred_uncond.split(3, dim=1)
noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond)
noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond)
# w(t), sigma_t^2
w = 1 - self.alphas[t]
# w(t), sigma_t^2
w = 1 - self.alphas[t]
grad = w * (noise_pred - noise)
grad = torch.nan_to_num(grad)
grad = w * (noise_pred - noise)
grad = torch.nan_to_num(grad)
if grad_scaler is not None:
loss = cast(Tensor, _SDSGradient.apply(grad_scaler.scale(image), grad))
else:
loss = cast(Tensor, _SDSGradient.apply(image, grad))
target = (image - grad).detach()
loss = 0.5 * F.mse_loss(image, target, reduction="sum") / image.shape[0]
return loss
def prompt_to_img(
def prompt_to_image(
self,
prompts: Union[str, List[str]],
negative_prompts: Union[str, List[str]] = "",
@@ -201,16 +207,17 @@ class DeepFloyd(nn.Module):
prompts = [prompts] if isinstance(prompts, str) else prompts
negative_prompts = [negative_prompts] if isinstance(negative_prompts, str) else negative_prompts
assert isinstance(self.pipe, IFPipeline)
assert isinstance(self.pipe, DiffusionPipeline)
prompt_embeds, negative_embeds = self.pipe.encode_prompt(prompts, negative_prompt=negative_prompts)
assert isinstance(self.pipe, IFOrig)
model_output = self.pipe(
prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, generator=generator
)
assert isinstance(model_output, IFPipelineOutput)
image = model_output.images[0]
assert isinstance(model_output, IFOutputOrig)
output_image = model_output.images[0]
return image
return output_image
def generate_image(
@@ -228,7 +235,7 @@ def generate_image(
cuda_device = torch.device("cuda")
with torch.no_grad():
df = DeepFloyd(cuda_device)
img = df.prompt_to_img(prompt, negative, generator, steps)
img = df.prompt_to_image(prompt, negative, generator, steps)
img.save(save_path)
@@ -0,0 +1,120 @@
# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility helper functions for generative 3D models"""
import torch
from torch import Tensor
from jaxtyping import Float
from typing_extensions import Literal
from typing import Union
from nerfstudio.generative.stable_diffusion import StableDiffusion
from nerfstudio.generative.deepfloyd import DeepFloyd
class PositionalTextEmbeddings:
"""Postional Prompts. Currently the following location based text embeddings are supported:
- discrete: Choose the embedding closest to the camera position
- interpolated: Interpolate between the embeddings based on the camera position
- off: Don't modify the text embedding based on the camera position
Args:
base_prompt: Prompt for base view
top_prompt: Prompt for top view
side_prompt: Prompt for side view
back_prompt: Prompt for back view
front_prompt: Prompt for front view
diffusion_model: Instance of StableDiffusion
positional_prompting: how to incorporate position into prompt.
"""
def __init__(
self,
base_prompt: str,
top_prompt: str,
side_prompt: str,
back_prompt: str,
front_prompt: str,
diffusion_model: Union[StableDiffusion, DeepFloyd],
positional_prompting: Literal["discrete", "interpolated", "off"] = "discrete",
):
self.positional_prompting = positional_prompting
self.diffusion_device = diffusion_model.device
self.diffusion = diffusion_model
self.update_prompt(base_prompt, top_prompt, side_prompt, back_prompt, front_prompt)
def update_prompt(self, base_prompt: str, top_prompt: str, side_prompt: str, back_prompt: str, front_prompt: str):
"""Update the text embeddings based on the new prompts.
Args:
base_prompt: Prompt for base view
top_prompt: Prompt for top view
side_prompt: Prompt for side view
back_prompt: Prompt for back view
front_prompt: Prompt for front view
"""
self.base_embed = self.diffusion.get_text_embeds(base_prompt, "")
self.top_embed = self.diffusion.get_text_embeds(top_prompt, "")
self.side_embed = self.diffusion.get_text_embeds(side_prompt, "")
self.back_embed = self.diffusion.get_text_embeds(back_prompt, "")
self.front_embed = self.diffusion.get_text_embeds(front_prompt, "")
if isinstance(self.diffusion, DeepFloyd):
self.diffusion.delete_text_encoder()
def get_text_embedding(
self, vertical_angle: Float[Tensor, "1"], horizontal_angle: Float[Tensor, "1"]
) -> Float[Tensor, "2 max_length embed_dim"]:
"""Get text embedding based on the position of the camera relative to the scene.
This trick is used in Dreamfusion (https://dreamfusion3d.github.io/).
Args:
vertical_angle: vertical angle of the camera
horizonal_angle: horizonal angle of the camera
"""
# set horizontal_angle between 0, 360
horizontal_angle = torch.fmod(horizontal_angle, 360)
horizontal_angle = torch.where(horizontal_angle < 0, horizontal_angle + 360, horizontal_angle)
if self.positional_prompting == "discrete":
if vertical_angle < 40:
text_embedding = self.top_embed
elif 315 < horizontal_angle or horizontal_angle <= 45:
text_embedding = self.front_embed
elif 45 < horizontal_angle <= 135:
text_embedding = self.side_embed
elif 135 < horizontal_angle <= 225:
text_embedding = self.back_embed
else: # horizontal_angle > 225 and horizontal_angle <= 315:
text_embedding = self.side_embed
elif self.positional_prompting == "interpolated":
horiz = horizontal_angle.detach().numpy()[0]
vert = max(vertical_angle.detach().numpy()[0], 0)
if 0 < horizontal_angle <= 90:
text_embedding = (horiz) * self.side_embed + (90 - horiz) * self.front_embed
elif 90 < horizontal_angle <= 180:
text_embedding = (horiz - 90) * self.back_embed + (180 - horiz) * self.side_embed
elif 180 < horizontal_angle <= 270:
text_embedding = (horiz - 180) * self.side_embed + (270 - horiz) * self.back_embed
else: # 270 < horizontal_angle <= 360:
text_embedding = (horiz - 270) * self.front_embed + (360 - horiz) * self.side_embed
text_embedding = text_embedding / 90.0
text_embedding = (vert * text_embedding + (90 - vert) * self.top_embed) / 90.0
else:
text_embedding = self.base_embed
return text_embedding
+12 -25
View File
@@ -16,10 +16,9 @@
# Modified from https://github.com/ashawkey/stable-dreamfusion/blob/main/nerf/sd.py
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Union, cast
from typing import List, Optional, Union
from nerfstudio.utils.rich_utils import CONSOLE
import mediapy
import numpy as np
@@ -30,22 +29,16 @@ from jaxtyping import Float
from torch import Tensor, nn
from torch.cuda.amp.grad_scaler import GradScaler
from nerfstudio.utils.rich_utils import CONSOLE
from nerfstudio.generative.utils import _SDSGradient
from nerfstudio.generative.utils import CatchMissingPackages
try:
from diffusers import PNDMScheduler, StableDiffusionPipeline
from transformers import logging
from diffusers import PNDMScheduler, StableDiffusionPipeline, DiffusionPipeline
except ImportError:
CONSOLE.print("[bold red]Missing Stable Diffusion packages.")
CONSOLE.print(r"Install using [yellow]pip install nerfstudio\[gen][/yellow]")
CONSOLE.print(r"or [yellow]pip install -e .\[gen][/yellow] if installing from source.")
sys.exit(1)
PNDMScheduler = StableDiffusionPipeline = CatchMissingPackages()
logging.set_verbosity_error()
IMG_DIM = 512
CONST_SCALE = 0.18215
SD_IDENTIFIERS = {
@@ -55,13 +48,6 @@ SD_IDENTIFIERS = {
}
@dataclass
class UNet2DConditionOutput:
"""Class to hold traced model"""
sample: torch.FloatTensor
class StableDiffusion(nn.Module):
"""Stable Diffusion implementation
Args:
@@ -88,7 +74,8 @@ class StableDiffusion(nn.Module):
sd_id = SD_IDENTIFIERS[version]
pipe = StableDiffusionPipeline.from_pretrained(sd_id, torch_dtype=torch.float16)
assert isinstance(pipe, StableDiffusionPipeline)
assert isinstance(pipe, DiffusionPipeline) # and hasattr(pipe, "to")
pipe = pipe.to(self.device)
pipe.enable_attention_slicing()
@@ -154,7 +141,7 @@ class StableDiffusion(nn.Module):
Returns:
The loss
"""
image = F.interpolate(image, (IMG_DIM, IMG_DIM), mode="bilinear")
image = F.interpolate(image, (IMG_DIM, IMG_DIM), mode="bilinear").to(torch.float16)
t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device)
latents = self.imgs_to_latent(image)
@@ -177,9 +164,8 @@ class StableDiffusion(nn.Module):
grad = w * (noise_pred - noise)
grad = torch.nan_to_num(grad)
if grad_scaler is not None:
latents = grad_scaler.scale(latents)
loss = cast(Tensor, _SDSGradient.apply(latents, grad))
target = (latents - grad).detach()
loss = 0.5 * F.mse_loss(latents, target, reduction="sum") / latents.shape[0]
return loss
@@ -230,6 +216,7 @@ class StableDiffusion(nn.Module):
# compute the previous noisy sample x_t -> x_t-1
latents = self.scheduler.step(noise_pred, t, latents)["prev_sample"] # type: ignore
assert isinstance(latents, Tensor)
return latents
def latents_to_img(self, latents: Float[Tensor, "BS 4 H W"]) -> Float[Tensor, "BS 3 H W"]:
+15 -20
View File
@@ -12,28 +12,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility helper functions for diffusion models"""
import torch
from torch.cuda.amp import custom_bwd, custom_fwd
"""Gradient helper functions for SDS loss"""
import sys
from nerfstudio.utils.rich_utils import CONSOLE
class _SDSGradient(torch.autograd.Function):
"""Custom gradient function for SDS loss. Since it is already computed, we can just return it."""
class CatchMissingPackages:
"""Class to catch missing environment packages related to diffusion models."""
@staticmethod
@custom_fwd
def forward(ctx, input_tensor, gt_grad):
del input_tensor
ctx.save_for_backward(gt_grad)
# Return magniture of gradient, not the actual loss.
return torch.mean(gt_grad**2) ** 0.5
def __init__(self):
pass
@staticmethod
@custom_bwd
def backward(ctx, grad):
del grad
(gt_grad,) = ctx.saved_tensors
batch_size = len(gt_grad)
return gt_grad / batch_size, None
def __call__(self, *args, **kwargs):
CONSOLE.print("[bold red]Missing Stable Diffusion packages.")
CONSOLE.print(r"Install using [yellow]pip install nerfstudio\[gen][/yellow]")
CONSOLE.print(r"or [yellow]pip install -e .\[gen][/yellow] if installing from source.")
sys.exit(1)
def __getattr__(self, attr):
return self.__call__