From 57461f10eaa6b5225a33a26292178e4a4428f208 Mon Sep 17 00:00:00 2001 From: terrance Date: Thu, 23 Mar 2023 02:37:08 +0000 Subject: [PATCH] fixing data rendering / updating with SD --- nerfstudio/configs/method_configs.py | 32 +- .../datamanagers/iterative_datamanager.py | 24 +- .../generative/stable_diffusion_img2img.py | 434 ++++++++++++++++++ nerfstudio/pipelines/iterative_pipeline.py | 90 +++- 4 files changed, 558 insertions(+), 22 deletions(-) create mode 100644 nerfstudio/generative/stable_diffusion_img2img.py diff --git a/nerfstudio/configs/method_configs.py b/nerfstudio/configs/method_configs.py index cc5bada47..e2ff15ca9 100644 --- a/nerfstudio/configs/method_configs.py +++ b/nerfstudio/configs/method_configs.py @@ -32,6 +32,7 @@ from nerfstudio.data.datamanagers.dreamfusion_datamanager import ( ) from nerfstudio.data.datamanagers.sdf_datamanager import SDFDataManagerConfig from nerfstudio.data.datamanagers.semantic_datamanager import SemanticDataManagerConfig +from nerfstudio.data.datamanagers.iterative_datamanager import IterativeDataManagerConfig from nerfstudio.data.datamanagers.variable_res_datamanager import ( VariableResDataManagerConfig, ) @@ -68,6 +69,7 @@ from nerfstudio.models.tensorf import TensoRFModelConfig from nerfstudio.models.vanilla_nerf import NeRFModel, VanillaModelConfig from nerfstudio.pipelines.base_pipeline import VanillaPipelineConfig from nerfstudio.pipelines.dynamic_batch import DynamicBatchPipelineConfig +from nerfstudio.pipelines.iterative_pipeline import IterativePipelineConfig from nerfstudio.plugins.registry import discover_methods method_configs: Dict[str, TrainerConfig] = {} @@ -86,7 +88,7 @@ descriptions = { "dreamfusion": "Generative Text to NeRF model", "nerfplayer-nerfacto": "NeRFPlayer with nerfacto backbone.", "nerfplayer-ngp": "NeRFPlayer with InstantNGP backbone.", - "neus": "Implementation of NeuS. (slow)", + "neus": "Implementation of NeuS. (slow)" } method_configs["nerfacto"] = TrainerConfig( @@ -436,6 +438,34 @@ method_configs["dreamfusion"] = TrainerConfig( vis="viewer", ) +method_configs["iter_test"] = TrainerConfig( + method_name="iter_test", + experiment_name="iter_test", + steps_per_eval_batch=50, + steps_per_eval_image=50, + steps_per_save=200, + max_num_iterations=20000, + mixed_precision=True, + pipeline=IterativePipelineConfig( + generative=True, + datamanager=IterativeDataManagerConfig( + ), + model=NerfactoModelConfig(eval_num_rays_per_chunk=1 << 15), + ), + optimizers={ + "proposal_networks": { + "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": None, + }, + "fields": { + "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": None, + }, + }, + viewer=ViewerConfig(num_rays_per_chunk=1 << 15), + vis="viewer", +) + method_configs["dreamembed"] = TrainerConfig( method_name="dreamembed", experiment_name="dream-embed", diff --git a/nerfstudio/data/datamanagers/iterative_datamanager.py b/nerfstudio/data/datamanagers/iterative_datamanager.py index e33e582f4..514d35b49 100644 --- a/nerfstudio/data/datamanagers/iterative_datamanager.py +++ b/nerfstudio/data/datamanagers/iterative_datamanager.py @@ -21,12 +21,16 @@ from __future__ import annotations import sys from dataclasses import dataclass, field from typing import Dict, List, Tuple, Type, Union +from pathlib import Path +from copy import deepcopy import torch from rich.progress import Console from torch.nn import Parameter from typing_extensions import Literal +from nerfstudio.data.dataparsers.base_dataparser import DataparserOutputs + from nerfstudio.cameras.cameras import Cameras from nerfstudio.cameras.rays import RayBundle from nerfstudio.configs.config_utils import to_immutable_dict @@ -231,11 +235,23 @@ class IterativeDataManager(DataManager): # pylint: disable=abstract-method # pylint: disable=non-parent-init-called DataManager.__init__(self) - def render_train_dataset(self, step: int) -> InputDataset: + def create_dataset(self, filepaths: List[Path], cameras: Cameras): + dataparser_outputs = DataparserOutputs( + image_filenames=filepaths, + cameras=cameras, + scene_box=None, + mask_filenames=None, + dataparser_transform=None, + dataparser_scale=None, + metadata=None, + ) + return InputDataset(dataparser_outputs) + + def random_train_views(self, step: int, resolution:int, num_views: int) -> InputDataset: """eawoijfaw""" cameras, _, _ = random_train_pose( - size=10, - resolution=512, + size=num_views, + resolution=resolution, device= self.device, radius_mean=self.config.radius_mean, radius_std=self.config.radius_std, @@ -247,7 +263,7 @@ class IterativeDataManager(DataManager): # pylint: disable=abstract-method ) ray_bundle = cameras.generate_rays( - torch.tensor([[i] for i in range(self.config.train_images_per_batch)]) + torch.tensor([[i] for i in range(num_views)]) ).flatten() return ray_bundle, cameras diff --git a/nerfstudio/generative/stable_diffusion_img2img.py b/nerfstudio/generative/stable_diffusion_img2img.py new file mode 100644 index 000000000..0237adb96 --- /dev/null +++ b/nerfstudio/generative/stable_diffusion_img2img.py @@ -0,0 +1,434 @@ +# 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. + +"""Stable Diffusion helpers""" + +# 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 + +import appdirs +import mediapy +import numpy as np +import torch +import torch.nn.functional as F +import tyro +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 + +try: + from diffusers import PNDMScheduler, StableDiffusionPipeline + from transformers import logging + + SD_AVAILABLE = True + +except ImportError: + SD_AVAILABLE = False + +CONSOLE = Console(width=120) +IMG_DIM = 512 +CONST_SCALE = 0.18215 +SD_IDENTIFIERS = { + "1-5": "runwayml/stable-diffusion-v1-5", + "2-0": "stabilityai/stable-diffusion-2-base", + "2-1": "stabilityai/stable-diffusion-2-1-base", +} + + +@dataclass +class UNet2DConditionOutput: + """Class to hold traced model""" + + sample: torch.FloatTensor + + +class StableDiffusionImg2Img(nn.Module): + """Stable Diffusion Img2Img implementation + Args: + device: device to use + num_train_timesteps: number of training timesteps + """ + + def __init__(self, device: Union[torch.device, str], num_train_timesteps: int = 1000, version="1-5") -> None: + super().__init__() + + if not SD_AVAILABLE: + 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) + + logging.set_verbosity_error() + + self.device = device + self.num_train_timesteps = num_train_timesteps + + self.min_step = int(self.num_train_timesteps * 0.02) + self.max_step = int(self.num_train_timesteps * 0.98) + + self.scheduler = PNDMScheduler( + beta_start=0.00085, + beta_end=0.012, + beta_schedule="scaled_linear", + num_train_timesteps=self.num_train_timesteps, + ) + self.alphas = self.scheduler.alphas_cumprod.to(self.device) # type: ignore + + sd_id = SD_IDENTIFIERS[version] + pipe = StableDiffusionPipeline.from_pretrained(sd_id, torch_dtype=torch.float16) + print('SD Pipe Loaded') + assert pipe is not None + pipe = pipe.to(self.device) + + pipe.enable_attention_slicing() + pipe.enable_xformers_memory_efficient_attention() + + # use jitted unet + filename_sd_id = sd_id.split("/")[-1] + unet_traced_filename = Path(appdirs.user_data_dir("nerfstudio")) / f"{filename_sd_id}_unet_traced.pt" + if unet_traced_filename.exists(): + CONSOLE.print("Loading traced UNet.") + unet_traced = torch.jit.load(unet_traced_filename) + + class TracedUNet(torch.nn.Module): + """Jitted version of UNet""" + + def __init__(self): + super().__init__() + self.in_channels = pipe.unet.in_channels + self.device = pipe.unet.device + + def forward(self, latent_model_input, t, encoder_hidden_states): # pylint: disable=no-self-use + """Forward pass""" + sample = unet_traced(latent_model_input, t, encoder_hidden_states)[0] + return UNet2DConditionOutput(sample=sample) + + self.unet = TracedUNet() + del pipe.unet + + else: + CONSOLE.print("[bold yellow] Warning: Loading UNet without JIT acceleration.") + CONSOLE.print(f"Run [yellow]ns-trace-sd --sd-version {version} [/yellow] for a speedup!") + self.unet = pipe.unet + self.unet.to(memory_format=torch.channels_last) + + self.tokenizer = pipe.tokenizer + self.text_encoder = pipe.text_encoder + self.auto_encoder = pipe.vae + + CONSOLE.print("Stable Diffusion loaded!") + + def get_text_embeds( + self, prompt: Union[str, List[str]], negative_prompt: Union[str, List[str]] + ) -> TensorType[2, "max_length", "embed_dim"]: + """Get text embeddings for prompt and negative prompt + Args: + prompt: Prompt text + negative_prompt: Negative prompt text + Returns: + Text embeddings + """ + + # Tokenize text and get embeddings + text_input = self.tokenizer( + prompt, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + + with torch.no_grad(): + text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0] + + # Do the same for unconditional embeddings + uncond_input = self.tokenizer( + negative_prompt, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt" + ) + + with torch.no_grad(): + uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0] + + # Cat for final embeddings + text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) + + return text_embeddings + + def sds_loss_latent( + self, + text_embeddings: TensorType["N", "max_length", "embed_dim"], + latents: TensorType["BS", 3, "H", "W"], + guidance_scale: float = 100.0, + grad_scaler: Optional[GradScaler] = None, + ) -> torch.Tensor: + # Disable autocast when using diffusers pipeline. + with torch.autocast(device_type="cuda", enabled=False): + t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device) + latents = latents.half() + # predict the noise residual with unet, NO grad! + with torch.no_grad(): + # 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) + + # w(t), sigma_t^2 + w = 1 - self.alphas[t] + + grad = w * (noise_pred - noise) + grad = torch.nan_to_num(grad) + + if grad_scaler is not None: + latents = grad_scaler.scale(latents) + loss = _SDSGradient.apply(latents, grad) + + return loss + + def sds_loss( + 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: + """Score Distilation Sampling loss proposed in DreamFusion paper (https://dreamfusion3d.github.io/) + Args: + text_embeddings: Text embeddings + image: Rendered image + guidance_scale: How much to weigh the guidance + grad_scaler: Grad scaler + Returns: + The loss + """ + # Disable autocast when using diffusers pipeline. + 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) + + # predict the noise residual with unet, NO grad! + with torch.no_grad(): + # 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) + + # w(t), sigma_t^2 + w = 1 - self.alphas[t] + + grad = w * (noise_pred - noise) * 0.01 + grad = torch.nan_to_num(grad) + + if grad_scaler is not None: + latents = grad_scaler.scale(latents) + loss = _SDSGradient.apply(latents, grad) + + return loss + + def produce_latents( + self, + text_embeddings: TensorType["N", "max_length", "embed_dim"], + height: int = IMG_DIM, + width: int = IMG_DIM, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + latents: Optional[TensorType["BS", 4, "H", "W"]] = None, + ) -> TensorType["BS", 4, "H", "W"]: + """Produce latents for a given text embedding + Args: + text_embeddings: Text embeddings + height: Height of the image + width: Width of the image + num_inference_steps: Number of inference steps + guidance_scale: How much to weigh the guidance + latents: Latents to start with + Returns: + Latents + """ + + if latents is None: + latents = torch.randn( + (text_embeddings.shape[0] // 2, self.unet.in_channels, height // 8, width // 8), device=self.device + ) + + self.scheduler.set_timesteps(num_inference_steps) # type: ignore + + with torch.autocast("cuda"): + for t in self.scheduler.timesteps: # type: ignore + assert latents is not None + # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes. + latent_model_input = torch.cat([latents] * 2) + + # predict the noise residual + with torch.no_grad(): + noise_pred = self.unet( + latent_model_input, t.to(self.device), 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) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents)["prev_sample"] # type: ignore + return latents + + def latents_to_img(self, latents: TensorType["BS", 4, "H", "W"]) -> TensorType["BS", 3, "H", "W"]: + """Convert latents to images + Args: + latents: Latents to convert + Returns: + Images + """ + + latents = 1 / CONST_SCALE * latents + + with torch.no_grad(): + imgs = self.auto_encoder.decode(latents).sample + + imgs = (imgs / 2 + 0.5).clamp(0, 1) + + return imgs + + def imgs_to_latent(self, imgs: TensorType["BS", 3, "H", "W"]) -> TensorType["BS", 4, "H", "W"]: + """Convert images to latents + Args: + imgs: Images to convert + Returns: + Latents + """ + imgs = 2 * imgs - 1 + + posterior = self.auto_encoder.encode(imgs).latent_dist + latents = posterior.sample() * CONST_SCALE + + return latents + + def update_img(self, prompt, negative_prompt, image, num_inference_steps, guidance_scale): + prompt = [prompt] if isinstance(prompt, str) else prompt + negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt + text_embeddings = self.get_text_embeds(prompt, negative_prompt) + + # image = F.interpolate(image.half(), (IMG_DIM, IMG_DIM), mode="bilinear") + init_latents = self.imgs_to_latent(image.half()) + + latents = self.produce_latents( + text_embeddings, + height=IMG_DIM, + width=IMG_DIM, + latents=init_latents, + num_inference_steps=num_inference_steps, + guidance_scale=guidance_scale, + ) # [1, 4, resolution, resolution] + + diffused_img = self.latents_to_img(latents.half()) + # diffused_img = F.interpolate(diffused_img, (128, 128), mode="bilinear") + 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 + + return diffused_img + + def prompt_to_img( + self, + prompts: Union[str, List[str]], + negative_prompts: Union[str, List[str]] = "", + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + latents=None, + ) -> np.ndarray: + """Generate an images from a prompts. + Args: + prompts: The prompt to generate an image from. + negative_prompts: The negative prompt to generate an image from. + num_inference_steps: The number of inference steps to perform. + guidance_scale: The scale of the guidance. + latents: The latents to start from, defaults to random. + Returns: + The generated image. + """ + + prompts = [prompts] if isinstance(prompts, str) else prompts + negative_prompts = [negative_prompts] if isinstance(negative_prompts, str) else negative_prompts + text_embeddings = self.get_text_embeds(prompts, negative_prompts) + latents = self.produce_latents( + text_embeddings, + height=IMG_DIM, + width=IMG_DIM, + latents=latents, + num_inference_steps=num_inference_steps, + guidance_scale=guidance_scale, + ) # [1, 4, resolution, resolution] + + diffused_img = self.latents_to_img(latents.half()) + diffused_img = diffused_img.detach().cpu().permute(0, 2, 3, 1).numpy() + diffused_img = (diffused_img * 255).round().astype("uint8") + + return diffused_img + + def forward( + self, prompts, negative_prompts="", num_inference_steps=50, guidance_scale=7.5, latents=None + ) -> np.ndarray: + """Generate an image from a prompt. + Args: + prompts: The prompt to generate an image from. + negative_prompts: The negative prompt to generate an image from. + num_inference_steps: The number of inference steps to perform. + guidance_scale: The scale of the guidance. + latents: The latents to start from, defaults to random. + Returns: + The generated image. + """ + return self.prompt_to_img(prompts, negative_prompts, num_inference_steps, guidance_scale, latents) + + +def generate_image( + prompt: str, negative: str = "", seed: int = 0, steps: int = 50, save_path: Path = Path("test_sd.png") +): + """Generate an image from a prompt using Stable Diffusion. + Args: + prompt: The prompt to use. + negative: The negative prompt to use. + seed: The random seed to use. + steps: The number of steps to use. + save_path: The path to save the image to. + """ + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + cuda_device = torch.device("cuda") + with torch.no_grad(): + sd = StableDiffusion(cuda_device) + imgs = sd.prompt_to_img(prompt, negative, steps) + mediapy.write_image(str(save_path), imgs[0]) + + +if __name__ == "__main__": + tyro.cli(generate_image) diff --git a/nerfstudio/pipelines/iterative_pipeline.py b/nerfstudio/pipelines/iterative_pipeline.py index 200ba0831..933eb81f5 100644 --- a/nerfstudio/pipelines/iterative_pipeline.py +++ b/nerfstudio/pipelines/iterative_pipeline.py @@ -17,7 +17,7 @@ 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, Union, cast +from typing import Any, Dict, List, Mapping, Optional, Type, cast from pathlib import Path, PurePath @@ -31,16 +31,17 @@ import mediapy from nerfstudio.data.datamanagers.base_datamanager import ( DataManager, DataManagerConfig, - VanillaDataManager, - VanillaDataManagerConfig, ) +from nerfstudio.generative.stable_diffusion_img2img import StableDiffusionImg2Img + from nerfstudio.data.datamanagers.iterative_datamanager import IterativeDataManager, IterativeDataManagerConfig 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): @@ -52,9 +53,11 @@ class IterativePipelineConfig(VanillaPipelineConfig): """specifies the datamanager config""" model: ModelConfig = ModelConfig() """specifies the model config""" - generative: bool = False + generative: bool = True """specifies whether the pipeline is for generative models""" - temp_save_path: Path= PurePath("") + temp_save_path: Path=PurePath("") + """save path for generated dataset""" + prompt: str="a pineapple" class IterativePipeline(VanillaPipeline): """Pipeline with logic for saving outputs from nerf for use as training images.""" @@ -68,12 +71,16 @@ class IterativePipeline(VanillaPipeline): local_rank: int = 0, grad_scaler: Optional[GradScaler] = None, ): - super().__init__() + super().__init__(config, device, test_mode, world_size, local_rank) self.temp_save_path = config.temp_save_path self.datamanager: IterativeDataManager = config.datamanager.setup( device=device, test_mode=test_mode, world_size=world_size, local_rank=local_rank ) - self.train_img_cameras = [] + self.train_dataset = None + sd_version = "1-5" + self.prompt = config.prompt + self.sd = StableDiffusionImg2Img(self.device, version=sd_version) + def forward(self): """Blank forward method @@ -82,19 +89,68 @@ class IterativePipeline(VanillaPipeline): we do not need a forward() method""" raise NotImplementedError - def save_new_train_images(self): - ray_bundle, cameras = self.datamanager.render_train_dataset() - model_outputs = self.model(ray_bundle) - imgs = model_outputs.reshape() # something - + @torch.no_grad() + def save_new_train_images(self, step: int): + print("saving training images") + num_images_per_train = 5 + resolution = 512 + ray_bundles, cameras = self.datamanager.random_train_views(step, resolution=resolution, num_views=num_images_per_train) train_img_paths = [] - for i in range(10): - img = imgs[i] - save_path = PurePath(self.temp_save_path, f"img_{i}") - train_img_paths.append(save_path) + num_rays_per_chunk = 512 + + self.model.eval() + + for i in range(num_images_per_train): + total_rgb = [] + for j in range(0, resolution * resolution, num_rays_per_chunk): + start_idx = (i * resolution * resolution) + j + end_idx = (i * resolution * resolution) + j + num_rays_per_chunk + + ray_bundle = ray_bundles.get_row_major_sliced_ray_bundle(start_idx, end_idx) + outputs = self.model(ray_bundle) + total_rgb.append(outputs['rgb']) + + img = torch.cat(total_rgb).reshape(resolution, resolution, 3).detach().cpu().numpy() # something + save_path = PurePath(self.temp_save_path, f"img_{i}.png") + train_img_paths.append(str(save_path)) mediapy.write_image(str(save_path), img) + self.train_dataset = self.datamanager.create_dataset(train_img_paths, cameras) + + @torch.no_grad() + def update_train_images(self): + print("updating training images") + for i in range(len(self.train_dataset)): + # for i in range(1): + image = self.train_dataset.get_image(i)[None, :, :, :].permute(0, 3, 1, 2).to(self.sd.device) + print(i) + image = self.sd.update_img(self.prompt, "", image, num_inference_steps=50, guidance_scale=7.5) + mediapy.write_image(self.train_dataset.image_filenames[i], image) + del image + @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 + + if step == 0: + self.save_new_train_images(step) + + # snapshot1 = tracemalloc.take_snapshot() + + if step % 20 == 0: + self.update_train_images() + + # snapshot2 = tracemalloc.take_snapshot() + # top_stats = snapshot2.compare_to(snapshot1, 'lineno') + + # print("[ Top 10 differences ]") + # for stat in top_stats[:10]: + # print(stat) + + raise Exception + return \ No newline at end of file