Run this model with HF Jobs
Run SumantBobade/Image_To_3D_Generator on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/SumantBobade/Image_To_3D_Generator. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/SumantBobade/Image_To_3D_Generator on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use SumantBobade/Image_To_3D_Generator with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use SumantBobade/Image_To_3D_Generator with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("SumantBobade/Image_To_3D_Generator", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
reformat, further clean
Browse filesFiles changed (6)
- convert_mvdream_to_diffusers.py+203-53
- main.py+15-8
- mvdream/attention.py+181-62
- mvdream/models.py+249-226
- mvdream/pipeline_mvdream.py+152-70
- mvdream/util.py+10-9
3 unmodified lines456789104 unmodified lines15161718192021222324252627282930313233346 unmodified lines414243444546474 unmodified lines525354555657586 unmodified lines6566676869707150 unmodified lines1221231241251261271281291301311321331341351361371381 unmodified line1401411421431441451461471481491501511521531541551561571581591601611622 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881892 unmodified lines1921931941951961971981992002012022037 unmodified lines21121221321421521621723 unmodified lines24124224324424524624711 unmodified lines2592602612622632642652664 unmodified lines27127227327427527627719 unmodified lines2972982993003013023033043053061 unmodified line3083093103113123133143153163174 unmodified lines3223233243253263273283293303313323333349 unmodified lines3443453463473483493505 unmodified lines3563573583593603613623633643653663673686 unmodified lines3753763773783793803816 unmodified lines3883893903913923933943953963973 unmodified lines4014024034044054064073 unmodified linesimport torchimport syssys.path.insert(0, '.')from diffusers.models import (AutoencoderKL,4 unmodified linesfrom typing import Anyfrom accelerate import init_empty_weightsfrom accelerate.utils import set_module_tensor_to_devicefrom mvdream.models import MultiViewUNetWrapperModelfrom mvdream.pipeline_mvdream import MVDreamStableDiffusionPipelinefrom transformers import CLIPTokenizer, CLIPTextModellogger = logging.get_logger(__name__)def assign_to_checkpoint(paths, checkpoint, old_checkpoint, attention_paths_to_split=None, additional_replacements=None, config=None):"""This does the final conversion step: take locally converted weights and apply a global renaming to them. It splitsattention layers, and takes into account additional replacements that may arise.Assigns the weights to the new checkpoint."""assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."# Splits the attention layers into three variables.if attention_paths_to_split is not None:6 unmodified linesassert config is not Nonenum_heads = old_tensor.shape[0] // config["num_head_channels"] // 3old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])query, key, value = old_tensor.split(channels // num_heads, dim=1)checkpoint[path_map["query"]] = query.reshape(target_shape)4 unmodified linesnew_path = path["new"]# These have already been assignedif attention_paths_to_split is not None and new_path in attention_paths_to_split:continue# Global renaming happens here6 unmodified linesnew_path = new_path.replace(replacement["old"], replacement["new"])# proj_attn.weight has to be converted from conv 1D to linearis_attn_weight = "proj_attn.weight" in new_path or ("attentions" in new_path and "to_" in new_path)shape = old_checkpoint[path["old"]].shapeif is_attn_weight and len(shape) == 3:checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]50 unmodified linesnew_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]1 unmodified linenew_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]# Retrieves the keys for the encoder down blocks onlynum_down_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "encoder.down" in layer})down_blocks = {layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)}# Retrieves the keys for the decoder up blocks onlynum_up_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "decoder.up" in layer})up_blocks = {layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)}for i in range(num_down_blocks):resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(f"encoder.down.{i}.downsample.conv.weight")new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(f"encoder.down.{i}.downsample.conv.bias")paths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]num_mid_res_blocks = 22 unmodified linespaths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]paths = renew_vae_attention_paths(mid_attentions)meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)conv_attn_to_linear(new_checkpoint)for i in range(num_up_blocks):block_id = num_up_blocks - 1 - iresnets = [key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key]if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[f"decoder.up.{block_id}.upsample.conv.weight"]new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[f"decoder.up.{block_id}.upsample.conv.bias"]paths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]num_mid_res_blocks = 22 unmodified linespaths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]paths = renew_vae_attention_paths(mid_attentions)meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)conv_attn_to_linear(new_checkpoint)return new_checkpoint7 unmodified linesnew_item = old_itemnew_item = new_item.replace("nin_shortcut", "conv_shortcut")new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)mapping.append({"old": old_item, "new": new_item})23 unmodified linesnew_item = new_item.replace("proj_out.weight", "to_out.0.weight")new_item = new_item.replace("proj_out.bias", "to_out.0.bias")new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)mapping.append({"old": old_item, "new": new_item})11 unmodified linesif checkpoint[key].ndim > 2:checkpoint[key] = checkpoint[key][:, :, 0]def create_unet_config(original_config) -> Any:return OmegaConf.to_container(original_config.model.params.unet_config.params, resolve=True)def convert_from_original_mvdream_ckpt(checkpoint_path, original_config_file, device):checkpoint = torch.load(checkpoint_path, map_location=device)4 unmodified lines# print(f"Original Config: {original_config}")prediction_type = "epsilon"image_size = 256num_train_timesteps = getattr(original_config.model.params, "timesteps", None) or 1000beta_start = getattr(original_config.model.params, "linear_start", None) or 0.02beta_end = getattr(original_config.model.params, "linear_end", None) or 0.085scheduler = DDIMScheduler(19 unmodified lines# )# print(f"Unet Config: {original_config.model.params.unet_config.params}")unet_config = create_unet_config(original_config)unet: MultiViewUNetWrapperModel = MultiViewUNetWrapperModel(**unet_config)unet.register_to_config(**unet_config)# print(f"Unet State Dict: {unet.state_dict().keys()}")unet.load_state_dict({key.replace("model.diffusion_model.", "unet."): value for key, value in checkpoint.items() if key.replace("model.diffusion_model.", "unet.") in unet.state_dict()})for param_name, param in unet.state_dict().items():set_module_tensor_to_device(unet, param_name, device=device, value=param)1 unmodified linevae_config = create_vae_diffusers_config(original_config, image_size=image_size)converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)if ("model" in original_config and "params" in original_config.model and "scale_factor" in original_config.model.params):vae_scaling_factor = original_config.model.params.scale_factorelse:vae_scaling_factor = 0.18215 # default SD scaling factorvae_config["scaling_factor"] = vae_scaling_factor4 unmodified linesset_module_tensor_to_device(vae, param_name, device=device, value=param)if original_config.model.params.unet_config.params.context_dim == 768:tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")text_encoder: CLIPTextModel = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").to(device=device) # type: ignoreelif original_config.model.params.unet_config.params.context_dim == 1024:tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="tokenizer")text_encoder: CLIPTextModel = CLIPTextModel.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="text_encoder").to(device=device) # type: ignoreelse:raise ValueError(f"Unknown context_dim: {original_config.model.paams.unet_config.params.context_dim}")pipe = MVDreamStableDiffusionPipeline(vae=vae,9 unmodified linesif __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert.")parser.add_argument("--original_config_file",default=None,5 unmodified linesaction="store_true",help="Whether to store pipeline in safetensors format or not.",)parser.add_argument("--half", action="store_true", help="Save weights in half precision.")parser.add_argument("--test", action="store_true", help="Whether to test inference after convertion.")parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")args = parser.parse_args()args.device = torch.device(args.device if args.device is not None else "cuda" if torch.cuda.is_available() else "cpu")pipe = convert_from_original_mvdream_ckpt(checkpoint_path=args.checkpoint_path,6 unmodified linesprint(f"Saving pipeline to {args.dump_path}...")pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)if args.test:try:print(f"Testing each subcomponent of the pipeline...")6 unmodified linesdevice=args.device,)for i, image in enumerate(images):image.save(f"image_{i}.png") # type: ignoreprint(f"Testing entire pipeline...")loaded_pipe: MVDreamStableDiffusionPipeline = MVDreamStableDiffusionPipeline.from_pretrained(args.dump_path, safe_serialization=args.to_safetensors) # type: ignoreimages = loaded_pipe(prompt="Head of Hatsune Miku",negative_prompt="painting, bad quality, flat",3 unmodified linesdevice=args.device,)for i, image in enumerate(images):image.save(f"image_{i}.png") # type: ignoreexcept Exception as e:print(f"Failed to test inference: {e}")raise e from e3 unmodified lines456789104 unmodified lines15161718192021222324252627282930313233343536373839404142436 unmodified lines5051525354555657584 unmodified lines636465666768697071726 unmodified lines79808182838485868750 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661 unmodified line1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752 unmodified lines2782792802812822832842852862872882892902912922932942952962972982993003017 unmodified lines30931031131231331431531631723 unmodified lines34134234334434534634734834911 unmodified lines3613623633643653663673683693703713724 unmodified lines37737837938038138238338438519 unmodified lines4054064074084094104114124134144154164174184194201 unmodified line4224234244254264274284294304314324334344354 unmodified lines4404414424434444454464474484494504514524534544554564574589 unmodified lines4684694704714724734744754764774784794805 unmodified lines4864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175186 unmodified lines5255265275285295305316 unmodified lines5385395405415425435445455465473 unmodified lines5515525535545555565573 unmodified linesimport torchimport syssys.path.insert(0, ".")from diffusers.models import (AutoencoderKL,4 unmodified linesfrom typing import Anyfrom accelerate import init_empty_weightsfrom accelerate.utils import set_module_tensor_to_devicefrom mvdream.models import MultiViewUNetModelfrom mvdream.pipeline_mvdream import MVDreamStableDiffusionPipelinefrom transformers import CLIPTokenizer, CLIPTextModellogger = logging.get_logger(__name__)def assign_to_checkpoint(paths,checkpoint,old_checkpoint,attention_paths_to_split=None,additional_replacements=None,config=None,):"""This does the final conversion step: take locally converted weights and apply a global renaming to them. It splitsattention layers, and takes into account additional replacements that may arise.Assigns the weights to the new checkpoint."""assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."# Splits the attention layers into three variables.if attention_paths_to_split is not None:6 unmodified linesassert config is not Nonenum_heads = old_tensor.shape[0] // config["num_head_channels"] // 3old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])query, key, value = old_tensor.split(channels // num_heads, dim=1)checkpoint[path_map["query"]] = query.reshape(target_shape)4 unmodified linesnew_path = path["new"]# These have already been assignedif (attention_paths_to_split is not Noneand new_path in attention_paths_to_split):continue# Global renaming happens here6 unmodified linesnew_path = new_path.replace(replacement["old"], replacement["new"])# proj_attn.weight has to be converted from conv 1D to linearis_attn_weight = "proj_attn.weight" in new_path or ("attentions" in new_path and "to_" in new_path)shape = old_checkpoint[path["old"]].shapeif is_attn_weight and len(shape) == 3:checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]50 unmodified linesnew_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]1 unmodified linenew_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]# Retrieves the keys for the encoder down blocks onlynum_down_blocks = len({".".join(layer.split(".")[:3])for layer in vae_state_dictif "encoder.down" in layer})down_blocks = {layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key]for layer_id in range(num_down_blocks)}# Retrieves the keys for the decoder up blocks onlynum_up_blocks = len({".".join(layer.split(".")[:3])for layer in vae_state_dictif "decoder.up" in layer})up_blocks = {layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key]for layer_id in range(num_up_blocks)}for i in range(num_down_blocks):resnets = [keyfor key in down_blocks[i]if f"down.{i}" in key and f"down.{i}.downsample" not in key]if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(f"encoder.down.{i}.downsample.conv.weight")new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(f"encoder.down.{i}.downsample.conv.bias")paths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}assign_to_checkpoint(paths,new_checkpoint,vae_state_dict,additional_replacements=[meta_path],config=config,)mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]num_mid_res_blocks = 22 unmodified linespaths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}assign_to_checkpoint(paths,new_checkpoint,vae_state_dict,additional_replacements=[meta_path],config=config,)mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]paths = renew_vae_attention_paths(mid_attentions)meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}assign_to_checkpoint(paths,new_checkpoint,vae_state_dict,additional_replacements=[meta_path],config=config,)conv_attn_to_linear(new_checkpoint)for i in range(num_up_blocks):block_id = num_up_blocks - 1 - iresnets = [keyfor key in up_blocks[block_id]if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key]if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[f"decoder.up.{block_id}.upsample.conv.weight"]new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[f"decoder.up.{block_id}.upsample.conv.bias"]paths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}assign_to_checkpoint(paths,new_checkpoint,vae_state_dict,additional_replacements=[meta_path],config=config,)mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]num_mid_res_blocks = 22 unmodified linespaths = renew_vae_resnet_paths(resnets)meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}assign_to_checkpoint(paths,new_checkpoint,vae_state_dict,additional_replacements=[meta_path],config=config,)mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]paths = renew_vae_attention_paths(mid_attentions)meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}assign_to_checkpoint(paths,new_checkpoint,vae_state_dict,additional_replacements=[meta_path],config=config,)conv_attn_to_linear(new_checkpoint)return new_checkpoint7 unmodified linesnew_item = old_itemnew_item = new_item.replace("nin_shortcut", "conv_shortcut")new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)mapping.append({"old": old_item, "new": new_item})23 unmodified linesnew_item = new_item.replace("proj_out.weight", "to_out.0.weight")new_item = new_item.replace("proj_out.bias", "to_out.0.bias")new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)mapping.append({"old": old_item, "new": new_item})11 unmodified linesif checkpoint[key].ndim > 2:checkpoint[key] = checkpoint[key][:, :, 0]def create_unet_config(original_config) -> Any:return OmegaConf.to_container(original_config.model.params.unet_config.params, resolve=True)def convert_from_original_mvdream_ckpt(checkpoint_path, original_config_file, device):checkpoint = torch.load(checkpoint_path, map_location=device)4 unmodified lines# print(f"Original Config: {original_config}")prediction_type = "epsilon"image_size = 256num_train_timesteps = (getattr(original_config.model.params, "timesteps", None) or 1000)beta_start = getattr(original_config.model.params, "linear_start", None) or 0.02beta_end = getattr(original_config.model.params, "linear_end", None) or 0.085scheduler = DDIMScheduler(19 unmodified lines# )# print(f"Unet Config: {original_config.model.params.unet_config.params}")unet_config = create_unet_config(original_config)unet = MultiViewUNetModel(**unet_config)unet.register_to_config(**unet_config)# print(f"Unet State Dict: {unet.state_dict().keys()}")unet.load_state_dict({key.replace("model.diffusion_model.", ""): valuefor key, value in checkpoint.items()if key.replace("model.diffusion_model.", "") in unet.state_dict()})for param_name, param in unet.state_dict().items():set_module_tensor_to_device(unet, param_name, device=device, value=param)1 unmodified linevae_config = create_vae_diffusers_config(original_config, image_size=image_size)converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)if ("model" in original_configand "params" in original_config.modeland "scale_factor" in original_config.model.params):vae_scaling_factor = original_config.model.params.scale_factorelse:vae_scaling_factor = 0.18215 # default SD scaling factorvae_config["scaling_factor"] = vae_scaling_factor4 unmodified linesset_module_tensor_to_device(vae, param_name, device=device, value=param)if original_config.model.params.unet_config.params.context_dim == 768:tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")text_encoder: CLIPTextModel = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").to(device=device) # type: ignoreelif original_config.model.params.unet_config.params.context_dim == 1024:tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="tokenizer")text_encoder: CLIPTextModel = CLIPTextModel.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="text_encoder").to(device=device) # type: ignoreelse:raise ValueError(f"Unknown context_dim: {original_config.model.paams.unet_config.params.context_dim}")pipe = MVDreamStableDiffusionPipeline(vae=vae,9 unmodified linesif __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("--checkpoint_path",default=None,type=str,required=True,help="Path to the checkpoint to convert.",)parser.add_argument("--original_config_file",default=None,5 unmodified linesaction="store_true",help="Whether to store pipeline in safetensors format or not.",)parser.add_argument("--half", action="store_true", help="Save weights in half precision.")parser.add_argument("--test",action="store_true",help="Whether to test inference after convertion.",)parser.add_argument("--dump_path",default=None,type=str,required=True,help="Path to the output model.",)parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")args = parser.parse_args()args.device = torch.device(args.deviceif args.device is not Noneelse "cuda"if torch.cuda.is_available()else "cpu")pipe = convert_from_original_mvdream_ckpt(checkpoint_path=args.checkpoint_path,6 unmodified linesprint(f"Saving pipeline to {args.dump_path}...")pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)if args.test:try:print(f"Testing each subcomponent of the pipeline...")6 unmodified linesdevice=args.device,)for i, image in enumerate(images):image.save(f"image_{i}.png") # type: ignoreprint(f"Testing entire pipeline...")loaded_pipe: MVDreamStableDiffusionPipeline = MVDreamStableDiffusionPipeline.from_pretrained(args.dump_path, safe_serialization=args.to_safetensors) # type: ignoreimages = loaded_pipe(prompt="Head of Hatsune Miku",negative_prompt="painting, bad quality, flat",3 unmodified linesdevice=args.device,)for i, image in enumerate(images):image.save(f"image_{i}.png") # type: ignoreexcept Exception as e:print(f"Failed to test inference: {e}")raise e from e
3 unmodified lines4567891011121314151617181920213 unmodified linesimport argparsefrom mvdream.pipeline_mvdream import MVDreamStableDiffusionPipelinepipe = MVDreamStableDiffusionPipeline.from_pretrained('./weights', torch_dtype=torch.float16)pipe = pipe.to("cuda")parser = argparse.ArgumentParser(description='MVDream')parser.add_argument('prompt', type=str, default="a cute owl 3d model")args = parser.parse_args()while True:image = pipe(args.prompt)grid = np.concatenate([np.concatenate([image[0], image[2]], axis=0),np.concatenate([image[1], image[3]], axis=0),], axis=1)kiui.vis.plot_image(grid)3 unmodified lines456789101112131415161718192021222324252627283 unmodified linesimport argparsefrom mvdream.pipeline_mvdream import MVDreamStableDiffusionPipelinepipe = MVDreamStableDiffusionPipeline.from_pretrained(# "./weights", # local weights"ashawkey/mvdream-sd2.1-diffusers",torch_dtype=torch.float16)pipe = pipe.to("cuda")parser = argparse.ArgumentParser(description="MVDream")parser.add_argument("prompt", type=str, default="a cute owl 3d model")args = parser.parse_args()while True:image = pipe(args.prompt)grid = np.concatenate([np.concatenate([image[0], image[2]], axis=0),np.concatenate([image[1], image[3]], axis=0),],axis=1,)kiui.vis.plot_image(grid)
11 unmodified lines121314151617181927 unmodified lines474849505152534 unmodified lines58596061626364656667686970719 unmodified lines818283848586878889909192939495969798991004 unmodified lines1051061071081091101111121131141151161171181191201211221231241251261271281291305 unmodified lines1361371381391401411423 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317412 unmodified lines1871881891901911921934 unmodified lines1981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402419 unmodified lines2512522532542552562572 unmodified lines2602612622632642652662672682692702712727 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013023033043053061 unmodified line3083093103113123133143153162 unmodified lines3193203213223233243253263273283293303317 unmodified lines33934034134234334434534634734834935035135211 unmodified linesfrom .util import checkpointtry:import xformers # type: ignoreimport xformers.ops # type: ignoreXFORMERS_IS_AVAILBLE = Trueexcept:XFORMERS_IS_AVAILBLE = False27 unmodified lines# feedforwardclass GEGLU(nn.Module):def __init__(self, dim_in, dim_out):super().__init__()self.proj = nn.Linear(dim_in, dim_out * 2)4 unmodified linesclass FeedForward(nn.Module):def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):super().__init__()inner_dim = int(dim * mult)dim_out = default(dim_out, dim)project_in = nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) if not glu else GEGLU(dim, inner_dim)self.net = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))def forward(self, x):return self.net(x)9 unmodified linesdef Normalize(in_channels):return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)class SpatialSelfAttention(nn.Module):def __init__(self, in_channels):super().__init__()self.in_channels = in_channelsself.norm = Normalize(in_channels)self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)def forward(self, x):h_ = x4 unmodified lines# compute attentionb, c, h, w = q.shapeq = rearrange(q, 'b c h w -> b (h w) c')k = rearrange(k, 'b c h w -> b c (h w)')w_ = torch.einsum('bij,bjk->bik', q, k)w_ = w_ * (int(c)**(-0.5))w_ = torch.nn.functional.softmax(w_, dim=2)# attend to valuesv = rearrange(v, 'b c h w -> b c (h w)')w_ = rearrange(w_, 'b i j -> b j i')h_ = torch.einsum('bij,bjk->bik', v, w_)h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)h_ = self.proj_out(h_)return x + h_class CrossAttention(nn.Module):def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):super().__init__()inner_dim = dim_head * headscontext_dim = default(context_dim, query_dim)5 unmodified linesself.to_k = nn.Linear(context_dim, inner_dim, bias=False)self.to_v = nn.Linear(context_dim, inner_dim, bias=False)self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))def forward(self, x, context=None, mask=None):h = self.heads3 unmodified linesk = self.to_k(context)v = self.to_v(context)q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))# force cast to fp32 to avoid overflowingif _ATTN_PRECISION == "fp32":with autocast(enabled=False, device_type='cuda'):q, k = q.float(), k.float()sim = einsum('b i d, b j d -> b i j', q, k) * self.scaleelse:sim = einsum('b i d, b j d -> b i j', q, k) * self.scaledel q, kif mask is not None:mask = rearrange(mask, 'b ... -> b (...)')max_neg_value = -torch.finfo(sim.dtype).maxmask = repeat(mask, 'b j -> (b h) () j', h=h)sim.masked_fill_(~mask, max_neg_value)# attention, what we cannot get enough ofsim = sim.softmax(dim=-1)out = einsum('b i j, b j d -> b i d', sim, v)out = rearrange(out, '(b h) n d -> b n (h d)', h=h)return self.to_out(out)12 unmodified linesself.to_k = nn.Linear(context_dim, inner_dim, bias=False)self.to_v = nn.Linear(context_dim, inner_dim, bias=False)self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))self.attention_op: Optional[Any] = Nonedef forward(self, x, context=None, mask=None):4 unmodified linesb, _, _ = q.shapeq, k, v = map(lambda t: t.unsqueeze(3).reshape(b, t.shape[1], self.heads, self.dim_head).permute(0, 2, 1, 3).reshape(b * self.heads, t.shape[1], self.dim_head).contiguous(),(q, k, v),)# actually compute the attention, what we cannot get enough ofout = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)if mask is not None:raise NotImplementedErrorout = (out.unsqueeze(0).reshape(b, self.heads, out.shape[1], self.dim_head).permute(0, 2, 1, 3).reshape(b, out.shape[1], self.heads * self.dim_head))return self.to_out(out)class BasicTransformerBlock(nn.Module):ATTENTION_MODES = {"softmax": CrossAttention, # vanilla attention"softmax-xformers": MemoryEfficientCrossAttention}def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True, disable_self_attn=False):super().__init__()attn_mode = "softmax-xformers" if XFORMERS_IS_AVAILBLE else "softmax"assert attn_mode in self.ATTENTION_MODESattn_cls = self.ATTENTION_MODES[attn_mode]self.disable_self_attn = disable_self_attnself.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout, context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attnself.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim, heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is noneself.norm1 = nn.LayerNorm(dim)self.norm2 = nn.LayerNorm(dim)self.norm3 = nn.LayerNorm(dim)self.checkpoint = checkpointdef forward(self, x, context=None):return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)def _forward(self, x, context=None):x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + xx = self.attn2(self.norm2(x), context=context) + xx = self.ff(self.norm3(x)) + xreturn x9 unmodified linesNEW: use_linear for more efficiency instead of the 1x1 convs"""def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None, disable_self_attn=False, use_linear=False, use_checkpoint=True):super().__init__()assert context_dim is not Noneif not isinstance(context_dim, list):2 unmodified linesinner_dim = n_heads * d_headself.norm = Normalize(in_channels)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)else:self.proj_in = nn.Linear(in_channels, inner_dim)self.transformer_blocks = nn.ModuleList([BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d], disable_self_attn=disable_self_attn, checkpoint=use_checkpoint) for d in range(depth)])if not use_linear:self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))else:self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))self.use_linear = use_linear7 unmodified linesx = self.norm(x)if not self.use_linear:x = self.proj_in(x)x = rearrange(x, 'b c h w -> b (h w) c').contiguous()if self.use_linear:x = self.proj_in(x)for i, block in enumerate(self.transformer_blocks):x = block(x, context=context[i])if self.use_linear:x = self.proj_out(x)x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()if not self.use_linear:x = self.proj_out(x)return x + x_inclass BasicTransformerBlock3D(BasicTransformerBlock):def forward(self, x, context=None, num_frames=1):return checkpoint(self._forward, (x, context, num_frames), self.parameters(), self.checkpoint)def _forward(self, x, context=None, num_frames=1):x = rearrange(x, "(b f) l c -> b (f l) c", f=num_frames).contiguous()x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + xx = rearrange(x, "b (f l) c -> (b f) l c", f=num_frames).contiguous()x = self.attn2(self.norm2(x), context=context) + xx = self.ff(self.norm3(x)) + x1 unmodified lineclass SpatialTransformer3D(nn.Module):''' 3D self-attention '''def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None, disable_self_attn=False, use_linear=False, use_checkpoint=True):super().__init__()assert context_dim is not Noneif not isinstance(context_dim, list):2 unmodified linesinner_dim = n_heads * d_headself.norm = Normalize(in_channels)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)else:self.proj_in = nn.Linear(in_channels, inner_dim)self.transformer_blocks = nn.ModuleList([BasicTransformerBlock3D(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d], disable_self_attn=disable_self_attn, checkpoint=use_checkpoint) for d in range(depth)])if not use_linear:self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))else:self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))self.use_linear = use_linear7 unmodified linesx = self.norm(x)if not self.use_linear:x = self.proj_in(x)x = rearrange(x, 'b c h w -> b (h w) c').contiguous()if self.use_linear:x = self.proj_in(x)for i, block in enumerate(self.transformer_blocks):x = block(x, context=context[i], num_frames=num_frames)if self.use_linear:x = self.proj_out(x)x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()if not self.use_linear:x = self.proj_out(x)return x + x_in11 unmodified lines12131415161718192027 unmodified lines4849505152534 unmodified lines585960616263646566676869707172737475769 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131144 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421435 unmodified lines1491501511521531541551561573 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518618718818912 unmodified lines2022032042052062072082092104 unmodified lines2152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972989 unmodified lines3083093103113123133143153163173183193203213223233243252 unmodified lines3283293303313323333343353363373383393403413423433443453463473483493503513523533543553563577 unmodified lines3653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963971 unmodified line3994004014024034044054064074084094104114124134144154164174182 unmodified lines4214224234244254264274284294304314324334344354364374384394404414424434444454464474484494507 unmodified lines45845946046146246346446546646746846947047111 unmodified linesfrom .util import checkpointtry:import xformers # type: ignoreimport xformers.ops # type: ignoreXFORMERS_IS_AVAILBLE = Trueexcept:XFORMERS_IS_AVAILBLE = False27 unmodified lines# feedforwardclass GEGLU(nn.Module):def __init__(self, dim_in, dim_out):super().__init__()self.proj = nn.Linear(dim_in, dim_out * 2)4 unmodified linesclass FeedForward(nn.Module):def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0):super().__init__()inner_dim = int(dim * mult)dim_out = default(dim_out, dim)project_in = (nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU())if not gluelse GEGLU(dim, inner_dim))self.net = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))def forward(self, x):return self.net(x)9 unmodified linesdef Normalize(in_channels):return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)class SpatialSelfAttention(nn.Module):def __init__(self, in_channels):super().__init__()self.in_channels = in_channelsself.norm = Normalize(in_channels)self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)def forward(self, x):h_ = x4 unmodified lines# compute attentionb, c, h, w = q.shapeq = rearrange(q, "b c h w -> b (h w) c")k = rearrange(k, "b c h w -> b c (h w)")w_ = torch.einsum("bij,bjk->bik", q, k)w_ = w_ * (int(c) ** (-0.5))w_ = torch.nn.functional.softmax(w_, dim=2)# attend to valuesv = rearrange(v, "b c h w -> b c (h w)")w_ = rearrange(w_, "b i j -> b j i")h_ = torch.einsum("bij,bjk->bik", v, w_)h_ = rearrange(h_, "b c (h w) -> b c h w", h=h)h_ = self.proj_out(h_)return x + h_class CrossAttention(nn.Module):def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):super().__init__()inner_dim = dim_head * headscontext_dim = default(context_dim, query_dim)5 unmodified linesself.to_k = nn.Linear(context_dim, inner_dim, bias=False)self.to_v = nn.Linear(context_dim, inner_dim, bias=False)self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))def forward(self, x, context=None, mask=None):h = self.heads3 unmodified linesk = self.to_k(context)v = self.to_v(context)q, k, v = map(lambda t: rearrange(t, "b n (h d) -> (b h) n d", h=h), (q, k, v))# force cast to fp32 to avoid overflowingif _ATTN_PRECISION == "fp32":with autocast(enabled=False, device_type="cuda"):q, k = q.float(), k.float()sim = einsum("b i d, b j d -> b i j", q, k) * self.scaleelse:sim = einsum("b i d, b j d -> b i j", q, k) * self.scaledel q, kif mask is not None:mask = rearrange(mask, "b ... -> b (...)")max_neg_value = -torch.finfo(sim.dtype).maxmask = repeat(mask, "b j -> (b h) () j", h=h)sim.masked_fill_(~mask, max_neg_value)# attention, what we cannot get enough ofsim = sim.softmax(dim=-1)out = einsum("b i j, b j d -> b i d", sim, v)out = rearrange(out, "(b h) n d -> b n (h d)", h=h)return self.to_out(out)12 unmodified linesself.to_k = nn.Linear(context_dim, inner_dim, bias=False)self.to_v = nn.Linear(context_dim, inner_dim, bias=False)self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))self.attention_op: Optional[Any] = Nonedef forward(self, x, context=None, mask=None):4 unmodified linesb, _, _ = q.shapeq, k, v = map(lambda t: t.unsqueeze(3).reshape(b, t.shape[1], self.heads, self.dim_head).permute(0, 2, 1, 3).reshape(b * self.heads, t.shape[1], self.dim_head).contiguous(),(q, k, v),)# actually compute the attention, what we cannot get enough ofout = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)if mask is not None:raise NotImplementedErrorout = (out.unsqueeze(0).reshape(b, self.heads, out.shape[1], self.dim_head).permute(0, 2, 1, 3).reshape(b, out.shape[1], self.heads * self.dim_head))return self.to_out(out)class BasicTransformerBlock(nn.Module):ATTENTION_MODES = {"softmax": CrossAttention,"softmax-xformers": MemoryEfficientCrossAttention,} # vanilla attentiondef __init__(self,dim,n_heads,d_head,dropout=0.0,context_dim=None,gated_ff=True,checkpoint=True,disable_self_attn=False,):super().__init__()attn_mode = "softmax-xformers" if XFORMERS_IS_AVAILBLE else "softmax"assert attn_mode in self.ATTENTION_MODESattn_cls = self.ATTENTION_MODES[attn_mode]self.disable_self_attn = disable_self_attnself.attn1 = attn_cls(query_dim=dim,heads=n_heads,dim_head=d_head,dropout=dropout,context_dim=context_dim if self.disable_self_attn else None,) # is a self-attention if not self.disable_self_attnself.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)self.attn2 = attn_cls(query_dim=dim,context_dim=context_dim,heads=n_heads,dim_head=d_head,dropout=dropout,) # is self-attn if context is noneself.norm1 = nn.LayerNorm(dim)self.norm2 = nn.LayerNorm(dim)self.norm3 = nn.LayerNorm(dim)self.checkpoint = checkpointdef forward(self, x, context=None):return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)def _forward(self, x, context=None):x = (self.attn1(self.norm1(x), context=context if self.disable_self_attn else None)+ x)x = self.attn2(self.norm2(x), context=context) + xx = self.ff(self.norm3(x)) + xreturn x9 unmodified linesNEW: use_linear for more efficiency instead of the 1x1 convs"""def __init__(self,in_channels,n_heads,d_head,depth=1,dropout=0.0,context_dim=None,disable_self_attn=False,use_linear=False,use_checkpoint=True,):super().__init__()assert context_dim is not Noneif not isinstance(context_dim, list):2 unmodified linesinner_dim = n_heads * d_headself.norm = Normalize(in_channels)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)else:self.proj_in = nn.Linear(in_channels, inner_dim)self.transformer_blocks = nn.ModuleList([BasicTransformerBlock(inner_dim,n_heads,d_head,dropout=dropout,context_dim=context_dim[d],disable_self_attn=disable_self_attn,checkpoint=use_checkpoint,)for d in range(depth)])if not use_linear:self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))else:self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))self.use_linear = use_linear7 unmodified linesx = self.norm(x)if not self.use_linear:x = self.proj_in(x)x = rearrange(x, "b c h w -> b (h w) c").contiguous()if self.use_linear:x = self.proj_in(x)for i, block in enumerate(self.transformer_blocks):x = block(x, context=context[i])if self.use_linear:x = self.proj_out(x)x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous()if not self.use_linear:x = self.proj_out(x)return x + x_inclass BasicTransformerBlock3D(BasicTransformerBlock):def forward(self, x, context=None, num_frames=1):return checkpoint(self._forward, (x, context, num_frames), self.parameters(), self.checkpoint)def _forward(self, x, context=None, num_frames=1):x = rearrange(x, "(b f) l c -> b (f l) c", f=num_frames).contiguous()x = (self.attn1(self.norm1(x), context=context if self.disable_self_attn else None)+ x)x = rearrange(x, "b (f l) c -> (b f) l c", f=num_frames).contiguous()x = self.attn2(self.norm2(x), context=context) + xx = self.ff(self.norm3(x)) + x1 unmodified lineclass SpatialTransformer3D(nn.Module):"""3D self-attention"""def __init__(self,in_channels,n_heads,d_head,depth=1,dropout=0.0,context_dim=None,disable_self_attn=False,use_linear=False,use_checkpoint=True,):super().__init__()assert context_dim is not Noneif not isinstance(context_dim, list):2 unmodified linesinner_dim = n_heads * d_headself.norm = Normalize(in_channels)if not use_linear:self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)else:self.proj_in = nn.Linear(in_channels, inner_dim)self.transformer_blocks = nn.ModuleList([BasicTransformerBlock3D(inner_dim,n_heads,d_head,dropout=dropout,context_dim=context_dim[d],disable_self_attn=disable_self_attn,checkpoint=use_checkpoint,)for d in range(depth)])if not use_linear:self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))else:self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))self.use_linear = use_linear7 unmodified linesx = self.norm(x)if not self.use_linear:x = self.proj_in(x)x = rearrange(x, "b c h w -> b (h w) c").contiguous()if self.use_linear:x = self.proj_in(x)for i, block in enumerate(self.transformer_blocks):x = block(x, context=context[i], num_frames=num_frames)if self.use_linear:x = self.proj_out(x)x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous()if not self.use_linear:x = self.proj_out(x)return x + x_in
4 unmodified lines56789104 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939442 unmodified lines13713813914014114214314414514614714818 unmodified lines16716816917017117217369 unmodified lines2432442452462472482492502512522532542554 unmodified lines26026126226326426526638 unmodified lines3053063073083093103118 unmodified lines3203213223233243253263274 unmodified lines33233333433533633733833934034134234334434534634734834935035135235335435535635714 unmodified lines37237337437537637737837938038138238338438538619 unmodified lines40640740840941041141241341441541641741841942042142225 unmodified lines4484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904911 unmodified line4934944954964974984995005015023 unmodified lines50650750850951051151251351451551651751851952052152252352429 unmodified lines5545555565575585595605615625635645655665675685695705715725735745755765775785795805815825832 unmodified lines5865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206215 unmodified lines62762862963063163263310 unmodified lines6446456466476486496506519 unmodified lines6616626636646656666676686696706716726736746752 unmodified lines6786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107 unmodified lines7187197207217227237247257267273 unmodified lines7317327337347357367377387397407414 unmodified linesimport torch as thimport torch.nn as nnimport torch.nn.functional as Ffrom abc import abstractmethodfrom .util import (4 unmodified linestimestep_embedding,)from .attention import SpatialTransformer, SpatialTransformer3Dfrom diffusers.configuration_utils import ConfigMixinfrom diffusers.models.modeling_utils import ModelMixinfrom typing import Any, List, Optionalfrom torch import Tensorclass MultiViewUNetWrapperModel(ModelMixin, ConfigMixin):def __init__(self,image_size,in_channels,model_channels,out_channels,num_res_blocks,attention_resolutions,dropout=0,channel_mult=(1, 2, 4, 8),conv_resample=True,dims=2,num_classes=None,use_checkpoint=False,num_heads=-1,num_head_channels=-1,num_heads_upsample=-1,use_scale_shift_norm=False,resblock_updown=False,use_new_attention_order=False,use_spatial_transformer=False, # custom transformer supporttransformer_depth=1, # custom transformer supportcontext_dim=None, # custom transformer supportn_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq modellegacy=True,disable_self_attentions=None,num_attention_blocks=None,disable_middle_self_attn=False,use_linear_in_transformer=False,adm_in_channels=None,camera_dim=None,):super().__init__()self.unet = MultiViewUNetModel(image_size=image_size,in_channels=in_channels,model_channels=model_channels,out_channels=out_channels,num_res_blocks=num_res_blocks,attention_resolutions=attention_resolutions,dropout=dropout,channel_mult=channel_mult,conv_resample=conv_resample,dims=dims,num_classes=num_classes,use_checkpoint=use_checkpoint,num_heads=num_heads,num_head_channels=num_head_channels,num_heads_upsample=num_heads_upsample,use_scale_shift_norm=use_scale_shift_norm,resblock_updown=resblock_updown,use_new_attention_order=use_new_attention_order,use_spatial_transformer=use_spatial_transformer,transformer_depth=transformer_depth,context_dim=context_dim,n_embed=n_embed,legacy=legacy,disable_self_attentions=disable_self_attentions,num_attention_blocks=num_attention_blocks,disable_middle_self_attn=disable_middle_self_attn,use_linear_in_transformer=use_linear_in_transformer,adm_in_channels=adm_in_channels,camera_dim=camera_dim,)def forward(self, *args, **kwargs):return self.unet(*args, **kwargs)class TimestepBlock(nn.Module):"""42 unmodified linesself.use_conv = use_convself.dims = dimsif use_conv:self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)def forward(self, x):assert x.shape[1] == self.channelsif self.dims == 3:x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest")else:x = F.interpolate(x, scale_factor=2, mode="nearest")if self.use_conv:18 unmodified linesself.dims = dimsstride = 2 if dims != 3 else (1, 2, 2)if use_conv:self.op = conv_nd(dims, self.channels, self.out_channels, 3, stride=stride, padding=padding)else:assert self.channels == self.out_channelsself.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)69 unmodified linesnn.GroupNorm(32, self.out_channels),nn.SiLU(),nn.Dropout(p=dropout),zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)),)if self.out_channels == channels:self.skip_connection = nn.Identity()elif use_conv:self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)else:self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)4 unmodified lines:param emb: an [N x emb_channels] Tensor of timestep embeddings.:return: an [N x C x ...] Tensor of outputs."""return checkpoint(self._forward, (x, emb), self.parameters(), self.use_checkpoint)def _forward(self, x, emb):if self.updown:38 unmodified linesif num_head_channels == -1:self.num_heads = num_headselse:assert (channels % num_head_channels == 0), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"self.num_heads = channels // num_head_channelsself.use_checkpoint = use_checkpointself.norm = nn.GroupNorm(32, channels)8 unmodified linesself.proj_out = zero_module(conv_nd(1, channels, channels, 1))def forward(self, x):return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!#return pt_checkpoint(self._forward, x) # pytorchdef _forward(self, x):b, c, *spatial = x.shape4 unmodified linesreturn (x + h).reshape(b, c, *spatial)def count_flops_attn(model, _x, y):"""A counter for the `thop` package to count the operations in anattention operation.Meant to be used like:macs, params = thop.profile(model,inputs=(inputs, timestamps),custom_ops={QKVAttention: QKVAttention.count_flops},)"""b, c, *spatial = y[0].shapenum_spatial = int(np.prod(spatial))# We perform two matmuls with the same number of ops.# The first computes the weight matrix, the second computes# the combination of the value vectors.matmul_ops = 2 * b * (num_spatial**2) * cmodel.total_ops += th.DoubleTensor([matmul_ops])class QKVAttentionLegacy(nn.Module):"""A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping14 unmodified linesch = width // (3 * self.n_heads)q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)scale = 1 / math.sqrt(math.sqrt(ch))weight = th.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwardsweight = th.softmax(weight.float(), dim=-1).type(weight.dtype)a = th.einsum("bts,bcs->bct", weight, v)return a.reshape(bs, -1, length)@staticmethoddef count_flops(model, _x, y):return count_flops_attn(model, _x, y)class QKVAttention(nn.Module):"""19 unmodified lines"bct,bcs->bts",(q * scale).view(bs * self.n_heads, ch, length),(k * scale).view(bs * self.n_heads, ch, length),) # More stable with f16 than dividing afterwardsweight = th.softmax(weight.float(), dim=-1).type(weight.dtype)a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))return a.reshape(bs, -1, length)@staticmethoddef count_flops(model, _x, y):return count_flops_attn(model, _x, y)class MultiViewUNetModel(nn.Module):"""The full multi-view UNet model with attention, timestep embedding and camera embedding.:param in_channels: channels in the input Tensor.25 unmodified lines"""def __init__(self,image_size,in_channels,model_channels,out_channels,num_res_blocks,attention_resolutions,dropout=0,channel_mult=(1, 2, 4, 8),conv_resample=True,dims=2,num_classes=None,use_checkpoint=False,num_heads=-1,num_head_channels=-1,num_heads_upsample=-1,use_scale_shift_norm=False,resblock_updown=False,use_new_attention_order=False,use_spatial_transformer=False, # custom transformer supporttransformer_depth=1, # custom transformer supportcontext_dim=None, # custom transformer supportn_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq modellegacy=True,disable_self_attentions=None,num_attention_blocks=None,disable_middle_self_attn=False,use_linear_in_transformer=False,adm_in_channels=None,camera_dim=None,):super().__init__()if use_spatial_transformer:assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'if context_dim is not None:assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'from omegaconf.listconfig import ListConfigif type(context_dim) == ListConfig:context_dim = list(context_dim)1 unmodified linenum_heads_upsample = num_headsif num_heads == -1:assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'if num_head_channels == -1:assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'self.image_size = image_sizeself.in_channels = in_channels3 unmodified linesself.num_res_blocks = len(channel_mult) * [num_res_blocks]else:if len(num_res_blocks) != len(channel_mult):raise ValueError("provide num_res_blocks either as an int (globally constant) or ""as a list/tuple (per-level) with the same length as channel_mult")self.num_res_blocks = num_res_blocksif disable_self_attentions is not None:# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or notassert len(disable_self_attentions) == len(channel_mult)if num_attention_blocks is not None:assert len(num_attention_blocks) == len(self.num_res_blocks)assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "f"This option has LESS priority than attention_resolutions {attention_resolutions}, "f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "f"attention will still not be set.")self.attention_resolutions = attention_resolutionsself.dropout = dropout29 unmodified linesself.label_emb = nn.Linear(1, time_embed_dim)elif self.num_classes == "sequential":assert adm_in_channels is not Noneself.label_emb = nn.Sequential(nn.Sequential(nn.Linear(adm_in_channels, time_embed_dim),nn.SiLU(),nn.Linear(time_embed_dim, time_embed_dim),))else:raise ValueError()self.input_blocks = nn.ModuleList([TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))])self._feature_size = model_channelsinput_block_chans = [model_channels]ch = model_channelsds = 1for level, mult in enumerate(channel_mult):for nr in range(self.num_res_blocks[level]):layers: List[Any] = [ResBlock(ch,time_embed_dim,dropout,out_channels=mult * model_channels,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,)]ch = mult * model_channelsif ds in attention_resolutions:if num_head_channels == -1:2 unmodified linesnum_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:#num_heads = 1dim_head = ch // num_heads if use_spatial_transformer else num_head_channelsif disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:disabled_sa = Falseif num_attention_blocks is None or nr < num_attention_blocks[level]:layers.append(AttentionBlock(ch,use_checkpoint=use_checkpoint,num_heads=num_heads,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,) if not use_spatial_transformer else SpatialTransformer3D(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint))self.input_blocks.append(TimestepEmbedSequential(*layers))self._feature_size += chinput_block_chans.append(ch)if level != len(channel_mult) - 1:out_ch = chself.input_blocks.append(TimestepEmbedSequential(ResBlock(ch,time_embed_dim,dropout,out_channels=out_ch,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,down=True,) if resblock_updown else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)))ch = out_chinput_block_chans.append(ch)ds *= 25 unmodified linesnum_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:#num_heads = 1dim_head = ch // num_heads if use_spatial_transformer else num_head_channelsself.middle_block = TimestepEmbedSequential(ResBlock(10 unmodified linesnum_heads=num_heads,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,) if not use_spatial_transformer else SpatialTransformer3D( # always uses a self-attnch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint),ResBlock(ch,time_embed_dim,9 unmodified linesfor level, mult in list(enumerate(channel_mult))[::-1]:for i in range(self.num_res_blocks[level] + 1):ich = input_block_chans.pop()layers = [ResBlock(ch + ich,time_embed_dim,dropout,out_channels=model_channels * mult,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,)]ch = model_channels * multif ds in attention_resolutions:if num_head_channels == -1:2 unmodified linesnum_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:#num_heads = 1dim_head = ch // num_heads if use_spatial_transformer else num_head_channelsif disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:disabled_sa = Falseif num_attention_blocks is None or i < num_attention_blocks[level]:layers.append(AttentionBlock(ch,use_checkpoint=use_checkpoint,num_heads=num_heads_upsample,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,) if not use_spatial_transformer else SpatialTransformer3D(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint))if level and i == self.num_res_blocks[level]:out_ch = chlayers.append(ResBlock(ch,time_embed_dim,dropout,out_channels=out_ch,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,up=True,) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch))ds //= 2self.output_blocks.append(TimestepEmbedSequential(*layers))self._feature_size += ch7 unmodified linesself.id_predictor = nn.Sequential(nn.GroupNorm(32, ch),conv_nd(dims, model_channels, n_embed, 1),#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits)def forward(self, x, timesteps=None, context=None, y: Optional[Tensor] = None, camera=None, num_frames=1, **kwargs):"""Apply the model to an input batch.:param x: an [(N x F) x C x ...] Tensor of inputs. F is the number of frames (views).3 unmodified lines:param num_frames: a integer indicating number of frames for tensor reshaping.:return: an [(N x F) x C x ...] Tensor of outputs. F is the number of frames (views)."""assert x.shape[0] % num_frames == 0, "[UNet] input batch size must be dividable by num_frames!"assert (y is not None) == (self.num_classes is not None), "must specify y if and only if the model is class-conditional"hs = []t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)emb = self.time_embed(t_emb)if self.num_classes is not None:4 unmodified lines5678910111213144 unmodified lines19202122232442 unmodified lines6768697071727374757677787980818218 unmodified lines10110210310410510610710810911011111211311469 unmodified lines1841851861871881891901911921931941951961971981992004 unmodified lines20520620720820921021121221338 unmodified lines2522532542552562572582592608 unmodified lines2692702712722732742754 unmodified lines28028128228328428514 unmodified lines30030130230330430530630730830931031131219 unmodified lines33233333433533633733833934034134234334425 unmodified lines3703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174181 unmodified line4204214224234244254264274284294304314324333 unmodified lines43743843944044144244344444544644744844945045145245345445545645745845946046146246346429 unmodified lines4944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325332 unmodified lines5365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965 unmodified lines60260360460560660760810 unmodified lines6196206216226236246256266276286296306316326336346356369 unmodified lines6466476486496506516526536546556566576586596606616622 unmodified lines6656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187 unmodified lines7267277287297307317327337347357367377387397407417427437443 unmodified lines7487497507517527537547557567577587597607617627637644 unmodified linesimport torch as thimport torch.nn as nnimport torch.nn.functional as Ffrom diffusers.configuration_utils import ConfigMixinfrom diffusers.models.modeling_utils import ModelMixinfrom typing import Any, List, Optionalfrom torch import Tensorfrom abc import abstractmethodfrom .util import (4 unmodified linestimestep_embedding,)from .attention import SpatialTransformer, SpatialTransformer3Dclass TimestepBlock(nn.Module):"""42 unmodified linesself.use_conv = use_convself.dims = dimsif use_conv:self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)def forward(self, x):assert x.shape[1] == self.channelsif self.dims == 3:x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest")else:x = F.interpolate(x, scale_factor=2, mode="nearest")if self.use_conv:18 unmodified linesself.dims = dimsstride = 2 if dims != 3 else (1, 2, 2)if use_conv:self.op = conv_nd(dims,self.channels,self.out_channels,3,stride=stride,padding=padding,)else:assert self.channels == self.out_channelsself.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)69 unmodified linesnn.GroupNorm(32, self.out_channels),nn.SiLU(),nn.Dropout(p=dropout),zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)),)if self.out_channels == channels:self.skip_connection = nn.Identity()elif use_conv:self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)else:self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)4 unmodified lines:param emb: an [N x emb_channels] Tensor of timestep embeddings.:return: an [N x C x ...] Tensor of outputs."""return checkpoint(self._forward, (x, emb), self.parameters(), self.use_checkpoint)def _forward(self, x, emb):if self.updown:38 unmodified linesif num_head_channels == -1:self.num_heads = num_headselse:assert (channels % num_head_channels == 0), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"self.num_heads = channels // num_head_channelsself.use_checkpoint = use_checkpointself.norm = nn.GroupNorm(32, channels)8 unmodified linesself.proj_out = zero_module(conv_nd(1, channels, channels, 1))def forward(self, x):return checkpoint(self._forward, (x,), self.parameters(), True)def _forward(self, x):b, c, *spatial = x.shape4 unmodified linesreturn (x + h).reshape(b, c, *spatial)class QKVAttentionLegacy(nn.Module):"""A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping14 unmodified linesch = width // (3 * self.n_heads)q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)scale = 1 / math.sqrt(math.sqrt(ch))weight = th.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwardsweight = th.softmax(weight.float(), dim=-1).type(weight.dtype)a = th.einsum("bts,bcs->bct", weight, v)return a.reshape(bs, -1, length)class QKVAttention(nn.Module):"""19 unmodified lines"bct,bcs->bts",(q * scale).view(bs * self.n_heads, ch, length),(k * scale).view(bs * self.n_heads, ch, length),) # More stable with f16 than dividing afterwardsweight = th.softmax(weight.float(), dim=-1).type(weight.dtype)a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))return a.reshape(bs, -1, length)class MultiViewUNetModel(ModelMixin, ConfigMixin):"""The full multi-view UNet model with attention, timestep embedding and camera embedding.:param in_channels: channels in the input Tensor.25 unmodified lines"""def __init__(self,image_size,in_channels,model_channels,out_channels,num_res_blocks,attention_resolutions,dropout=0,channel_mult=(1, 2, 4, 8),conv_resample=True,dims=2,num_classes=None,use_checkpoint=False,num_heads=-1,num_head_channels=-1,num_heads_upsample=-1,use_scale_shift_norm=False,resblock_updown=False,use_new_attention_order=False,use_spatial_transformer=False, # custom transformer supporttransformer_depth=1, # custom transformer supportcontext_dim=None, # custom transformer supportn_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq modellegacy=True,disable_self_attentions=None,num_attention_blocks=None,disable_middle_self_attn=False,use_linear_in_transformer=False,adm_in_channels=None,camera_dim=None,):super().__init__()if use_spatial_transformer:assert (context_dim is not None), "Fool!! You forgot to include the dimension of your cross-attention conditioning..."if context_dim is not None:assert (use_spatial_transformer), "Fool!! You forgot to use the spatial transformer for your cross-attention conditioning..."from omegaconf.listconfig import ListConfigif type(context_dim) == ListConfig:context_dim = list(context_dim)1 unmodified linenum_heads_upsample = num_headsif num_heads == -1:assert (num_head_channels != -1), "Either num_heads or num_head_channels has to be set"if num_head_channels == -1:assert (num_heads != -1), "Either num_heads or num_head_channels has to be set"self.image_size = image_sizeself.in_channels = in_channels3 unmodified linesself.num_res_blocks = len(channel_mult) * [num_res_blocks]else:if len(num_res_blocks) != len(channel_mult):raise ValueError("provide num_res_blocks either as an int (globally constant) or ""as a list/tuple (per-level) with the same length as channel_mult")self.num_res_blocks = num_res_blocksif disable_self_attentions is not None:# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or notassert len(disable_self_attentions) == len(channel_mult)if num_attention_blocks is not None:assert len(num_attention_blocks) == len(self.num_res_blocks)assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i],range(len(num_attention_blocks)),))print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "f"This option has LESS priority than attention_resolutions {attention_resolutions}, "f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "f"attention will still not be set.")self.attention_resolutions = attention_resolutionsself.dropout = dropout29 unmodified linesself.label_emb = nn.Linear(1, time_embed_dim)elif self.num_classes == "sequential":assert adm_in_channels is not Noneself.label_emb = nn.Sequential(nn.Sequential(nn.Linear(adm_in_channels, time_embed_dim),nn.SiLU(),nn.Linear(time_embed_dim, time_embed_dim),))else:raise ValueError()self.input_blocks = nn.ModuleList([TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))])self._feature_size = model_channelsinput_block_chans = [model_channels]ch = model_channelsds = 1for level, mult in enumerate(channel_mult):for nr in range(self.num_res_blocks[level]):layers: List[Any] = [ResBlock(ch,time_embed_dim,dropout,out_channels=mult * model_channels,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,)]ch = mult * model_channelsif ds in attention_resolutions:if num_head_channels == -1:2 unmodified linesnum_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:# num_heads = 1dim_head = (ch // num_headsif use_spatial_transformerelse num_head_channels)if disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:disabled_sa = Falseif num_attention_blocks is None or nr < num_attention_blocks[level]:layers.append(AttentionBlock(ch,use_checkpoint=use_checkpoint,num_heads=num_heads,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,)if not use_spatial_transformerelse SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disabled_sa,use_linear=use_linear_in_transformer,use_checkpoint=use_checkpoint,))self.input_blocks.append(TimestepEmbedSequential(*layers))self._feature_size += chinput_block_chans.append(ch)if level != len(channel_mult) - 1:out_ch = chself.input_blocks.append(TimestepEmbedSequential(ResBlock(ch,time_embed_dim,dropout,out_channels=out_ch,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,down=True,)if resblock_updownelse Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)))ch = out_chinput_block_chans.append(ch)ds *= 25 unmodified linesnum_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:# num_heads = 1dim_head = ch // num_heads if use_spatial_transformer else num_head_channelsself.middle_block = TimestepEmbedSequential(ResBlock(10 unmodified linesnum_heads=num_heads,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,)if not use_spatial_transformerelse SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disable_middle_self_attn,use_linear=use_linear_in_transformer,use_checkpoint=use_checkpoint,), # always uses a self-attnResBlock(ch,time_embed_dim,9 unmodified linesfor level, mult in list(enumerate(channel_mult))[::-1]:for i in range(self.num_res_blocks[level] + 1):ich = input_block_chans.pop()layers = [ResBlock(ch + ich,time_embed_dim,dropout,out_channels=model_channels * mult,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,)]ch = model_channels * multif ds in attention_resolutions:if num_head_channels == -1:2 unmodified linesnum_heads = ch // num_head_channelsdim_head = num_head_channelsif legacy:# num_heads = 1dim_head = (ch // num_headsif use_spatial_transformerelse num_head_channels)if disable_self_attentions is not None:disabled_sa = disable_self_attentions[level]else:disabled_sa = Falseif num_attention_blocks is None or i < num_attention_blocks[level]:layers.append(AttentionBlock(ch,use_checkpoint=use_checkpoint,num_heads=num_heads_upsample,num_head_channels=dim_head,use_new_attention_order=use_new_attention_order,)if not use_spatial_transformerelse SpatialTransformer3D(ch,num_heads,dim_head,depth=transformer_depth,context_dim=context_dim,disable_self_attn=disabled_sa,use_linear=use_linear_in_transformer,use_checkpoint=use_checkpoint,))if level and i == self.num_res_blocks[level]:out_ch = chlayers.append(ResBlock(ch,time_embed_dim,dropout,out_channels=out_ch,dims=dims,use_checkpoint=use_checkpoint,use_scale_shift_norm=use_scale_shift_norm,up=True,)if resblock_updownelse Upsample(ch, conv_resample, dims=dims, out_channels=out_ch))ds //= 2self.output_blocks.append(TimestepEmbedSequential(*layers))self._feature_size += ch7 unmodified linesself.id_predictor = nn.Sequential(nn.GroupNorm(32, ch),conv_nd(dims, model_channels, n_embed, 1),# nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits)def forward(self,x,timesteps=None,context=None,y: Optional[Tensor] = None,camera=None,num_frames=1,**kwargs,):"""Apply the model to an input batch.:param x: an [(N x F) x C x ...] Tensor of inputs. F is the number of frames (views).3 unmodified lines:param num_frames: a integer indicating number of frames for tensor reshaping.:return: an [(N x F) x C x ...] Tensor of outputs. F is the number of frames (views)."""assert (x.shape[0] % num_frames == 0), "[UNet] input batch size must be dividable by num_frames!"assert (y is not None) == (self.num_classes is not None), "must specify y if and only if the model is class-conditional"hs = []t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)emb = self.time_embed(t_emb)if self.num_classes is not None:
1234565 unmodified lines12131415161718192021222324252628 unmodified lines55565758596061626364656667685 unmodified lines74757677787980818283841 unmodified line86878889909192939495969798991001011021031041051061071081091105 unmodified lines11611711811912012112239 unmodified lines1621631641651661671681691701711721731748 unmodified lines1831841851861871881891901911921931941951961971981998 unmodified lines20820921021121221321434 unmodified lines2492502512522532542553 unmodified lines2592602612622632642652662672682692702712729 unmodified lines2822832842852862872881 unmodified line2902912922932942952962972982993003013023036 unmodified lines3103113123133143153167 unmodified lines32432532632732832933033133233316 unmodified lines35035135235335435535635735835936036136236336436536636736836937037137237337417 unmodified lines3923933943953963973983994004014024034044059 unmodified lines4154164174184194204217 unmodified lines4294304314324334344356 unmodified lines4424434444454464474484494504514524534541 unmodified line456457458459460461462463464465466467468469470471472import torchimport numpy as npimport inspectfrom typing import Callable, List, Optional, Unionfrom transformers import CLIPTextModel, CLIPTokenizerfrom diffusers import AutoencoderKL, DiffusionPipeline5 unmodified lines)from diffusers.configuration_utils import FrozenDictfrom diffusers.schedulers import DDIMSchedulertry:from diffusers import randn_tensor # old import # type: ignoreexcept ImportError:from diffusers.utils.torch_utils import randn_tensor # new import # type: ignorefrom .models import MultiViewUNetWrapperModelfrom accelerate.utils import set_module_tensor_to_devicelogger = logging.get_logger(__name__) # pylint: disable=invalid-namedef create_camera_to_world_matrix(elevation, azimuth):elevation = np.radians(elevation)28 unmodified linescamera_matrix_blender = np.dot(flip_yz, camera_matrix)else:# Construct transformation matrix to convert from OpenGL space to Blender spaceflip_yz = torch.tensor([[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])if camera_matrix.ndim == 3:flip_yz = flip_yz.unsqueeze(0)camera_matrix_blender = torch.matmul(flip_yz.to(camera_matrix), camera_matrix)return camera_matrix_blenderdef get_camera(num_frames, elevation=15, azimuth_start=0, azimuth_span=360, blender_coord=True):angle_gap = azimuth_span / num_framescameras = []for azimuth in np.arange(azimuth_start, azimuth_span + azimuth_start, angle_gap):5 unmodified linesclass MVDreamStableDiffusionPipeline(DiffusionPipeline):def __init__(self,vae: AutoencoderKL,unet: MultiViewUNetWrapperModel,tokenizer: CLIPTokenizer,text_encoder: CLIPTextModel,scheduler: DDIMScheduler,1 unmodified line):super().__init__()if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: # type: ignoredeprecation_message = (f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " # type: ignore"to update the config accordingly as leaving `steps_offset` might led to incorrect results"" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"" file")deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)new_config = dict(scheduler.config)new_config["steps_offset"] = 1scheduler._internal_dict = FrozenDict(new_config)if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: # type: ignoredeprecation_message = (f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."" `clip_sample` should be set to False in the configuration file. Please make sure to update the"" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file")deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)new_config = dict(scheduler.config)new_config["clip_sample"] = Falsescheduler._internal_dict = FrozenDict(new_config)5 unmodified linestokenizer=tokenizer,text_encoder=text_encoder,)self.vae_scale_factor = 2**(len(self.vae.config.block_out_channels) - 1)self.register_to_config(requires_safety_checker=requires_safety_checker)def enable_vae_slicing(self):39 unmodified linesif is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):from accelerate import cpu_offloadelse:raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")device = torch.device(f"cuda:{gpu_id}")if self.device.type != "cpu":self.to("cpu", silence_dtype_warnings=True)torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:cpu_offload(cpu_offloaded_model, device)8 unmodified linesif is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):from accelerate import cpu_offload_with_hookelse:raise ImportError("`enable_model_offload` requires `accelerate v0.17.0` or higher.")device = torch.device(f"cuda:{gpu_id}")if self.device.type != "cpu":self.to("cpu", silence_dtype_warnings=True)torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)hook = Nonefor cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:_, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)# We'll offload the last model manually.self.final_offload_hook = hook8 unmodified linesif not hasattr(self.unet, "_hf_hook"):return self.devicefor module in self.unet.modules():if (hasattr(module, "_hf_hook") and hasattr(module._hf_hook, "execution_device") and module._hf_hook.execution_device is not None):return torch.device(module._hf_hook.execution_device)return self.device34 unmodified lineselif prompt is not None and isinstance(prompt, list):batch_size = len(prompt)else:raise ValueError(f"`prompt` should be either a string or a list of strings, but got {type(prompt)}.")text_inputs = self.tokenizer(prompt,3 unmodified linesreturn_tensors="pt",)text_input_ids = text_inputs.input_idsuntruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_idsif untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1:-1])logger.warning("The following part of your input was truncated because CLIP can only handle sequences up to"f" {self.tokenizer.model_max_length} tokens: {removed_text}")if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:attention_mask = text_inputs.attention_mask.to(device)else:attention_mask = None9 unmodified linesbs_embed, seq_len, _ = prompt_embeds.shape# duplicate text embeddings for each generation per prompt, using mps friendly methodprompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)# get unconditional embeddings for classifier free guidanceif do_classifier_free_guidance:1 unmodified lineif negative_prompt is None:uncond_tokens = [""] * batch_sizeelif type(prompt) is not type(negative_prompt):raise TypeError(f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="f" {type(prompt)}.")elif isinstance(negative_prompt, str):uncond_tokens = [negative_prompt]elif batch_size != len(negative_prompt):raise ValueError(f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"" the batch size of `prompt`.")else:uncond_tokens = negative_prompt6 unmodified linesreturn_tensors="pt",)if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:attention_mask = uncond_input.attention_mask.to(device)else:attention_mask = None7 unmodified lines# duplicate unconditional embeddings for each generation per prompt, using mps friendly methodseq_len = negative_prompt_embeds.shape[1]negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)# For classifier free guidance, we need to do two forward passes.# Here we concatenate the unconditional and text embeddings into a single batch16 unmodified lines# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502# and should be between [0, 1]accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())extra_step_kwargs = {}if accepts_eta:extra_step_kwargs["eta"] = eta# check if the scheduler accepts generatoraccepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())if accepts_generator:extra_step_kwargs["generator"] = generatorreturn extra_step_kwargsdef prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)if isinstance(generator, list) and len(generator) != batch_size:raise ValueError(f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"f" size of {batch_size}. Make sure the batch size matches the length of the generators.")if latents is None:latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)else:latents = latents.to(device)17 unmodified linescallback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,callback_steps: int = 1,batch_size: int = 4,device = torch.device("cuda:0"),):self.unet = self.unet.to(device=device)self.vae = self.vae.to(device=device)self.text_encoder = self.text_encoder.to(device=device)# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`# corresponds to doing no classifier free guidance.9 unmodified linesnum_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=do_classifier_free_guidance,negative_prompt=negative_prompt,) # type: ignoreprompt_embeds_neg, prompt_embeds_pos = _prompt_embeds.chunk(2)# Prepare latent variables7 unmodified linesgenerator,None,)camera = get_camera(batch_size).to(dtype=latents.dtype, device=device)# Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline6 unmodified lines# expand the latents if we are doing classifier free guidancemultiplier = 2 if do_classifier_free_guidance else 1latent_model_input = torch.cat([latents] * multiplier)latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)# predict the noise residualnoise_pred = self.unet.forward(x=latent_model_input,timesteps=torch.tensor([t] * 4 * multiplier, dtype=latent_model_input.dtype, device=device),context=torch.cat([prompt_embeds_neg] * 4 + [prompt_embeds_pos] * 4),num_frames=4,camera=torch.cat([camera] * multiplier),)1 unmodified line# perform guidanceif do_classifier_free_guidance:noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)# compute the previous noisy sample x_t -> x_t-1# latents = self.scheduler.step(noise_pred.to(dtype=torch.float32), t, latents.to(dtype=torch.float32)).prev_sample.to(prompt_embeds.dtype)latents: torch.Tensor = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):progress_bar.update()if callback is not None and i % callback_steps == 0:callback(i, t, latents) # type: ignore# Post-processingif output_type == "latent":1234565 unmodified lines12131415161718192021222328 unmodified lines5253545556575859606162636465666768695 unmodified lines757677787980818283841 unmodified line86878889909192939495969798991001011021031041051061071081091101111121131141151161171185 unmodified lines12412512612712812913039 unmodified lines1701711721731741751761771781791801811821831848 unmodified lines1931941951961971981992002012022032042052062072082092102112122138 unmodified lines22222322422522622722822923023123234 unmodified lines2672682692702712722732742753 unmodified lines2792802812822832842852862872882892902912922932942952962972982993003013023039 unmodified lines3133143153163173183193203211 unmodified line3233243253263273283293303313323333343353363373383393406 unmodified lines3473483493503513523533543553567 unmodified lines36436536636736836937037137237337437537637737837916 unmodified lines39639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244317 unmodified lines4614624634644654664674684694704714724739 unmodified lines4834844854864874884897 unmodified lines4974984995005015025036 unmodified lines5105115125135145155165175185195205215225235245255265275285295301 unmodified line532533534535536537538539540541542543544545546547548549550551552553554import torchimport inspectimport numpy as npfrom typing import Callable, List, Optional, Unionfrom transformers import CLIPTextModel, CLIPTokenizerfrom diffusers import AutoencoderKL, DiffusionPipeline5 unmodified lines)from diffusers.configuration_utils import FrozenDictfrom diffusers.schedulers import DDIMSchedulerfrom diffusers.utils.torch_utils import randn_tensorfrom .models import MultiViewUNetModellogger = logging.get_logger(__name__) # pylint: disable=invalid-namedef create_camera_to_world_matrix(elevation, azimuth):elevation = np.radians(elevation)28 unmodified linescamera_matrix_blender = np.dot(flip_yz, camera_matrix)else:# Construct transformation matrix to convert from OpenGL space to Blender spaceflip_yz = torch.tensor([[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])if camera_matrix.ndim == 3:flip_yz = flip_yz.unsqueeze(0)camera_matrix_blender = torch.matmul(flip_yz.to(camera_matrix), camera_matrix)return camera_matrix_blenderdef get_camera(num_frames, elevation=15, azimuth_start=0, azimuth_span=360, blender_coord=True):angle_gap = azimuth_span / num_framescameras = []for azimuth in np.arange(azimuth_start, azimuth_span + azimuth_start, angle_gap):5 unmodified linesclass MVDreamStableDiffusionPipeline(DiffusionPipeline):def __init__(self,vae: AutoencoderKL,unet: MultiViewUNetModel,tokenizer: CLIPTokenizer,text_encoder: CLIPTextModel,scheduler: DDIMScheduler,1 unmodified line):super().__init__()if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: # type: ignoredeprecation_message = (f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " # type: ignore"to update the config accordingly as leaving `steps_offset` might led to incorrect results"" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"" file")deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)new_config = dict(scheduler.config)new_config["steps_offset"] = 1scheduler._internal_dict = FrozenDict(new_config)if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: # type: ignoredeprecation_message = (f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."" `clip_sample` should be set to False in the configuration file. Please make sure to update the"" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file")deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)new_config = dict(scheduler.config)new_config["clip_sample"] = Falsescheduler._internal_dict = FrozenDict(new_config)5 unmodified linestokenizer=tokenizer,text_encoder=text_encoder,)self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)self.register_to_config(requires_safety_checker=requires_safety_checker)def enable_vae_slicing(self):39 unmodified linesif is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):from accelerate import cpu_offloadelse:raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")device = torch.device(f"cuda:{gpu_id}")if self.device.type != "cpu":self.to("cpu", silence_dtype_warnings=True)torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:cpu_offload(cpu_offloaded_model, device)8 unmodified linesif is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):from accelerate import cpu_offload_with_hookelse:raise ImportError("`enable_model_offload` requires `accelerate v0.17.0` or higher.")device = torch.device(f"cuda:{gpu_id}")if self.device.type != "cpu":self.to("cpu", silence_dtype_warnings=True)torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)hook = Nonefor cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:_, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)# We'll offload the last model manually.self.final_offload_hook = hook8 unmodified linesif not hasattr(self.unet, "_hf_hook"):return self.devicefor module in self.unet.modules():if (hasattr(module, "_hf_hook")and hasattr(module._hf_hook, "execution_device")and module._hf_hook.execution_device is not None):return torch.device(module._hf_hook.execution_device)return self.device34 unmodified lineselif prompt is not None and isinstance(prompt, list):batch_size = len(prompt)else:raise ValueError(f"`prompt` should be either a string or a list of strings, but got {type(prompt)}.")text_inputs = self.tokenizer(prompt,3 unmodified linesreturn_tensors="pt",)text_input_ids = text_inputs.input_idsuntruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_idsif untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])logger.warning("The following part of your input was truncated because CLIP can only handle sequences up to"f" {self.tokenizer.model_max_length} tokens: {removed_text}")if (hasattr(self.text_encoder.config, "use_attention_mask")and self.text_encoder.config.use_attention_mask):attention_mask = text_inputs.attention_mask.to(device)else:attention_mask = None9 unmodified linesbs_embed, seq_len, _ = prompt_embeds.shape# duplicate text embeddings for each generation per prompt, using mps friendly methodprompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)# get unconditional embeddings for classifier free guidanceif do_classifier_free_guidance:1 unmodified lineif negative_prompt is None:uncond_tokens = [""] * batch_sizeelif type(prompt) is not type(negative_prompt):raise TypeError(f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="f" {type(prompt)}.")elif isinstance(negative_prompt, str):uncond_tokens = [negative_prompt]elif batch_size != len(negative_prompt):raise ValueError(f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"" the batch size of `prompt`.")else:uncond_tokens = negative_prompt6 unmodified linesreturn_tensors="pt",)if (hasattr(self.text_encoder.config, "use_attention_mask")and self.text_encoder.config.use_attention_mask):attention_mask = uncond_input.attention_mask.to(device)else:attention_mask = None7 unmodified lines# duplicate unconditional embeddings for each generation per prompt, using mps friendly methodseq_len = negative_prompt_embeds.shape[1]negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)# For classifier free guidance, we need to do two forward passes.# Here we concatenate the unconditional and text embeddings into a single batch16 unmodified lines# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502# and should be between [0, 1]accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())extra_step_kwargs = {}if accepts_eta:extra_step_kwargs["eta"] = eta# check if the scheduler accepts generatoraccepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())if accepts_generator:extra_step_kwargs["generator"] = generatorreturn extra_step_kwargsdef prepare_latents(self,batch_size,num_channels_latents,height,width,dtype,device,generator,latents=None,):shape = (batch_size,num_channels_latents,height // self.vae_scale_factor,width // self.vae_scale_factor,)if isinstance(generator, list) and len(generator) != batch_size:raise ValueError(f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"f" size of {batch_size}. Make sure the batch size matches the length of the generators.")if latents is None:latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)else:latents = latents.to(device)17 unmodified linescallback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,callback_steps: int = 1,batch_size: int = 4,device=torch.device("cuda:0"),):self.unet = self.unet.to(device=device)self.vae = self.vae.to(device=device)self.text_encoder = self.text_encoder.to(device=device)# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`# corresponds to doing no classifier free guidance.9 unmodified linesnum_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=do_classifier_free_guidance,negative_prompt=negative_prompt,) # type: ignoreprompt_embeds_neg, prompt_embeds_pos = _prompt_embeds.chunk(2)# Prepare latent variables7 unmodified linesgenerator,None,)camera = get_camera(batch_size).to(dtype=latents.dtype, device=device)# Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline6 unmodified lines# expand the latents if we are doing classifier free guidancemultiplier = 2 if do_classifier_free_guidance else 1latent_model_input = torch.cat([latents] * multiplier)latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)# predict the noise residualnoise_pred = self.unet.forward(x=latent_model_input,timesteps=torch.tensor([t] * 4 * multiplier,dtype=latent_model_input.dtype,device=device,),context=torch.cat([prompt_embeds_neg] * 4 + [prompt_embeds_pos] * 4),num_frames=4,camera=torch.cat([camera] * multiplier),)1 unmodified line# perform guidanceif do_classifier_free_guidance:noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)# compute the previous noisy sample x_t -> x_t-1# latents = self.scheduler.step(noise_pred.to(dtype=torch.float32), t, latents.to(dtype=torch.float32)).prev_sample.to(prompt_embeds.dtype)latents: torch.Tensor = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):progress_bar.update()if callback is not None and i % callback_steps == 0:callback(i, t, latents) # type: ignore# Post-processingif output_type == "latent":
11 unmodified lines12131415161712 unmodified lines303132333435366 unmodified lines43444546474849505124 unmodified lines767778798081828384858687888990916 unmodified lines989910010110210311 unmodified linesimport torch.nn as nnfrom einops import repeatdef checkpoint(func, inputs, params, flag):"""Evaluate a function without caching intermediate activations, allowing for12 unmodified linesclass CheckpointFunction(torch.autograd.Function):@staticmethoddef forward(ctx, run_function, length, *args):ctx.run_function = run_function6 unmodified lines@staticmethoddef backward(ctx, *output_grads):ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]with torch.enable_grad():# Fixes a bug where the first op in run_function modifies the# Tensor storage in place, which is not allowed for detach()'d24 unmodified linesif not repeat_only:half = dim // 2freqs = torch.exp(-math.log(max_period) *torch.arange(start=0, end=half, dtype=torch.float32) /half).to(device=timesteps.device)args = timesteps[:, None] * freqs[None]embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)if dim % 2:embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)else:embedding = repeat(timesteps, 'b -> b d', d=dim)# import pdb; pdb.set_trace()return embedding6 unmodified linesp.detach().zero_()return moduledef conv_nd(dims, *args, **kwargs):"""Create a 1D, 2D, or 3D convolution module.11 unmodified lines1213141516171812 unmodified lines3132333435366 unmodified lines4344454647484924 unmodified lines7475767778798081828384858687888990916 unmodified lines989910010110210310411 unmodified linesimport torch.nn as nnfrom einops import repeatdef checkpoint(func, inputs, params, flag):"""Evaluate a function without caching intermediate activations, allowing for12 unmodified linesclass CheckpointFunction(torch.autograd.Function):@staticmethoddef forward(ctx, run_function, length, *args):ctx.run_function = run_function6 unmodified lines@staticmethoddef backward(ctx, *output_grads):ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]with torch.enable_grad():# Fixes a bug where the first op in run_function modifies the# Tensor storage in place, which is not allowed for detach()'d24 unmodified linesif not repeat_only:half = dim // 2freqs = torch.exp(-math.log(max_period)* torch.arange(start=0, end=half, dtype=torch.float32)/ half).to(device=timesteps.device)args = timesteps[:, None] * freqs[None]embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)if dim % 2:embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)else:embedding = repeat(timesteps, "b -> b d", d=dim)# import pdb; pdb.set_trace()return embedding6 unmodified linesp.detach().zero_()return moduledef conv_nd(dims, *args, **kwargs):"""Create a 1D, 2D, or 3D convolution module.
convert_mvdream_to_diffusers.py+203-53
main.py+15-8
mvdream/attention.py+181-62
mvdream/models.py+249-226
mvdream/pipeline_mvdream.py+152-70
mvdream/util.py+10-9