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

This commit is contained in:
terrance committed 2023-05-12 00:56:15 +00:00
1 parent 7af729c414
commit 2945640d80
5 files changed
+114 -37

No files matched your search

+2 -1
View File
@@ -28,6 +28,7 @@ from nerfstudio.data.datamanagers.base_datamanager import (
VanillaDataManager, VanillaDataManager,
VanillaDataManagerConfig, VanillaDataManagerConfig,
) )
from nerfstudio.data.datamanagers.dreamfusion_datamanager import DreamFusionDataManagerConfig
from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig
from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig
from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig
@@ -456,7 +457,7 @@ method_configs["dreamfusion"] = TrainerConfig(
pipeline=VanillaPipelineConfig( pipeline=VanillaPipelineConfig(
generative=True, generative=True,
datamanager=DreamFusionDataManagerConfig( datamanager=DreamFusionDataManagerConfig(
horizontal_rotation_warmup=4000, horizontal_rotation_warmup=0,
), ),
model=DreamFusionModelConfig( model=DreamFusionModelConfig(
eval_num_rays_per_chunk=1 << 15, eval_num_rays_per_chunk=1 << 15,
@@ -54,7 +54,10 @@ class TrivialDataset(InputDataset):
return self.size return self.size
def __getitem__(self, index: int) -> Dict: def __getitem__(self, index: int) -> Dict:
return {"image": torch.cat([torch.ones(128, 256, 3), torch.zeros(128, 256, 3)], dim=0), "image_idx": index} return {
"image": torch.cat([torch.ones(128, 256, 3), torch.zeros(128, 256, 3)], dim=0),
"image_idx": index,
}
def random_train_pose( def random_train_pose(
@@ -84,7 +87,10 @@ def random_train_pose(
poses: [size, 4, 4] poses: [size, 4, 4]
""" """
vertical_rotation_range = [vertical_rotation_range[0] + 90, vertical_rotation_range[1] + 90] vertical_rotation_range = (
vertical_rotation_range[0] + 90,
vertical_rotation_range[1] + 90,
)
# This is the uniform sample on the part of the sphere we care about where 0 = 0 degrees and 1 = 360 degrees # This is the uniform sample on the part of the sphere we care about where 0 = 0 degrees and 1 = 360 degrees
sampled_uniform = ( sampled_uniform = (
torch.rand(size) * (vertical_rotation_range[1] - vertical_rotation_range[0]) + vertical_rotation_range[0] torch.rand(size) * (vertical_rotation_range[1] - vertical_rotation_range[0]) + vertical_rotation_range[0]
@@ -158,7 +164,7 @@ class DreamFusionDataManagerConfig(DataManagerConfig):
"""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"""
radius_mean: float = 2.2 radius_mean: float = 2.5
"""Mean radius of camera orbit""" """Mean radius of camera orbit"""
radius_std: float = 0.1 radius_std: float = 0.1
"""Std of radius of camera orbit""" """Std of radius of camera orbit"""
@@ -218,6 +224,7 @@ class DreamFusionDataManager(DataManager): # pylint: disable=abstract-method
radius_mean=self.config.radius_mean, radius_mean=self.config.radius_mean,
radius_std=self.config.radius_std, radius_std=self.config.radius_std,
focal_range=self.config.focal_range, focal_range=self.config.focal_range,
central_rotation_range=(-180, 180),
vertical_rotation_range=self.config.vertical_rotation_range, vertical_rotation_range=self.config.vertical_rotation_range,
jitter_std=self.config.jitter_std, jitter_std=self.config.jitter_std,
center=self.config.center, center=self.config.center,
@@ -251,7 +258,7 @@ class DreamFusionDataManager(DataManager): # pylint: disable=abstract-method
# ).flatten() # ).flatten()
# return ray_bundle, {"initialization": False} # return ray_bundle, {"initialization": False}
horizontal_range = min((step / self.config.horizontal_rotation_warmup), 1) * 180 horizontal_range = min((step / max(1, self.config.horizontal_rotation_warmup)), 1) * 180
cameras, vertical_rotation, central_rotation = random_train_pose( cameras, vertical_rotation, central_rotation = random_train_pose(
self.config.train_images_per_batch, self.config.train_images_per_batch,
@@ -267,9 +274,6 @@ class DreamFusionDataManager(DataManager): # pylint: disable=abstract-method
) )
ray_bundle = cameras.generate_rays(torch.tensor(list(range(self.config.train_images_per_batch)))).flatten() ray_bundle = cameras.generate_rays(torch.tensor(list(range(self.config.train_images_per_batch)))).flatten()
# camera_idx = torch.randint(0, self.eval_cameras.shape[0], [1], dtype=torch.long, device=self.device)
# ray_bundle = self.eval_cameras.generate_rays(camera_idx).flatten()
return ray_bundle, { return ray_bundle, {
"vertical": vertical_rotation, "vertical": vertical_rotation,
"central": central_rotation, "central": central_rotation,
@@ -310,7 +314,9 @@ class DreamFusionDataManager(DataManager): # pylint: disable=abstract-method
def get_eval_rays_per_batch(self) -> int: def get_eval_rays_per_batch(self) -> int:
return self.config.eval_resolution**2 return self.config.eval_resolution**2
def get_param_groups(self) -> Dict[str, List[Parameter]]: # pylint: disable=no-self-use def get_param_groups(
self,
) -> Dict[str, List[Parameter]]: # pylint: disable=no-self-use
"""Get the param groups for the data manager. """Get the param groups for the data manager.
Returns: Returns:
A list of dictionaries containing the data manager's param groups. A list of dictionaries containing the data manager's param groups.
+53 -7
View File
@@ -1,4 +1,5 @@
import sys import sys
import gc
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import List, Optional, Union from typing import List, Optional, Union
@@ -15,11 +16,30 @@ from torch.cuda.amp import custom_bwd, custom_fwd
from torch.cuda.amp.grad_scaler import GradScaler from torch.cuda.amp.grad_scaler import GradScaler
from torchtyping import TensorType from torchtyping import TensorType
from diffusers import IFPipeline from diffusers import IFPipeline
from transformers import T5EncoderModel, T5Tokenizer from transformers import T5EncoderModel, T5Tokenizer
IMG_DIM = 64
class _SDSGradient(torch.autograd.Function): # pylint: disable=abstract-method
"""Custom gradient function for SDS loss. Since it is already computed, we can just return it."""
@staticmethod
@custom_fwd
def forward(ctx, input_tensor, gt_grad): # pylint: disable=arguments-differ
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
@staticmethod
@custom_bwd
def backward(ctx, grad): # pylint: disable=arguments-differ
del grad
(gt_grad,) = ctx.saved_tensors
batch_size = len(gt_grad)
return gt_grad / batch_size, None
class DeepFloyd(nn.Module): class DeepFloyd(nn.Module):
# load in model # load in model
@@ -28,7 +48,7 @@ class DeepFloyd(nn.Module):
self.device = device self.device = device
self.text_encoder = T5EncoderModel.from_pretrained( self.text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-M-v1.0", "DeepFloyd/IF-I-L-v1.0",
subfolder="text_encoder", subfolder="text_encoder",
load_in_8bit=True, load_in_8bit=True,
variant="8bit", variant="8bit",
@@ -36,7 +56,7 @@ class DeepFloyd(nn.Module):
) )
self.pipe = IFPipeline.from_pretrained( self.pipe = IFPipeline.from_pretrained(
"DeepFloyd/IF-I-M-v1.0", "DeepFloyd/IF-I-L-v1.0",
text_encoder=self.text_encoder, text_encoder=self.text_encoder,
safety_checker=None, safety_checker=None,
watermarker=None, watermarker=None,
@@ -64,9 +84,35 @@ class DeepFloyd(nn.Module):
self.device self.device
) )
def delete_text_encoder(self):
del self.text_encoder
del self.pipe
gc.collect()
torch.cuda.empty_cache()
self.pipe = IFPipeline.from_pretrained(
"DeepFloyd/IF-I-L-v1.0",
text_encoder=None,
safety_checker=None,
watermarker=None,
feature_extractor=None,
requires_safety_checker=False,
variant="fp16",
torch_dtype=torch.float16,
).to(self.device)
self.pipe.enable_attention_slicing(1)
self.pipe.unet.to(memory_format=torch.channels_last)
self.unet = self.pipe.unet
for p in self.unet.parameters():
p.requires_grad_(False)
self.scheduler = self.pipe.scheduler
def get_text_embeds( def get_text_embeds(
self, prompt: Union[str, List[str]], negative_prompt: Union[str, List[str]] self, prompt: Union[str, List[str]], negative_prompt: Union[str, List[str]]
) -> TensorType[2, "max_length", "embed_dim"]: ) -> TensorType[2, "max_length", "embed_dim"]:
prompt = [prompt] if isinstance(prompt, str) else prompt prompt = [prompt] if isinstance(prompt, str) else prompt
negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
prompt_embeds, negative_embeds = self.pipe.encode_prompt(prompt, negative_prompt=negative_prompt) prompt_embeds, negative_embeds = self.pipe.encode_prompt(prompt, negative_prompt=negative_prompt)
@@ -107,8 +153,8 @@ class DeepFloyd(nn.Module):
grad = torch.nan_to_num(grad) grad = torch.nan_to_num(grad)
if grad_scaler is not None: if grad_scaler is not None:
latents = grad_scaler.scale(latents) image = grad_scaler.scale(image)
loss = _SDSGradient.apply(latents, grad) loss = _SDSGradient.apply(image, grad)
return loss return loss
+17 -13
View File
@@ -18,9 +18,11 @@ Stable diffusion utils
from torchtyping import TensorType from torchtyping import TensorType
from typing_extensions import Literal from typing_extensions import Literal
from typing import Union
import torch import torch
from nerfstudio.generative.stable_diffusion import StableDiffusion from nerfstudio.generative.stable_diffusion import StableDiffusion
from nerfstudio.generative.deepfloyd import DeepFloyd
class PositionalTextEmbeddings: class PositionalTextEmbeddings:
@@ -35,7 +37,7 @@ class PositionalTextEmbeddings:
side_prompt: Prompt for side view side_prompt: Prompt for side view
back_prompt: Prompt for back view back_prompt: Prompt for back view
front_prompt: Prompt for front view front_prompt: Prompt for front view
stable_diffusion: Instance of StableDiffusion diffusion_model: Instance of StableDiffusion
positional_prompting: how to incorporate position into prompt. positional_prompting: how to incorporate position into prompt.
""" """
@@ -46,12 +48,12 @@ class PositionalTextEmbeddings:
side_prompt: str, side_prompt: str,
back_prompt: str, back_prompt: str,
front_prompt: str, front_prompt: str,
stable_diffusion: StableDiffusion, diffusion_model: Union[StableDiffusion, DeepFloyd],
positional_prompting: Literal["discrete", "interpolated", "off"] = "discrete", positional_prompting: Literal["discrete", "interpolated", "off"] = "discrete",
): ):
self.positional_prompting = positional_prompting self.positional_prompting = positional_prompting
self.sd_device = stable_diffusion.device self.diffusion_device = diffusion_model.device
self.sd = stable_diffusion self.diffusion = diffusion_model
self.update_prompt(base_prompt, top_prompt, side_prompt, back_prompt, front_prompt) 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): def update_prompt(self, base_prompt: str, top_prompt: str, side_prompt: str, back_prompt: str, front_prompt: str):
@@ -63,12 +65,15 @@ class PositionalTextEmbeddings:
side_prompt: Prompt for side view side_prompt: Prompt for side view
back_prompt: Prompt for back view back_prompt: Prompt for back view
front_prompt: Prompt for front view front_prompt: Prompt for front view
""" """
self.base_embed = self.sd.get_text_embeds(base_prompt, "") self.base_embed = self.diffusion.get_text_embeds(base_prompt, "")
self.top_embed = self.sd.get_text_embeds(top_prompt, "") self.top_embed = self.diffusion.get_text_embeds(top_prompt, "")
self.side_embed = self.sd.get_text_embeds(side_prompt, "") self.side_embed = self.diffusion.get_text_embeds(side_prompt, "")
self.back_embed = self.sd.get_text_embeds(back_prompt, "") self.back_embed = self.diffusion.get_text_embeds(back_prompt, "")
self.front_embed = self.sd.get_text_embeds(front_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: TensorType[1], horizontal_angle: TensorType[1]): def get_text_embedding(self, vertical_angle: TensorType[1], horizontal_angle: TensorType[1]):
"""Get text embedding based on the position of the camera relative to the scene. """Get text embedding based on the position of the camera relative to the scene.
@@ -94,8 +99,8 @@ class PositionalTextEmbeddings:
else: # horizontal_angle > 225 and horizontal_angle <= 315: else: # horizontal_angle > 225 and horizontal_angle <= 315:
text_embedding = self.side_embed text_embedding = self.side_embed
elif self.positional_prompting == "interpolated": elif self.positional_prompting == "interpolated":
horiz = horizontal_angle.to(self.sd_device) horiz = horizontal_angle.to(self.diffusion_device)
vert = max(vertical_angle.to(self.sd_device), 0) vert = max(vertical_angle.to(self.diffusion_device), 0)
if 0 < horizontal_angle <= 90: if 0 < horizontal_angle <= 90:
text_embedding = (horiz) * self.side_embed + (90 - horiz) * self.front_embed text_embedding = (horiz) * self.side_embed + (90 - horiz) * self.front_embed
@@ -109,7 +114,6 @@ class PositionalTextEmbeddings:
text_embedding = text_embedding / 90.0 text_embedding = text_embedding / 90.0
text_embedding = (vert * text_embedding + (90 - vert) * self.top_embed) / 90.0 text_embedding = (vert * text_embedding + (90 - vert) * self.top_embed) / 90.0
else: else:
print("here")
text_embedding = self.base_embed text_embedding = self.base_embed
return text_embedding return text_embedding
+28 -8
View File
@@ -67,7 +67,10 @@ class DreamFusionModelConfig(ModelConfig):
_target: Type = field(default_factory=lambda: DreamFusionModel) _target: Type = field(default_factory=lambda: DreamFusionModel)
"""target class to instantiate""" """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 pineapple"
# prompt: str = "A DSLR photo of an orangutan making a clay bowl on a throwing wheel"
# prompt: str = "A DSLR photo of a tiger dressed as a doctor"
prompt: str = "a high quality photo of an all utility vehicle driving across a stream"
"""prompt for stable dreamfusion""" """prompt for stable dreamfusion"""
orientation_loss_mult: float = 0.0001 orientation_loss_mult: float = 0.0001
@@ -86,6 +89,7 @@ class DreamFusionModelConfig(ModelConfig):
"""Use spherical collider instead of box""" """Use spherical collider instead of box"""
random_background: bool = True random_background: bool = True
"""Randomly choose between using background mlp and random color for background""" """Randomly choose between using background mlp and random color for background"""
target_transmittance_start: float = 0.4 target_transmittance_start: float = 0.4
"""target transmittance for opacity penalty. This is the percent of the scene that is """target transmittance for opacity penalty. This is the percent of the scene that is
background when rendered at the start of training""" background when rendered at the start of training"""
@@ -94,6 +98,7 @@ class DreamFusionModelConfig(ModelConfig):
background when rendered at the end of training""" background when rendered at the end of training"""
transmittance_end_schedule: int = 1500 transmittance_end_schedule: int = 1500
"""number of iterations to reach target_transmittance_end""" """number of iterations to reach target_transmittance_end"""
num_proposal_samples_per_ray: Tuple[int, ...] = (256, 96) num_proposal_samples_per_ray: Tuple[int, ...] = (256, 96)
"""Number of samples per ray for each proposal network.""" """Number of samples per ray for each proposal network."""
num_nerf_samples_per_ray: int = 48 num_nerf_samples_per_ray: int = 48
@@ -148,7 +153,7 @@ class DreamFusionModelConfig(ModelConfig):
"""appended to prompt for front view""" """appended to prompt for front view"""
back_prompt: str = ", back view" back_prompt: str = ", back view"
"""appended to prompt for back view""" """appended to prompt for back view"""
guidance_scale: float = 100 guidance_scale: float = 20
"""guidance scale for sds loss""" """guidance scale for sds loss"""
stablediffusion_device: Optional[str] = None stablediffusion_device: Optional[str] = None
"""device for stable diffusion""" """device for stable diffusion"""
@@ -200,7 +205,7 @@ class DreamFusionModel(Model):
super().populate_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.df = DeepFloyd(self.sd_device) self._df = DeepFloyd(self.sd_device)
self.text_embeddings = PositionalTextEmbeddings( self.text_embeddings = PositionalTextEmbeddings(
base_prompt=self.cur_prompt, base_prompt=self.cur_prompt,
top_prompt=self.cur_prompt + self.top_prompt, top_prompt=self.cur_prompt + self.top_prompt,
@@ -208,7 +213,7 @@ class DreamFusionModel(Model):
back_prompt=self.cur_prompt + self.back_prompt, back_prompt=self.cur_prompt + self.back_prompt,
front_prompt=self.cur_prompt + self.front_prompt, front_prompt=self.cur_prompt + self.front_prompt,
# stable_diffusion=self.sd, # stable_diffusion=self.sd,
stable_diffusion=self.df, diffusion_model=self._df,
positional_prompting=self.positional_prompting, positional_prompting=self.positional_prompting,
) )
@@ -407,13 +412,28 @@ class DreamFusionModel(Model):
rgb=rgb, normals=normals, light_direction=light_d, shading_weight=shading_weight, detach_normals=False rgb=rgb, normals=normals, light_direction=light_d, shading_weight=shading_weight, detach_normals=False
) )
shaded, shaded_albedo = accum_mask * shaded, accum_mask * shaded_albedo
outputs["normals"] = self.shader_normals(normals, weights=accum_mask) outputs["normals"] = self.shader_normals(normals, weights=accum_mask)
outputs["pred_normals"] = self.shader_normals(pred_normals, weights=accum_mask) outputs["pred_normals"] = self.shader_normals(pred_normals, weights=accum_mask)
outputs["shaded"] = accum_mask * shaded outputs["shaded"] = shaded
outputs["other_train_output"] = accum_mask * shaded_albedo + background outputs["other_train_output"] = shaded_albedo + background
outputs["shaded_albedo"] = accum_mask * shaded_albedo outputs["shaded_albedo"] = shaded_albedo
outputs["rgb"] = accum_mask * rgb + background outputs["rgb"] = accum_mask * rgb + background
# while training 20% of the time use a random background
if np.random.random_sample() < 0.2 and self.random_background and self.training:
background = torch.ones_like(background) * torch.rand(3, device=self.device) * accum_mask_inv
if shading_weight > 0:
samp = np.random.random_sample()
if samp > 0.5:
outputs["train_output"] = outputs["shaded"]
else:
outputs["train_output"] = shaded_albedo + background
else:
outputs["train_output"] = accum_mask * rgb + background
if shading_weight > 0: if shading_weight > 0:
samp = np.random.random_sample() samp = np.random.random_sample()
if samp > 0.5 and not self.training: if samp > 0.5 and not self.training:
@@ -490,7 +510,7 @@ class DreamFusionModel(Model):
# grad_scaler=self.grad_scaler, # grad_scaler=self.grad_scaler,
# ) # )
sds_loss = self.df.sds_loss( sds_loss = self._df.sds_loss(
text_embedding.to(self.sd_device), text_embedding.to(self.sd_device),
train_output.to(self.sd_device), train_output.to(self.sd_device),
guidance_scale=int(self.guidance_scale), guidance_scale=int(self.guidance_scale),