diff --git a/diffsynth/data/__init__.py b/diffsynth/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de09a29905d289673e40e53278a0a3181232640d --- /dev/null +++ b/diffsynth/data/__init__.py @@ -0,0 +1 @@ +from .video import VideoData, save_video, save_frames diff --git a/diffsynth/data/__pycache__/__init__.cpython-311.pyc b/diffsynth/data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f01e07c21a2225eb2f36d7ecfe89d05b12b06f7 Binary files /dev/null and b/diffsynth/data/__pycache__/__init__.cpython-311.pyc differ diff --git a/diffsynth/data/__pycache__/video.cpython-311.pyc b/diffsynth/data/__pycache__/video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abebea8bd1a5343e5a8faabf7eb3316e4918573e Binary files /dev/null and b/diffsynth/data/__pycache__/video.cpython-311.pyc differ diff --git a/diffsynth/data/simple_text_image.py b/diffsynth/data/simple_text_image.py new file mode 100644 index 0000000000000000000000000000000000000000..7a9525e3c8a4d21418c1464fe11fc621450fd0d8 --- /dev/null +++ b/diffsynth/data/simple_text_image.py @@ -0,0 +1,41 @@ +import torch, os, torchvision +from torchvision import transforms +import pandas as pd +from PIL import Image + + + +class TextImageDataset(torch.utils.data.Dataset): + def __init__(self, dataset_path, steps_per_epoch=10000, height=1024, width=1024, center_crop=True, random_flip=False): + self.steps_per_epoch = steps_per_epoch + metadata = pd.read_csv(os.path.join(dataset_path, "train/metadata.csv")) + self.path = [os.path.join(dataset_path, "train", file_name) for file_name in metadata["file_name"]] + self.text = metadata["text"].to_list() + self.height = height + self.width = width + self.image_processor = transforms.Compose( + [ + transforms.CenterCrop((height, width)) if center_crop else transforms.RandomCrop((height, width)), + transforms.RandomHorizontalFlip() if random_flip else transforms.Lambda(lambda x: x), + transforms.ToTensor(), + transforms.Normalize([0.5], [0.5]), + ] + ) + + + def __getitem__(self, index): + data_id = torch.randint(0, len(self.path), (1,))[0] + data_id = (data_id + index) % len(self.path) # For fixed seed. + text = self.text[data_id] + image = Image.open(self.path[data_id]).convert("RGB") + target_height, target_width = self.height, self.width + width, height = image.size + scale = max(target_width / width, target_height / height) + shape = [round(height*scale),round(width*scale)] + image = torchvision.transforms.functional.resize(image,shape,interpolation=transforms.InterpolationMode.BILINEAR) + image = self.image_processor(image) + return {"text": text, "image": image} + + + def __len__(self): + return self.steps_per_epoch diff --git a/diffsynth/data/video.py b/diffsynth/data/video.py new file mode 100644 index 0000000000000000000000000000000000000000..8eafa66855fa5668d42a65ac205776ed254213cf --- /dev/null +++ b/diffsynth/data/video.py @@ -0,0 +1,148 @@ +import imageio, os +import numpy as np +from PIL import Image +from tqdm import tqdm + + +class LowMemoryVideo: + def __init__(self, file_name): + self.reader = imageio.get_reader(file_name) + + def __len__(self): + return self.reader.count_frames() + + def __getitem__(self, item): + return Image.fromarray(np.array(self.reader.get_data(item))).convert("RGB") + + def __del__(self): + self.reader.close() + + +def split_file_name(file_name): + result = [] + number = -1 + for i in file_name: + if ord(i)>=ord("0") and ord(i)<=ord("9"): + if number == -1: + number = 0 + number = number*10 + ord(i) - ord("0") + else: + if number != -1: + result.append(number) + number = -1 + result.append(i) + if number != -1: + result.append(number) + result = tuple(result) + return result + + +def search_for_images(folder): + file_list = [i for i in os.listdir(folder) if i.endswith(".jpg") or i.endswith(".png")] + file_list = [(split_file_name(file_name), file_name) for file_name in file_list] + file_list = [i[1] for i in sorted(file_list)] + file_list = [os.path.join(folder, i) for i in file_list] + return file_list + + +class LowMemoryImageFolder: + def __init__(self, folder, file_list=None): + if file_list is None: + self.file_list = search_for_images(folder) + else: + self.file_list = [os.path.join(folder, file_name) for file_name in file_list] + + def __len__(self): + return len(self.file_list) + + def __getitem__(self, item): + return Image.open(self.file_list[item]).convert("RGB") + + def __del__(self): + pass + + +def crop_and_resize(image, height, width): + image = np.array(image) + image_height, image_width, _ = image.shape + if image_height / image_width < height / width: + croped_width = int(image_height / height * width) + left = (image_width - croped_width) // 2 + image = image[:, left: left+croped_width] + image = Image.fromarray(image).resize((width, height)) + else: + croped_height = int(image_width / width * height) + left = (image_height - croped_height) // 2 + image = image[left: left+croped_height, :] + image = Image.fromarray(image).resize((width, height)) + return image + + +class VideoData: + def __init__(self, video_file=None, image_folder=None, height=None, width=None, **kwargs): + if video_file is not None: + self.data_type = "video" + self.data = LowMemoryVideo(video_file, **kwargs) + elif image_folder is not None: + self.data_type = "images" + self.data = LowMemoryImageFolder(image_folder, **kwargs) + else: + raise ValueError("Cannot open video or image folder") + self.length = None + self.set_shape(height, width) + + def raw_data(self): + frames = [] + for i in range(self.__len__()): + frames.append(self.__getitem__(i)) + return frames + + def set_length(self, length): + self.length = length + + def set_shape(self, height, width): + self.height = height + self.width = width + + def __len__(self): + if self.length is None: + return len(self.data) + else: + return self.length + + def shape(self): + if self.height is not None and self.width is not None: + return self.height, self.width + else: + height, width, _ = self.__getitem__(0).shape + return height, width + + def __getitem__(self, item): + frame = self.data.__getitem__(item) + width, height = frame.size + if self.height is not None and self.width is not None: + if self.height != height or self.width != width: + frame = crop_and_resize(frame, self.height, self.width) + return frame + + def __del__(self): + pass + + def save_images(self, folder): + os.makedirs(folder, exist_ok=True) + for i in tqdm(range(self.__len__()), desc="Saving images"): + frame = self.__getitem__(i) + frame.save(os.path.join(folder, f"{i}.png")) + + +def save_video(frames, save_path, fps, quality=9, ffmpeg_params=None): + writer = imageio.get_writer(save_path, fps=fps, quality=quality, ffmpeg_params=ffmpeg_params) + for frame in tqdm(frames, desc="Saving video"): + frame = np.array(frame) + writer.append_data(frame) + writer.close() + +def save_frames(frames, save_path): + os.makedirs(save_path, exist_ok=True) + for i, frame in enumerate(tqdm(frames, desc="Saving images")): + frame.save(os.path.join(save_path, f"{i}.png")) diff --git a/diffsynth/distributed/__init__.py b/diffsynth/distributed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/diffsynth/distributed/__pycache__/__init__.cpython-311.pyc b/diffsynth/distributed/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..041c508042fb3f0dbc89f042a48bb6bdd53b5f35 Binary files /dev/null and b/diffsynth/distributed/__pycache__/__init__.cpython-311.pyc differ diff --git a/diffsynth/distributed/__pycache__/xdit_context_parallel.cpython-311.pyc b/diffsynth/distributed/__pycache__/xdit_context_parallel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13d480e5d10f005a52e392b3d6251ee5fe8c3b07 Binary files /dev/null and b/diffsynth/distributed/__pycache__/xdit_context_parallel.cpython-311.pyc differ diff --git a/diffsynth/distributed/xdit_context_parallel.py b/diffsynth/distributed/xdit_context_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..2c1a2572539aba98ecf900ae264dbaaf29286371 --- /dev/null +++ b/diffsynth/distributed/xdit_context_parallel.py @@ -0,0 +1,129 @@ +import torch +from typing import Optional +from einops import rearrange +from xfuser.core.distributed import (get_sequence_parallel_rank, + get_sequence_parallel_world_size, + get_sp_group) +from xfuser.core.long_ctx_attention import xFuserLongContextAttention + +def sinusoidal_embedding_1d(dim, position): + sinusoid = torch.outer(position.type(torch.float64), torch.pow( + 10000, -torch.arange(dim//2, dtype=torch.float64, device=position.device).div(dim//2))) + x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1) + return x.to(position.dtype) + +def pad_freqs(original_tensor, target_len): + seq_len, s1, s2 = original_tensor.shape + pad_size = target_len - seq_len + padding_tensor = torch.ones( + pad_size, + s1, + s2, + dtype=original_tensor.dtype, + device=original_tensor.device) + padded_tensor = torch.cat([original_tensor, padding_tensor], dim=0) + return padded_tensor + +def rope_apply(x, freqs, num_heads): + x = rearrange(x, "b s (n d) -> b s n d", n=num_heads) + s_per_rank = x.shape[1] + + x_out = torch.view_as_complex(x.to(torch.float64).reshape( + x.shape[0], x.shape[1], x.shape[2], -1, 2)) + + sp_size = get_sequence_parallel_world_size() + sp_rank = get_sequence_parallel_rank() + freqs = pad_freqs(freqs, s_per_rank * sp_size) + freqs_rank = freqs[(sp_rank * s_per_rank):((sp_rank + 1) * s_per_rank), :, :] + + x_out = torch.view_as_real(x_out * freqs_rank).flatten(2) + return x_out.to(x.dtype) + +def usp_dit_forward(self, + x: torch.Tensor, + timestep: torch.Tensor, + context: torch.Tensor, + clip_feature: Optional[torch.Tensor] = None, + y: Optional[torch.Tensor] = None, + use_gradient_checkpointing: bool = False, + use_gradient_checkpointing_offload: bool = False, + **kwargs, + ): + t = self.time_embedding( + sinusoidal_embedding_1d(self.freq_dim, timestep)) + t_mod = self.time_projection(t).unflatten(1, (6, self.dim)) + context = self.text_embedding(context) + + if self.has_image_input: + x = torch.cat([x, y], dim=1) # (b, c_x + c_y, f, h, w) + clip_embdding = self.img_emb(clip_feature) + context = torch.cat([clip_embdding, context], dim=1) + + x, (f, h, w) = self.patchify(x) + + freqs = torch.cat([ + self.freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1), + self.freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1), + self.freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1) + ], dim=-1).reshape(f * h * w, 1, -1).to(x.device) + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + # Context Parallel + x = torch.chunk( + x, get_sequence_parallel_world_size(), + dim=1)[get_sequence_parallel_rank()] + + for block in self.blocks: + if self.training and use_gradient_checkpointing: + if use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = block(x, context, t_mod, freqs) + + x = self.head(x, t) + + # Context Parallel + x = get_sp_group().all_gather(x, dim=1) + + # unpatchify + x = self.unpatchify(x, (f, h, w)) + return x + + +def usp_attn_forward(self, x, freqs): + q = self.norm_q(self.q(x)) + k = self.norm_k(self.k(x)) + v = self.v(x) + + q = rope_apply(q, freqs, self.num_heads) + k = rope_apply(k, freqs, self.num_heads) + q = rearrange(q, "b s (n d) -> b s n d", n=self.num_heads) + k = rearrange(k, "b s (n d) -> b s n d", n=self.num_heads) + v = rearrange(v, "b s (n d) -> b s n d", n=self.num_heads) + + x = xFuserLongContextAttention()( + None, + query=q, + key=k, + value=v, + ) + x = x.flatten(2) + + del q, k, v + torch.cuda.empty_cache() + return self.o(x) \ No newline at end of file diff --git a/diffsynth/pipelines/__init__.py b/diffsynth/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af9e5c9ee17744617eed47b6fc1efe4845106716 --- /dev/null +++ b/diffsynth/pipelines/__init__.py @@ -0,0 +1,15 @@ +from .sd_image import SDImagePipeline +from .sd_video import SDVideoPipeline +from .sdxl_image import SDXLImagePipeline +from .sdxl_video import SDXLVideoPipeline +from .sd3_image import SD3ImagePipeline +from .hunyuan_image import HunyuanDiTImagePipeline +from .svd_video import SVDVideoPipeline +from .flux_image import FluxImagePipeline +from .cog_video import CogVideoPipeline +from .omnigen_image import OmnigenImagePipeline +from .pipeline_runner import SDVideoPipelineRunner +from .hunyuan_video import HunyuanVideoPipeline +from .step_video import StepVideoPipeline +from .wan_video import WanVideoPipeline, WanUniAnimateVideoPipeline, WanRepalceAnyoneVideoPipeline, WanUniAnimateLongVideoPipeline +KolorsImagePipeline = SDXLImagePipeline diff --git a/diffsynth/pipelines/__pycache__/__init__.cpython-311.pyc b/diffsynth/pipelines/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..197abdba12b5c96530a9e9c2ea18fbea0cdcbe87 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/__init__.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/base.cpython-311.pyc b/diffsynth/pipelines/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8921f6d8261a591d01633f47d254931014ebc561 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/base.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/cog_video.cpython-311.pyc b/diffsynth/pipelines/__pycache__/cog_video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78de6e37afa10d63239de0389f6fe771075fdd51 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/cog_video.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/dancer.cpython-311.pyc b/diffsynth/pipelines/__pycache__/dancer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef17705827679ec8365041885da486afff7482e8 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/dancer.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/flux_image.cpython-311.pyc b/diffsynth/pipelines/__pycache__/flux_image.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4df8ae0f1fe930b629d3159e612808dc637d57d8 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/flux_image.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/hunyuan_image.cpython-311.pyc b/diffsynth/pipelines/__pycache__/hunyuan_image.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3add46bfd3d423c4378a0b14c92d9be53e05aef Binary files /dev/null and b/diffsynth/pipelines/__pycache__/hunyuan_image.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/hunyuan_video.cpython-311.pyc b/diffsynth/pipelines/__pycache__/hunyuan_video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa468cb101f6ef59a025426269e64754a2fffb06 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/hunyuan_video.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/omnigen_image.cpython-311.pyc b/diffsynth/pipelines/__pycache__/omnigen_image.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af292aa3bc53ab25fbfa9f66da24c5c00214c2f1 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/omnigen_image.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/pipeline_runner.cpython-311.pyc b/diffsynth/pipelines/__pycache__/pipeline_runner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b24a8875b41e2ed8822499204284acbc187210eb Binary files /dev/null and b/diffsynth/pipelines/__pycache__/pipeline_runner.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/sd3_image.cpython-311.pyc b/diffsynth/pipelines/__pycache__/sd3_image.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e1f113e3537090fc363e5cf1f26fe63db2c5e6f Binary files /dev/null and b/diffsynth/pipelines/__pycache__/sd3_image.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/sd_image.cpython-311.pyc b/diffsynth/pipelines/__pycache__/sd_image.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81ffeb75ef8f19edcaa515eafc65a9647026cc61 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/sd_image.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/sd_video.cpython-311.pyc b/diffsynth/pipelines/__pycache__/sd_video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..874086b01d811bded3e1ef3ab65248268cd3b04b Binary files /dev/null and b/diffsynth/pipelines/__pycache__/sd_video.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/sdxl_image.cpython-311.pyc b/diffsynth/pipelines/__pycache__/sdxl_image.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed818a1efb3d1f610447cf42f7101b5aef47417c Binary files /dev/null and b/diffsynth/pipelines/__pycache__/sdxl_image.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/sdxl_video.cpython-311.pyc b/diffsynth/pipelines/__pycache__/sdxl_video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf02ab014a17b78c6219589f328dd8b7b11facc1 Binary files /dev/null and b/diffsynth/pipelines/__pycache__/sdxl_video.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/step_video.cpython-311.pyc b/diffsynth/pipelines/__pycache__/step_video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b57c3db191676ad8f02d0539b39dcc094a337ed Binary files /dev/null and b/diffsynth/pipelines/__pycache__/step_video.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/svd_video.cpython-311.pyc b/diffsynth/pipelines/__pycache__/svd_video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d704f902dcb11aa0903d5e471fdde5e7bd2462c Binary files /dev/null and b/diffsynth/pipelines/__pycache__/svd_video.cpython-311.pyc differ diff --git a/diffsynth/pipelines/__pycache__/wan_video.cpython-311.pyc b/diffsynth/pipelines/__pycache__/wan_video.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81c20f50ec4d114a1e74b3aa56c636dd80a1b78d Binary files /dev/null and b/diffsynth/pipelines/__pycache__/wan_video.cpython-311.pyc differ diff --git a/diffsynth/pipelines/cog_video.py b/diffsynth/pipelines/cog_video.py new file mode 100644 index 0000000000000000000000000000000000000000..f42d295187e718617cc7d4e327067700f2a689fd --- /dev/null +++ b/diffsynth/pipelines/cog_video.py @@ -0,0 +1,135 @@ +from ..models import ModelManager, FluxTextEncoder2, CogDiT, CogVAEEncoder, CogVAEDecoder +from ..prompters import CogPrompter +from ..schedulers import EnhancedDDIMScheduler +from .base import BasePipeline +import torch +from tqdm import tqdm +from PIL import Image +import numpy as np +from einops import rearrange + + + +class CogVideoPipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16) + self.scheduler = EnhancedDDIMScheduler(rescale_zero_terminal_snr=True, prediction_type="v_prediction") + self.prompter = CogPrompter() + # models + self.text_encoder: FluxTextEncoder2 = None + self.dit: CogDiT = None + self.vae_encoder: CogVAEEncoder = None + self.vae_decoder: CogVAEDecoder = None + + + def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]): + self.text_encoder = model_manager.fetch_model("flux_text_encoder_2") + self.dit = model_manager.fetch_model("cog_dit") + self.vae_encoder = model_manager.fetch_model("cog_vae_encoder") + self.vae_decoder = model_manager.fetch_model("cog_vae_decoder") + self.prompter.fetch_models(self.text_encoder) + self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes) + + + @staticmethod + def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[]): + pipe = CogVideoPipeline( + device=model_manager.device, + torch_dtype=model_manager.torch_dtype + ) + pipe.fetch_models(model_manager, prompt_refiner_classes) + return pipe + + + def tensor2video(self, frames): + frames = rearrange(frames, "C T H W -> T H W C") + frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8) + frames = [Image.fromarray(frame) for frame in frames] + return frames + + + def encode_prompt(self, prompt, positive=True): + prompt_emb = self.prompter.encode_prompt(prompt, device=self.device, positive=positive) + return {"prompt_emb": prompt_emb} + + + def prepare_extra_input(self, latents): + return {"image_rotary_emb": self.dit.prepare_rotary_positional_embeddings(latents.shape[3], latents.shape[4], latents.shape[2], device=self.device)} + + + @torch.no_grad() + def __call__( + self, + prompt, + negative_prompt="", + input_video=None, + cfg_scale=7.0, + denoising_strength=1.0, + num_frames=49, + height=480, + width=720, + num_inference_steps=20, + tiled=False, + tile_size=(60, 90), + tile_stride=(30, 45), + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Tiler parameters + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength) + + # Prepare latent tensors + noise = self.generate_noise((1, 16, num_frames // 4 + 1, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype) + + if denoising_strength == 1.0: + latents = noise.clone() + else: + input_video = self.preprocess_images(input_video) + input_video = torch.stack(input_video, dim=2) + latents = self.vae_encoder.encode_video(input_video, **tiler_kwargs, progress_bar=progress_bar_cmd).to(dtype=self.torch_dtype) + latents = self.scheduler.add_noise(latents, noise, self.scheduler.timesteps[0]) + if not tiled: latents = latents.to(self.device) + + # Encode prompt + prompt_emb_posi = self.encode_prompt(prompt, positive=True) + if cfg_scale != 1.0: + prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False) + + # Extra input + extra_input = self.prepare_extra_input(latents) + + # Denoise + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(self.device) + + # Classifier-free guidance + noise_pred_posi = self.dit( + latents, timestep=timestep, **prompt_emb_posi, **tiler_kwargs, **extra_input + ) + if cfg_scale != 1.0: + noise_pred_nega = self.dit( + latents, timestep=timestep, **prompt_emb_nega, **tiler_kwargs, **extra_input + ) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + else: + noise_pred = noise_pred_posi + + # DDIM + latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents) + + # Update progress bar + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + video = self.vae_decoder.decode_video(latents.to("cpu"), **tiler_kwargs, progress_bar=progress_bar_cmd) + video = self.tensor2video(video[0]) + + return video diff --git a/diffsynth/pipelines/dancer.py b/diffsynth/pipelines/dancer.py new file mode 100644 index 0000000000000000000000000000000000000000..593b57c8363f94e312debf7c7f69bf6decdb7dbd --- /dev/null +++ b/diffsynth/pipelines/dancer.py @@ -0,0 +1,236 @@ +import torch +from ..models import SDUNet, SDMotionModel, SDXLUNet, SDXLMotionModel +from ..models.sd_unet import PushBlock, PopBlock +from ..controlnets import MultiControlNetManager + + +def lets_dance( + unet: SDUNet, + motion_modules: SDMotionModel = None, + controlnet: MultiControlNetManager = None, + sample = None, + timestep = None, + encoder_hidden_states = None, + ipadapter_kwargs_list = {}, + controlnet_frames = None, + unet_batch_size = 1, + controlnet_batch_size = 1, + cross_frame_attention = False, + tiled=False, + tile_size=64, + tile_stride=32, + device = "cuda", + vram_limit_level = 0, +): + # 0. Text embedding alignment (only for video processing) + if encoder_hidden_states.shape[0] != sample.shape[0]: + encoder_hidden_states = encoder_hidden_states.repeat(sample.shape[0], 1, 1, 1) + + # 1. ControlNet + # This part will be repeated on overlapping frames if animatediff_batch_size > animatediff_stride. + # I leave it here because I intend to do something interesting on the ControlNets. + controlnet_insert_block_id = 30 + if controlnet is not None and controlnet_frames is not None: + res_stacks = [] + # process controlnet frames with batch + for batch_id in range(0, sample.shape[0], controlnet_batch_size): + batch_id_ = min(batch_id + controlnet_batch_size, sample.shape[0]) + res_stack = controlnet( + sample[batch_id: batch_id_], + timestep, + encoder_hidden_states[batch_id: batch_id_], + controlnet_frames[:, batch_id: batch_id_], + tiled=tiled, tile_size=tile_size, tile_stride=tile_stride + ) + if vram_limit_level >= 1: + res_stack = [res.cpu() for res in res_stack] + res_stacks.append(res_stack) + # concat the residual + additional_res_stack = [] + for i in range(len(res_stacks[0])): + res = torch.concat([res_stack[i] for res_stack in res_stacks], dim=0) + additional_res_stack.append(res) + else: + additional_res_stack = None + + # 2. time + time_emb = unet.time_proj(timestep).to(sample.dtype) + time_emb = unet.time_embedding(time_emb) + + # 3. pre-process + height, width = sample.shape[2], sample.shape[3] + hidden_states = unet.conv_in(sample) + text_emb = encoder_hidden_states + res_stack = [hidden_states.cpu() if vram_limit_level>=1 else hidden_states] + + # 4. blocks + for block_id, block in enumerate(unet.blocks): + # 4.1 UNet + if isinstance(block, PushBlock): + hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack) + if vram_limit_level>=1: + res_stack[-1] = res_stack[-1].cpu() + elif isinstance(block, PopBlock): + if vram_limit_level>=1: + res_stack[-1] = res_stack[-1].to(device) + hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack) + else: + hidden_states_input = hidden_states + hidden_states_output = [] + for batch_id in range(0, sample.shape[0], unet_batch_size): + batch_id_ = min(batch_id + unet_batch_size, sample.shape[0]) + hidden_states, _, _, _ = block( + hidden_states_input[batch_id: batch_id_], + time_emb, + text_emb[batch_id: batch_id_], + res_stack, + cross_frame_attention=cross_frame_attention, + ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id, {}), + tiled=tiled, tile_size=tile_size, tile_stride=tile_stride + ) + hidden_states_output.append(hidden_states) + hidden_states = torch.concat(hidden_states_output, dim=0) + # 4.2 AnimateDiff + if motion_modules is not None: + if block_id in motion_modules.call_block_id: + motion_module_id = motion_modules.call_block_id[block_id] + hidden_states, time_emb, text_emb, res_stack = motion_modules.motion_modules[motion_module_id]( + hidden_states, time_emb, text_emb, res_stack, + batch_size=1 + ) + # 4.3 ControlNet + if block_id == controlnet_insert_block_id and additional_res_stack is not None: + hidden_states += additional_res_stack.pop().to(device) + if vram_limit_level>=1: + res_stack = [(res.to(device) + additional_res.to(device)).cpu() for res, additional_res in zip(res_stack, additional_res_stack)] + else: + res_stack = [res + additional_res for res, additional_res in zip(res_stack, additional_res_stack)] + + # 5. output + hidden_states = unet.conv_norm_out(hidden_states) + hidden_states = unet.conv_act(hidden_states) + hidden_states = unet.conv_out(hidden_states) + + return hidden_states + + + + +def lets_dance_xl( + unet: SDXLUNet, + motion_modules: SDXLMotionModel = None, + controlnet: MultiControlNetManager = None, + sample = None, + add_time_id = None, + add_text_embeds = None, + timestep = None, + encoder_hidden_states = None, + ipadapter_kwargs_list = {}, + controlnet_frames = None, + unet_batch_size = 1, + controlnet_batch_size = 1, + cross_frame_attention = False, + tiled=False, + tile_size=64, + tile_stride=32, + device = "cuda", + vram_limit_level = 0, +): + # 0. Text embedding alignment (only for video processing) + if encoder_hidden_states.shape[0] != sample.shape[0]: + encoder_hidden_states = encoder_hidden_states.repeat(sample.shape[0], 1, 1, 1) + if add_text_embeds.shape[0] != sample.shape[0]: + add_text_embeds = add_text_embeds.repeat(sample.shape[0], 1) + + # 1. ControlNet + controlnet_insert_block_id = 22 + if controlnet is not None and controlnet_frames is not None: + res_stacks = [] + # process controlnet frames with batch + for batch_id in range(0, sample.shape[0], controlnet_batch_size): + batch_id_ = min(batch_id + controlnet_batch_size, sample.shape[0]) + res_stack = controlnet( + sample[batch_id: batch_id_], + timestep, + encoder_hidden_states[batch_id: batch_id_], + controlnet_frames[:, batch_id: batch_id_], + add_time_id=add_time_id, + add_text_embeds=add_text_embeds, + tiled=tiled, tile_size=tile_size, tile_stride=tile_stride, + unet=unet, # for Kolors, some modules in ControlNets will be replaced. + ) + if vram_limit_level >= 1: + res_stack = [res.cpu() for res in res_stack] + res_stacks.append(res_stack) + # concat the residual + additional_res_stack = [] + for i in range(len(res_stacks[0])): + res = torch.concat([res_stack[i] for res_stack in res_stacks], dim=0) + additional_res_stack.append(res) + else: + additional_res_stack = None + + # 2. time + t_emb = unet.time_proj(timestep).to(sample.dtype) + t_emb = unet.time_embedding(t_emb) + + time_embeds = unet.add_time_proj(add_time_id) + time_embeds = time_embeds.reshape((add_text_embeds.shape[0], -1)) + add_embeds = torch.concat([add_text_embeds, time_embeds], dim=-1) + add_embeds = add_embeds.to(sample.dtype) + add_embeds = unet.add_time_embedding(add_embeds) + + time_emb = t_emb + add_embeds + + # 3. pre-process + height, width = sample.shape[2], sample.shape[3] + hidden_states = unet.conv_in(sample) + text_emb = encoder_hidden_states if unet.text_intermediate_proj is None else unet.text_intermediate_proj(encoder_hidden_states) + res_stack = [hidden_states] + + # 4. blocks + for block_id, block in enumerate(unet.blocks): + # 4.1 UNet + if isinstance(block, PushBlock): + hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack) + if vram_limit_level>=1: + res_stack[-1] = res_stack[-1].cpu() + elif isinstance(block, PopBlock): + if vram_limit_level>=1: + res_stack[-1] = res_stack[-1].to(device) + hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack) + else: + hidden_states_input = hidden_states + hidden_states_output = [] + for batch_id in range(0, sample.shape[0], unet_batch_size): + batch_id_ = min(batch_id + unet_batch_size, sample.shape[0]) + hidden_states, _, _, _ = block( + hidden_states_input[batch_id: batch_id_], + time_emb[batch_id: batch_id_], + text_emb[batch_id: batch_id_], + res_stack, + cross_frame_attention=cross_frame_attention, + ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id, {}), + tiled=tiled, tile_size=tile_size, tile_stride=tile_stride, + ) + hidden_states_output.append(hidden_states) + hidden_states = torch.concat(hidden_states_output, dim=0) + # 4.2 AnimateDiff + if motion_modules is not None: + if block_id in motion_modules.call_block_id: + motion_module_id = motion_modules.call_block_id[block_id] + hidden_states, time_emb, text_emb, res_stack = motion_modules.motion_modules[motion_module_id]( + hidden_states, time_emb, text_emb, res_stack, + batch_size=1 + ) + # 4.3 ControlNet + if block_id == controlnet_insert_block_id and additional_res_stack is not None: + hidden_states += additional_res_stack.pop().to(device) + res_stack = [res + additional_res for res, additional_res in zip(res_stack, additional_res_stack)] + + # 5. output + hidden_states = unet.conv_norm_out(hidden_states) + hidden_states = unet.conv_act(hidden_states) + hidden_states = unet.conv_out(hidden_states) + + return hidden_states \ No newline at end of file diff --git a/diffsynth/pipelines/flux_image.py b/diffsynth/pipelines/flux_image.py new file mode 100644 index 0000000000000000000000000000000000000000..7303dff16d79b40eb74874df6e91ed15dcfa0d98 --- /dev/null +++ b/diffsynth/pipelines/flux_image.py @@ -0,0 +1,646 @@ +from ..models import ModelManager, FluxDiT, SD3TextEncoder1, FluxTextEncoder2, FluxVAEDecoder, FluxVAEEncoder, FluxIpAdapter +from ..controlnets import FluxMultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator +from ..prompters import FluxPrompter +from ..schedulers import FlowMatchScheduler +from .base import BasePipeline +from typing import List +import torch +from tqdm import tqdm +import numpy as np +from PIL import Image +from ..models.tiler import FastTileWorker +from transformers import SiglipVisionModel +from copy import deepcopy +from transformers.models.t5.modeling_t5 import T5LayerNorm, T5DenseActDense, T5DenseGatedActDense +from ..models.flux_dit import RMSNorm +from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear + + +class FluxImagePipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16) + self.scheduler = FlowMatchScheduler() + self.prompter = FluxPrompter() + # models + self.text_encoder_1: SD3TextEncoder1 = None + self.text_encoder_2: FluxTextEncoder2 = None + self.dit: FluxDiT = None + self.vae_decoder: FluxVAEDecoder = None + self.vae_encoder: FluxVAEEncoder = None + self.controlnet: FluxMultiControlNetManager = None + self.ipadapter: FluxIpAdapter = None + self.ipadapter_image_encoder: SiglipVisionModel = None + self.model_names = ['text_encoder_1', 'text_encoder_2', 'dit', 'vae_decoder', 'vae_encoder', 'controlnet', 'ipadapter', 'ipadapter_image_encoder'] + + + def enable_vram_management(self, num_persistent_param_in_dit=None): + dtype = next(iter(self.text_encoder_1.parameters())).dtype + enable_vram_management( + self.text_encoder_1, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Embedding: AutoWrappedModule, + torch.nn.LayerNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + dtype = next(iter(self.text_encoder_2.parameters())).dtype + enable_vram_management( + self.text_encoder_2, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Embedding: AutoWrappedModule, + T5LayerNorm: AutoWrappedModule, + T5DenseActDense: AutoWrappedModule, + T5DenseGatedActDense: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + dtype = next(iter(self.dit.parameters())).dtype + enable_vram_management( + self.dit, + module_map = { + RMSNorm: AutoWrappedModule, + torch.nn.Linear: AutoWrappedLinear, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cuda", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + max_num_param=num_persistent_param_in_dit, + overflow_module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + dtype = next(iter(self.vae_decoder.parameters())).dtype + enable_vram_management( + self.vae_decoder, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv2d: AutoWrappedModule, + torch.nn.GroupNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + dtype = next(iter(self.vae_encoder.parameters())).dtype + enable_vram_management( + self.vae_encoder, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv2d: AutoWrappedModule, + torch.nn.GroupNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + self.enable_cpu_offload() + + + def denoising_model(self): + return self.dit + + + def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[], prompt_extender_classes=[]): + self.text_encoder_1 = model_manager.fetch_model("sd3_text_encoder_1") + self.text_encoder_2 = model_manager.fetch_model("flux_text_encoder_2") + self.dit = model_manager.fetch_model("flux_dit") + self.vae_decoder = model_manager.fetch_model("flux_vae_decoder") + self.vae_encoder = model_manager.fetch_model("flux_vae_encoder") + self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2) + self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes) + self.prompter.load_prompt_extenders(model_manager, prompt_extender_classes) + + # ControlNets + controlnet_units = [] + for config in controlnet_config_units: + controlnet_unit = ControlNetUnit( + Annotator(config.processor_id, device=self.device, skip_processor=config.skip_processor), + model_manager.fetch_model("flux_controlnet", config.model_path), + config.scale + ) + controlnet_units.append(controlnet_unit) + self.controlnet = FluxMultiControlNetManager(controlnet_units) + + # IP-Adapters + self.ipadapter = model_manager.fetch_model("flux_ipadapter") + self.ipadapter_image_encoder = model_manager.fetch_model("siglip_vision_model") + + + @staticmethod + def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[], prompt_extender_classes=[], device=None, torch_dtype=None): + pipe = FluxImagePipeline( + device=model_manager.device if device is None else device, + torch_dtype=model_manager.torch_dtype if torch_dtype is None else torch_dtype, + ) + pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes, prompt_extender_classes) + return pipe + + + def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32): + latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + return latents + + + def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32): + image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + image = self.vae_output_to_image(image) + return image + + + def encode_prompt(self, prompt, positive=True, t5_sequence_length=512): + prompt_emb, pooled_prompt_emb, text_ids = self.prompter.encode_prompt( + prompt, device=self.device, positive=positive, t5_sequence_length=t5_sequence_length + ) + return {"prompt_emb": prompt_emb, "pooled_prompt_emb": pooled_prompt_emb, "text_ids": text_ids} + + + def prepare_extra_input(self, latents=None, guidance=1.0): + latent_image_ids = self.dit.prepare_image_ids(latents) + guidance = torch.Tensor([guidance] * latents.shape[0]).to(device=latents.device, dtype=latents.dtype) + return {"image_ids": latent_image_ids, "guidance": guidance} + + + def apply_controlnet_mask_on_latents(self, latents, mask): + mask = (self.preprocess_image(mask) + 1) / 2 + mask = mask.mean(dim=1, keepdim=True) + mask = mask.to(dtype=self.torch_dtype, device=self.device) + mask = 1 - torch.nn.functional.interpolate(mask, size=latents.shape[-2:]) + latents = torch.concat([latents, mask], dim=1) + return latents + + + def apply_controlnet_mask_on_image(self, image, mask): + mask = mask.resize(image.size) + mask = self.preprocess_image(mask).mean(dim=[0, 1]) + image = np.array(image) + image[mask > 0] = 0 + image = Image.fromarray(image) + return image + + + def prepare_controlnet_input(self, controlnet_image, controlnet_inpaint_mask, tiler_kwargs): + if isinstance(controlnet_image, Image.Image): + controlnet_image = [controlnet_image] * len(self.controlnet.processors) + + controlnet_frames = [] + for i in range(len(self.controlnet.processors)): + # image annotator + image = self.controlnet.process_image(controlnet_image[i], processor_id=i)[0] + if controlnet_inpaint_mask is not None and self.controlnet.processors[i].processor_id == "inpaint": + image = self.apply_controlnet_mask_on_image(image, controlnet_inpaint_mask) + + # image to tensor + image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype) + + # vae encoder + image = self.encode_image(image, **tiler_kwargs) + if controlnet_inpaint_mask is not None and self.controlnet.processors[i].processor_id == "inpaint": + image = self.apply_controlnet_mask_on_latents(image, controlnet_inpaint_mask) + + # store it + controlnet_frames.append(image) + return controlnet_frames + + + def prepare_ipadapter_inputs(self, images, height=384, width=384): + images = [image.convert("RGB").resize((width, height), resample=3) for image in images] + images = [self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype) for image in images] + return torch.cat(images, dim=0) + + + def inpaint_fusion(self, latents, inpaint_latents, pred_noise, fg_mask, bg_mask, progress_id, background_weight=0.): + # inpaint noise + inpaint_noise = (latents - inpaint_latents) / self.scheduler.sigmas[progress_id] + # merge noise + weight = torch.ones_like(inpaint_noise) + inpaint_noise[fg_mask] = pred_noise[fg_mask] + inpaint_noise[bg_mask] += pred_noise[bg_mask] * background_weight + weight[bg_mask] += background_weight + inpaint_noise /= weight + return inpaint_noise + + + def preprocess_masks(self, masks, height, width, dim): + out_masks = [] + for mask in masks: + mask = self.preprocess_image(mask.resize((width, height), resample=Image.NEAREST)).mean(dim=1, keepdim=True) > 0 + mask = mask.repeat(1, dim, 1, 1).to(device=self.device, dtype=self.torch_dtype) + out_masks.append(mask) + return out_masks + + + def prepare_entity_inputs(self, entity_prompts, entity_masks, width, height, t5_sequence_length=512, enable_eligen_inpaint=False): + fg_mask, bg_mask = None, None + if enable_eligen_inpaint: + masks_ = deepcopy(entity_masks) + fg_masks = torch.cat([self.preprocess_image(mask.resize((width//8, height//8))).mean(dim=1, keepdim=True) for mask in masks_]) + fg_masks = (fg_masks > 0).float() + fg_mask = fg_masks.sum(dim=0, keepdim=True).repeat(1, 16, 1, 1) > 0 + bg_mask = ~fg_mask + entity_masks = self.preprocess_masks(entity_masks, height//8, width//8, 1) + entity_masks = torch.cat(entity_masks, dim=0).unsqueeze(0) # b, n_mask, c, h, w + entity_prompts = self.encode_prompt(entity_prompts, t5_sequence_length=t5_sequence_length)['prompt_emb'].unsqueeze(0) + return entity_prompts, entity_masks, fg_mask, bg_mask + + + def prepare_latents(self, input_image, height, width, seed, tiled, tile_size, tile_stride): + if input_image is not None: + self.load_models_to_device(['vae_encoder']) + image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype) + input_latents = self.encode_image(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + noise = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + latents = self.scheduler.add_noise(input_latents, noise, timestep=self.scheduler.timesteps[0]) + else: + latents = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + input_latents = None + return latents, input_latents + + + def prepare_ipadapter(self, ipadapter_images, ipadapter_scale): + if ipadapter_images is not None: + self.load_models_to_device(['ipadapter_image_encoder']) + ipadapter_images = self.prepare_ipadapter_inputs(ipadapter_images) + ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images).pooler_output + self.load_models_to_device(['ipadapter']) + ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)} + ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))} + else: + ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}} + return ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega + + + def prepare_controlnet(self, controlnet_image, masks, controlnet_inpaint_mask, tiler_kwargs, enable_controlnet_on_negative): + if controlnet_image is not None: + self.load_models_to_device(['vae_encoder']) + controlnet_kwargs_posi = {"controlnet_frames": self.prepare_controlnet_input(controlnet_image, controlnet_inpaint_mask, tiler_kwargs)} + if len(masks) > 0 and controlnet_inpaint_mask is not None: + print("The controlnet_inpaint_mask will be overridden by masks.") + local_controlnet_kwargs = [{"controlnet_frames": self.prepare_controlnet_input(controlnet_image, mask, tiler_kwargs)} for mask in masks] + else: + local_controlnet_kwargs = None + else: + controlnet_kwargs_posi, local_controlnet_kwargs = {"controlnet_frames": None}, [{}] * len(masks) + controlnet_kwargs_nega = controlnet_kwargs_posi if enable_controlnet_on_negative else {} + return controlnet_kwargs_posi, controlnet_kwargs_nega, local_controlnet_kwargs + + + def prepare_eligen(self, prompt_emb_nega, eligen_entity_prompts, eligen_entity_masks, width, height, t5_sequence_length, enable_eligen_inpaint, enable_eligen_on_negative, cfg_scale): + if eligen_entity_masks is not None: + entity_prompt_emb_posi, entity_masks_posi, fg_mask, bg_mask = self.prepare_entity_inputs(eligen_entity_prompts, eligen_entity_masks, width, height, t5_sequence_length, enable_eligen_inpaint) + if enable_eligen_on_negative and cfg_scale != 1.0: + entity_prompt_emb_nega = prompt_emb_nega['prompt_emb'].unsqueeze(1).repeat(1, entity_masks_posi.shape[1], 1, 1) + entity_masks_nega = entity_masks_posi + else: + entity_prompt_emb_nega, entity_masks_nega = None, None + else: + entity_prompt_emb_posi, entity_masks_posi, entity_prompt_emb_nega, entity_masks_nega = None, None, None, None + fg_mask, bg_mask = None, None + eligen_kwargs_posi = {"entity_prompt_emb": entity_prompt_emb_posi, "entity_masks": entity_masks_posi} + eligen_kwargs_nega = {"entity_prompt_emb": entity_prompt_emb_nega, "entity_masks": entity_masks_nega} + return eligen_kwargs_posi, eligen_kwargs_nega, fg_mask, bg_mask + + + def prepare_prompts(self, prompt, local_prompts, masks, mask_scales, t5_sequence_length, negative_prompt, cfg_scale): + # Extend prompt + self.load_models_to_device(['text_encoder_1', 'text_encoder_2']) + prompt, local_prompts, masks, mask_scales = self.extend_prompt(prompt, local_prompts, masks, mask_scales) + + # Encode prompts + prompt_emb_posi = self.encode_prompt(prompt, t5_sequence_length=t5_sequence_length) + prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False, t5_sequence_length=t5_sequence_length) if cfg_scale != 1.0 else None + prompt_emb_locals = [self.encode_prompt(prompt_local, t5_sequence_length=t5_sequence_length) for prompt_local in local_prompts] + return prompt_emb_posi, prompt_emb_nega, prompt_emb_locals + + + @torch.no_grad() + def __call__( + self, + # Prompt + prompt, + negative_prompt="", + cfg_scale=1.0, + embedded_guidance=3.5, + t5_sequence_length=512, + # Image + input_image=None, + denoising_strength=1.0, + height=1024, + width=1024, + seed=None, + # Steps + num_inference_steps=30, + # local prompts + local_prompts=(), + masks=(), + mask_scales=(), + # ControlNet + controlnet_image=None, + controlnet_inpaint_mask=None, + enable_controlnet_on_negative=False, + # IP-Adapter + ipadapter_images=None, + ipadapter_scale=1.0, + # EliGen + eligen_entity_prompts=None, + eligen_entity_masks=None, + enable_eligen_on_negative=False, + enable_eligen_inpaint=False, + # TeaCache + tea_cache_l1_thresh=None, + # Tile + tiled=False, + tile_size=128, + tile_stride=64, + # Progress bar + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Tiler parameters + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Prepare latent tensors + latents, input_latents = self.prepare_latents(input_image, height, width, seed, tiled, tile_size, tile_stride) + + # Prompt + prompt_emb_posi, prompt_emb_nega, prompt_emb_locals = self.prepare_prompts(prompt, local_prompts, masks, mask_scales, t5_sequence_length, negative_prompt, cfg_scale) + + # Extra input + extra_input = self.prepare_extra_input(latents, guidance=embedded_guidance) + + # Entity control + eligen_kwargs_posi, eligen_kwargs_nega, fg_mask, bg_mask = self.prepare_eligen(prompt_emb_nega, eligen_entity_prompts, eligen_entity_masks, width, height, t5_sequence_length, enable_eligen_inpaint, enable_eligen_on_negative, cfg_scale) + + # IP-Adapter + ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = self.prepare_ipadapter(ipadapter_images, ipadapter_scale) + + # ControlNets + controlnet_kwargs_posi, controlnet_kwargs_nega, local_controlnet_kwargs = self.prepare_controlnet(controlnet_image, masks, controlnet_inpaint_mask, tiler_kwargs, enable_controlnet_on_negative) + + # TeaCache + tea_cache_kwargs = {"tea_cache": TeaCache(num_inference_steps, rel_l1_thresh=tea_cache_l1_thresh) if tea_cache_l1_thresh is not None else None} + + # Denoise + self.load_models_to_device(['dit', 'controlnet']) + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(self.device) + + # Positive side + inference_callback = lambda prompt_emb_posi, controlnet_kwargs: lets_dance_flux( + dit=self.dit, controlnet=self.controlnet, + hidden_states=latents, timestep=timestep, + **prompt_emb_posi, **tiler_kwargs, **extra_input, **controlnet_kwargs, **ipadapter_kwargs_list_posi, **eligen_kwargs_posi, **tea_cache_kwargs, + ) + noise_pred_posi = self.control_noise_via_local_prompts( + prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback, + special_kwargs=controlnet_kwargs_posi, special_local_kwargs_list=local_controlnet_kwargs + ) + + # Inpaint + if enable_eligen_inpaint: + noise_pred_posi = self.inpaint_fusion(latents, input_latents, noise_pred_posi, fg_mask, bg_mask, progress_id) + + # Classifier-free guidance + if cfg_scale != 1.0: + # Negative side + noise_pred_nega = lets_dance_flux( + dit=self.dit, controlnet=self.controlnet, + hidden_states=latents, timestep=timestep, + **prompt_emb_nega, **tiler_kwargs, **extra_input, **controlnet_kwargs_nega, **ipadapter_kwargs_list_nega, **eligen_kwargs_nega, + ) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + else: + noise_pred = noise_pred_posi + + # Iterate + latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents) + + # UI + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + self.load_models_to_device(['vae_decoder']) + image = self.decode_image(latents, **tiler_kwargs) + + # Offload all models + self.load_models_to_device([]) + return image + + +class TeaCache: + def __init__(self, num_inference_steps, rel_l1_thresh): + self.num_inference_steps = num_inference_steps + self.step = 0 + self.accumulated_rel_l1_distance = 0 + self.previous_modulated_input = None + self.rel_l1_thresh = rel_l1_thresh + self.previous_residual = None + self.previous_hidden_states = None + + def check(self, dit: FluxDiT, hidden_states, conditioning): + inp = hidden_states.clone() + temb_ = conditioning.clone() + modulated_inp, _, _, _, _ = dit.blocks[0].norm1_a(inp, emb=temb_) + if self.step == 0 or self.step == self.num_inference_steps - 1: + should_calc = True + self.accumulated_rel_l1_distance = 0 + else: + coefficients = [4.98651651e+02, -2.83781631e+02, 5.58554382e+01, -3.82021401e+00, 2.64230861e-01] + rescale_func = np.poly1d(coefficients) + self.accumulated_rel_l1_distance += rescale_func(((modulated_inp-self.previous_modulated_input).abs().mean() / self.previous_modulated_input.abs().mean()).cpu().item()) + if self.accumulated_rel_l1_distance < self.rel_l1_thresh: + should_calc = False + else: + should_calc = True + self.accumulated_rel_l1_distance = 0 + self.previous_modulated_input = modulated_inp + self.step += 1 + if self.step == self.num_inference_steps: + self.step = 0 + if should_calc: + self.previous_hidden_states = hidden_states.clone() + return not should_calc + + def store(self, hidden_states): + self.previous_residual = hidden_states - self.previous_hidden_states + self.previous_hidden_states = None + + def update(self, hidden_states): + hidden_states = hidden_states + self.previous_residual + return hidden_states + + +def lets_dance_flux( + dit: FluxDiT, + controlnet: FluxMultiControlNetManager = None, + hidden_states=None, + timestep=None, + prompt_emb=None, + pooled_prompt_emb=None, + guidance=None, + text_ids=None, + image_ids=None, + controlnet_frames=None, + tiled=False, + tile_size=128, + tile_stride=64, + entity_prompt_emb=None, + entity_masks=None, + ipadapter_kwargs_list={}, + tea_cache: TeaCache = None, + **kwargs +): + if tiled: + def flux_forward_fn(hl, hr, wl, wr): + tiled_controlnet_frames = [f[:, :, hl: hr, wl: wr] for f in controlnet_frames] if controlnet_frames is not None else None + return lets_dance_flux( + dit=dit, + controlnet=controlnet, + hidden_states=hidden_states[:, :, hl: hr, wl: wr], + timestep=timestep, + prompt_emb=prompt_emb, + pooled_prompt_emb=pooled_prompt_emb, + guidance=guidance, + text_ids=text_ids, + image_ids=None, + controlnet_frames=tiled_controlnet_frames, + tiled=False, + **kwargs + ) + return FastTileWorker().tiled_forward( + flux_forward_fn, + hidden_states, + tile_size=tile_size, + tile_stride=tile_stride, + tile_device=hidden_states.device, + tile_dtype=hidden_states.dtype + ) + + + # ControlNet + if controlnet is not None and controlnet_frames is not None: + controlnet_extra_kwargs = { + "hidden_states": hidden_states, + "timestep": timestep, + "prompt_emb": prompt_emb, + "pooled_prompt_emb": pooled_prompt_emb, + "guidance": guidance, + "text_ids": text_ids, + "image_ids": image_ids, + "tiled": tiled, + "tile_size": tile_size, + "tile_stride": tile_stride, + } + controlnet_res_stack, controlnet_single_res_stack = controlnet( + controlnet_frames, **controlnet_extra_kwargs + ) + + if image_ids is None: + image_ids = dit.prepare_image_ids(hidden_states) + + conditioning = dit.time_embedder(timestep, hidden_states.dtype) + dit.pooled_text_embedder(pooled_prompt_emb) + if dit.guidance_embedder is not None: + guidance = guidance * 1000 + conditioning = conditioning + dit.guidance_embedder(guidance, hidden_states.dtype) + + height, width = hidden_states.shape[-2:] + hidden_states = dit.patchify(hidden_states) + hidden_states = dit.x_embedder(hidden_states) + + if entity_prompt_emb is not None and entity_masks is not None: + prompt_emb, image_rotary_emb, attention_mask = dit.process_entity_masks(hidden_states, prompt_emb, entity_prompt_emb, entity_masks, text_ids, image_ids) + else: + prompt_emb = dit.context_embedder(prompt_emb) + image_rotary_emb = dit.pos_embedder(torch.cat((text_ids, image_ids), dim=1)) + attention_mask = None + + # TeaCache + if tea_cache is not None: + tea_cache_update = tea_cache.check(dit, hidden_states, conditioning) + else: + tea_cache_update = False + + if tea_cache_update: + hidden_states = tea_cache.update(hidden_states) + else: + # Joint Blocks + for block_id, block in enumerate(dit.blocks): + hidden_states, prompt_emb = block( + hidden_states, + prompt_emb, + conditioning, + image_rotary_emb, + attention_mask, + ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id, None) + ) + # ControlNet + if controlnet is not None and controlnet_frames is not None: + hidden_states = hidden_states + controlnet_res_stack[block_id] + + # Single Blocks + hidden_states = torch.cat([prompt_emb, hidden_states], dim=1) + num_joint_blocks = len(dit.blocks) + for block_id, block in enumerate(dit.single_blocks): + hidden_states, prompt_emb = block( + hidden_states, + prompt_emb, + conditioning, + image_rotary_emb, + attention_mask, + ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id + num_joint_blocks, None) + ) + # ControlNet + if controlnet is not None and controlnet_frames is not None: + hidden_states[:, prompt_emb.shape[1]:] = hidden_states[:, prompt_emb.shape[1]:] + controlnet_single_res_stack[block_id] + hidden_states = hidden_states[:, prompt_emb.shape[1]:] + + if tea_cache is not None: + tea_cache.store(hidden_states) + + hidden_states = dit.final_norm_out(hidden_states, conditioning) + hidden_states = dit.final_proj_out(hidden_states) + hidden_states = dit.unpatchify(hidden_states, height, width) + + return hidden_states diff --git a/diffsynth/pipelines/hunyuan_image.py b/diffsynth/pipelines/hunyuan_image.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6f6d5dedc6aac50b06a9f10701f7f8ab33117f --- /dev/null +++ b/diffsynth/pipelines/hunyuan_image.py @@ -0,0 +1,288 @@ +from ..models.hunyuan_dit import HunyuanDiT +from ..models.hunyuan_dit_text_encoder import HunyuanDiTCLIPTextEncoder, HunyuanDiTT5TextEncoder +from ..models.sdxl_vae_encoder import SDXLVAEEncoder +from ..models.sdxl_vae_decoder import SDXLVAEDecoder +from ..models import ModelManager +from ..prompters import HunyuanDiTPrompter +from ..schedulers import EnhancedDDIMScheduler +from .base import BasePipeline +import torch +from tqdm import tqdm +import numpy as np + + + +class ImageSizeManager: + def __init__(self): + pass + + + def _to_tuple(self, x): + if isinstance(x, int): + return x, x + else: + return x + + + def get_fill_resize_and_crop(self, src, tgt): + th, tw = self._to_tuple(tgt) + h, w = self._to_tuple(src) + + tr = th / tw # base 分辨率 + r = h / w # 目标分辨率 + + # resize + if r > tr: + resize_height = th + resize_width = int(round(th / h * w)) + else: + resize_width = tw + resize_height = int(round(tw / w * h)) # 根据base分辨率,将目标分辨率resize下来 + + crop_top = int(round((th - resize_height) / 2.0)) + crop_left = int(round((tw - resize_width) / 2.0)) + + return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width) + + + def get_meshgrid(self, start, *args): + if len(args) == 0: + # start is grid_size + num = self._to_tuple(start) + start = (0, 0) + stop = num + elif len(args) == 1: + # start is start, args[0] is stop, step is 1 + start = self._to_tuple(start) + stop = self._to_tuple(args[0]) + num = (stop[0] - start[0], stop[1] - start[1]) + elif len(args) == 2: + # start is start, args[0] is stop, args[1] is num + start = self._to_tuple(start) # 左上角 eg: 12,0 + stop = self._to_tuple(args[0]) # 右下角 eg: 20,32 + num = self._to_tuple(args[1]) # 目标大小 eg: 32,124 + else: + raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}") + + grid_h = np.linspace(start[0], stop[0], num[0], endpoint=False, dtype=np.float32) # 12-20 中间差值32份 0-32 中间差值124份 + grid_w = np.linspace(start[1], stop[1], num[1], endpoint=False, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) # [2, W, H] + return grid + + + def get_2d_rotary_pos_embed(self, embed_dim, start, *args, use_real=True): + grid = self.get_meshgrid(start, *args) # [2, H, w] + grid = grid.reshape([2, 1, *grid.shape[1:]]) # 返回一个采样矩阵 分辨率与目标分辨率一致 + pos_embed = self.get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=use_real) + return pos_embed + + + def get_2d_rotary_pos_embed_from_grid(self, embed_dim, grid, use_real=False): + assert embed_dim % 4 == 0 + + # use half of dimensions to encode grid_h + emb_h = self.get_1d_rotary_pos_embed(embed_dim // 2, grid[0].reshape(-1), use_real=use_real) # (H*W, D/4) + emb_w = self.get_1d_rotary_pos_embed(embed_dim // 2, grid[1].reshape(-1), use_real=use_real) # (H*W, D/4) + + if use_real: + cos = torch.cat([emb_h[0], emb_w[0]], dim=1) # (H*W, D/2) + sin = torch.cat([emb_h[1], emb_w[1]], dim=1) # (H*W, D/2) + return cos, sin + else: + emb = torch.cat([emb_h, emb_w], dim=1) # (H*W, D/2) + return emb + + + def get_1d_rotary_pos_embed(self, dim: int, pos, theta: float = 10000.0, use_real=False): + if isinstance(pos, int): + pos = np.arange(pos) + freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) # [D/2] + t = torch.from_numpy(pos).to(freqs.device) # type: ignore # [S] + freqs = torch.outer(t, freqs).float() # type: ignore # [S, D/2] + if use_real: + freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D] + freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D] + return freqs_cos, freqs_sin + else: + freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 # [S, D/2] + return freqs_cis + + + def calc_rope(self, height, width): + patch_size = 2 + head_size = 88 + th = height // 8 // patch_size + tw = width // 8 // patch_size + base_size = 512 // 8 // patch_size + start, stop = self.get_fill_resize_and_crop((th, tw), base_size) + sub_args = [start, stop, (th, tw)] + rope = self.get_2d_rotary_pos_embed(head_size, *sub_args) + return rope + + + +class HunyuanDiTImagePipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16) + self.scheduler = EnhancedDDIMScheduler(prediction_type="v_prediction", beta_start=0.00085, beta_end=0.03) + self.prompter = HunyuanDiTPrompter() + self.image_size_manager = ImageSizeManager() + # models + self.text_encoder: HunyuanDiTCLIPTextEncoder = None + self.text_encoder_t5: HunyuanDiTT5TextEncoder = None + self.dit: HunyuanDiT = None + self.vae_decoder: SDXLVAEDecoder = None + self.vae_encoder: SDXLVAEEncoder = None + self.model_names = ['text_encoder', 'text_encoder_t5', 'dit', 'vae_decoder', 'vae_encoder'] + + + def denoising_model(self): + return self.dit + + + def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]): + # Main models + self.text_encoder = model_manager.fetch_model("hunyuan_dit_clip_text_encoder") + self.text_encoder_t5 = model_manager.fetch_model("hunyuan_dit_t5_text_encoder") + self.dit = model_manager.fetch_model("hunyuan_dit") + self.vae_decoder = model_manager.fetch_model("sdxl_vae_decoder") + self.vae_encoder = model_manager.fetch_model("sdxl_vae_encoder") + self.prompter.fetch_models(self.text_encoder, self.text_encoder_t5) + self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes) + + + @staticmethod + def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[], device=None): + pipe = HunyuanDiTImagePipeline( + device=model_manager.device if device is None else device, + torch_dtype=model_manager.torch_dtype, + ) + pipe.fetch_models(model_manager, prompt_refiner_classes) + return pipe + + + def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32): + latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + return latents + + + def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32): + image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + image = self.vae_output_to_image(image) + return image + + + def encode_prompt(self, prompt, clip_skip=1, clip_skip_2=1, positive=True): + text_emb, text_emb_mask, text_emb_t5, text_emb_mask_t5 = self.prompter.encode_prompt( + prompt, + clip_skip=clip_skip, + clip_skip_2=clip_skip_2, + positive=positive, + device=self.device + ) + return { + "text_emb": text_emb, + "text_emb_mask": text_emb_mask, + "text_emb_t5": text_emb_t5, + "text_emb_mask_t5": text_emb_mask_t5 + } + + + def prepare_extra_input(self, latents=None, tiled=False, tile_size=64, tile_stride=32): + batch_size, height, width = latents.shape[0], latents.shape[2] * 8, latents.shape[3] * 8 + if tiled: + height, width = tile_size * 16, tile_size * 16 + image_meta_size = torch.as_tensor([width, height, width, height, 0, 0]).to(device=self.device) + freqs_cis_img = self.image_size_manager.calc_rope(height, width) + image_meta_size = torch.stack([image_meta_size] * batch_size) + return { + "size_emb": image_meta_size, + "freq_cis_img": (freqs_cis_img[0].to(dtype=self.torch_dtype, device=self.device), freqs_cis_img[1].to(dtype=self.torch_dtype, device=self.device)), + "tiled": tiled, + "tile_size": tile_size, + "tile_stride": tile_stride + } + + + @torch.no_grad() + def __call__( + self, + prompt, + local_prompts=[], + masks=[], + mask_scales=[], + negative_prompt="", + cfg_scale=7.5, + clip_skip=1, + clip_skip_2=1, + input_image=None, + reference_strengths=[0.4], + denoising_strength=1.0, + height=1024, + width=1024, + num_inference_steps=20, + tiled=False, + tile_size=64, + tile_stride=32, + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Prepare latent tensors + noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + if input_image is not None: + self.load_models_to_device(['vae_encoder']) + image = self.preprocess_image(input_image).to(device=self.device, dtype=torch.float32) + latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(self.torch_dtype) + latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0]) + else: + latents = noise.clone() + + # Encode prompts + self.load_models_to_device(['text_encoder', 'text_encoder_t5']) + prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, clip_skip_2=clip_skip_2, positive=True) + if cfg_scale != 1.0: + prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, clip_skip_2=clip_skip_2, positive=True) + prompt_emb_locals = [self.encode_prompt(prompt_local, clip_skip=clip_skip, clip_skip_2=clip_skip_2, positive=True) for prompt_local in local_prompts] + + # Prepare positional id + extra_input = self.prepare_extra_input(latents, tiled, tile_size) + + # Denoise + self.load_models_to_device(['dit']) + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = torch.tensor([timestep]).to(dtype=self.torch_dtype, device=self.device) + + # Positive side + inference_callback = lambda prompt_emb_posi: self.dit(latents, timestep=timestep, **prompt_emb_posi, **extra_input) + noise_pred_posi = self.control_noise_via_local_prompts(prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback) + + if cfg_scale != 1.0: + # Negative side + noise_pred_nega = self.dit( + latents, timestep=timestep, **prompt_emb_nega, **extra_input, + ) + # Classifier-free guidance + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + else: + noise_pred = noise_pred_posi + + latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents) + + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + self.load_models_to_device(['vae_decoder']) + image = self.decode_image(latents.to(torch.float32), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + + # Offload all models + self.load_models_to_device([]) + return image diff --git a/diffsynth/pipelines/hunyuan_video.py b/diffsynth/pipelines/hunyuan_video.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a0411e155f293e86a2b64073fa8b25af3d83d5 --- /dev/null +++ b/diffsynth/pipelines/hunyuan_video.py @@ -0,0 +1,395 @@ +from ..models import ModelManager, SD3TextEncoder1, HunyuanVideoVAEDecoder, HunyuanVideoVAEEncoder +from ..models.hunyuan_video_dit import HunyuanVideoDiT +from ..models.hunyuan_video_text_encoder import HunyuanVideoLLMEncoder +from ..schedulers.flow_match import FlowMatchScheduler +from .base import BasePipeline +from ..prompters import HunyuanVideoPrompter +import torch +import torchvision.transforms as transforms +from einops import rearrange +import numpy as np +from PIL import Image +from tqdm import tqdm + + +class HunyuanVideoPipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype) + self.scheduler = FlowMatchScheduler(shift=7.0, sigma_min=0.0, extra_one_step=True) + self.prompter = HunyuanVideoPrompter() + self.text_encoder_1: SD3TextEncoder1 = None + self.text_encoder_2: HunyuanVideoLLMEncoder = None + self.dit: HunyuanVideoDiT = None + self.vae_decoder: HunyuanVideoVAEDecoder = None + self.vae_encoder: HunyuanVideoVAEEncoder = None + self.model_names = ['text_encoder_1', 'text_encoder_2', 'dit', 'vae_decoder', 'vae_encoder'] + self.vram_management = False + + + def enable_vram_management(self): + self.vram_management = True + self.enable_cpu_offload() + self.text_encoder_2.enable_auto_offload(dtype=self.torch_dtype, device=self.device) + self.dit.enable_auto_offload(dtype=self.torch_dtype, device=self.device) + + + def fetch_models(self, model_manager: ModelManager): + self.text_encoder_1 = model_manager.fetch_model("sd3_text_encoder_1") + self.text_encoder_2 = model_manager.fetch_model("hunyuan_video_text_encoder_2") + self.dit = model_manager.fetch_model("hunyuan_video_dit") + self.vae_decoder = model_manager.fetch_model("hunyuan_video_vae_decoder") + self.vae_encoder = model_manager.fetch_model("hunyuan_video_vae_encoder") + self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2) + + + @staticmethod + def from_model_manager(model_manager: ModelManager, torch_dtype=None, device=None, enable_vram_management=True): + if device is None: device = model_manager.device + if torch_dtype is None: torch_dtype = model_manager.torch_dtype + pipe = HunyuanVideoPipeline(device=device, torch_dtype=torch_dtype) + pipe.fetch_models(model_manager) + if enable_vram_management: + pipe.enable_vram_management() + return pipe + + def generate_crop_size_list(self, base_size=256, patch_size=32, max_ratio=4.0): + num_patches = round((base_size / patch_size)**2) + assert max_ratio >= 1.0 + crop_size_list = [] + wp, hp = num_patches, 1 + while wp > 0: + if max(wp, hp) / min(wp, hp) <= max_ratio: + crop_size_list.append((wp * patch_size, hp * patch_size)) + if (hp + 1) * wp <= num_patches: + hp += 1 + else: + wp -= 1 + return crop_size_list + + + def get_closest_ratio(self, height: float, width: float, ratios: list, buckets: list): + aspect_ratio = float(height) / float(width) + closest_ratio_id = np.abs(ratios - aspect_ratio).argmin() + closest_ratio = min(ratios, key=lambda ratio: abs(float(ratio) - aspect_ratio)) + return buckets[closest_ratio_id], float(closest_ratio) + + + def prepare_vae_images_inputs(self, semantic_images, i2v_resolution="720p"): + if i2v_resolution == "720p": + bucket_hw_base_size = 960 + elif i2v_resolution == "540p": + bucket_hw_base_size = 720 + elif i2v_resolution == "360p": + bucket_hw_base_size = 480 + else: + raise ValueError(f"i2v_resolution: {i2v_resolution} must be in [360p, 540p, 720p]") + origin_size = semantic_images[0].size + + crop_size_list = self.generate_crop_size_list(bucket_hw_base_size, 32) + aspect_ratios = np.array([round(float(h) / float(w), 5) for h, w in crop_size_list]) + closest_size, closest_ratio = self.get_closest_ratio(origin_size[1], origin_size[0], aspect_ratios, crop_size_list) + ref_image_transform = transforms.Compose([ + transforms.Resize(closest_size), + transforms.CenterCrop(closest_size), + transforms.ToTensor(), + transforms.Normalize([0.5], [0.5]) + ]) + + semantic_image_pixel_values = [ref_image_transform(semantic_image) for semantic_image in semantic_images] + semantic_image_pixel_values = torch.cat(semantic_image_pixel_values).unsqueeze(0).unsqueeze(2).to(self.device) + target_height, target_width = closest_size + return semantic_image_pixel_values, target_height, target_width + + + def encode_prompt(self, prompt, positive=True, clip_sequence_length=77, llm_sequence_length=256, input_images=None): + prompt_emb, pooled_prompt_emb, text_mask = self.prompter.encode_prompt( + prompt, device=self.device, positive=positive, clip_sequence_length=clip_sequence_length, llm_sequence_length=llm_sequence_length, images=input_images + ) + return {"prompt_emb": prompt_emb, "pooled_prompt_emb": pooled_prompt_emb, "text_mask": text_mask} + + + def prepare_extra_input(self, latents=None, guidance=1.0): + freqs_cos, freqs_sin = self.dit.prepare_freqs(latents) + guidance = torch.Tensor([guidance] * latents.shape[0]).to(device=latents.device, dtype=latents.dtype) + return {"freqs_cos": freqs_cos, "freqs_sin": freqs_sin, "guidance": guidance} + + + def tensor2video(self, frames): + frames = rearrange(frames, "C T H W -> T H W C") + frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8) + frames = [Image.fromarray(frame) for frame in frames] + return frames + + + def encode_video(self, frames, tile_size=(17, 30, 30), tile_stride=(12, 20, 20)): + tile_size = ((tile_size[0] - 1) * 4 + 1, tile_size[1] * 8, tile_size[2] * 8) + tile_stride = (tile_stride[0] * 4, tile_stride[1] * 8, tile_stride[2] * 8) + latents = self.vae_encoder.encode_video(frames, tile_size=tile_size, tile_stride=tile_stride) + return latents + + + @torch.no_grad() + def __call__( + self, + prompt, + negative_prompt="", + input_video=None, + input_images=None, + i2v_resolution="720p", + i2v_stability=True, + denoising_strength=1.0, + seed=None, + rand_device=None, + height=720, + width=1280, + num_frames=129, + embedded_guidance=6.0, + cfg_scale=1.0, + num_inference_steps=30, + tea_cache_l1_thresh=None, + tile_size=(17, 30, 30), + tile_stride=(12, 20, 20), + step_processor=None, + progress_bar_cmd=lambda x: x, + progress_bar_st=None, + ): + # Tiler parameters + tiler_kwargs = {"tile_size": tile_size, "tile_stride": tile_stride} + + # Scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # encoder input images + if input_images is not None: + self.load_models_to_device(['vae_encoder']) + image_pixel_values, height, width = self.prepare_vae_images_inputs(input_images, i2v_resolution=i2v_resolution) + with torch.autocast(device_type=self.device, dtype=torch.float16, enabled=True): + image_latents = self.vae_encoder(image_pixel_values) + + # Initialize noise + rand_device = self.device if rand_device is None else rand_device + noise = self.generate_noise((1, 16, (num_frames - 1) // 4 + 1, height//8, width//8), seed=seed, device=rand_device, dtype=self.torch_dtype).to(self.device) + if input_video is not None: + self.load_models_to_device(['vae_encoder']) + input_video = self.preprocess_images(input_video) + input_video = torch.stack(input_video, dim=2) + latents = self.encode_video(input_video, **tiler_kwargs).to(dtype=self.torch_dtype, device=self.device) + latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0]) + elif input_images is not None and i2v_stability: + noise = self.generate_noise((1, 16, (num_frames - 1) // 4 + 1, height//8, width//8), seed=seed, device=rand_device, dtype=image_latents.dtype).to(self.device) + t = torch.tensor([0.999]).to(device=self.device) + latents = noise * t + image_latents.repeat(1, 1, (num_frames - 1) // 4 + 1, 1, 1) * (1 - t) + latents = latents.to(dtype=image_latents.dtype) + else: + latents = noise + + # Encode prompts + # current mllm does not support vram_management + self.load_models_to_device(["text_encoder_1"] if self.vram_management and input_images is None else ["text_encoder_1", "text_encoder_2"]) + prompt_emb_posi = self.encode_prompt(prompt, positive=True, input_images=input_images) + if cfg_scale != 1.0: + prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False) + + # Extra input + extra_input = self.prepare_extra_input(latents, guidance=embedded_guidance) + + # TeaCache + tea_cache_kwargs = {"tea_cache": TeaCache(num_inference_steps, rel_l1_thresh=tea_cache_l1_thresh) if tea_cache_l1_thresh is not None else None} + + # Denoise + self.load_models_to_device([] if self.vram_management else ["dit"]) + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(self.device) + print(f"Step {progress_id + 1} / {len(self.scheduler.timesteps)}") + + forward_func = lets_dance_hunyuan_video + if input_images is not None: + latents = torch.concat([image_latents, latents[:, :, 1:, :, :]], dim=2) + forward_func = lets_dance_hunyuan_video_i2v + + # Inference + with torch.autocast(device_type=self.device, dtype=self.torch_dtype): + noise_pred_posi = forward_func(self.dit, latents, timestep, **prompt_emb_posi, **extra_input, **tea_cache_kwargs) + if cfg_scale != 1.0: + noise_pred_nega = forward_func(self.dit, latents, timestep, **prompt_emb_nega, **extra_input) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + else: + noise_pred = noise_pred_posi + + # (Experimental feature, may be removed in the future) + if step_processor is not None: + self.load_models_to_device(['vae_decoder']) + rendered_frames = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents, to_final=True) + rendered_frames = self.vae_decoder.decode_video(rendered_frames, **tiler_kwargs) + rendered_frames = self.tensor2video(rendered_frames[0]) + rendered_frames = step_processor(rendered_frames, original_frames=input_video) + self.load_models_to_device(['vae_encoder']) + rendered_frames = self.preprocess_images(rendered_frames) + rendered_frames = torch.stack(rendered_frames, dim=2) + target_latents = self.encode_video(rendered_frames).to(dtype=self.torch_dtype, device=self.device) + noise_pred = self.scheduler.return_to_timestep(self.scheduler.timesteps[progress_id], latents, target_latents) + self.load_models_to_device([] if self.vram_management else ["dit"]) + + # Scheduler + if input_images is not None: + latents = self.scheduler.step(noise_pred[:, :, 1:, :, :], self.scheduler.timesteps[progress_id], latents[:, :, 1:, :, :]) + latents = torch.concat([image_latents, latents], dim=2) + else: + latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents) + + # Decode + self.load_models_to_device(['vae_decoder']) + frames = self.vae_decoder.decode_video(latents, **tiler_kwargs) + self.load_models_to_device([]) + frames = self.tensor2video(frames[0]) + + return frames + + + +class TeaCache: + def __init__(self, num_inference_steps, rel_l1_thresh): + self.num_inference_steps = num_inference_steps + self.step = 0 + self.accumulated_rel_l1_distance = 0 + self.previous_modulated_input = None + self.rel_l1_thresh = rel_l1_thresh + self.previous_residual = None + self.previous_hidden_states = None + + def check(self, dit: HunyuanVideoDiT, img, vec): + img_ = img.clone() + vec_ = vec.clone() + img_mod1_shift, img_mod1_scale, _, _, _, _ = dit.double_blocks[0].component_a.mod(vec_).chunk(6, dim=-1) + normed_inp = dit.double_blocks[0].component_a.norm1(img_) + modulated_inp = normed_inp * (1 + img_mod1_scale.unsqueeze(1)) + img_mod1_shift.unsqueeze(1) + if self.step == 0 or self.step == self.num_inference_steps - 1: + should_calc = True + self.accumulated_rel_l1_distance = 0 + else: + coefficients = [7.33226126e+02, -4.01131952e+02, 6.75869174e+01, -3.14987800e+00, 9.61237896e-02] + rescale_func = np.poly1d(coefficients) + self.accumulated_rel_l1_distance += rescale_func(((modulated_inp-self.previous_modulated_input).abs().mean() / self.previous_modulated_input.abs().mean()).cpu().item()) + if self.accumulated_rel_l1_distance < self.rel_l1_thresh: + should_calc = False + else: + should_calc = True + self.accumulated_rel_l1_distance = 0 + self.previous_modulated_input = modulated_inp + self.step += 1 + if self.step == self.num_inference_steps: + self.step = 0 + if should_calc: + self.previous_hidden_states = img.clone() + return not should_calc + + def store(self, hidden_states): + self.previous_residual = hidden_states - self.previous_hidden_states + self.previous_hidden_states = None + + def update(self, hidden_states): + hidden_states = hidden_states + self.previous_residual + return hidden_states + + + +def lets_dance_hunyuan_video( + dit: HunyuanVideoDiT, + x: torch.Tensor, + t: torch.Tensor, + prompt_emb: torch.Tensor = None, + text_mask: torch.Tensor = None, + pooled_prompt_emb: torch.Tensor = None, + freqs_cos: torch.Tensor = None, + freqs_sin: torch.Tensor = None, + guidance: torch.Tensor = None, + tea_cache: TeaCache = None, + **kwargs +): + B, C, T, H, W = x.shape + + vec = dit.time_in(t, dtype=torch.float32) + dit.vector_in(pooled_prompt_emb) + dit.guidance_in(guidance * 1000, dtype=torch.float32) + img = dit.img_in(x) + txt = dit.txt_in(prompt_emb, t, text_mask) + + # TeaCache + if tea_cache is not None: + tea_cache_update = tea_cache.check(dit, img, vec) + else: + tea_cache_update = False + + if tea_cache_update: + print("TeaCache skip forward.") + img = tea_cache.update(img) + else: + split_token = int(text_mask.sum(dim=1)) + txt_len = int(txt.shape[1]) + for block in tqdm(dit.double_blocks, desc="Double stream blocks"): + img, txt = block(img, txt, vec, (freqs_cos, freqs_sin), split_token=split_token) + + x = torch.concat([img, txt], dim=1) + for block in tqdm(dit.single_blocks, desc="Single stream blocks"): + x = block(x, vec, (freqs_cos, freqs_sin), txt_len=txt_len, split_token=split_token) + img = x[:, :-txt_len] + + if tea_cache is not None: + tea_cache.store(img) + img = dit.final_layer(img, vec) + img = dit.unpatchify(img, T=T//1, H=H//2, W=W//2) + return img + + +def lets_dance_hunyuan_video_i2v( + dit: HunyuanVideoDiT, + x: torch.Tensor, + t: torch.Tensor, + prompt_emb: torch.Tensor = None, + text_mask: torch.Tensor = None, + pooled_prompt_emb: torch.Tensor = None, + freqs_cos: torch.Tensor = None, + freqs_sin: torch.Tensor = None, + guidance: torch.Tensor = None, + tea_cache: TeaCache = None, + **kwargs +): + B, C, T, H, W = x.shape + # Uncomment below to keep same as official implementation + # guidance = guidance.to(dtype=torch.float32).to(torch.bfloat16) + vec = dit.time_in(t, dtype=torch.bfloat16) + vec_2 = dit.vector_in(pooled_prompt_emb) + vec = vec + vec_2 + vec = vec + dit.guidance_in(guidance * 1000., dtype=torch.bfloat16) + + token_replace_vec = dit.time_in(torch.zeros_like(t), dtype=torch.bfloat16) + tr_token = (H // 2) * (W // 2) + token_replace_vec = token_replace_vec + vec_2 + + img = dit.img_in(x) + txt = dit.txt_in(prompt_emb, t, text_mask) + + # TeaCache + if tea_cache is not None: + tea_cache_update = tea_cache.check(dit, img, vec) + else: + tea_cache_update = False + + if tea_cache_update: + print("TeaCache skip forward.") + img = tea_cache.update(img) + else: + split_token = int(text_mask.sum(dim=1)) + txt_len = int(txt.shape[1]) + for block in tqdm(dit.double_blocks, desc="Double stream blocks"): + img, txt = block(img, txt, vec, (freqs_cos, freqs_sin), token_replace_vec, tr_token, split_token) + + x = torch.concat([img, txt], dim=1) + for block in tqdm(dit.single_blocks, desc="Single stream blocks"): + x = block(x, vec, (freqs_cos, freqs_sin), txt_len, token_replace_vec, tr_token, split_token) + img = x[:, :-txt_len] + + if tea_cache is not None: + tea_cache.store(img) + img = dit.final_layer(img, vec) + img = dit.unpatchify(img, T=T//1, H=H//2, W=W//2) + return img diff --git a/diffsynth/pipelines/omnigen_image.py b/diffsynth/pipelines/omnigen_image.py new file mode 100644 index 0000000000000000000000000000000000000000..ddb2ae656639550084b7143fe690186602c0387d --- /dev/null +++ b/diffsynth/pipelines/omnigen_image.py @@ -0,0 +1,289 @@ +from ..models.omnigen import OmniGenTransformer +from ..models.sdxl_vae_encoder import SDXLVAEEncoder +from ..models.sdxl_vae_decoder import SDXLVAEDecoder +from ..models.model_manager import ModelManager +from ..prompters.omnigen_prompter import OmniGenPrompter +from ..schedulers import FlowMatchScheduler +from .base import BasePipeline +from typing import Optional, Dict, Any, Tuple, List +from transformers.cache_utils import DynamicCache +import torch, os +from tqdm import tqdm + + + +class OmniGenCache(DynamicCache): + def __init__(self, + num_tokens_for_img: int, offload_kv_cache: bool=False) -> None: + if not torch.cuda.is_available(): + print("No available GPU, offload_kv_cache will be set to False, which will result in large memory usage and time cost when input multiple images!!!") + offload_kv_cache = False + raise RuntimeError("OffloadedCache can only be used with a GPU") + super().__init__() + self.original_device = [] + self.prefetch_stream = torch.cuda.Stream() + self.num_tokens_for_img = num_tokens_for_img + self.offload_kv_cache = offload_kv_cache + + def prefetch_layer(self, layer_idx: int): + "Starts prefetching the next layer cache" + if layer_idx < len(self): + with torch.cuda.stream(self.prefetch_stream): + # Prefetch next layer tensors to GPU + device = self.original_device[layer_idx] + self.key_cache[layer_idx] = self.key_cache[layer_idx].to(device, non_blocking=True) + self.value_cache[layer_idx] = self.value_cache[layer_idx].to(device, non_blocking=True) + + + def evict_previous_layer(self, layer_idx: int): + "Moves the previous layer cache to the CPU" + if len(self) > 2: + # We do it on the default stream so it occurs after all earlier computations on these tensors are done + if layer_idx == 0: + prev_layer_idx = -1 + else: + prev_layer_idx = (layer_idx - 1) % len(self) + self.key_cache[prev_layer_idx] = self.key_cache[prev_layer_idx].to("cpu", non_blocking=True) + self.value_cache[prev_layer_idx] = self.value_cache[prev_layer_idx].to("cpu", non_blocking=True) + + + def __getitem__(self, layer_idx: int) -> List[Tuple[torch.Tensor]]: + "Gets the cache for this layer to the device. Prefetches the next and evicts the previous layer." + if layer_idx < len(self): + if self.offload_kv_cache: + # Evict the previous layer if necessary + torch.cuda.current_stream().synchronize() + self.evict_previous_layer(layer_idx) + # Load current layer cache to its original device if not already there + original_device = self.original_device[layer_idx] + # self.prefetch_stream.synchronize(original_device) + torch.cuda.synchronize(self.prefetch_stream) + key_tensor = self.key_cache[layer_idx] + value_tensor = self.value_cache[layer_idx] + + # Prefetch the next layer + self.prefetch_layer((layer_idx + 1) % len(self)) + else: + key_tensor = self.key_cache[layer_idx] + value_tensor = self.value_cache[layer_idx] + return (key_tensor, value_tensor) + else: + raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}") + + + def update( + self, + key_states: torch.Tensor, + value_states: torch.Tensor, + layer_idx: int, + cache_kwargs: Optional[Dict[str, Any]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`. + Parameters: + key_states (`torch.Tensor`): + The new key states to cache. + value_states (`torch.Tensor`): + The new value states to cache. + layer_idx (`int`): + The index of the layer to cache the states for. + cache_kwargs (`Dict[str, Any]`, `optional`): + Additional arguments for the cache subclass. No additional arguments are used in `OffloadedCache`. + Return: + A tuple containing the updated key and value states. + """ + # Update the cache + if len(self.key_cache) < layer_idx: + raise ValueError("OffloadedCache does not support model usage where layers are skipped. Use DynamicCache.") + elif len(self.key_cache) == layer_idx: + # only cache the states for condition tokens + key_states = key_states[..., :-(self.num_tokens_for_img+1), :] + value_states = value_states[..., :-(self.num_tokens_for_img+1), :] + + # Update the number of seen tokens + if layer_idx == 0: + self._seen_tokens += key_states.shape[-2] + + self.key_cache.append(key_states) + self.value_cache.append(value_states) + self.original_device.append(key_states.device) + if self.offload_kv_cache: + self.evict_previous_layer(layer_idx) + return self.key_cache[layer_idx], self.value_cache[layer_idx] + else: + # only cache the states for condition tokens + key_tensor, value_tensor = self[layer_idx] + k = torch.cat([key_tensor, key_states], dim=-2) + v = torch.cat([value_tensor, value_states], dim=-2) + return k, v + + + +class OmnigenImagePipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype) + self.scheduler = FlowMatchScheduler(num_train_timesteps=1, shift=1, inverse_timesteps=True, sigma_min=0, sigma_max=1) + # models + self.vae_decoder: SDXLVAEDecoder = None + self.vae_encoder: SDXLVAEEncoder = None + self.transformer: OmniGenTransformer = None + self.prompter: OmniGenPrompter = None + self.model_names = ['transformer', 'vae_decoder', 'vae_encoder'] + + + def denoising_model(self): + return self.transformer + + + def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]): + # Main models + self.transformer, model_path = model_manager.fetch_model("omnigen_transformer", require_model_path=True) + self.vae_decoder = model_manager.fetch_model("sdxl_vae_decoder") + self.vae_encoder = model_manager.fetch_model("sdxl_vae_encoder") + self.prompter = OmniGenPrompter.from_pretrained(os.path.dirname(model_path)) + + + @staticmethod + def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[], device=None): + pipe = OmnigenImagePipeline( + device=model_manager.device if device is None else device, + torch_dtype=model_manager.torch_dtype, + ) + pipe.fetch_models(model_manager, prompt_refiner_classes=[]) + return pipe + + + def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32): + latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + return latents + + + def encode_images(self, images, tiled=False, tile_size=64, tile_stride=32): + latents = [self.encode_image(image.to(device=self.device), tiled, tile_size, tile_stride).to(self.torch_dtype) for image in images] + return latents + + + def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32): + image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + image = self.vae_output_to_image(image) + return image + + + def encode_prompt(self, prompt, clip_skip=1, positive=True): + prompt_emb = self.prompter.encode_prompt(prompt, clip_skip=clip_skip, device=self.device, positive=positive) + return {"encoder_hidden_states": prompt_emb} + + + def prepare_extra_input(self, latents=None): + return {} + + + def crop_position_ids_for_cache(self, position_ids, num_tokens_for_img): + if isinstance(position_ids, list): + for i in range(len(position_ids)): + position_ids[i] = position_ids[i][:, -(num_tokens_for_img+1):] + else: + position_ids = position_ids[:, -(num_tokens_for_img+1):] + return position_ids + + + def crop_attention_mask_for_cache(self, attention_mask, num_tokens_for_img): + if isinstance(attention_mask, list): + return [x[..., -(num_tokens_for_img+1):, :] for x in attention_mask] + return attention_mask[..., -(num_tokens_for_img+1):, :] + + + @torch.no_grad() + def __call__( + self, + prompt, + reference_images=[], + cfg_scale=2.0, + image_cfg_scale=2.0, + use_kv_cache=True, + offload_kv_cache=True, + input_image=None, + denoising_strength=1.0, + height=1024, + width=1024, + num_inference_steps=20, + tiled=False, + tile_size=64, + tile_stride=32, + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Tiler parameters + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Prepare latent tensors + if input_image is not None: + self.load_models_to_device(['vae_encoder']) + image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype) + latents = self.encode_image(image, **tiler_kwargs) + noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0]) + else: + latents = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + latents = latents.repeat(3, 1, 1, 1) + + # Encode prompts + input_data = self.prompter(prompt, reference_images, height=height, width=width, use_img_cfg=True, separate_cfg_input=True, use_input_image_size_as_output=False) + + # Encode images + reference_latents = [self.encode_images(images, **tiler_kwargs) for images in input_data['input_pixel_values']] + + # Pack all parameters + model_kwargs = dict(input_ids=[input_ids.to(self.device) for input_ids in input_data['input_ids']], + input_img_latents=reference_latents, + input_image_sizes=input_data['input_image_sizes'], + attention_mask=[attention_mask.to(self.device) for attention_mask in input_data["attention_mask"]], + position_ids=[position_ids.to(self.device) for position_ids in input_data["position_ids"]], + cfg_scale=cfg_scale, + img_cfg_scale=image_cfg_scale, + use_img_cfg=True, + use_kv_cache=use_kv_cache, + offload_model=False, + ) + + # Denoise + self.load_models_to_device(['transformer']) + cache = [OmniGenCache(latents.size(-1)*latents.size(-2) // 4, offload_kv_cache) for _ in range(len(model_kwargs['input_ids']))] if use_kv_cache else None + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).repeat(latents.shape[0]).to(self.device) + + # Forward + noise_pred, cache = self.transformer.forward_with_separate_cfg(latents, timestep, past_key_values=cache, **model_kwargs) + + # Scheduler + latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents) + + # Update KV cache + if progress_id == 0 and use_kv_cache: + num_tokens_for_img = latents.size(-1)*latents.size(-2) // 4 + if isinstance(cache, list): + model_kwargs['input_ids'] = [None] * len(cache) + else: + model_kwargs['input_ids'] = None + model_kwargs['position_ids'] = self.crop_position_ids_for_cache(model_kwargs['position_ids'], num_tokens_for_img) + model_kwargs['attention_mask'] = self.crop_attention_mask_for_cache(model_kwargs['attention_mask'], num_tokens_for_img) + + # UI + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + del cache + self.load_models_to_device(['vae_decoder']) + image = self.decode_image(latents, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + + # offload all models + self.load_models_to_device([]) + return image diff --git a/diffsynth/pipelines/pipeline_runner.py b/diffsynth/pipelines/pipeline_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..1b842f9bd7b25edca1c9951e67ebe5c364deca81 --- /dev/null +++ b/diffsynth/pipelines/pipeline_runner.py @@ -0,0 +1,105 @@ +import os, torch, json +from .sd_video import ModelManager, SDVideoPipeline, ControlNetConfigUnit +from ..processors.sequencial_processor import SequencialProcessor +from ..data import VideoData, save_frames, save_video + + + +class SDVideoPipelineRunner: + def __init__(self, in_streamlit=False): + self.in_streamlit = in_streamlit + + + def load_pipeline(self, model_list, textual_inversion_folder, device, lora_alphas, controlnet_units): + # Load models + model_manager = ModelManager(torch_dtype=torch.float16, device=device) + model_manager.load_models(model_list) + pipe = SDVideoPipeline.from_model_manager( + model_manager, + [ + ControlNetConfigUnit( + processor_id=unit["processor_id"], + model_path=unit["model_path"], + scale=unit["scale"] + ) for unit in controlnet_units + ] + ) + textual_inversion_paths = [] + for file_name in os.listdir(textual_inversion_folder): + if file_name.endswith(".pt") or file_name.endswith(".bin") or file_name.endswith(".pth") or file_name.endswith(".safetensors"): + textual_inversion_paths.append(os.path.join(textual_inversion_folder, file_name)) + pipe.prompter.load_textual_inversions(textual_inversion_paths) + return model_manager, pipe + + + def load_smoother(self, model_manager, smoother_configs): + smoother = SequencialProcessor.from_model_manager(model_manager, smoother_configs) + return smoother + + + def synthesize_video(self, model_manager, pipe, seed, smoother, **pipeline_inputs): + torch.manual_seed(seed) + if self.in_streamlit: + import streamlit as st + progress_bar_st = st.progress(0.0) + output_video = pipe(**pipeline_inputs, smoother=smoother, progress_bar_st=progress_bar_st) + progress_bar_st.progress(1.0) + else: + output_video = pipe(**pipeline_inputs, smoother=smoother) + model_manager.to("cpu") + return output_video + + + def load_video(self, video_file, image_folder, height, width, start_frame_id, end_frame_id): + video = VideoData(video_file=video_file, image_folder=image_folder, height=height, width=width) + if start_frame_id is None: + start_frame_id = 0 + if end_frame_id is None: + end_frame_id = len(video) + frames = [video[i] for i in range(start_frame_id, end_frame_id)] + return frames + + + def add_data_to_pipeline_inputs(self, data, pipeline_inputs): + pipeline_inputs["input_frames"] = self.load_video(**data["input_frames"]) + pipeline_inputs["num_frames"] = len(pipeline_inputs["input_frames"]) + pipeline_inputs["width"], pipeline_inputs["height"] = pipeline_inputs["input_frames"][0].size + if len(data["controlnet_frames"]) > 0: + pipeline_inputs["controlnet_frames"] = [self.load_video(**unit) for unit in data["controlnet_frames"]] + return pipeline_inputs + + + def save_output(self, video, output_folder, fps, config): + os.makedirs(output_folder, exist_ok=True) + save_frames(video, os.path.join(output_folder, "frames")) + save_video(video, os.path.join(output_folder, "video.mp4"), fps=fps) + config["pipeline"]["pipeline_inputs"]["input_frames"] = [] + config["pipeline"]["pipeline_inputs"]["controlnet_frames"] = [] + with open(os.path.join(output_folder, "config.json"), 'w') as file: + json.dump(config, file, indent=4) + + + def run(self, config): + if self.in_streamlit: + import streamlit as st + if self.in_streamlit: st.markdown("Loading videos ...") + config["pipeline"]["pipeline_inputs"] = self.add_data_to_pipeline_inputs(config["data"], config["pipeline"]["pipeline_inputs"]) + if self.in_streamlit: st.markdown("Loading videos ... done!") + if self.in_streamlit: st.markdown("Loading models ...") + model_manager, pipe = self.load_pipeline(**config["models"]) + if self.in_streamlit: st.markdown("Loading models ... done!") + if "smoother_configs" in config: + if self.in_streamlit: st.markdown("Loading smoother ...") + smoother = self.load_smoother(model_manager, config["smoother_configs"]) + if self.in_streamlit: st.markdown("Loading smoother ... done!") + else: + smoother = None + if self.in_streamlit: st.markdown("Synthesizing videos ...") + output_video = self.synthesize_video(model_manager, pipe, config["pipeline"]["seed"], smoother, **config["pipeline"]["pipeline_inputs"]) + if self.in_streamlit: st.markdown("Synthesizing videos ... done!") + if self.in_streamlit: st.markdown("Saving videos ...") + self.save_output(output_video, config["data"]["output_folder"], config["data"]["fps"], config) + if self.in_streamlit: st.markdown("Saving videos ... done!") + if self.in_streamlit: st.markdown("Finished!") + video_file = open(os.path.join(os.path.join(config["data"]["output_folder"], "video.mp4")), 'rb') + if self.in_streamlit: st.video(video_file.read()) diff --git a/diffsynth/pipelines/sd3_image.py b/diffsynth/pipelines/sd3_image.py new file mode 100644 index 0000000000000000000000000000000000000000..c6098739b2701d59958ef3fa85b0dc96b5ffe86a --- /dev/null +++ b/diffsynth/pipelines/sd3_image.py @@ -0,0 +1,147 @@ +from ..models import ModelManager, SD3TextEncoder1, SD3TextEncoder2, SD3TextEncoder3, SD3DiT, SD3VAEDecoder, SD3VAEEncoder +from ..prompters import SD3Prompter +from ..schedulers import FlowMatchScheduler +from .base import BasePipeline +import torch +from tqdm import tqdm + + + +class SD3ImagePipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16) + self.scheduler = FlowMatchScheduler() + self.prompter = SD3Prompter() + # models + self.text_encoder_1: SD3TextEncoder1 = None + self.text_encoder_2: SD3TextEncoder2 = None + self.text_encoder_3: SD3TextEncoder3 = None + self.dit: SD3DiT = None + self.vae_decoder: SD3VAEDecoder = None + self.vae_encoder: SD3VAEEncoder = None + self.model_names = ['text_encoder_1', 'text_encoder_2', 'text_encoder_3', 'dit', 'vae_decoder', 'vae_encoder'] + + + def denoising_model(self): + return self.dit + + + def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]): + self.text_encoder_1 = model_manager.fetch_model("sd3_text_encoder_1") + self.text_encoder_2 = model_manager.fetch_model("sd3_text_encoder_2") + self.text_encoder_3 = model_manager.fetch_model("sd3_text_encoder_3") + self.dit = model_manager.fetch_model("sd3_dit") + self.vae_decoder = model_manager.fetch_model("sd3_vae_decoder") + self.vae_encoder = model_manager.fetch_model("sd3_vae_encoder") + self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2, self.text_encoder_3) + self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes) + + + @staticmethod + def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[], device=None): + pipe = SD3ImagePipeline( + device=model_manager.device if device is None else device, + torch_dtype=model_manager.torch_dtype, + ) + pipe.fetch_models(model_manager, prompt_refiner_classes) + return pipe + + + def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32): + latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + return latents + + + def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32): + image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + image = self.vae_output_to_image(image) + return image + + + def encode_prompt(self, prompt, positive=True, t5_sequence_length=77): + prompt_emb, pooled_prompt_emb = self.prompter.encode_prompt( + prompt, device=self.device, positive=positive, t5_sequence_length=t5_sequence_length + ) + return {"prompt_emb": prompt_emb, "pooled_prompt_emb": pooled_prompt_emb} + + + def prepare_extra_input(self, latents=None): + return {} + + + @torch.no_grad() + def __call__( + self, + prompt, + local_prompts=[], + masks=[], + mask_scales=[], + negative_prompt="", + cfg_scale=7.5, + input_image=None, + denoising_strength=1.0, + height=1024, + width=1024, + num_inference_steps=20, + t5_sequence_length=77, + tiled=False, + tile_size=128, + tile_stride=64, + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Tiler parameters + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Prepare latent tensors + if input_image is not None: + self.load_models_to_device(['vae_encoder']) + image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype) + latents = self.encode_image(image, **tiler_kwargs) + noise = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0]) + else: + latents = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + + # Encode prompts + self.load_models_to_device(['text_encoder_1', 'text_encoder_2', 'text_encoder_3']) + prompt_emb_posi = self.encode_prompt(prompt, positive=True, t5_sequence_length=t5_sequence_length) + prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False, t5_sequence_length=t5_sequence_length) + prompt_emb_locals = [self.encode_prompt(prompt_local, t5_sequence_length=t5_sequence_length) for prompt_local in local_prompts] + + # Denoise + self.load_models_to_device(['dit']) + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(self.device) + + # Classifier-free guidance + inference_callback = lambda prompt_emb_posi: self.dit( + latents, timestep=timestep, **prompt_emb_posi, **tiler_kwargs, + ) + noise_pred_posi = self.control_noise_via_local_prompts(prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback) + noise_pred_nega = self.dit( + latents, timestep=timestep, **prompt_emb_nega, **tiler_kwargs, + ) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + + # DDIM + latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents) + + # UI + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + self.load_models_to_device(['vae_decoder']) + image = self.decode_image(latents, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + + # offload all models + self.load_models_to_device([]) + return image diff --git a/diffsynth/pipelines/sd_image.py b/diffsynth/pipelines/sd_image.py new file mode 100644 index 0000000000000000000000000000000000000000..c22c3fe69578f28925be900036bf21afeb750f17 --- /dev/null +++ b/diffsynth/pipelines/sd_image.py @@ -0,0 +1,191 @@ +from ..models import SDTextEncoder, SDUNet, SDVAEDecoder, SDVAEEncoder, SDIpAdapter, IpAdapterCLIPImageEmbedder +from ..models.model_manager import ModelManager +from ..controlnets import MultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator +from ..prompters import SDPrompter +from ..schedulers import EnhancedDDIMScheduler +from .base import BasePipeline +from .dancer import lets_dance +from typing import List +import torch +from tqdm import tqdm + + + +class SDImagePipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype) + self.scheduler = EnhancedDDIMScheduler() + self.prompter = SDPrompter() + # models + self.text_encoder: SDTextEncoder = None + self.unet: SDUNet = None + self.vae_decoder: SDVAEDecoder = None + self.vae_encoder: SDVAEEncoder = None + self.controlnet: MultiControlNetManager = None + self.ipadapter_image_encoder: IpAdapterCLIPImageEmbedder = None + self.ipadapter: SDIpAdapter = None + self.model_names = ['text_encoder', 'unet', 'vae_decoder', 'vae_encoder', 'controlnet', 'ipadapter_image_encoder', 'ipadapter'] + + + def denoising_model(self): + return self.unet + + + def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]): + # Main models + self.text_encoder = model_manager.fetch_model("sd_text_encoder") + self.unet = model_manager.fetch_model("sd_unet") + self.vae_decoder = model_manager.fetch_model("sd_vae_decoder") + self.vae_encoder = model_manager.fetch_model("sd_vae_encoder") + self.prompter.fetch_models(self.text_encoder) + self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes) + + # ControlNets + controlnet_units = [] + for config in controlnet_config_units: + controlnet_unit = ControlNetUnit( + Annotator(config.processor_id, device=self.device), + model_manager.fetch_model("sd_controlnet", config.model_path), + config.scale + ) + controlnet_units.append(controlnet_unit) + self.controlnet = MultiControlNetManager(controlnet_units) + + # IP-Adapters + self.ipadapter = model_manager.fetch_model("sd_ipadapter") + self.ipadapter_image_encoder = model_manager.fetch_model("sd_ipadapter_clip_image_encoder") + + + @staticmethod + def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[], device=None): + pipe = SDImagePipeline( + device=model_manager.device if device is None else device, + torch_dtype=model_manager.torch_dtype, + ) + pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes=[]) + return pipe + + + def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32): + latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + return latents + + + def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32): + image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + image = self.vae_output_to_image(image) + return image + + + def encode_prompt(self, prompt, clip_skip=1, positive=True): + prompt_emb = self.prompter.encode_prompt(prompt, clip_skip=clip_skip, device=self.device, positive=positive) + return {"encoder_hidden_states": prompt_emb} + + + def prepare_extra_input(self, latents=None): + return {} + + + @torch.no_grad() + def __call__( + self, + prompt, + local_prompts=[], + masks=[], + mask_scales=[], + negative_prompt="", + cfg_scale=7.5, + clip_skip=1, + input_image=None, + ipadapter_images=None, + ipadapter_scale=1.0, + controlnet_image=None, + denoising_strength=1.0, + height=512, + width=512, + num_inference_steps=20, + tiled=False, + tile_size=64, + tile_stride=32, + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Tiler parameters + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Prepare latent tensors + if input_image is not None: + self.load_models_to_device(['vae_encoder']) + image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype) + latents = self.encode_image(image, **tiler_kwargs) + noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0]) + else: + latents = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + + # Encode prompts + self.load_models_to_device(['text_encoder']) + prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, positive=True) + prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, positive=False) + prompt_emb_locals = [self.encode_prompt(prompt_local, clip_skip=clip_skip, positive=True) for prompt_local in local_prompts] + + # IP-Adapter + if ipadapter_images is not None: + self.load_models_to_device(['ipadapter_image_encoder']) + ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images) + self.load_models_to_device(['ipadapter']) + ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)} + ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))} + else: + ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}} + + # Prepare ControlNets + if controlnet_image is not None: + self.load_models_to_device(['controlnet']) + controlnet_image = self.controlnet.process_image(controlnet_image).to(device=self.device, dtype=self.torch_dtype) + controlnet_image = controlnet_image.unsqueeze(1) + controlnet_kwargs = {"controlnet_frames": controlnet_image} + else: + controlnet_kwargs = {"controlnet_frames": None} + + # Denoise + self.load_models_to_device(['controlnet', 'unet']) + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(self.device) + + # Classifier-free guidance + inference_callback = lambda prompt_emb_posi: lets_dance( + self.unet, motion_modules=None, controlnet=self.controlnet, + sample=latents, timestep=timestep, + **prompt_emb_posi, **controlnet_kwargs, **tiler_kwargs, **ipadapter_kwargs_list_posi, + device=self.device, + ) + noise_pred_posi = self.control_noise_via_local_prompts(prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback) + noise_pred_nega = lets_dance( + self.unet, motion_modules=None, controlnet=self.controlnet, + sample=latents, timestep=timestep, **prompt_emb_nega, **controlnet_kwargs, **tiler_kwargs, **ipadapter_kwargs_list_nega, + device=self.device, + ) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + + # DDIM + latents = self.scheduler.step(noise_pred, timestep, latents) + + # UI + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + self.load_models_to_device(['vae_decoder']) + image = self.decode_image(latents, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + + # offload all models + self.load_models_to_device([]) + return image diff --git a/diffsynth/pipelines/sd_video.py b/diffsynth/pipelines/sd_video.py new file mode 100644 index 0000000000000000000000000000000000000000..4337beb4f7a2d4a08c5955fdbd5f528ea328b39e --- /dev/null +++ b/diffsynth/pipelines/sd_video.py @@ -0,0 +1,269 @@ +from ..models import SDTextEncoder, SDUNet, SDVAEDecoder, SDVAEEncoder, SDIpAdapter, IpAdapterCLIPImageEmbedder, SDMotionModel +from ..models.model_manager import ModelManager +from ..controlnets import MultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator +from ..prompters import SDPrompter +from ..schedulers import EnhancedDDIMScheduler +from .sd_image import SDImagePipeline +from .dancer import lets_dance +from typing import List +import torch +from tqdm import tqdm + + + +def lets_dance_with_long_video( + unet: SDUNet, + motion_modules: SDMotionModel = None, + controlnet: MultiControlNetManager = None, + sample = None, + timestep = None, + encoder_hidden_states = None, + ipadapter_kwargs_list = {}, + controlnet_frames = None, + unet_batch_size = 1, + controlnet_batch_size = 1, + cross_frame_attention = False, + tiled=False, + tile_size=64, + tile_stride=32, + device="cuda", + animatediff_batch_size=16, + animatediff_stride=8, +): + num_frames = sample.shape[0] + hidden_states_output = [(torch.zeros(sample[0].shape, dtype=sample[0].dtype), 0) for i in range(num_frames)] + + for batch_id in range(0, num_frames, animatediff_stride): + batch_id_ = min(batch_id + animatediff_batch_size, num_frames) + + # process this batch + hidden_states_batch = lets_dance( + unet, motion_modules, controlnet, + sample[batch_id: batch_id_].to(device), + timestep, + encoder_hidden_states, + ipadapter_kwargs_list=ipadapter_kwargs_list, + controlnet_frames=controlnet_frames[:, batch_id: batch_id_].to(device) if controlnet_frames is not None else None, + unet_batch_size=unet_batch_size, controlnet_batch_size=controlnet_batch_size, + cross_frame_attention=cross_frame_attention, + tiled=tiled, tile_size=tile_size, tile_stride=tile_stride, device=device + ).cpu() + + # update hidden_states + for i, hidden_states_updated in zip(range(batch_id, batch_id_), hidden_states_batch): + bias = max(1 - abs(i - (batch_id + batch_id_ - 1) / 2) / ((batch_id_ - batch_id - 1 + 1e-2) / 2), 1e-2) + hidden_states, num = hidden_states_output[i] + hidden_states = hidden_states * (num / (num + bias)) + hidden_states_updated * (bias / (num + bias)) + hidden_states_output[i] = (hidden_states, num + bias) + + if batch_id_ == num_frames: + break + + # output + hidden_states = torch.stack([h for h, _ in hidden_states_output]) + return hidden_states + + + +class SDVideoPipeline(SDImagePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16, use_original_animatediff=True): + super().__init__(device=device, torch_dtype=torch_dtype) + self.scheduler = EnhancedDDIMScheduler(beta_schedule="linear" if use_original_animatediff else "scaled_linear") + self.prompter = SDPrompter() + # models + self.text_encoder: SDTextEncoder = None + self.unet: SDUNet = None + self.vae_decoder: SDVAEDecoder = None + self.vae_encoder: SDVAEEncoder = None + self.controlnet: MultiControlNetManager = None + self.ipadapter_image_encoder: IpAdapterCLIPImageEmbedder = None + self.ipadapter: SDIpAdapter = None + self.motion_modules: SDMotionModel = None + + + def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]): + # Main models + self.text_encoder = model_manager.fetch_model("sd_text_encoder") + self.unet = model_manager.fetch_model("sd_unet") + self.vae_decoder = model_manager.fetch_model("sd_vae_decoder") + self.vae_encoder = model_manager.fetch_model("sd_vae_encoder") + self.prompter.fetch_models(self.text_encoder) + self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes) + + # ControlNets + controlnet_units = [] + for config in controlnet_config_units: + controlnet_unit = ControlNetUnit( + Annotator(config.processor_id, device=self.device), + model_manager.fetch_model("sd_controlnet", config.model_path), + config.scale + ) + controlnet_units.append(controlnet_unit) + self.controlnet = MultiControlNetManager(controlnet_units) + + # IP-Adapters + self.ipadapter = model_manager.fetch_model("sd_ipadapter") + self.ipadapter_image_encoder = model_manager.fetch_model("sd_ipadapter_clip_image_encoder") + + # Motion Modules + self.motion_modules = model_manager.fetch_model("sd_motion_modules") + if self.motion_modules is None: + self.scheduler = EnhancedDDIMScheduler(beta_schedule="scaled_linear") + + + @staticmethod + def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]): + pipe = SDVideoPipeline( + device=model_manager.device, + torch_dtype=model_manager.torch_dtype, + ) + pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes) + return pipe + + + def decode_video(self, latents, tiled=False, tile_size=64, tile_stride=32): + images = [ + self.decode_image(latents[frame_id: frame_id+1], tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + for frame_id in range(latents.shape[0]) + ] + return images + + + def encode_video(self, processed_images, tiled=False, tile_size=64, tile_stride=32): + latents = [] + for image in processed_images: + image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype) + latent = self.encode_image(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + latents.append(latent.cpu()) + latents = torch.concat(latents, dim=0) + return latents + + + @torch.no_grad() + def __call__( + self, + prompt, + negative_prompt="", + cfg_scale=7.5, + clip_skip=1, + num_frames=None, + input_frames=None, + ipadapter_images=None, + ipadapter_scale=1.0, + controlnet_frames=None, + denoising_strength=1.0, + height=512, + width=512, + num_inference_steps=20, + animatediff_batch_size = 16, + animatediff_stride = 8, + unet_batch_size = 1, + controlnet_batch_size = 1, + cross_frame_attention = False, + smoother=None, + smoother_progress_ids=[], + tiled=False, + tile_size=64, + tile_stride=32, + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Tiler parameters, batch size ... + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + other_kwargs = { + "animatediff_batch_size": animatediff_batch_size, "animatediff_stride": animatediff_stride, + "unet_batch_size": unet_batch_size, "controlnet_batch_size": controlnet_batch_size, + "cross_frame_attention": cross_frame_attention, + } + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Prepare latent tensors + if self.motion_modules is None: + noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype).repeat(num_frames, 1, 1, 1) + else: + noise = self.generate_noise((num_frames, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype) + if input_frames is None or denoising_strength == 1.0: + latents = noise + else: + latents = self.encode_video(input_frames, **tiler_kwargs) + latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0]) + + # Encode prompts + prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, positive=True) + prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, positive=False) + + # IP-Adapter + if ipadapter_images is not None: + ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images) + ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)} + ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))} + else: + ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}} + + # Prepare ControlNets + if controlnet_frames is not None: + if isinstance(controlnet_frames[0], list): + controlnet_frames_ = [] + for processor_id in range(len(controlnet_frames)): + controlnet_frames_.append( + torch.stack([ + self.controlnet.process_image(controlnet_frame, processor_id=processor_id).to(self.torch_dtype) + for controlnet_frame in progress_bar_cmd(controlnet_frames[processor_id]) + ], dim=1) + ) + controlnet_frames = torch.concat(controlnet_frames_, dim=0) + else: + controlnet_frames = torch.stack([ + self.controlnet.process_image(controlnet_frame).to(self.torch_dtype) + for controlnet_frame in progress_bar_cmd(controlnet_frames) + ], dim=1) + controlnet_kwargs = {"controlnet_frames": controlnet_frames} + else: + controlnet_kwargs = {"controlnet_frames": None} + + # Denoise + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(self.device) + + # Classifier-free guidance + noise_pred_posi = lets_dance_with_long_video( + self.unet, motion_modules=self.motion_modules, controlnet=self.controlnet, + sample=latents, timestep=timestep, + **prompt_emb_posi, **controlnet_kwargs, **ipadapter_kwargs_list_posi, **other_kwargs, **tiler_kwargs, + device=self.device, + ) + noise_pred_nega = lets_dance_with_long_video( + self.unet, motion_modules=self.motion_modules, controlnet=self.controlnet, + sample=latents, timestep=timestep, + **prompt_emb_nega, **controlnet_kwargs, **ipadapter_kwargs_list_nega, **other_kwargs, **tiler_kwargs, + device=self.device, + ) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + + # DDIM and smoother + if smoother is not None and progress_id in smoother_progress_ids: + rendered_frames = self.scheduler.step(noise_pred, timestep, latents, to_final=True) + rendered_frames = self.decode_video(rendered_frames) + rendered_frames = smoother(rendered_frames, original_frames=input_frames) + target_latents = self.encode_video(rendered_frames) + noise_pred = self.scheduler.return_to_timestep(timestep, latents, target_latents) + latents = self.scheduler.step(noise_pred, timestep, latents) + + # UI + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + output_frames = self.decode_video(latents, **tiler_kwargs) + + # Post-process + if smoother is not None and (num_inference_steps in smoother_progress_ids or -1 in smoother_progress_ids): + output_frames = smoother(output_frames, original_frames=input_frames) + + return output_frames diff --git a/diffsynth/pipelines/sdxl_video.py b/diffsynth/pipelines/sdxl_video.py new file mode 100644 index 0000000000000000000000000000000000000000..308590ca6a874c5803da95db1d90fced26126893 --- /dev/null +++ b/diffsynth/pipelines/sdxl_video.py @@ -0,0 +1,226 @@ +from ..models import SDXLTextEncoder, SDXLTextEncoder2, SDXLUNet, SDXLVAEDecoder, SDXLVAEEncoder, SDXLIpAdapter, IpAdapterXLCLIPImageEmbedder, SDXLMotionModel +from ..models.kolors_text_encoder import ChatGLMModel +from ..models.model_manager import ModelManager +from ..controlnets import MultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator +from ..prompters import SDXLPrompter, KolorsPrompter +from ..schedulers import EnhancedDDIMScheduler +from .sdxl_image import SDXLImagePipeline +from .dancer import lets_dance_xl +from typing import List +import torch +from tqdm import tqdm + + + +class SDXLVideoPipeline(SDXLImagePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16, use_original_animatediff=True): + super().__init__(device=device, torch_dtype=torch_dtype) + self.scheduler = EnhancedDDIMScheduler(beta_schedule="linear" if use_original_animatediff else "scaled_linear") + self.prompter = SDXLPrompter() + # models + self.text_encoder: SDXLTextEncoder = None + self.text_encoder_2: SDXLTextEncoder2 = None + self.text_encoder_kolors: ChatGLMModel = None + self.unet: SDXLUNet = None + self.vae_decoder: SDXLVAEDecoder = None + self.vae_encoder: SDXLVAEEncoder = None + # self.controlnet: MultiControlNetManager = None (TODO) + self.ipadapter_image_encoder: IpAdapterXLCLIPImageEmbedder = None + self.ipadapter: SDXLIpAdapter = None + self.motion_modules: SDXLMotionModel = None + + + def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]): + # Main models + self.text_encoder = model_manager.fetch_model("sdxl_text_encoder") + self.text_encoder_2 = model_manager.fetch_model("sdxl_text_encoder_2") + self.text_encoder_kolors = model_manager.fetch_model("kolors_text_encoder") + self.unet = model_manager.fetch_model("sdxl_unet") + self.vae_decoder = model_manager.fetch_model("sdxl_vae_decoder") + self.vae_encoder = model_manager.fetch_model("sdxl_vae_encoder") + self.prompter.fetch_models(self.text_encoder) + self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes) + + # ControlNets (TODO) + + # IP-Adapters + self.ipadapter = model_manager.fetch_model("sdxl_ipadapter") + self.ipadapter_image_encoder = model_manager.fetch_model("sdxl_ipadapter_clip_image_encoder") + + # Motion Modules + self.motion_modules = model_manager.fetch_model("sdxl_motion_modules") + if self.motion_modules is None: + self.scheduler = EnhancedDDIMScheduler(beta_schedule="scaled_linear") + + # Kolors + if self.text_encoder_kolors is not None: + print("Switch to Kolors. The prompter will be replaced.") + self.prompter = KolorsPrompter() + self.prompter.fetch_models(self.text_encoder_kolors) + # The schedulers of AniamteDiff and Kolors are incompatible. We align it with AniamteDiff. + if self.motion_modules is None: + self.scheduler = EnhancedDDIMScheduler(beta_end=0.014, num_train_timesteps=1100) + else: + self.prompter.fetch_models(self.text_encoder, self.text_encoder_2) + + + @staticmethod + def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]): + pipe = SDXLVideoPipeline( + device=model_manager.device, + torch_dtype=model_manager.torch_dtype, + ) + pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes) + return pipe + + + def decode_video(self, latents, tiled=False, tile_size=64, tile_stride=32): + images = [ + self.decode_image(latents[frame_id: frame_id+1], tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + for frame_id in range(latents.shape[0]) + ] + return images + + + def encode_video(self, processed_images, tiled=False, tile_size=64, tile_stride=32): + latents = [] + for image in processed_images: + image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype) + latent = self.encode_image(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + latents.append(latent.cpu()) + latents = torch.concat(latents, dim=0) + return latents + + + @torch.no_grad() + def __call__( + self, + prompt, + negative_prompt="", + cfg_scale=7.5, + clip_skip=1, + num_frames=None, + input_frames=None, + ipadapter_images=None, + ipadapter_scale=1.0, + ipadapter_use_instant_style=False, + controlnet_frames=None, + denoising_strength=1.0, + height=512, + width=512, + num_inference_steps=20, + animatediff_batch_size = 16, + animatediff_stride = 8, + unet_batch_size = 1, + controlnet_batch_size = 1, + cross_frame_attention = False, + smoother=None, + smoother_progress_ids=[], + tiled=False, + tile_size=64, + tile_stride=32, + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Tiler parameters, batch size ... + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Prepare latent tensors + if self.motion_modules is None: + noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype).repeat(num_frames, 1, 1, 1) + else: + noise = self.generate_noise((num_frames, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype) + if input_frames is None or denoising_strength == 1.0: + latents = noise + else: + latents = self.encode_video(input_frames, **tiler_kwargs) + latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0]) + latents = latents.to(self.device) # will be deleted for supporting long videos + + # Encode prompts + prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, positive=True) + prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, positive=False) + + # IP-Adapter + if ipadapter_images is not None: + if ipadapter_use_instant_style: + self.ipadapter.set_less_adapter() + else: + self.ipadapter.set_full_adapter() + ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images) + ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)} + ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))} + else: + ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}} + + # Prepare ControlNets + if controlnet_frames is not None: + if isinstance(controlnet_frames[0], list): + controlnet_frames_ = [] + for processor_id in range(len(controlnet_frames)): + controlnet_frames_.append( + torch.stack([ + self.controlnet.process_image(controlnet_frame, processor_id=processor_id).to(self.torch_dtype) + for controlnet_frame in progress_bar_cmd(controlnet_frames[processor_id]) + ], dim=1) + ) + controlnet_frames = torch.concat(controlnet_frames_, dim=0) + else: + controlnet_frames = torch.stack([ + self.controlnet.process_image(controlnet_frame).to(self.torch_dtype) + for controlnet_frame in progress_bar_cmd(controlnet_frames) + ], dim=1) + controlnet_kwargs = {"controlnet_frames": controlnet_frames} + else: + controlnet_kwargs = {"controlnet_frames": None} + + # Prepare extra input + extra_input = self.prepare_extra_input(latents) + + # Denoise + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(self.device) + + # Classifier-free guidance + noise_pred_posi = lets_dance_xl( + self.unet, motion_modules=self.motion_modules, controlnet=None, + sample=latents, timestep=timestep, + **prompt_emb_posi, **controlnet_kwargs, **ipadapter_kwargs_list_posi, **extra_input, **tiler_kwargs, + device=self.device, + ) + noise_pred_nega = lets_dance_xl( + self.unet, motion_modules=self.motion_modules, controlnet=None, + sample=latents, timestep=timestep, + **prompt_emb_nega, **controlnet_kwargs, **ipadapter_kwargs_list_nega, **extra_input, **tiler_kwargs, + device=self.device, + ) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + + # DDIM and smoother + if smoother is not None and progress_id in smoother_progress_ids: + rendered_frames = self.scheduler.step(noise_pred, timestep, latents, to_final=True) + rendered_frames = self.decode_video(rendered_frames) + rendered_frames = smoother(rendered_frames, original_frames=input_frames) + target_latents = self.encode_video(rendered_frames) + noise_pred = self.scheduler.return_to_timestep(timestep, latents, target_latents) + latents = self.scheduler.step(noise_pred, timestep, latents) + + # UI + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + output_frames = self.decode_video(latents, **tiler_kwargs) + + # Post-process + if smoother is not None and (num_inference_steps in smoother_progress_ids or -1 in smoother_progress_ids): + output_frames = smoother(output_frames, original_frames=input_frames) + + return output_frames diff --git a/diffsynth/pipelines/step_video.py b/diffsynth/pipelines/step_video.py new file mode 100644 index 0000000000000000000000000000000000000000..56140178e9d6cdaf5efeca77ea061f8232836f11 --- /dev/null +++ b/diffsynth/pipelines/step_video.py @@ -0,0 +1,209 @@ +from ..models import ModelManager +from ..models.hunyuan_dit_text_encoder import HunyuanDiTCLIPTextEncoder +from ..models.stepvideo_text_encoder import STEP1TextEncoder +from ..models.stepvideo_dit import StepVideoModel +from ..models.stepvideo_vae import StepVideoVAE +from ..schedulers.flow_match import FlowMatchScheduler +from .base import BasePipeline +from ..prompters import StepVideoPrompter +import torch +from einops import rearrange +import numpy as np +from PIL import Image +from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear +from transformers.models.bert.modeling_bert import BertEmbeddings +from ..models.stepvideo_dit import RMSNorm +from ..models.stepvideo_vae import CausalConv, CausalConvAfterNorm, Upsample2D, BaseGroupNorm + + + +class StepVideoPipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype) + self.scheduler = FlowMatchScheduler(sigma_min=0.0, extra_one_step=True, shift=13.0, reverse_sigmas=True, num_train_timesteps=1) + self.prompter = StepVideoPrompter() + self.text_encoder_1: HunyuanDiTCLIPTextEncoder = None + self.text_encoder_2: STEP1TextEncoder = None + self.dit: StepVideoModel = None + self.vae: StepVideoVAE = None + self.model_names = ['text_encoder_1', 'text_encoder_2', 'dit', 'vae'] + + + def enable_vram_management(self, num_persistent_param_in_dit=None): + dtype = next(iter(self.text_encoder_1.parameters())).dtype + enable_vram_management( + self.text_encoder_1, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + BertEmbeddings: AutoWrappedModule, + torch.nn.LayerNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=torch.float32, + computation_device=self.device, + ), + ) + dtype = next(iter(self.text_encoder_2.parameters())).dtype + enable_vram_management( + self.text_encoder_2, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + RMSNorm: AutoWrappedModule, + torch.nn.Embedding: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + dtype = next(iter(self.dit.parameters())).dtype + enable_vram_management( + self.dit, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv2d: AutoWrappedModule, + torch.nn.LayerNorm: AutoWrappedModule, + RMSNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device=self.device, + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + max_num_param=num_persistent_param_in_dit, + overflow_module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + dtype = next(iter(self.vae.parameters())).dtype + enable_vram_management( + self.vae, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv3d: AutoWrappedModule, + CausalConv: AutoWrappedModule, + CausalConvAfterNorm: AutoWrappedModule, + Upsample2D: AutoWrappedModule, + BaseGroupNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + ) + self.enable_cpu_offload() + + + def fetch_models(self, model_manager: ModelManager): + self.text_encoder_1 = model_manager.fetch_model("hunyuan_dit_clip_text_encoder") + self.text_encoder_2 = model_manager.fetch_model("stepvideo_text_encoder_2") + self.dit = model_manager.fetch_model("stepvideo_dit") + self.vae = model_manager.fetch_model("stepvideo_vae") + self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2) + + + @staticmethod + def from_model_manager(model_manager: ModelManager, torch_dtype=None, device=None): + if device is None: device = model_manager.device + if torch_dtype is None: torch_dtype = model_manager.torch_dtype + pipe = StepVideoPipeline(device=device, torch_dtype=torch_dtype) + pipe.fetch_models(model_manager) + return pipe + + + def encode_prompt(self, prompt, positive=True): + clip_embeds, llm_embeds, llm_mask = self.prompter.encode_prompt(prompt, device=self.device, positive=positive) + clip_embeds = clip_embeds.to(dtype=self.torch_dtype, device=self.device) + llm_embeds = llm_embeds.to(dtype=self.torch_dtype, device=self.device) + llm_mask = llm_mask.to(dtype=self.torch_dtype, device=self.device) + return {"encoder_hidden_states_2": clip_embeds, "encoder_hidden_states": llm_embeds, "encoder_attention_mask": llm_mask} + + + def tensor2video(self, frames): + frames = rearrange(frames, "C T H W -> T H W C") + frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8) + frames = [Image.fromarray(frame) for frame in frames] + return frames + + + @torch.no_grad() + def __call__( + self, + prompt, + negative_prompt="", + input_video=None, + denoising_strength=1.0, + seed=None, + rand_device="cpu", + height=544, + width=992, + num_frames=204, + cfg_scale=9.0, + num_inference_steps=30, + tiled=True, + tile_size=(34, 34), + tile_stride=(16, 16), + smooth_scale=0.6, + progress_bar_cmd=lambda x: x, + progress_bar_st=None, + ): + # Tiler parameters + tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride} + + # Scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength) + + # Initialize noise + latents = self.generate_noise((1, max(num_frames//17*3, 1), 64, height//16, width//16), seed=seed, device=rand_device, dtype=self.torch_dtype).to(self.device) + + # Encode prompts + self.load_models_to_device(["text_encoder_1", "text_encoder_2"]) + prompt_emb_posi = self.encode_prompt(prompt, positive=True) + if cfg_scale != 1.0: + prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False) + + # Denoise + self.load_models_to_device(["dit"]) + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + timestep = timestep.unsqueeze(0).to(dtype=self.torch_dtype, device=self.device) + print(f"Step {progress_id + 1} / {len(self.scheduler.timesteps)}") + + # Inference + noise_pred_posi = self.dit(latents, timestep=timestep, **prompt_emb_posi) + if cfg_scale != 1.0: + noise_pred_nega = self.dit(latents, timestep=timestep, **prompt_emb_nega) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + else: + noise_pred = noise_pred_posi + + # Scheduler + latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents) + + # Decode + self.load_models_to_device(['vae']) + frames = self.vae.decode(latents, device=self.device, smooth_scale=smooth_scale, **tiler_kwargs) + self.load_models_to_device([]) + frames = self.tensor2video(frames[0]) + + return frames diff --git a/diffsynth/pipelines/svd_video.py b/diffsynth/pipelines/svd_video.py new file mode 100644 index 0000000000000000000000000000000000000000..b71597efa73783f7e3746a2bcf6b7be5c70c360e --- /dev/null +++ b/diffsynth/pipelines/svd_video.py @@ -0,0 +1,300 @@ +from ..models import ModelManager, SVDImageEncoder, SVDUNet, SVDVAEEncoder, SVDVAEDecoder +from ..schedulers import ContinuousODEScheduler +from .base import BasePipeline +import torch +from tqdm import tqdm +from PIL import Image +import numpy as np +from einops import rearrange, repeat + + + +class SVDVideoPipeline(BasePipeline): + + def __init__(self, device="cuda", torch_dtype=torch.float16): + super().__init__(device=device, torch_dtype=torch_dtype) + self.scheduler = ContinuousODEScheduler() + # models + self.image_encoder: SVDImageEncoder = None + self.unet: SVDUNet = None + self.vae_encoder: SVDVAEEncoder = None + self.vae_decoder: SVDVAEDecoder = None + + + def fetch_models(self, model_manager: ModelManager): + self.image_encoder = model_manager.fetch_model("svd_image_encoder") + self.unet = model_manager.fetch_model("svd_unet") + self.vae_encoder = model_manager.fetch_model("svd_vae_encoder") + self.vae_decoder = model_manager.fetch_model("svd_vae_decoder") + + + @staticmethod + def from_model_manager(model_manager: ModelManager, **kwargs): + pipe = SVDVideoPipeline( + device=model_manager.device, + torch_dtype=model_manager.torch_dtype + ) + pipe.fetch_models(model_manager) + return pipe + + + def encode_image_with_clip(self, image): + image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype) + image = SVDCLIPImageProcessor().resize_with_antialiasing(image, (224, 224)) + image = (image + 1.0) / 2.0 + mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).reshape(1, 3, 1, 1).to(device=self.device, dtype=self.torch_dtype) + std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).reshape(1, 3, 1, 1).to(device=self.device, dtype=self.torch_dtype) + image = (image - mean) / std + image_emb = self.image_encoder(image) + return image_emb + + + def encode_image_with_vae(self, image, noise_aug_strength, seed=None): + image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype) + noise = self.generate_noise(image.shape, seed=seed, device=self.device, dtype=self.torch_dtype) + image = image + noise_aug_strength * noise + image_emb = self.vae_encoder(image) / self.vae_encoder.scaling_factor + return image_emb + + + def encode_video_with_vae(self, video): + video = torch.concat([self.preprocess_image(frame) for frame in video], dim=0) + video = rearrange(video, "T C H W -> 1 C T H W") + video = video.to(device=self.device, dtype=self.torch_dtype) + latents = self.vae_encoder.encode_video(video) + latents = rearrange(latents[0], "C T H W -> T C H W") + return latents + + + def tensor2video(self, frames): + frames = rearrange(frames, "C T H W -> T H W C") + frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8) + frames = [Image.fromarray(frame) for frame in frames] + return frames + + + def calculate_noise_pred( + self, + latents, + timestep, + add_time_id, + cfg_scales, + image_emb_vae_posi, image_emb_clip_posi, + image_emb_vae_nega, image_emb_clip_nega + ): + # Positive side + noise_pred_posi = self.unet( + torch.cat([latents, image_emb_vae_posi], dim=1), + timestep, image_emb_clip_posi, add_time_id + ) + # Negative side + noise_pred_nega = self.unet( + torch.cat([latents, image_emb_vae_nega], dim=1), + timestep, image_emb_clip_nega, add_time_id + ) + + # Classifier-free guidance + noise_pred = noise_pred_nega + cfg_scales * (noise_pred_posi - noise_pred_nega) + + return noise_pred + + + def post_process_latents(self, latents, post_normalize=True, contrast_enhance_scale=1.0): + if post_normalize: + mean, std = latents.mean(), latents.std() + latents = (latents - latents.mean(dim=[1, 2, 3], keepdim=True)) / latents.std(dim=[1, 2, 3], keepdim=True) * std + mean + latents = latents * contrast_enhance_scale + return latents + + + @torch.no_grad() + def __call__( + self, + input_image=None, + input_video=None, + mask_frames=[], + mask_frame_ids=[], + min_cfg_scale=1.0, + max_cfg_scale=3.0, + denoising_strength=1.0, + num_frames=25, + height=576, + width=1024, + fps=7, + motion_bucket_id=127, + noise_aug_strength=0.02, + num_inference_steps=20, + post_normalize=True, + contrast_enhance_scale=1.2, + seed=None, + progress_bar_cmd=tqdm, + progress_bar_st=None, + ): + height, width = self.check_resize_height_width(height, width) + + # Prepare scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength) + + # Prepare latent tensors + noise = self.generate_noise((num_frames, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype) + if denoising_strength == 1.0: + latents = noise.clone() + else: + latents = self.encode_video_with_vae(input_video) + latents = self.scheduler.add_noise(latents, noise, self.scheduler.timesteps[0]) + + # Prepare mask frames + if len(mask_frames) > 0: + mask_latents = self.encode_video_with_vae(mask_frames) + + # Encode image + image_emb_clip_posi = self.encode_image_with_clip(input_image) + image_emb_clip_nega = torch.zeros_like(image_emb_clip_posi) + image_emb_vae_posi = repeat(self.encode_image_with_vae(input_image, noise_aug_strength, seed=seed), "B C H W -> (B T) C H W", T=num_frames) + image_emb_vae_nega = torch.zeros_like(image_emb_vae_posi) + + # Prepare classifier-free guidance + cfg_scales = torch.linspace(min_cfg_scale, max_cfg_scale, num_frames) + cfg_scales = cfg_scales.reshape(num_frames, 1, 1, 1).to(device=self.device, dtype=self.torch_dtype) + + # Prepare positional id + add_time_id = torch.tensor([[fps-1, motion_bucket_id, noise_aug_strength]], device=self.device) + + # Denoise + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + + # Mask frames + for frame_id, mask_frame_id in enumerate(mask_frame_ids): + latents[mask_frame_id] = self.scheduler.add_noise(mask_latents[frame_id], noise[mask_frame_id], timestep) + + # Fetch model output + noise_pred = self.calculate_noise_pred( + latents, timestep, add_time_id, cfg_scales, + image_emb_vae_posi, image_emb_clip_posi, image_emb_vae_nega, image_emb_clip_nega + ) + + # Forward Euler + latents = self.scheduler.step(noise_pred, timestep, latents) + + # Update progress bar + if progress_bar_st is not None: + progress_bar_st.progress(progress_id / len(self.scheduler.timesteps)) + + # Decode image + latents = self.post_process_latents(latents, post_normalize=post_normalize, contrast_enhance_scale=contrast_enhance_scale) + video = self.vae_decoder.decode_video(latents, progress_bar=progress_bar_cmd) + video = self.tensor2video(video) + + return video + + + +class SVDCLIPImageProcessor: + def __init__(self): + pass + + def resize_with_antialiasing(self, input, size, interpolation="bicubic", align_corners=True): + h, w = input.shape[-2:] + factors = (h / size[0], w / size[1]) + + # First, we have to determine sigma + # Taken from skimage: https://github.com/scikit-image/scikit-image/blob/v0.19.2/skimage/transform/_warps.py#L171 + sigmas = ( + max((factors[0] - 1.0) / 2.0, 0.001), + max((factors[1] - 1.0) / 2.0, 0.001), + ) + + # Now kernel size. Good results are for 3 sigma, but that is kind of slow. Pillow uses 1 sigma + # https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206 + # But they do it in the 2 passes, which gives better results. Let's try 2 sigmas for now + ks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3)) + + # Make sure it is odd + if (ks[0] % 2) == 0: + ks = ks[0] + 1, ks[1] + + if (ks[1] % 2) == 0: + ks = ks[0], ks[1] + 1 + + input = self._gaussian_blur2d(input, ks, sigmas) + + output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners) + return output + + + def _compute_padding(self, kernel_size): + """Compute padding tuple.""" + # 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom) + # https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad + if len(kernel_size) < 2: + raise AssertionError(kernel_size) + computed = [k - 1 for k in kernel_size] + + # for even kernels we need to do asymmetric padding :( + out_padding = 2 * len(kernel_size) * [0] + + for i in range(len(kernel_size)): + computed_tmp = computed[-(i + 1)] + + pad_front = computed_tmp // 2 + pad_rear = computed_tmp - pad_front + + out_padding[2 * i + 0] = pad_front + out_padding[2 * i + 1] = pad_rear + + return out_padding + + + def _filter2d(self, input, kernel): + # prepare kernel + b, c, h, w = input.shape + tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype) + + tmp_kernel = tmp_kernel.expand(-1, c, -1, -1) + + height, width = tmp_kernel.shape[-2:] + + padding_shape: list[int] = self._compute_padding([height, width]) + input = torch.nn.functional.pad(input, padding_shape, mode="reflect") + + # kernel and input tensor reshape to align element-wise or batch-wise params + tmp_kernel = tmp_kernel.reshape(-1, 1, height, width) + input = input.view(-1, tmp_kernel.size(0), input.size(-2), input.size(-1)) + + # convolve the tensor with the kernel. + output = torch.nn.functional.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1) + + out = output.view(b, c, h, w) + return out + + + def _gaussian(self, window_size: int, sigma): + if isinstance(sigma, float): + sigma = torch.tensor([[sigma]]) + + batch_size = sigma.shape[0] + + x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1) + + if window_size % 2 == 0: + x = x + 0.5 + + gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0))) + + return gauss / gauss.sum(-1, keepdim=True) + + + def _gaussian_blur2d(self, input, kernel_size, sigma): + if isinstance(sigma, tuple): + sigma = torch.tensor([sigma], dtype=input.dtype) + else: + sigma = sigma.to(dtype=input.dtype) + + ky, kx = int(kernel_size[0]), int(kernel_size[1]) + bs = sigma.shape[0] + kernel_x = self._gaussian(kx, sigma[:, 1].view(bs, 1)) + kernel_y = self._gaussian(ky, sigma[:, 0].view(bs, 1)) + out_x = self._filter2d(input, kernel_x[..., None, :]) + out = self._filter2d(out_x, kernel_y[..., None]) + + return out diff --git a/diffsynth/processors/FastBlend.py b/diffsynth/processors/FastBlend.py new file mode 100644 index 0000000000000000000000000000000000000000..fed33f4fdd215c8c9dc46f3b07d9453a12cc6b98 --- /dev/null +++ b/diffsynth/processors/FastBlend.py @@ -0,0 +1,142 @@ +from PIL import Image +import cupy as cp +import numpy as np +from tqdm import tqdm +from ..extensions.FastBlend.patch_match import PyramidPatchMatcher +from ..extensions.FastBlend.runners.fast import TableManager +from .base import VideoProcessor + + +class FastBlendSmoother(VideoProcessor): + def __init__( + self, + inference_mode="fast", batch_size=8, window_size=60, + minimum_patch_size=5, threads_per_block=8, num_iter=5, gpu_id=0, guide_weight=10.0, initialize="identity", tracking_window_size=0 + ): + self.inference_mode = inference_mode + self.batch_size = batch_size + self.window_size = window_size + self.ebsynth_config = { + "minimum_patch_size": minimum_patch_size, + "threads_per_block": threads_per_block, + "num_iter": num_iter, + "gpu_id": gpu_id, + "guide_weight": guide_weight, + "initialize": initialize, + "tracking_window_size": tracking_window_size + } + + @staticmethod + def from_model_manager(model_manager, **kwargs): + # TODO: fetch GPU ID from model_manager + return FastBlendSmoother(**kwargs) + + def inference_fast(self, frames_guide, frames_style): + table_manager = TableManager() + patch_match_engine = PyramidPatchMatcher( + image_height=frames_style[0].shape[0], + image_width=frames_style[0].shape[1], + channel=3, + **self.ebsynth_config + ) + # left part + table_l = table_manager.build_remapping_table(frames_guide, frames_style, patch_match_engine, self.batch_size, desc="Fast Mode Step 1/4") + table_l = table_manager.remapping_table_to_blending_table(table_l) + table_l = table_manager.process_window_sum(frames_guide, table_l, patch_match_engine, self.window_size, self.batch_size, desc="Fast Mode Step 2/4") + # right part + table_r = table_manager.build_remapping_table(frames_guide[::-1], frames_style[::-1], patch_match_engine, self.batch_size, desc="Fast Mode Step 3/4") + table_r = table_manager.remapping_table_to_blending_table(table_r) + table_r = table_manager.process_window_sum(frames_guide[::-1], table_r, patch_match_engine, self.window_size, self.batch_size, desc="Fast Mode Step 4/4")[::-1] + # merge + frames = [] + for (frame_l, weight_l), frame_m, (frame_r, weight_r) in zip(table_l, frames_style, table_r): + weight_m = -1 + weight = weight_l + weight_m + weight_r + frame = frame_l * (weight_l / weight) + frame_m * (weight_m / weight) + frame_r * (weight_r / weight) + frames.append(frame) + frames = [frame.clip(0, 255).astype("uint8") for frame in frames] + frames = [Image.fromarray(frame) for frame in frames] + return frames + + def inference_balanced(self, frames_guide, frames_style): + patch_match_engine = PyramidPatchMatcher( + image_height=frames_style[0].shape[0], + image_width=frames_style[0].shape[1], + channel=3, + **self.ebsynth_config + ) + output_frames = [] + # tasks + n = len(frames_style) + tasks = [] + for target in range(n): + for source in range(target - self.window_size, target + self.window_size + 1): + if source >= 0 and source < n and source != target: + tasks.append((source, target)) + # run + frames = [(None, 1) for i in range(n)] + for batch_id in tqdm(range(0, len(tasks), self.batch_size), desc="Balanced Mode"): + tasks_batch = tasks[batch_id: min(batch_id+self.batch_size, len(tasks))] + source_guide = np.stack([frames_guide[source] for source, target in tasks_batch]) + target_guide = np.stack([frames_guide[target] for source, target in tasks_batch]) + source_style = np.stack([frames_style[source] for source, target in tasks_batch]) + _, target_style = patch_match_engine.estimate_nnf(source_guide, target_guide, source_style) + for (source, target), result in zip(tasks_batch, target_style): + frame, weight = frames[target] + if frame is None: + frame = frames_style[target] + frames[target] = ( + frame * (weight / (weight + 1)) + result / (weight + 1), + weight + 1 + ) + if weight + 1 == min(n, target + self.window_size + 1) - max(0, target - self.window_size): + frame = frame.clip(0, 255).astype("uint8") + output_frames.append(Image.fromarray(frame)) + frames[target] = (None, 1) + return output_frames + + def inference_accurate(self, frames_guide, frames_style): + patch_match_engine = PyramidPatchMatcher( + image_height=frames_style[0].shape[0], + image_width=frames_style[0].shape[1], + channel=3, + use_mean_target_style=True, + **self.ebsynth_config + ) + output_frames = [] + # run + n = len(frames_style) + for target in tqdm(range(n), desc="Accurate Mode"): + l, r = max(target - self.window_size, 0), min(target + self.window_size + 1, n) + remapped_frames = [] + for i in range(l, r, self.batch_size): + j = min(i + self.batch_size, r) + source_guide = np.stack([frames_guide[source] for source in range(i, j)]) + target_guide = np.stack([frames_guide[target]] * (j - i)) + source_style = np.stack([frames_style[source] for source in range(i, j)]) + _, target_style = patch_match_engine.estimate_nnf(source_guide, target_guide, source_style) + remapped_frames.append(target_style) + frame = np.concatenate(remapped_frames, axis=0).mean(axis=0) + frame = frame.clip(0, 255).astype("uint8") + output_frames.append(Image.fromarray(frame)) + return output_frames + + def release_vram(self): + mempool = cp.get_default_memory_pool() + pinned_mempool = cp.get_default_pinned_memory_pool() + mempool.free_all_blocks() + pinned_mempool.free_all_blocks() + + def __call__(self, rendered_frames, original_frames=None, **kwargs): + rendered_frames = [np.array(frame) for frame in rendered_frames] + original_frames = [np.array(frame) for frame in original_frames] + if self.inference_mode == "fast": + output_frames = self.inference_fast(original_frames, rendered_frames) + elif self.inference_mode == "balanced": + output_frames = self.inference_balanced(original_frames, rendered_frames) + elif self.inference_mode == "accurate": + output_frames = self.inference_accurate(original_frames, rendered_frames) + else: + raise ValueError("inference_mode must be fast, balanced or accurate") + self.release_vram() + return output_frames diff --git a/diffsynth/processors/PILEditor.py b/diffsynth/processors/PILEditor.py new file mode 100644 index 0000000000000000000000000000000000000000..01011d8724f61283550d503c5c20ae6fd0375ec7 --- /dev/null +++ b/diffsynth/processors/PILEditor.py @@ -0,0 +1,28 @@ +from PIL import ImageEnhance +from .base import VideoProcessor + + +class ContrastEditor(VideoProcessor): + def __init__(self, rate=1.5): + self.rate = rate + + @staticmethod + def from_model_manager(model_manager, **kwargs): + return ContrastEditor(**kwargs) + + def __call__(self, rendered_frames, **kwargs): + rendered_frames = [ImageEnhance.Contrast(i).enhance(self.rate) for i in rendered_frames] + return rendered_frames + + +class SharpnessEditor(VideoProcessor): + def __init__(self, rate=1.5): + self.rate = rate + + @staticmethod + def from_model_manager(model_manager, **kwargs): + return SharpnessEditor(**kwargs) + + def __call__(self, rendered_frames, **kwargs): + rendered_frames = [ImageEnhance.Sharpness(i).enhance(self.rate) for i in rendered_frames] + return rendered_frames diff --git a/diffsynth/processors/RIFE.py b/diffsynth/processors/RIFE.py new file mode 100644 index 0000000000000000000000000000000000000000..4186eb31496e9a1bf38df06eb64921226f07ee09 --- /dev/null +++ b/diffsynth/processors/RIFE.py @@ -0,0 +1,77 @@ +import torch +import numpy as np +from PIL import Image +from .base import VideoProcessor + + +class RIFESmoother(VideoProcessor): + def __init__(self, model, device="cuda", scale=1.0, batch_size=4, interpolate=True): + self.model = model + self.device = device + + # IFNet only does not support float16 + self.torch_dtype = torch.float32 + + # Other parameters + self.scale = scale + self.batch_size = batch_size + self.interpolate = interpolate + + @staticmethod + def from_model_manager(model_manager, **kwargs): + return RIFESmoother(model_manager.RIFE, device=model_manager.device, **kwargs) + + def process_image(self, image): + width, height = image.size + if width % 32 != 0 or height % 32 != 0: + width = (width + 31) // 32 + height = (height + 31) // 32 + image = image.resize((width, height)) + image = torch.Tensor(np.array(image, dtype=np.float32)[:, :, [2,1,0]] / 255).permute(2, 0, 1) + return image + + def process_images(self, images): + images = [self.process_image(image) for image in images] + images = torch.stack(images) + return images + + def decode_images(self, images): + images = (images[:, [2,1,0]].permute(0, 2, 3, 1) * 255).clip(0, 255).numpy().astype(np.uint8) + images = [Image.fromarray(image) for image in images] + return images + + def process_tensors(self, input_tensor, scale=1.0, batch_size=4): + output_tensor = [] + for batch_id in range(0, input_tensor.shape[0], batch_size): + batch_id_ = min(batch_id + batch_size, input_tensor.shape[0]) + batch_input_tensor = input_tensor[batch_id: batch_id_] + batch_input_tensor = batch_input_tensor.to(device=self.device, dtype=self.torch_dtype) + flow, mask, merged = self.model(batch_input_tensor, [4/scale, 2/scale, 1/scale]) + output_tensor.append(merged[2].cpu()) + output_tensor = torch.concat(output_tensor, dim=0) + return output_tensor + + @torch.no_grad() + def __call__(self, rendered_frames, **kwargs): + # Preprocess + processed_images = self.process_images(rendered_frames) + + # Input + input_tensor = torch.cat((processed_images[:-2], processed_images[2:]), dim=1) + + # Interpolate + output_tensor = self.process_tensors(input_tensor, scale=self.scale, batch_size=self.batch_size) + + if self.interpolate: + # Blend + input_tensor = torch.cat((processed_images[1:-1], output_tensor), dim=1) + output_tensor = self.process_tensors(input_tensor, scale=self.scale, batch_size=self.batch_size) + processed_images[1:-1] = output_tensor + else: + processed_images[1:-1] = (processed_images[1:-1] + output_tensor) / 2 + + # To images + output_images = self.decode_images(processed_images) + if output_images[0].size != rendered_frames[0].size: + output_images = [image.resize(rendered_frames[0].size) for image in output_images] + return output_images diff --git a/diffsynth/processors/__init__.py b/diffsynth/processors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/diffsynth/processors/__pycache__/__init__.cpython-311.pyc b/diffsynth/processors/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91ff049624d8992aa08cfff63be976a872a6bc1a Binary files /dev/null and b/diffsynth/processors/__pycache__/__init__.cpython-311.pyc differ diff --git a/diffsynth/processors/__pycache__/base.cpython-311.pyc b/diffsynth/processors/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7469d8db9be41c0fd1f831eed654ff35152c58d9 Binary files /dev/null and b/diffsynth/processors/__pycache__/base.cpython-311.pyc differ diff --git a/diffsynth/processors/__pycache__/sequencial_processor.cpython-311.pyc b/diffsynth/processors/__pycache__/sequencial_processor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee9164c0e064438f9a396f54467f025c49e17eef Binary files /dev/null and b/diffsynth/processors/__pycache__/sequencial_processor.cpython-311.pyc differ diff --git a/diffsynth/processors/base.py b/diffsynth/processors/base.py new file mode 100644 index 0000000000000000000000000000000000000000..278a9c1b74044987cc116de35292a96de8b13737 --- /dev/null +++ b/diffsynth/processors/base.py @@ -0,0 +1,6 @@ +class VideoProcessor: + def __init__(self): + pass + + def __call__(self): + raise NotImplementedError diff --git a/diffsynth/processors/sequencial_processor.py b/diffsynth/processors/sequencial_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5bc9454f0b9d74f10bb4a6bff92db77f26325c --- /dev/null +++ b/diffsynth/processors/sequencial_processor.py @@ -0,0 +1,41 @@ +from .base import VideoProcessor + + +class AutoVideoProcessor(VideoProcessor): + def __init__(self): + pass + + @staticmethod + def from_model_manager(model_manager, processor_type, **kwargs): + if processor_type == "FastBlend": + from .FastBlend import FastBlendSmoother + return FastBlendSmoother.from_model_manager(model_manager, **kwargs) + elif processor_type == "Contrast": + from .PILEditor import ContrastEditor + return ContrastEditor.from_model_manager(model_manager, **kwargs) + elif processor_type == "Sharpness": + from .PILEditor import SharpnessEditor + return SharpnessEditor.from_model_manager(model_manager, **kwargs) + elif processor_type == "RIFE": + from .RIFE import RIFESmoother + return RIFESmoother.from_model_manager(model_manager, **kwargs) + else: + raise ValueError(f"invalid processor_type: {processor_type}") + + +class SequencialProcessor(VideoProcessor): + def __init__(self, processors=[]): + self.processors = processors + + @staticmethod + def from_model_manager(model_manager, configs): + processors = [ + AutoVideoProcessor.from_model_manager(model_manager, config["processor_type"], **config["config"]) + for config in configs + ] + return SequencialProcessor(processors) + + def __call__(self, rendered_frames, **kwargs): + for processor in self.processors: + rendered_frames = processor(rendered_frames, **kwargs) + return rendered_frames diff --git a/diffsynth/prompters/__pycache__/sd3_prompter.cpython-311.pyc b/diffsynth/prompters/__pycache__/sd3_prompter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb597a73cfdc7ae12dd77b290f419df6a30ab0f7 Binary files /dev/null and b/diffsynth/prompters/__pycache__/sd3_prompter.cpython-311.pyc differ diff --git a/diffsynth/prompters/base_prompter.py b/diffsynth/prompters/base_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..136abd18fabdb04e618f59801420c9ce5fb94634 --- /dev/null +++ b/diffsynth/prompters/base_prompter.py @@ -0,0 +1,70 @@ +from ..models.model_manager import ModelManager +import torch + + + +def tokenize_long_prompt(tokenizer, prompt, max_length=None): + # Get model_max_length from self.tokenizer + length = tokenizer.model_max_length if max_length is None else max_length + + # To avoid the warning. set self.tokenizer.model_max_length to +oo. + tokenizer.model_max_length = 99999999 + + # Tokenize it! + input_ids = tokenizer(prompt, return_tensors="pt").input_ids + + # Determine the real length. + max_length = (input_ids.shape[1] + length - 1) // length * length + + # Restore tokenizer.model_max_length + tokenizer.model_max_length = length + + # Tokenize it again with fixed length. + input_ids = tokenizer( + prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True + ).input_ids + + # Reshape input_ids to fit the text encoder. + num_sentence = input_ids.shape[1] // length + input_ids = input_ids.reshape((num_sentence, length)) + + return input_ids + + + +class BasePrompter: + def __init__(self): + self.refiners = [] + self.extenders = [] + + + def load_prompt_refiners(self, model_manager: ModelManager, refiner_classes=[]): + for refiner_class in refiner_classes: + refiner = refiner_class.from_model_manager(model_manager) + self.refiners.append(refiner) + + def load_prompt_extenders(self,model_manager:ModelManager,extender_classes=[]): + for extender_class in extender_classes: + extender = extender_class.from_model_manager(model_manager) + self.extenders.append(extender) + + + @torch.no_grad() + def process_prompt(self, prompt, positive=True): + if isinstance(prompt, list): + prompt = [self.process_prompt(prompt_, positive=positive) for prompt_ in prompt] + else: + for refiner in self.refiners: + prompt = refiner(prompt, positive=positive) + return prompt + + @torch.no_grad() + def extend_prompt(self, prompt:str, positive=True): + extended_prompt = dict(prompt=prompt) + for extender in self.extenders: + extended_prompt = extender(extended_prompt) + return extended_prompt \ No newline at end of file diff --git a/diffsynth/prompters/flux_prompter.py b/diffsynth/prompters/flux_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a06ff8df29345f505873cf1b79c963229f3efb --- /dev/null +++ b/diffsynth/prompters/flux_prompter.py @@ -0,0 +1,74 @@ +from .base_prompter import BasePrompter +from ..models.flux_text_encoder import FluxTextEncoder2 +from ..models.sd3_text_encoder import SD3TextEncoder1 +from transformers import CLIPTokenizer, T5TokenizerFast +import os, torch + + +class FluxPrompter(BasePrompter): + def __init__( + self, + tokenizer_1_path=None, + tokenizer_2_path=None + ): + if tokenizer_1_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_1_path = os.path.join(base_path, "tokenizer_configs/flux/tokenizer_1") + if tokenizer_2_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_2_path = os.path.join(base_path, "tokenizer_configs/flux/tokenizer_2") + super().__init__() + self.tokenizer_1 = CLIPTokenizer.from_pretrained(tokenizer_1_path) + self.tokenizer_2 = T5TokenizerFast.from_pretrained(tokenizer_2_path) + self.text_encoder_1: SD3TextEncoder1 = None + self.text_encoder_2: FluxTextEncoder2 = None + + + def fetch_models(self, text_encoder_1: SD3TextEncoder1 = None, text_encoder_2: FluxTextEncoder2 = None): + self.text_encoder_1 = text_encoder_1 + self.text_encoder_2 = text_encoder_2 + + + def encode_prompt_using_clip(self, prompt, text_encoder, tokenizer, max_length, device): + input_ids = tokenizer( + prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True + ).input_ids.to(device) + pooled_prompt_emb, _ = text_encoder(input_ids) + return pooled_prompt_emb + + + def encode_prompt_using_t5(self, prompt, text_encoder, tokenizer, max_length, device): + input_ids = tokenizer( + prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True, + ).input_ids.to(device) + prompt_emb = text_encoder(input_ids) + return prompt_emb + + + def encode_prompt( + self, + prompt, + positive=True, + device="cuda", + t5_sequence_length=512, + ): + prompt = self.process_prompt(prompt, positive=positive) + + # CLIP + pooled_prompt_emb = self.encode_prompt_using_clip(prompt, self.text_encoder_1, self.tokenizer_1, 77, device) + + # T5 + prompt_emb = self.encode_prompt_using_t5(prompt, self.text_encoder_2, self.tokenizer_2, t5_sequence_length, device) + + # text_ids + text_ids = torch.zeros(prompt_emb.shape[0], prompt_emb.shape[1], 3).to(device=device, dtype=prompt_emb.dtype) + + return prompt_emb, pooled_prompt_emb, text_ids diff --git a/diffsynth/prompters/hunyuan_dit_prompter.py b/diffsynth/prompters/hunyuan_dit_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..52a22ed72ab77ef668183119fff67db3141ee561 --- /dev/null +++ b/diffsynth/prompters/hunyuan_dit_prompter.py @@ -0,0 +1,69 @@ +from .base_prompter import BasePrompter +from ..models.model_manager import ModelManager +from ..models import HunyuanDiTCLIPTextEncoder, HunyuanDiTT5TextEncoder +from transformers import BertTokenizer, AutoTokenizer +import warnings, os + + +class HunyuanDiTPrompter(BasePrompter): + def __init__( + self, + tokenizer_path=None, + tokenizer_t5_path=None + ): + if tokenizer_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_path = os.path.join(base_path, "tokenizer_configs/hunyuan_dit/tokenizer") + if tokenizer_t5_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_t5_path = os.path.join(base_path, "tokenizer_configs/hunyuan_dit/tokenizer_t5") + super().__init__() + self.tokenizer = BertTokenizer.from_pretrained(tokenizer_path) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + self.tokenizer_t5 = AutoTokenizer.from_pretrained(tokenizer_t5_path) + self.text_encoder: HunyuanDiTCLIPTextEncoder = None + self.text_encoder_t5: HunyuanDiTT5TextEncoder = None + + + def fetch_models(self, text_encoder: HunyuanDiTCLIPTextEncoder = None, text_encoder_t5: HunyuanDiTT5TextEncoder = None): + self.text_encoder = text_encoder + self.text_encoder_t5 = text_encoder_t5 + + + def encode_prompt_using_signle_model(self, prompt, text_encoder, tokenizer, max_length, clip_skip, device): + text_inputs = tokenizer( + prompt, + padding="max_length", + max_length=max_length, + truncation=True, + return_attention_mask=True, + return_tensors="pt", + ) + text_input_ids = text_inputs.input_ids + attention_mask = text_inputs.attention_mask.to(device) + prompt_embeds = text_encoder( + text_input_ids.to(device), + attention_mask=attention_mask, + clip_skip=clip_skip + ) + return prompt_embeds, attention_mask + + + def encode_prompt( + self, + prompt, + clip_skip=1, + clip_skip_2=1, + positive=True, + device="cuda" + ): + prompt = self.process_prompt(prompt, positive=positive) + + # CLIP + prompt_emb, attention_mask = self.encode_prompt_using_signle_model(prompt, self.text_encoder, self.tokenizer, self.tokenizer.model_max_length, clip_skip, device) + + # T5 + prompt_emb_t5, attention_mask_t5 = self.encode_prompt_using_signle_model(prompt, self.text_encoder_t5, self.tokenizer_t5, self.tokenizer_t5.model_max_length, clip_skip_2, device) + + return prompt_emb, attention_mask, prompt_emb_t5, attention_mask_t5 diff --git a/diffsynth/prompters/hunyuan_video_prompter.py b/diffsynth/prompters/hunyuan_video_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..5b97356cacd4b9ccd9d0912b5694e1c1b4868ae9 --- /dev/null +++ b/diffsynth/prompters/hunyuan_video_prompter.py @@ -0,0 +1,275 @@ +from .base_prompter import BasePrompter +from ..models.sd3_text_encoder import SD3TextEncoder1 +from ..models.hunyuan_video_text_encoder import HunyuanVideoLLMEncoder, HunyuanVideoMLLMEncoder +from transformers import CLIPTokenizer, LlamaTokenizerFast, CLIPImageProcessor +import os, torch +from typing import Union + +PROMPT_TEMPLATE_ENCODE = ( + "<|start_header_id|>system<|end_header_id|>\n\nDescribe the image by detailing the color, shape, size, texture, " + "quantity, text, spatial relationships of the objects and background:<|eot_id|>" + "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>") + +PROMPT_TEMPLATE_ENCODE_VIDEO = ( + "<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: " + "1. The main content and theme of the video." + "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects." + "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects." + "4. background environment, light, style and atmosphere." + "5. camera angles, movements, and transitions used in the video:<|eot_id|>" + "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>") + +PROMPT_TEMPLATE_ENCODE_I2V = ( + "<|start_header_id|>system<|end_header_id|>\n\n\nDescribe the image by detailing the color, shape, size, texture, " + "quantity, text, spatial relationships of the objects and background:<|eot_id|>" + "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>" + "<|start_header_id|>assistant<|end_header_id|>\n\n" +) + +PROMPT_TEMPLATE_ENCODE_VIDEO_I2V = ( + "<|start_header_id|>system<|end_header_id|>\n\n\nDescribe the video by detailing the following aspects according to the reference image: " + "1. The main content and theme of the video." + "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects." + "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects." + "4. background environment, light, style and atmosphere." + "5. camera angles, movements, and transitions used in the video:<|eot_id|>\n\n" + "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>" + "<|start_header_id|>assistant<|end_header_id|>\n\n" +) + +PROMPT_TEMPLATE = { + "dit-llm-encode": { + "template": PROMPT_TEMPLATE_ENCODE, + "crop_start": 36, + }, + "dit-llm-encode-video": { + "template": PROMPT_TEMPLATE_ENCODE_VIDEO, + "crop_start": 95, + }, + "dit-llm-encode-i2v": { + "template": PROMPT_TEMPLATE_ENCODE_I2V, + "crop_start": 36, + "image_emb_start": 5, + "image_emb_end": 581, + "image_emb_len": 576, + "double_return_token_id": 271 + }, + "dit-llm-encode-video-i2v": { + "template": PROMPT_TEMPLATE_ENCODE_VIDEO_I2V, + "crop_start": 103, + "image_emb_start": 5, + "image_emb_end": 581, + "image_emb_len": 576, + "double_return_token_id": 271 + }, +} + +NEGATIVE_PROMPT = "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion" + + +class HunyuanVideoPrompter(BasePrompter): + + def __init__( + self, + tokenizer_1_path=None, + tokenizer_2_path=None, + ): + if tokenizer_1_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_1_path = os.path.join( + base_path, "tokenizer_configs/hunyuan_video/tokenizer_1") + if tokenizer_2_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_2_path = os.path.join( + base_path, "tokenizer_configs/hunyuan_video/tokenizer_2") + super().__init__() + self.tokenizer_1 = CLIPTokenizer.from_pretrained(tokenizer_1_path) + self.tokenizer_2 = LlamaTokenizerFast.from_pretrained(tokenizer_2_path, padding_side='right') + self.text_encoder_1: SD3TextEncoder1 = None + self.text_encoder_2: HunyuanVideoLLMEncoder = None + + self.prompt_template = PROMPT_TEMPLATE['dit-llm-encode'] + self.prompt_template_video = PROMPT_TEMPLATE['dit-llm-encode-video'] + + def fetch_models(self, + text_encoder_1: SD3TextEncoder1 = None, + text_encoder_2: Union[HunyuanVideoLLMEncoder, HunyuanVideoMLLMEncoder] = None): + self.text_encoder_1 = text_encoder_1 + self.text_encoder_2 = text_encoder_2 + if isinstance(text_encoder_2, HunyuanVideoMLLMEncoder): + # processor + # TODO: may need to replace processor with local implementation + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_2_path = os.path.join(base_path, "tokenizer_configs/hunyuan_video/tokenizer_2") + self.processor = CLIPImageProcessor.from_pretrained(tokenizer_2_path) + # template + self.prompt_template = PROMPT_TEMPLATE['dit-llm-encode-i2v'] + self.prompt_template_video = PROMPT_TEMPLATE['dit-llm-encode-video-i2v'] + + def apply_text_to_template(self, text, template): + assert isinstance(template, str) + if isinstance(text, list): + return [self.apply_text_to_template(text_) for text_ in text] + elif isinstance(text, str): + # Will send string to tokenizer. Used for llm + return template.format(text) + else: + raise TypeError(f"Unsupported prompt type: {type(text)}") + + def encode_prompt_using_clip(self, prompt, max_length, device): + tokenized_result = self.tokenizer_1( + prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True, + return_attention_mask=True + ) + input_ids = tokenized_result.input_ids.to(device) + attention_mask = tokenized_result.attention_mask.to(device) + return self.text_encoder_1(input_ids=input_ids, extra_mask=attention_mask)[0] + + def encode_prompt_using_llm(self, + prompt, + max_length, + device, + crop_start, + hidden_state_skip_layer=2, + use_attention_mask=True): + max_length += crop_start + inputs = self.tokenizer_2(prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True) + input_ids = inputs.input_ids.to(device) + attention_mask = inputs.attention_mask.to(device) + last_hidden_state = self.text_encoder_2(input_ids, attention_mask, hidden_state_skip_layer) + + # crop out + if crop_start > 0: + last_hidden_state = last_hidden_state[:, crop_start:] + attention_mask = (attention_mask[:, crop_start:] if use_attention_mask else None) + + return last_hidden_state, attention_mask + + def encode_prompt_using_mllm(self, + prompt, + images, + max_length, + device, + crop_start, + hidden_state_skip_layer=2, + use_attention_mask=True, + image_embed_interleave=4): + image_outputs = self.processor(images, return_tensors="pt")["pixel_values"].to(device) + max_length += crop_start + inputs = self.tokenizer_2(prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True) + input_ids = inputs.input_ids.to(device) + attention_mask = inputs.attention_mask.to(device) + last_hidden_state = self.text_encoder_2(input_ids=input_ids, + attention_mask=attention_mask, + hidden_state_skip_layer=hidden_state_skip_layer, + pixel_values=image_outputs) + + text_crop_start = (crop_start - 1 + self.prompt_template_video.get("image_emb_len", 576)) + image_crop_start = self.prompt_template_video.get("image_emb_start", 5) + image_crop_end = self.prompt_template_video.get("image_emb_end", 581) + batch_indices, last_double_return_token_indices = torch.where( + input_ids == self.prompt_template_video.get("double_return_token_id", 271)) + if last_double_return_token_indices.shape[0] == 3: + # in case the prompt is too long + last_double_return_token_indices = torch.cat(( + last_double_return_token_indices, + torch.tensor([input_ids.shape[-1]]), + )) + batch_indices = torch.cat((batch_indices, torch.tensor([0]))) + last_double_return_token_indices = (last_double_return_token_indices.reshape(input_ids.shape[0], -1)[:, -1]) + batch_indices = batch_indices.reshape(input_ids.shape[0], -1)[:, -1] + assistant_crop_start = (last_double_return_token_indices - 1 + self.prompt_template_video.get("image_emb_len", 576) - 4) + assistant_crop_end = (last_double_return_token_indices - 1 + self.prompt_template_video.get("image_emb_len", 576)) + attention_mask_assistant_crop_start = (last_double_return_token_indices - 4) + attention_mask_assistant_crop_end = last_double_return_token_indices + text_last_hidden_state = [] + text_attention_mask = [] + image_last_hidden_state = [] + image_attention_mask = [] + for i in range(input_ids.shape[0]): + text_last_hidden_state.append( + torch.cat([ + last_hidden_state[i, text_crop_start:assistant_crop_start[i].item()], + last_hidden_state[i, assistant_crop_end[i].item():], + ])) + text_attention_mask.append( + torch.cat([ + attention_mask[ + i, + crop_start:attention_mask_assistant_crop_start[i].item(), + ], + attention_mask[i, attention_mask_assistant_crop_end[i].item():], + ]) if use_attention_mask else None) + image_last_hidden_state.append(last_hidden_state[i, image_crop_start:image_crop_end]) + image_attention_mask.append( + torch.ones(image_last_hidden_state[-1].shape[0]).to(last_hidden_state.device). + to(attention_mask.dtype) if use_attention_mask else None) + + text_last_hidden_state = torch.stack(text_last_hidden_state) + text_attention_mask = torch.stack(text_attention_mask) + image_last_hidden_state = torch.stack(image_last_hidden_state) + image_attention_mask = torch.stack(image_attention_mask) + + image_last_hidden_state = image_last_hidden_state[:, ::image_embed_interleave, :] + image_attention_mask = image_attention_mask[:, ::image_embed_interleave] + + assert (text_last_hidden_state.shape[0] == text_attention_mask.shape[0] and + image_last_hidden_state.shape[0] == image_attention_mask.shape[0]) + + last_hidden_state = torch.cat([image_last_hidden_state, text_last_hidden_state], dim=1) + attention_mask = torch.cat([image_attention_mask, text_attention_mask], dim=1) + + return last_hidden_state, attention_mask + + def encode_prompt(self, + prompt, + images=None, + positive=True, + device="cuda", + clip_sequence_length=77, + llm_sequence_length=256, + data_type='video', + use_template=True, + hidden_state_skip_layer=2, + use_attention_mask=True, + image_embed_interleave=4): + + prompt = self.process_prompt(prompt, positive=positive) + + # apply template + if use_template: + template = self.prompt_template_video if data_type == 'video' else self.prompt_template + prompt_formated = self.apply_text_to_template(prompt, template['template']) + else: + prompt_formated = prompt + # Text encoder + if data_type == 'video': + crop_start = self.prompt_template_video.get("crop_start", 0) + else: + crop_start = self.prompt_template.get("crop_start", 0) + + # CLIP + pooled_prompt_emb = self.encode_prompt_using_clip(prompt, clip_sequence_length, device) + + # LLM + if images is None: + prompt_emb, attention_mask = self.encode_prompt_using_llm(prompt_formated, llm_sequence_length, device, crop_start, + hidden_state_skip_layer, use_attention_mask) + else: + prompt_emb, attention_mask = self.encode_prompt_using_mllm(prompt_formated, images, llm_sequence_length, device, + crop_start, hidden_state_skip_layer, use_attention_mask, + image_embed_interleave) + + return prompt_emb, pooled_prompt_emb, attention_mask diff --git a/diffsynth/prompters/kolors_prompter.py b/diffsynth/prompters/kolors_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d5d58a9dbb816ea8c8e0e3b4f0433bd11d3306 --- /dev/null +++ b/diffsynth/prompters/kolors_prompter.py @@ -0,0 +1,354 @@ +from .base_prompter import BasePrompter +from ..models.model_manager import ModelManager +import json, os, re +from typing import List, Optional, Union, Dict +from sentencepiece import SentencePieceProcessor +from transformers import PreTrainedTokenizer +from transformers.utils import PaddingStrategy +from transformers.tokenization_utils_base import EncodedInput, BatchEncoding +from ..models.kolors_text_encoder import ChatGLMModel + + +class SPTokenizer: + def __init__(self, model_path: str): + # reload tokenizer + assert os.path.isfile(model_path), model_path + self.sp_model = SentencePieceProcessor(model_file=model_path) + + # BOS / EOS token IDs + self.n_words: int = self.sp_model.vocab_size() + self.bos_id: int = self.sp_model.bos_id() + self.eos_id: int = self.sp_model.eos_id() + self.pad_id: int = self.sp_model.unk_id() + assert self.sp_model.vocab_size() == self.sp_model.get_piece_size() + + role_special_tokens = ["<|system|>", "<|user|>", "<|assistant|>", "<|observation|>"] + special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"] + role_special_tokens + self.special_tokens = {} + self.index_special_tokens = {} + for token in special_tokens: + self.special_tokens[token] = self.n_words + self.index_special_tokens[self.n_words] = token + self.n_words += 1 + self.role_special_token_expression = "|".join([re.escape(token) for token in role_special_tokens]) + + def tokenize(self, s: str, encode_special_tokens=False): + if encode_special_tokens: + last_index = 0 + t = [] + for match in re.finditer(self.role_special_token_expression, s): + if last_index < match.start(): + t.extend(self.sp_model.EncodeAsPieces(s[last_index:match.start()])) + t.append(s[match.start():match.end()]) + last_index = match.end() + if last_index < len(s): + t.extend(self.sp_model.EncodeAsPieces(s[last_index:])) + return t + else: + return self.sp_model.EncodeAsPieces(s) + + def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]: + assert type(s) is str + t = self.sp_model.encode(s) + if bos: + t = [self.bos_id] + t + if eos: + t = t + [self.eos_id] + return t + + def decode(self, t: List[int]) -> str: + text, buffer = "", [] + for token in t: + if token in self.index_special_tokens: + if buffer: + text += self.sp_model.decode(buffer) + buffer = [] + text += self.index_special_tokens[token] + else: + buffer.append(token) + if buffer: + text += self.sp_model.decode(buffer) + return text + + def decode_tokens(self, tokens: List[str]) -> str: + text = self.sp_model.DecodePieces(tokens) + return text + + def convert_token_to_id(self, token): + """ Converts a token (str) in an id using the vocab. """ + if token in self.special_tokens: + return self.special_tokens[token] + return self.sp_model.PieceToId(token) + + def convert_id_to_token(self, index): + """Converts an index (integer) in a token (str) using the vocab.""" + if index in self.index_special_tokens: + return self.index_special_tokens[index] + if index in [self.eos_id, self.bos_id, self.pad_id] or index < 0: + return "" + return self.sp_model.IdToPiece(index) + + + +class ChatGLMTokenizer(PreTrainedTokenizer): + vocab_files_names = {"vocab_file": "tokenizer.model"} + + model_input_names = ["input_ids", "attention_mask", "position_ids"] + + def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, encode_special_tokens=False, + **kwargs): + self.name = "GLMTokenizer" + + self.vocab_file = vocab_file + self.tokenizer = SPTokenizer(vocab_file) + self.special_tokens = { + "": self.tokenizer.bos_id, + "": self.tokenizer.eos_id, + "": self.tokenizer.pad_id + } + self.encode_special_tokens = encode_special_tokens + super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, + encode_special_tokens=encode_special_tokens, + **kwargs) + + def get_command(self, token): + if token in self.special_tokens: + return self.special_tokens[token] + assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}" + return self.tokenizer.special_tokens[token] + + @property + def unk_token(self) -> str: + return "" + + @property + def pad_token(self) -> str: + return "" + + @property + def pad_token_id(self): + return self.get_command("") + + @property + def eos_token(self) -> str: + return "" + + @property + def eos_token_id(self): + return self.get_command("") + + @property + def vocab_size(self): + return self.tokenizer.n_words + + def get_vocab(self): + """ Returns vocab as a dict """ + vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)} + vocab.update(self.added_tokens_encoder) + return vocab + + def _tokenize(self, text, **kwargs): + return self.tokenizer.tokenize(text, encode_special_tokens=self.encode_special_tokens) + + def _convert_token_to_id(self, token): + """ Converts a token (str) in an id using the vocab. """ + return self.tokenizer.convert_token_to_id(token) + + def _convert_id_to_token(self, index): + """Converts an index (integer) in a token (str) using the vocab.""" + return self.tokenizer.convert_id_to_token(index) + + def convert_tokens_to_string(self, tokens: List[str]) -> str: + return self.tokenizer.decode_tokens(tokens) + + def save_vocabulary(self, save_directory, filename_prefix=None): + """ + Save the vocabulary and special tokens file to a directory. + + Args: + save_directory (`str`): + The directory in which to save the vocabulary. + filename_prefix (`str`, *optional*): + An optional prefix to add to the named of the saved files. + + Returns: + `Tuple(str)`: Paths to the files saved. + """ + if os.path.isdir(save_directory): + vocab_file = os.path.join( + save_directory, self.vocab_files_names["vocab_file"] + ) + else: + vocab_file = save_directory + + with open(self.vocab_file, 'rb') as fin: + proto_str = fin.read() + + with open(vocab_file, "wb") as writer: + writer.write(proto_str) + + return (vocab_file,) + + def get_prefix_tokens(self): + prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")] + return prefix_tokens + + def build_single_message(self, role, metadata, message): + assert role in ["system", "user", "assistant", "observation"], role + role_tokens = [self.get_command(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n") + message_tokens = self.tokenizer.encode(message) + tokens = role_tokens + message_tokens + return tokens + + def build_chat_input(self, query, history=None, role="user"): + if history is None: + history = [] + input_ids = [] + for item in history: + content = item["content"] + if item["role"] == "system" and "tools" in item: + content = content + "\n" + json.dumps(item["tools"], indent=4, ensure_ascii=False) + input_ids.extend(self.build_single_message(item["role"], item.get("metadata", ""), content)) + input_ids.extend(self.build_single_message(role, "", query)) + input_ids.extend([self.get_command("<|assistant|>")]) + return self.batch_encode_plus([input_ids], return_tensors="pt", is_split_into_words=True) + + def build_inputs_with_special_tokens( + self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None + ) -> List[int]: + """ + Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and + adding special tokens. A BERT sequence has the following format: + + - single sequence: `[CLS] X [SEP]` + - pair of sequences: `[CLS] A [SEP] B [SEP]` + + Args: + token_ids_0 (`List[int]`): + List of IDs to which the special tokens will be added. + token_ids_1 (`List[int]`, *optional*): + Optional second list of IDs for sequence pairs. + + Returns: + `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. + """ + prefix_tokens = self.get_prefix_tokens() + token_ids_0 = prefix_tokens + token_ids_0 + if token_ids_1 is not None: + token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("")] + return token_ids_0 + + def _pad( + self, + encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding], + max_length: Optional[int] = None, + padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, + pad_to_multiple_of: Optional[int] = None, + return_attention_mask: Optional[bool] = None, + padding_side: Optional[str] = None, + ) -> dict: + """ + Pad encoded inputs (on left/right and up to predefined length or max length in the batch) + + Args: + encoded_inputs: + Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`). + max_length: maximum length of the returned list and optionally padding length (see below). + Will truncate by taking into account the special tokens. + padding_strategy: PaddingStrategy to use for padding. + + - PaddingStrategy.LONGEST Pad to the longest sequence in the batch + - PaddingStrategy.MAX_LENGTH: Pad to the max length (default) + - PaddingStrategy.DO_NOT_PAD: Do not pad + The tokenizer padding sides are defined in self.padding_side: + + - 'left': pads on the left of the sequences + - 'right': pads on the right of the sequences + pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value. + This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability + `>= 7.5` (Volta). + return_attention_mask: + (optional) Set to False to avoid returning attention mask (default: set to model specifics) + """ + # Load from model defaults + assert self.padding_side == "left" + + required_input = encoded_inputs[self.model_input_names[0]] + seq_length = len(required_input) + + if padding_strategy == PaddingStrategy.LONGEST: + max_length = len(required_input) + + if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): + max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of + + needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length + + # Initialize attention mask if not present. + if "attention_mask" not in encoded_inputs: + encoded_inputs["attention_mask"] = [1] * seq_length + + if "position_ids" not in encoded_inputs: + encoded_inputs["position_ids"] = list(range(seq_length)) + + if needs_to_be_padded: + difference = max_length - len(required_input) + + if "attention_mask" in encoded_inputs: + encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"] + if "position_ids" in encoded_inputs: + encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"] + encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input + + return encoded_inputs + + + +class KolorsPrompter(BasePrompter): + def __init__( + self, + tokenizer_path=None + ): + if tokenizer_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_path = os.path.join(base_path, "tokenizer_configs/kolors/tokenizer") + super().__init__() + self.tokenizer = ChatGLMTokenizer.from_pretrained(tokenizer_path) + self.text_encoder: ChatGLMModel = None + + + def fetch_models(self, text_encoder: ChatGLMModel = None): + self.text_encoder = text_encoder + + + def encode_prompt_using_ChatGLM(self, prompt, text_encoder, tokenizer, max_length, clip_skip, device): + text_inputs = tokenizer( + prompt, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ).to(device) + output = text_encoder( + input_ids=text_inputs['input_ids'] , + attention_mask=text_inputs['attention_mask'], + position_ids=text_inputs['position_ids'], + output_hidden_states=True + ) + prompt_emb = output.hidden_states[-clip_skip].permute(1, 0, 2).clone() + pooled_prompt_emb = output.hidden_states[-1][-1, :, :].clone() + return prompt_emb, pooled_prompt_emb + + + def encode_prompt( + self, + prompt, + clip_skip=1, + clip_skip_2=2, + positive=True, + device="cuda" + ): + prompt = self.process_prompt(prompt, positive=positive) + prompt_emb, pooled_prompt_emb = self.encode_prompt_using_ChatGLM(prompt, self.text_encoder, self.tokenizer, 256, clip_skip_2, device) + + return pooled_prompt_emb, prompt_emb diff --git a/diffsynth/prompters/omnigen_prompter.py b/diffsynth/prompters/omnigen_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..616efabebb7d327ecf968165dd12341ab8f83894 --- /dev/null +++ b/diffsynth/prompters/omnigen_prompter.py @@ -0,0 +1,356 @@ +import os +import re +from typing import Dict, List + +import torch +from PIL import Image +from torchvision import transforms +from transformers import AutoTokenizer +from huggingface_hub import snapshot_download +import numpy as np + + + +def crop_arr(pil_image, max_image_size): + while min(*pil_image.size) >= 2 * max_image_size: + pil_image = pil_image.resize( + tuple(x // 2 for x in pil_image.size), resample=Image.BOX + ) + + if max(*pil_image.size) > max_image_size: + scale = max_image_size / max(*pil_image.size) + pil_image = pil_image.resize( + tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC + ) + + if min(*pil_image.size) < 16: + scale = 16 / min(*pil_image.size) + pil_image = pil_image.resize( + tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC + ) + + arr = np.array(pil_image) + crop_y1 = (arr.shape[0] % 16) // 2 + crop_y2 = arr.shape[0] % 16 - crop_y1 + + crop_x1 = (arr.shape[1] % 16) // 2 + crop_x2 = arr.shape[1] % 16 - crop_x1 + + arr = arr[crop_y1:arr.shape[0]-crop_y2, crop_x1:arr.shape[1]-crop_x2] + return Image.fromarray(arr) + + + +class OmniGenPrompter: + def __init__(self, + text_tokenizer, + max_image_size: int=1024): + self.text_tokenizer = text_tokenizer + self.max_image_size = max_image_size + + self.image_transform = transforms.Compose([ + transforms.Lambda(lambda pil_image: crop_arr(pil_image, max_image_size)), + transforms.ToTensor(), + transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) + ]) + + self.collator = OmniGenCollator() + self.separate_collator = OmniGenSeparateCollator() + + @classmethod + def from_pretrained(cls, model_name): + if not os.path.exists(model_name): + cache_folder = os.getenv('HF_HUB_CACHE') + model_name = snapshot_download(repo_id=model_name, + cache_dir=cache_folder, + allow_patterns="*.json") + text_tokenizer = AutoTokenizer.from_pretrained(model_name) + + return cls(text_tokenizer) + + + def process_image(self, image): + return self.image_transform(image) + + def process_multi_modal_prompt(self, text, input_images): + text = self.add_prefix_instruction(text) + if input_images is None or len(input_images) == 0: + model_inputs = self.text_tokenizer(text) + return {"input_ids": model_inputs.input_ids, "pixel_values": None, "image_sizes": None} + + pattern = r"<\|image_\d+\|>" + prompt_chunks = [self.text_tokenizer(chunk).input_ids for chunk in re.split(pattern, text)] + + for i in range(1, len(prompt_chunks)): + if prompt_chunks[i][0] == 1: + prompt_chunks[i] = prompt_chunks[i][1:] + + image_tags = re.findall(pattern, text) + image_ids = [int(s.split("|")[1].split("_")[-1]) for s in image_tags] + + unique_image_ids = sorted(list(set(image_ids))) + assert unique_image_ids == list(range(1, len(unique_image_ids)+1)), f"image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be {unique_image_ids}" + # total images must be the same as the number of image tags + assert len(unique_image_ids) == len(input_images), f"total images must be the same as the number of image tags, got {len(unique_image_ids)} image tags and {len(input_images)} images" + + input_images = [input_images[x-1] for x in image_ids] + + all_input_ids = [] + img_inx = [] + idx = 0 + for i in range(len(prompt_chunks)): + all_input_ids.extend(prompt_chunks[i]) + if i != len(prompt_chunks) -1: + start_inx = len(all_input_ids) + size = input_images[i].size(-2) * input_images[i].size(-1) // 16 // 16 + img_inx.append([start_inx, start_inx+size]) + all_input_ids.extend([0]*size) + + return {"input_ids": all_input_ids, "pixel_values": input_images, "image_sizes": img_inx} + + + def add_prefix_instruction(self, prompt): + user_prompt = '<|user|>\n' + generation_prompt = 'Generate an image according to the following instructions\n' + assistant_prompt = '<|assistant|>\n<|diffusion|>' + prompt_suffix = "<|end|>\n" + prompt = f"{user_prompt}{generation_prompt}{prompt}{prompt_suffix}{assistant_prompt}" + return prompt + + + def __call__(self, + instructions: List[str], + input_images: List[List[str]] = None, + height: int = 1024, + width: int = 1024, + negative_prompt: str = "low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers.", + use_img_cfg: bool = True, + separate_cfg_input: bool = False, + use_input_image_size_as_output: bool=False, + ) -> Dict: + + if input_images is None: + use_img_cfg = False + if isinstance(instructions, str): + instructions = [instructions] + input_images = [input_images] + + input_data = [] + for i in range(len(instructions)): + cur_instruction = instructions[i] + cur_input_images = None if input_images is None else input_images[i] + if cur_input_images is not None and len(cur_input_images) > 0: + cur_input_images = [self.process_image(x) for x in cur_input_images] + else: + cur_input_images = None + assert "<|image_1|>" not in cur_instruction + + mllm_input = self.process_multi_modal_prompt(cur_instruction, cur_input_images) + + + neg_mllm_input, img_cfg_mllm_input = None, None + neg_mllm_input = self.process_multi_modal_prompt(negative_prompt, None) + if use_img_cfg: + if cur_input_images is not None and len(cur_input_images) >= 1: + img_cfg_prompt = [f"<|image_{i+1}|>" for i in range(len(cur_input_images))] + img_cfg_mllm_input = self.process_multi_modal_prompt(" ".join(img_cfg_prompt), cur_input_images) + else: + img_cfg_mllm_input = neg_mllm_input + + if use_input_image_size_as_output: + input_data.append((mllm_input, neg_mllm_input, img_cfg_mllm_input, [mllm_input['pixel_values'][0].size(-2), mllm_input['pixel_values'][0].size(-1)])) + else: + input_data.append((mllm_input, neg_mllm_input, img_cfg_mllm_input, [height, width])) + + if separate_cfg_input: + return self.separate_collator(input_data) + return self.collator(input_data) + + + + +class OmniGenCollator: + def __init__(self, pad_token_id=2, hidden_size=3072): + self.pad_token_id = pad_token_id + self.hidden_size = hidden_size + + def create_position(self, attention_mask, num_tokens_for_output_images): + position_ids = [] + text_length = attention_mask.size(-1) + img_length = max(num_tokens_for_output_images) + for mask in attention_mask: + temp_l = torch.sum(mask) + temp_position = [0]*(text_length-temp_l) + [i for i in range(temp_l+img_length+1)] # we add a time embedding into the sequence, so add one more token + position_ids.append(temp_position) + return torch.LongTensor(position_ids) + + def create_mask(self, attention_mask, num_tokens_for_output_images): + extended_mask = [] + padding_images = [] + text_length = attention_mask.size(-1) + img_length = max(num_tokens_for_output_images) + seq_len = text_length + img_length + 1 # we add a time embedding into the sequence, so add one more token + inx = 0 + for mask in attention_mask: + temp_l = torch.sum(mask) + pad_l = text_length - temp_l + + temp_mask = torch.tril(torch.ones(size=(temp_l+1, temp_l+1))) + + image_mask = torch.zeros(size=(temp_l+1, img_length)) + temp_mask = torch.cat([temp_mask, image_mask], dim=-1) + + image_mask = torch.ones(size=(img_length, temp_l+img_length+1)) + temp_mask = torch.cat([temp_mask, image_mask], dim=0) + + if pad_l > 0: + pad_mask = torch.zeros(size=(temp_l+1+img_length, pad_l)) + temp_mask = torch.cat([pad_mask, temp_mask], dim=-1) + + pad_mask = torch.ones(size=(pad_l, seq_len)) + temp_mask = torch.cat([pad_mask, temp_mask], dim=0) + + true_img_length = num_tokens_for_output_images[inx] + pad_img_length = img_length - true_img_length + if pad_img_length > 0: + temp_mask[:, -pad_img_length:] = 0 + temp_padding_imgs = torch.zeros(size=(1, pad_img_length, self.hidden_size)) + else: + temp_padding_imgs = None + + extended_mask.append(temp_mask.unsqueeze(0)) + padding_images.append(temp_padding_imgs) + inx += 1 + return torch.cat(extended_mask, dim=0), padding_images + + def adjust_attention_for_input_images(self, attention_mask, image_sizes): + for b_inx in image_sizes.keys(): + for start_inx, end_inx in image_sizes[b_inx]: + attention_mask[b_inx][start_inx:end_inx, start_inx:end_inx] = 1 + + return attention_mask + + def pad_input_ids(self, input_ids, image_sizes): + max_l = max([len(x) for x in input_ids]) + padded_ids = [] + attention_mask = [] + new_image_sizes = [] + + for i in range(len(input_ids)): + temp_ids = input_ids[i] + temp_l = len(temp_ids) + pad_l = max_l - temp_l + if pad_l == 0: + attention_mask.append([1]*max_l) + padded_ids.append(temp_ids) + else: + attention_mask.append([0]*pad_l+[1]*temp_l) + padded_ids.append([self.pad_token_id]*pad_l+temp_ids) + + if i in image_sizes: + new_inx = [] + for old_inx in image_sizes[i]: + new_inx.append([x+pad_l for x in old_inx]) + image_sizes[i] = new_inx + + return torch.LongTensor(padded_ids), torch.LongTensor(attention_mask), image_sizes + + + def process_mllm_input(self, mllm_inputs, target_img_size): + num_tokens_for_output_images = [] + for img_size in target_img_size: + num_tokens_for_output_images.append(img_size[0]*img_size[1]//16//16) + + pixel_values, image_sizes = [], {} + b_inx = 0 + for x in mllm_inputs: + if x['pixel_values'] is not None: + pixel_values.extend(x['pixel_values']) + for size in x['image_sizes']: + if b_inx not in image_sizes: + image_sizes[b_inx] = [size] + else: + image_sizes[b_inx].append(size) + b_inx += 1 + pixel_values = [x.unsqueeze(0) for x in pixel_values] + + + input_ids = [x['input_ids'] for x in mllm_inputs] + padded_input_ids, attention_mask, image_sizes = self.pad_input_ids(input_ids, image_sizes) + position_ids = self.create_position(attention_mask, num_tokens_for_output_images) + attention_mask, padding_images = self.create_mask(attention_mask, num_tokens_for_output_images) + attention_mask = self.adjust_attention_for_input_images(attention_mask, image_sizes) + + return padded_input_ids, position_ids, attention_mask, padding_images, pixel_values, image_sizes + + + def __call__(self, features): + mllm_inputs = [f[0] for f in features] + cfg_mllm_inputs = [f[1] for f in features] + img_cfg_mllm_input = [f[2] for f in features] + target_img_size = [f[3] for f in features] + + + if img_cfg_mllm_input[0] is not None: + mllm_inputs = mllm_inputs + cfg_mllm_inputs + img_cfg_mllm_input + target_img_size = target_img_size + target_img_size + target_img_size + else: + mllm_inputs = mllm_inputs + cfg_mllm_inputs + target_img_size = target_img_size + target_img_size + + + all_padded_input_ids, all_position_ids, all_attention_mask, all_padding_images, all_pixel_values, all_image_sizes = self.process_mllm_input(mllm_inputs, target_img_size) + + data = {"input_ids": all_padded_input_ids, + "attention_mask": all_attention_mask, + "position_ids": all_position_ids, + "input_pixel_values": all_pixel_values, + "input_image_sizes": all_image_sizes, + "padding_images": all_padding_images, + } + return data + + +class OmniGenSeparateCollator(OmniGenCollator): + def __call__(self, features): + mllm_inputs = [f[0] for f in features] + cfg_mllm_inputs = [f[1] for f in features] + img_cfg_mllm_input = [f[2] for f in features] + target_img_size = [f[3] for f in features] + + all_padded_input_ids, all_attention_mask, all_position_ids, all_pixel_values, all_image_sizes, all_padding_images = [], [], [], [], [], [] + + + padded_input_ids, position_ids, attention_mask, padding_images, pixel_values, image_sizes = self.process_mllm_input(mllm_inputs, target_img_size) + all_padded_input_ids.append(padded_input_ids) + all_attention_mask.append(attention_mask) + all_position_ids.append(position_ids) + all_pixel_values.append(pixel_values) + all_image_sizes.append(image_sizes) + all_padding_images.append(padding_images) + + if cfg_mllm_inputs[0] is not None: + padded_input_ids, position_ids, attention_mask, padding_images, pixel_values, image_sizes = self.process_mllm_input(cfg_mllm_inputs, target_img_size) + all_padded_input_ids.append(padded_input_ids) + all_attention_mask.append(attention_mask) + all_position_ids.append(position_ids) + all_pixel_values.append(pixel_values) + all_image_sizes.append(image_sizes) + all_padding_images.append(padding_images) + if img_cfg_mllm_input[0] is not None: + padded_input_ids, position_ids, attention_mask, padding_images, pixel_values, image_sizes = self.process_mllm_input(img_cfg_mllm_input, target_img_size) + all_padded_input_ids.append(padded_input_ids) + all_attention_mask.append(attention_mask) + all_position_ids.append(position_ids) + all_pixel_values.append(pixel_values) + all_image_sizes.append(image_sizes) + all_padding_images.append(padding_images) + + data = {"input_ids": all_padded_input_ids, + "attention_mask": all_attention_mask, + "position_ids": all_position_ids, + "input_pixel_values": all_pixel_values, + "input_image_sizes": all_image_sizes, + "padding_images": all_padding_images, + } + return data diff --git a/diffsynth/prompters/omost.py b/diffsynth/prompters/omost.py new file mode 100644 index 0000000000000000000000000000000000000000..81828ad79978103eea42389d439847c0877cbd85 --- /dev/null +++ b/diffsynth/prompters/omost.py @@ -0,0 +1,323 @@ +from transformers import AutoTokenizer, TextIteratorStreamer +import difflib +import torch +import numpy as np +import re +from ..models.model_manager import ModelManager +from PIL import Image + +valid_colors = { # r, g, b + 'aliceblue': (240, 248, 255), 'antiquewhite': (250, 235, 215), 'aqua': (0, 255, 255), + 'aquamarine': (127, 255, 212), 'azure': (240, 255, 255), 'beige': (245, 245, 220), + 'bisque': (255, 228, 196), 'black': (0, 0, 0), 'blanchedalmond': (255, 235, 205), 'blue': (0, 0, 255), + 'blueviolet': (138, 43, 226), 'brown': (165, 42, 42), 'burlywood': (222, 184, 135), + 'cadetblue': (95, 158, 160), 'chartreuse': (127, 255, 0), 'chocolate': (210, 105, 30), + 'coral': (255, 127, 80), 'cornflowerblue': (100, 149, 237), 'cornsilk': (255, 248, 220), + 'crimson': (220, 20, 60), 'cyan': (0, 255, 255), 'darkblue': (0, 0, 139), 'darkcyan': (0, 139, 139), + 'darkgoldenrod': (184, 134, 11), 'darkgray': (169, 169, 169), 'darkgrey': (169, 169, 169), + 'darkgreen': (0, 100, 0), 'darkkhaki': (189, 183, 107), 'darkmagenta': (139, 0, 139), + 'darkolivegreen': (85, 107, 47), 'darkorange': (255, 140, 0), 'darkorchid': (153, 50, 204), + 'darkred': (139, 0, 0), 'darksalmon': (233, 150, 122), 'darkseagreen': (143, 188, 143), + 'darkslateblue': (72, 61, 139), 'darkslategray': (47, 79, 79), 'darkslategrey': (47, 79, 79), + 'darkturquoise': (0, 206, 209), 'darkviolet': (148, 0, 211), 'deeppink': (255, 20, 147), + 'deepskyblue': (0, 191, 255), 'dimgray': (105, 105, 105), 'dimgrey': (105, 105, 105), + 'dodgerblue': (30, 144, 255), 'firebrick': (178, 34, 34), 'floralwhite': (255, 250, 240), + 'forestgreen': (34, 139, 34), 'fuchsia': (255, 0, 255), 'gainsboro': (220, 220, 220), + 'ghostwhite': (248, 248, 255), 'gold': (255, 215, 0), 'goldenrod': (218, 165, 32), + 'gray': (128, 128, 128), 'grey': (128, 128, 128), 'green': (0, 128, 0), 'greenyellow': (173, 255, 47), + 'honeydew': (240, 255, 240), 'hotpink': (255, 105, 180), 'indianred': (205, 92, 92), + 'indigo': (75, 0, 130), 'ivory': (255, 255, 240), 'khaki': (240, 230, 140), 'lavender': (230, 230, 250), + 'lavenderblush': (255, 240, 245), 'lawngreen': (124, 252, 0), 'lemonchiffon': (255, 250, 205), + 'lightblue': (173, 216, 230), 'lightcoral': (240, 128, 128), 'lightcyan': (224, 255, 255), + 'lightgoldenrodyellow': (250, 250, 210), 'lightgray': (211, 211, 211), 'lightgrey': (211, 211, 211), + 'lightgreen': (144, 238, 144), 'lightpink': (255, 182, 193), 'lightsalmon': (255, 160, 122), + 'lightseagreen': (32, 178, 170), 'lightskyblue': (135, 206, 250), 'lightslategray': (119, 136, 153), + 'lightslategrey': (119, 136, 153), 'lightsteelblue': (176, 196, 222), 'lightyellow': (255, 255, 224), + 'lime': (0, 255, 0), 'limegreen': (50, 205, 50), 'linen': (250, 240, 230), 'magenta': (255, 0, 255), + 'maroon': (128, 0, 0), 'mediumaquamarine': (102, 205, 170), 'mediumblue': (0, 0, 205), + 'mediumorchid': (186, 85, 211), 'mediumpurple': (147, 112, 219), 'mediumseagreen': (60, 179, 113), + 'mediumslateblue': (123, 104, 238), 'mediumspringgreen': (0, 250, 154), + 'mediumturquoise': (72, 209, 204), 'mediumvioletred': (199, 21, 133), 'midnightblue': (25, 25, 112), + 'mintcream': (245, 255, 250), 'mistyrose': (255, 228, 225), 'moccasin': (255, 228, 181), + 'navajowhite': (255, 222, 173), 'navy': (0, 0, 128), 'navyblue': (0, 0, 128), + 'oldlace': (253, 245, 230), 'olive': (128, 128, 0), 'olivedrab': (107, 142, 35), + 'orange': (255, 165, 0), 'orangered': (255, 69, 0), 'orchid': (218, 112, 214), + 'palegoldenrod': (238, 232, 170), 'palegreen': (152, 251, 152), 'paleturquoise': (175, 238, 238), + 'palevioletred': (219, 112, 147), 'papayawhip': (255, 239, 213), 'peachpuff': (255, 218, 185), + 'peru': (205, 133, 63), 'pink': (255, 192, 203), 'plum': (221, 160, 221), 'powderblue': (176, 224, 230), + 'purple': (128, 0, 128), 'rebeccapurple': (102, 51, 153), 'red': (255, 0, 0), + 'rosybrown': (188, 143, 143), 'royalblue': (65, 105, 225), 'saddlebrown': (139, 69, 19), + 'salmon': (250, 128, 114), 'sandybrown': (244, 164, 96), 'seagreen': (46, 139, 87), + 'seashell': (255, 245, 238), 'sienna': (160, 82, 45), 'silver': (192, 192, 192), + 'skyblue': (135, 206, 235), 'slateblue': (106, 90, 205), 'slategray': (112, 128, 144), + 'slategrey': (112, 128, 144), 'snow': (255, 250, 250), 'springgreen': (0, 255, 127), + 'steelblue': (70, 130, 180), 'tan': (210, 180, 140), 'teal': (0, 128, 128), 'thistle': (216, 191, 216), + 'tomato': (255, 99, 71), 'turquoise': (64, 224, 208), 'violet': (238, 130, 238), + 'wheat': (245, 222, 179), 'white': (255, 255, 255), 'whitesmoke': (245, 245, 245), + 'yellow': (255, 255, 0), 'yellowgreen': (154, 205, 50) +} + +valid_locations = { # x, y in 90*90 + 'in the center': (45, 45), + 'on the left': (15, 45), + 'on the right': (75, 45), + 'on the top': (45, 15), + 'on the bottom': (45, 75), + 'on the top-left': (15, 15), + 'on the top-right': (75, 15), + 'on the bottom-left': (15, 75), + 'on the bottom-right': (75, 75) +} + +valid_offsets = { # x, y in 90*90 + 'no offset': (0, 0), + 'slightly to the left': (-10, 0), + 'slightly to the right': (10, 0), + 'slightly to the upper': (0, -10), + 'slightly to the lower': (0, 10), + 'slightly to the upper-left': (-10, -10), + 'slightly to the upper-right': (10, -10), + 'slightly to the lower-left': (-10, 10), + 'slightly to the lower-right': (10, 10)} + +valid_areas = { # w, h in 90*90 + "a small square area": (50, 50), + "a small vertical area": (40, 60), + "a small horizontal area": (60, 40), + "a medium-sized square area": (60, 60), + "a medium-sized vertical area": (50, 80), + "a medium-sized horizontal area": (80, 50), + "a large square area": (70, 70), + "a large vertical area": (60, 90), + "a large horizontal area": (90, 60) +} + +def safe_str(x): + return x.strip(',. ') + '.' + +def closest_name(input_str, options): + input_str = input_str.lower() + + closest_match = difflib.get_close_matches(input_str, list(options.keys()), n=1, cutoff=0.5) + assert isinstance(closest_match, list) and len(closest_match) > 0, f'The value [{input_str}] is not valid!' + result = closest_match[0] + + if result != input_str: + print(f'Automatically corrected [{input_str}] -> [{result}].') + + return result + +class Canvas: + @staticmethod + def from_bot_response(response: str): + + matched = re.search(r'```python\n(.*?)\n```', response, re.DOTALL) + assert matched, 'Response does not contain codes!' + code_content = matched.group(1) + assert 'canvas = Canvas()' in code_content, 'Code block must include valid canvas var!' + local_vars = {'Canvas': Canvas} + exec(code_content, {}, local_vars) + canvas = local_vars.get('canvas', None) + assert isinstance(canvas, Canvas), 'Code block must produce valid canvas var!' + return canvas + + def __init__(self): + self.components = [] + self.color = None + self.record_tags = True + self.prefixes = [] + self.suffixes = [] + return + + def set_global_description(self, description: str, detailed_descriptions: list, tags: str, + HTML_web_color_name: str): + assert isinstance(description, str), 'Global description is not valid!' + assert isinstance(detailed_descriptions, list) and all(isinstance(item, str) for item in detailed_descriptions), \ + 'Global detailed_descriptions is not valid!' + assert isinstance(tags, str), 'Global tags is not valid!' + + HTML_web_color_name = closest_name(HTML_web_color_name, valid_colors) + self.color = np.array([[valid_colors[HTML_web_color_name]]], dtype=np.uint8) + + self.prefixes = [description] + self.suffixes = detailed_descriptions + + if self.record_tags: + self.suffixes = self.suffixes + [tags] + + self.prefixes = [safe_str(x) for x in self.prefixes] + self.suffixes = [safe_str(x) for x in self.suffixes] + + return + + def add_local_description(self, location: str, offset: str, area: str, distance_to_viewer: float, description: str, + detailed_descriptions: list, tags: str, atmosphere: str, style: str, + quality_meta: str, HTML_web_color_name: str): + assert isinstance(description, str), 'Local description is wrong!' + assert isinstance(distance_to_viewer, (int, float)) and distance_to_viewer > 0, \ + f'The distance_to_viewer for [{description}] is not positive float number!' + assert isinstance(detailed_descriptions, list) and all(isinstance(item, str) for item in detailed_descriptions), \ + f'The detailed_descriptions for [{description}] is not valid!' + assert isinstance(tags, str), f'The tags for [{description}] is not valid!' + assert isinstance(atmosphere, str), f'The atmosphere for [{description}] is not valid!' + assert isinstance(style, str), f'The style for [{description}] is not valid!' + assert isinstance(quality_meta, str), f'The quality_meta for [{description}] is not valid!' + + location = closest_name(location, valid_locations) + offset = closest_name(offset, valid_offsets) + area = closest_name(area, valid_areas) + HTML_web_color_name = closest_name(HTML_web_color_name, valid_colors) + + xb, yb = valid_locations[location] + xo, yo = valid_offsets[offset] + w, h = valid_areas[area] + rect = (yb + yo - h // 2, yb + yo + h // 2, xb + xo - w // 2, xb + xo + w // 2) + rect = [max(0, min(90, i)) for i in rect] + color = np.array([[valid_colors[HTML_web_color_name]]], dtype=np.uint8) + + prefixes = self.prefixes + [description] + suffixes = detailed_descriptions + + if self.record_tags: + suffixes = suffixes + [tags, atmosphere, style, quality_meta] + + prefixes = [safe_str(x) for x in prefixes] + suffixes = [safe_str(x) for x in suffixes] + + self.components.append(dict( + rect=rect, + distance_to_viewer=distance_to_viewer, + color=color, + prefixes=prefixes, + suffixes=suffixes, + location=location, + )) + + return + + def process(self): + # sort components + self.components = sorted(self.components, key=lambda x: x['distance_to_viewer'], reverse=True) + + # compute initial latent + # print(self.color) + initial_latent = np.zeros(shape=(90, 90, 3), dtype=np.float32) + self.color + + for component in self.components: + a, b, c, d = component['rect'] + initial_latent[a:b, c:d] = 0.7 * component['color'] + 0.3 * initial_latent[a:b, c:d] + + initial_latent = initial_latent.clip(0, 255).astype(np.uint8) + + # compute conditions + + bag_of_conditions = [ + dict(mask=np.ones(shape=(90, 90), dtype=np.float32), prefixes=self.prefixes, suffixes=self.suffixes,location= "full") + ] + + for i, component in enumerate(self.components): + a, b, c, d = component['rect'] + m = np.zeros(shape=(90, 90), dtype=np.float32) + m[a:b, c:d] = 1.0 + bag_of_conditions.append(dict( + mask = m, + prefixes = component['prefixes'], + suffixes = component['suffixes'], + location = component['location'], + )) + + return dict( + initial_latent = initial_latent, + bag_of_conditions = bag_of_conditions, + ) + + +class OmostPromter(torch.nn.Module): + + def __init__(self,model = None,tokenizer = None, template = "",device="cpu"): + super().__init__() + self.model=model + self.tokenizer = tokenizer + self.device = device + if template == "": + template = r'''You are a helpful AI assistant to compose images using the below python class `Canvas`: + ```python + class Canvas: + def set_global_description(self, description: str, detailed_descriptions: list[str], tags: str, HTML_web_color_name: str): + pass + + def add_local_description(self, location: str, offset: str, area: str, distance_to_viewer: float, description: str, detailed_descriptions: list[str], tags: str, atmosphere: str, style: str, quality_meta: str, HTML_web_color_name: str): + assert location in ["in the center", "on the left", "on the right", "on the top", "on the bottom", "on the top-left", "on the top-right", "on the bottom-left", "on the bottom-right"] + assert offset in ["no offset", "slightly to the left", "slightly to the right", "slightly to the upper", "slightly to the lower", "slightly to the upper-left", "slightly to the upper-right", "slightly to the lower-left", "slightly to the lower-right"] + assert area in ["a small square area", "a small vertical area", "a small horizontal area", "a medium-sized square area", "a medium-sized vertical area", "a medium-sized horizontal area", "a large square area", "a large vertical area", "a large horizontal area"] + assert distance_to_viewer > 0 + pass + ```''' + self.template = template + + @staticmethod + def from_model_manager(model_manager: ModelManager): + model, model_path = model_manager.fetch_model("omost_prompt", require_model_path=True) + tokenizer = AutoTokenizer.from_pretrained(model_path) + omost = OmostPromter( + model= model, + tokenizer = tokenizer, + device = model_manager.device + ) + return omost + + + def __call__(self,prompt_dict:dict): + raw_prompt=prompt_dict["prompt"] + conversation = [{"role": "system", "content": self.template}] + conversation.append({"role": "user", "content": raw_prompt}) + + input_ids = self.tokenizer.apply_chat_template(conversation, return_tensors="pt", add_generation_prompt=True).to(self.device) + streamer = TextIteratorStreamer(self.tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True) + attention_mask = torch.ones(input_ids.shape, dtype=torch.bfloat16, device=self.device) + + generate_kwargs = dict( + input_ids = input_ids, + streamer = streamer, + # stopping_criteria=stopping_criteria, + # max_new_tokens=max_new_tokens, + do_sample = True, + attention_mask = attention_mask, + pad_token_id = self.tokenizer.eos_token_id, + # temperature=temperature, + # top_p=top_p, + ) + self.model.generate(**generate_kwargs) + outputs = [] + for text in streamer: + outputs.append(text) + llm_outputs = "".join(outputs) + + canvas = Canvas.from_bot_response(llm_outputs) + canvas_output = canvas.process() + + prompts = [" ".join(_["prefixes"]+_["suffixes"][:2]) for _ in canvas_output["bag_of_conditions"]] + canvas_output["prompt"] = prompts[0] + canvas_output["prompts"] = prompts[1:] + + raw_masks = [_["mask"] for _ in canvas_output["bag_of_conditions"]] + masks=[] + for mask in raw_masks: + mask[mask>0.5]=255 + mask = np.stack([mask] * 3, axis=-1).astype("uint8") + masks.append(Image.fromarray(mask)) + + canvas_output["masks"] = masks + prompt_dict.update(canvas_output) + print(f"Your prompt is extended by Omost:\n") + cnt = 0 + for component,pmt in zip(canvas_output["bag_of_conditions"],prompts): + loc = component["location"] + cnt += 1 + print(f"Component {cnt} - Location : {loc}\nPrompt:{pmt}\n") + + return prompt_dict + + + + \ No newline at end of file diff --git a/diffsynth/prompters/prompt_refiners.py b/diffsynth/prompters/prompt_refiners.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac19f565b076cccb21d9e05149b604e4bb55854 --- /dev/null +++ b/diffsynth/prompters/prompt_refiners.py @@ -0,0 +1,130 @@ +from transformers import AutoTokenizer +from ..models.model_manager import ModelManager +import torch +from .omost import OmostPromter + +class BeautifulPrompt(torch.nn.Module): + def __init__(self, tokenizer_path=None, model=None, template=""): + super().__init__() + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) + self.model = model + self.template = template + + + @staticmethod + def from_model_manager(model_manager: ModelManager): + model, model_path = model_manager.fetch_model("beautiful_prompt", require_model_path=True) + template = 'Instruction: Give a simple description of the image to generate a drawing prompt.\nInput: {raw_prompt}\nOutput:' + if model_path.endswith("v2"): + template = """Converts a simple image description into a prompt. \ +Prompts are formatted as multiple related tags separated by commas, plus you can use () to increase the weight, [] to decrease the weight, \ +or use a number to specify the weight. You should add appropriate words to make the images described in the prompt more aesthetically pleasing, \ +but make sure there is a correlation between the input and output.\n\ +### Input: {raw_prompt}\n### Output:""" + beautiful_prompt = BeautifulPrompt( + tokenizer_path=model_path, + model=model, + template=template + ) + return beautiful_prompt + + + def __call__(self, raw_prompt, positive=True, **kwargs): + if positive: + model_input = self.template.format(raw_prompt=raw_prompt) + input_ids = self.tokenizer.encode(model_input, return_tensors='pt').to(self.model.device) + outputs = self.model.generate( + input_ids, + max_new_tokens=384, + do_sample=True, + temperature=0.9, + top_k=50, + top_p=0.95, + repetition_penalty=1.1, + num_return_sequences=1 + ) + prompt = raw_prompt + ", " + self.tokenizer.batch_decode( + outputs[:, input_ids.size(1):], + skip_special_tokens=True + )[0].strip() + print(f"Your prompt is refined by BeautifulPrompt: {prompt}") + return prompt + else: + return raw_prompt + + + +class QwenPrompt(torch.nn.Module): + # This class leverages the open-source Qwen model to translate Chinese prompts into English, + # with an integrated optimization mechanism for enhanced translation quality. + def __init__(self, tokenizer_path=None, model=None, system_prompt=""): + super().__init__() + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) + self.model = model + self.system_prompt = system_prompt + + + @staticmethod + def from_model_manager(model_nameger: ModelManager): + model, model_path = model_nameger.fetch_model("qwen_prompt", require_model_path=True) + system_prompt = """You are an English image describer. Here are some example image styles:\n\n1. Extreme close-up: Clear focus on a single object with a blurred background, highlighted under natural sunlight.\n2. Vintage: A photograph of a historical scene, using techniques such as Daguerreotype or cyanotype.\n3. Anime: A stylized cartoon image, emphasizing hyper-realistic portraits and luminous brushwork.\n4. Candid: A natural, unposed shot capturing spontaneous moments, often with cinematic qualities.\n5. Landscape: A photorealistic image of natural scenery, such as a sunrise over the sea.\n6. Design: Colorful and detailed illustrations, often in the style of 2D game art or botanical illustrations.\n7. Urban: An ultrarealistic scene in a modern setting, possibly a cityscape viewed from indoors.\n\nYour task is to translate a given Chinese image description into a concise and precise English description. Ensure that the imagery is vivid and descriptive, and include stylistic elements to enrich the description.\nPlease note the following points:\n\n1. Capture the essence and mood of the Chinese description without including direct phrases or words from the examples provided.\n2. You should add appropriate words to make the images described in the prompt more aesthetically pleasing. If the Chinese description does not specify a style, you need to add some stylistic descriptions based on the essence of the Chinese text.\n3. The generated English description should not exceed 200 words.\n\n""" + qwen_prompt = QwenPrompt( + tokenizer_path=model_path, + model=model, + system_prompt=system_prompt + ) + return qwen_prompt + + + def __call__(self, raw_prompt, positive=True, **kwargs): + if positive: + messages = [{ + 'role': 'system', + 'content': self.system_prompt + }, { + 'role': 'user', + 'content': raw_prompt + }] + text = self.tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + model_inputs = self.tokenizer([text], return_tensors="pt").to(self.model.device) + + generated_ids = self.model.generate( + model_inputs.input_ids, + max_new_tokens=512 + ) + generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) + ] + + prompt = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] + print(f"Your prompt is refined by Qwen: {prompt}") + return prompt + else: + return raw_prompt + + + +class Translator(torch.nn.Module): + def __init__(self, tokenizer_path=None, model=None): + super().__init__() + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) + self.model = model + + + @staticmethod + def from_model_manager(model_manager: ModelManager): + model, model_path = model_manager.fetch_model("translator", require_model_path=True) + translator = Translator(tokenizer_path=model_path, model=model) + return translator + + + def __call__(self, prompt, **kwargs): + input_ids = self.tokenizer.encode(prompt, return_tensors='pt').to(self.model.device) + output_ids = self.model.generate(input_ids) + prompt = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0] + print(f"Your prompt is translated: {prompt}") + return prompt diff --git a/diffsynth/prompters/sd3_prompter.py b/diffsynth/prompters/sd3_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..ecf9bca30ae53e78822d06d769a65a6c79e8b5d8 --- /dev/null +++ b/diffsynth/prompters/sd3_prompter.py @@ -0,0 +1,93 @@ +from .base_prompter import BasePrompter +from ..models.model_manager import ModelManager +from ..models import SD3TextEncoder1, SD3TextEncoder2, SD3TextEncoder3 +from transformers import CLIPTokenizer, T5TokenizerFast +import os, torch + + +class SD3Prompter(BasePrompter): + def __init__( + self, + tokenizer_1_path=None, + tokenizer_2_path=None, + tokenizer_3_path=None + ): + if tokenizer_1_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_1_path = os.path.join(base_path, "tokenizer_configs/stable_diffusion_3/tokenizer_1") + if tokenizer_2_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_2_path = os.path.join(base_path, "tokenizer_configs/stable_diffusion_3/tokenizer_2") + if tokenizer_3_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_3_path = os.path.join(base_path, "tokenizer_configs/stable_diffusion_3/tokenizer_3") + super().__init__() + self.tokenizer_1 = CLIPTokenizer.from_pretrained(tokenizer_1_path) + self.tokenizer_2 = CLIPTokenizer.from_pretrained(tokenizer_2_path) + self.tokenizer_3 = T5TokenizerFast.from_pretrained(tokenizer_3_path) + self.text_encoder_1: SD3TextEncoder1 = None + self.text_encoder_2: SD3TextEncoder2 = None + self.text_encoder_3: SD3TextEncoder3 = None + + + def fetch_models(self, text_encoder_1: SD3TextEncoder1 = None, text_encoder_2: SD3TextEncoder2 = None, text_encoder_3: SD3TextEncoder3 = None): + self.text_encoder_1 = text_encoder_1 + self.text_encoder_2 = text_encoder_2 + self.text_encoder_3 = text_encoder_3 + + + def encode_prompt_using_clip(self, prompt, text_encoder, tokenizer, max_length, device): + input_ids = tokenizer( + prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True + ).input_ids.to(device) + pooled_prompt_emb, prompt_emb = text_encoder(input_ids) + return pooled_prompt_emb, prompt_emb + + + def encode_prompt_using_t5(self, prompt, text_encoder, tokenizer, max_length, device): + input_ids = tokenizer( + prompt, + return_tensors="pt", + padding="max_length", + max_length=max_length, + truncation=True, + add_special_tokens=True, + ).input_ids.to(device) + prompt_emb = text_encoder(input_ids) + prompt_emb = prompt_emb.reshape((1, prompt_emb.shape[0]*prompt_emb.shape[1], -1)) + + return prompt_emb + + + def encode_prompt( + self, + prompt, + positive=True, + device="cuda", + t5_sequence_length=77, + ): + prompt = self.process_prompt(prompt, positive=positive) + + # CLIP + pooled_prompt_emb_1, prompt_emb_1 = self.encode_prompt_using_clip(prompt, self.text_encoder_1, self.tokenizer_1, 77, device) + pooled_prompt_emb_2, prompt_emb_2 = self.encode_prompt_using_clip(prompt, self.text_encoder_2, self.tokenizer_2, 77, device) + + # T5 + if self.text_encoder_3 is None: + prompt_emb_3 = torch.zeros((prompt_emb_1.shape[0], t5_sequence_length, 4096), dtype=prompt_emb_1.dtype, device=device) + else: + prompt_emb_3 = self.encode_prompt_using_t5(prompt, self.text_encoder_3, self.tokenizer_3, t5_sequence_length, device) + prompt_emb_3 = prompt_emb_3.to(prompt_emb_1.dtype) # float32 -> float16 + + # Merge + prompt_emb = torch.cat([ + torch.nn.functional.pad(torch.cat([prompt_emb_1, prompt_emb_2], dim=-1), (0, 4096 - 768 - 1280)), + prompt_emb_3 + ], dim=-2) + pooled_prompt_emb = torch.cat([pooled_prompt_emb_1, pooled_prompt_emb_2], dim=-1) + + return prompt_emb, pooled_prompt_emb diff --git a/diffsynth/prompters/sd_prompter.py b/diffsynth/prompters/sd_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b31ea2836b3b02edab37d7f610c13f2cf6cead --- /dev/null +++ b/diffsynth/prompters/sd_prompter.py @@ -0,0 +1,73 @@ +from .base_prompter import BasePrompter, tokenize_long_prompt +from ..models.utils import load_state_dict, search_for_embeddings +from ..models import SDTextEncoder +from transformers import CLIPTokenizer +import torch, os + + + +class SDPrompter(BasePrompter): + def __init__(self, tokenizer_path=None): + if tokenizer_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_path = os.path.join(base_path, "tokenizer_configs/stable_diffusion/tokenizer") + super().__init__() + self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer_path) + self.text_encoder: SDTextEncoder = None + self.textual_inversion_dict = {} + self.keyword_dict = {} + + + def fetch_models(self, text_encoder: SDTextEncoder = None): + self.text_encoder = text_encoder + + + def add_textual_inversions_to_model(self, textual_inversion_dict, text_encoder): + dtype = next(iter(text_encoder.parameters())).dtype + state_dict = text_encoder.token_embedding.state_dict() + token_embeddings = [state_dict["weight"]] + for keyword in textual_inversion_dict: + _, embeddings = textual_inversion_dict[keyword] + token_embeddings.append(embeddings.to(dtype=dtype, device=token_embeddings[0].device)) + token_embeddings = torch.concat(token_embeddings, dim=0) + state_dict["weight"] = token_embeddings + text_encoder.token_embedding = torch.nn.Embedding(token_embeddings.shape[0], token_embeddings.shape[1]) + text_encoder.token_embedding = text_encoder.token_embedding.to(dtype=dtype, device=token_embeddings[0].device) + text_encoder.token_embedding.load_state_dict(state_dict) + + + def add_textual_inversions_to_tokenizer(self, textual_inversion_dict, tokenizer): + additional_tokens = [] + for keyword in textual_inversion_dict: + tokens, _ = textual_inversion_dict[keyword] + additional_tokens += tokens + self.keyword_dict[keyword] = " " + " ".join(tokens) + " " + tokenizer.add_tokens(additional_tokens) + + + def load_textual_inversions(self, model_paths): + for model_path in model_paths: + keyword = os.path.splitext(os.path.split(model_path)[-1])[0] + state_dict = load_state_dict(model_path) + + # Search for embeddings + for embeddings in search_for_embeddings(state_dict): + if len(embeddings.shape) == 2 and embeddings.shape[1] == 768: + tokens = [f"{keyword}_{i}" for i in range(embeddings.shape[0])] + self.textual_inversion_dict[keyword] = (tokens, embeddings) + + self.add_textual_inversions_to_model(self.textual_inversion_dict, self.text_encoder) + self.add_textual_inversions_to_tokenizer(self.textual_inversion_dict, self.tokenizer) + + + def encode_prompt(self, prompt, clip_skip=1, device="cuda", positive=True): + prompt = self.process_prompt(prompt, positive=positive) + for keyword in self.keyword_dict: + if keyword in prompt: + print(f"Textual inversion {keyword} is enabled.") + prompt = prompt.replace(keyword, self.keyword_dict[keyword]) + input_ids = tokenize_long_prompt(self.tokenizer, prompt).to(device) + prompt_emb = self.text_encoder(input_ids, clip_skip=clip_skip) + prompt_emb = prompt_emb.reshape((1, prompt_emb.shape[0]*prompt_emb.shape[1], -1)) + + return prompt_emb \ No newline at end of file diff --git a/diffsynth/prompters/sdxl_prompter.py b/diffsynth/prompters/sdxl_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..d84145402538b89b23d39a98271cbad64c2d9fc3 --- /dev/null +++ b/diffsynth/prompters/sdxl_prompter.py @@ -0,0 +1,61 @@ +from .base_prompter import BasePrompter, tokenize_long_prompt +from ..models.model_manager import ModelManager +from ..models import SDXLTextEncoder, SDXLTextEncoder2 +from transformers import CLIPTokenizer +import torch, os + + + +class SDXLPrompter(BasePrompter): + def __init__( + self, + tokenizer_path=None, + tokenizer_2_path=None + ): + if tokenizer_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_path = os.path.join(base_path, "tokenizer_configs/stable_diffusion/tokenizer") + if tokenizer_2_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_2_path = os.path.join(base_path, "tokenizer_configs/stable_diffusion_xl/tokenizer_2") + super().__init__() + self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer_path) + self.tokenizer_2 = CLIPTokenizer.from_pretrained(tokenizer_2_path) + self.text_encoder: SDXLTextEncoder = None + self.text_encoder_2: SDXLTextEncoder2 = None + + + def fetch_models(self, text_encoder: SDXLTextEncoder = None, text_encoder_2: SDXLTextEncoder2 = None): + self.text_encoder = text_encoder + self.text_encoder_2 = text_encoder_2 + + + def encode_prompt( + self, + prompt, + clip_skip=1, + clip_skip_2=2, + positive=True, + device="cuda" + ): + prompt = self.process_prompt(prompt, positive=positive) + + # 1 + input_ids = tokenize_long_prompt(self.tokenizer, prompt).to(device) + prompt_emb_1 = self.text_encoder(input_ids, clip_skip=clip_skip) + + # 2 + input_ids_2 = tokenize_long_prompt(self.tokenizer_2, prompt).to(device) + add_text_embeds, prompt_emb_2 = self.text_encoder_2(input_ids_2, clip_skip=clip_skip_2) + + # Merge + if prompt_emb_1.shape[0] != prompt_emb_2.shape[0]: + max_batch_size = min(prompt_emb_1.shape[0], prompt_emb_2.shape[0]) + prompt_emb_1 = prompt_emb_1[: max_batch_size] + prompt_emb_2 = prompt_emb_2[: max_batch_size] + prompt_emb = torch.concatenate([prompt_emb_1, prompt_emb_2], dim=-1) + + # For very long prompt, we only use the first 77 tokens to compute `add_text_embeds`. + add_text_embeds = add_text_embeds[0:1] + prompt_emb = prompt_emb.reshape((1, prompt_emb.shape[0]*prompt_emb.shape[1], -1)) + return add_text_embeds, prompt_emb diff --git a/diffsynth/prompters/stepvideo_prompter.py b/diffsynth/prompters/stepvideo_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..79d374b1f8a4be2a2298520fcbf87800e0ca91d9 --- /dev/null +++ b/diffsynth/prompters/stepvideo_prompter.py @@ -0,0 +1,56 @@ +from .base_prompter import BasePrompter +from ..models.hunyuan_dit_text_encoder import HunyuanDiTCLIPTextEncoder +from ..models.stepvideo_text_encoder import STEP1TextEncoder +from transformers import BertTokenizer +import os, torch + + +class StepVideoPrompter(BasePrompter): + + def __init__( + self, + tokenizer_1_path=None, + ): + if tokenizer_1_path is None: + base_path = os.path.dirname(os.path.dirname(__file__)) + tokenizer_1_path = os.path.join( + base_path, "tokenizer_configs/hunyuan_dit/tokenizer") + super().__init__() + self.tokenizer_1 = BertTokenizer.from_pretrained(tokenizer_1_path) + + def fetch_models(self, text_encoder_1: HunyuanDiTCLIPTextEncoder = None, text_encoder_2: STEP1TextEncoder = None): + self.text_encoder_1 = text_encoder_1 + self.text_encoder_2 = text_encoder_2 + + def encode_prompt_using_clip(self, prompt, max_length, device): + text_inputs = self.tokenizer_1( + prompt, + padding="max_length", + max_length=max_length, + truncation=True, + return_attention_mask=True, + return_tensors="pt", + ) + prompt_embeds = self.text_encoder_1( + text_inputs.input_ids.to(device), + attention_mask=text_inputs.attention_mask.to(device), + ) + return prompt_embeds + + def encode_prompt_using_llm(self, prompt, max_length, device): + y, y_mask = self.text_encoder_2(prompt, max_length=max_length, device=device) + return y, y_mask + + def encode_prompt(self, + prompt, + positive=True, + device="cuda"): + + prompt = self.process_prompt(prompt, positive=positive) + + clip_embeds = self.encode_prompt_using_clip(prompt, max_length=77, device=device) + llm_embeds, llm_mask = self.encode_prompt_using_llm(prompt, max_length=320, device=device) + + llm_mask = torch.nn.functional.pad(llm_mask, (clip_embeds.shape[1], 0), value=1) + + return clip_embeds, llm_embeds, llm_mask diff --git a/diffsynth/prompters/wan_prompter.py b/diffsynth/prompters/wan_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..01a765d3cb3bf2ee4d06553fd061ed7dd75443b2 --- /dev/null +++ b/diffsynth/prompters/wan_prompter.py @@ -0,0 +1,109 @@ +from .base_prompter import BasePrompter +from ..models.wan_video_text_encoder import WanTextEncoder +from transformers import AutoTokenizer +import os, torch +import ftfy +import html +import string +import regex as re + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +def canonicalize(text, keep_punctuation_exact_string=None): + text = text.replace('_', ' ') + if keep_punctuation_exact_string: + text = keep_punctuation_exact_string.join( + part.translate(str.maketrans('', '', string.punctuation)) + for part in text.split(keep_punctuation_exact_string)) + else: + text = text.translate(str.maketrans('', '', string.punctuation)) + text = text.lower() + text = re.sub(r'\s+', ' ', text) + return text.strip() + + +class HuggingfaceTokenizer: + + def __init__(self, name, seq_len=None, clean=None, **kwargs): + assert clean in (None, 'whitespace', 'lower', 'canonicalize') + self.name = name + self.seq_len = seq_len + self.clean = clean + + # init tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(name, **kwargs) + self.vocab_size = self.tokenizer.vocab_size + + def __call__(self, sequence, **kwargs): + return_mask = kwargs.pop('return_mask', False) + + # arguments + _kwargs = {'return_tensors': 'pt'} + if self.seq_len is not None: + _kwargs.update({ + 'padding': 'max_length', + 'truncation': True, + 'max_length': self.seq_len + }) + _kwargs.update(**kwargs) + + # tokenization + if isinstance(sequence, str): + sequence = [sequence] + if self.clean: + sequence = [self._clean(u) for u in sequence] + ids = self.tokenizer(sequence, **_kwargs) + + # output + if return_mask: + return ids.input_ids, ids.attention_mask + else: + return ids.input_ids + + def _clean(self, text): + if self.clean == 'whitespace': + text = whitespace_clean(basic_clean(text)) + elif self.clean == 'lower': + text = whitespace_clean(basic_clean(text)).lower() + elif self.clean == 'canonicalize': + text = canonicalize(basic_clean(text)) + return text + + +class WanPrompter(BasePrompter): + + def __init__(self, tokenizer_path=None, text_len=512): + super().__init__() + self.text_len = text_len + self.text_encoder = None + self.fetch_tokenizer(tokenizer_path) + + def fetch_tokenizer(self, tokenizer_path=None): + if tokenizer_path is not None: + self.tokenizer = HuggingfaceTokenizer(name=tokenizer_path, seq_len=self.text_len, clean='whitespace') + + def fetch_models(self, text_encoder: WanTextEncoder = None): + self.text_encoder = text_encoder + + def encode_prompt(self, prompt, positive=True, device="cuda"): + prompt = self.process_prompt(prompt, positive=positive) + + ids, mask = self.tokenizer(prompt, return_mask=True, add_special_tokens=True) + ids = ids.to(device) + mask = mask.to(device) + seq_lens = mask.gt(0).sum(dim=1).long() + prompt_emb = self.text_encoder(ids, mask) + for i, v in enumerate(seq_lens): + prompt_emb[:, v:] = 0 + return prompt_emb diff --git a/diffsynth/schedulers/__init__.py b/diffsynth/schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ec43257b687c9b5504e08e05763332755566ea5 --- /dev/null +++ b/diffsynth/schedulers/__init__.py @@ -0,0 +1,3 @@ +from .ddim import EnhancedDDIMScheduler +from .continuous_ode import ContinuousODEScheduler +from .flow_match import FlowMatchScheduler diff --git a/diffsynth/schedulers/__pycache__/__init__.cpython-311.pyc b/diffsynth/schedulers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..708f578e2a2e9c41a8978eb7c35e38da33334059 Binary files /dev/null and b/diffsynth/schedulers/__pycache__/__init__.cpython-311.pyc differ diff --git a/diffsynth/schedulers/__pycache__/continuous_ode.cpython-311.pyc b/diffsynth/schedulers/__pycache__/continuous_ode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f94c9cc76a501276247a7684678c83b387bded87 Binary files /dev/null and b/diffsynth/schedulers/__pycache__/continuous_ode.cpython-311.pyc differ diff --git a/diffsynth/schedulers/__pycache__/ddim.cpython-311.pyc b/diffsynth/schedulers/__pycache__/ddim.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1303d3b5503d7ca22919a0b3670fcb6926a15d49 Binary files /dev/null and b/diffsynth/schedulers/__pycache__/ddim.cpython-311.pyc differ diff --git a/diffsynth/schedulers/__pycache__/flow_match.cpython-311.pyc b/diffsynth/schedulers/__pycache__/flow_match.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f29c4dc800a4f18c58caee3d2cc22ab5828fc9c7 Binary files /dev/null and b/diffsynth/schedulers/__pycache__/flow_match.cpython-311.pyc differ diff --git a/diffsynth/schedulers/continuous_ode.py b/diffsynth/schedulers/continuous_ode.py new file mode 100644 index 0000000000000000000000000000000000000000..c73b9e221aa54a8385322b42012c30c598550fcd --- /dev/null +++ b/diffsynth/schedulers/continuous_ode.py @@ -0,0 +1,59 @@ +import torch + + +class ContinuousODEScheduler(): + + def __init__(self, num_inference_steps=100, sigma_max=700.0, sigma_min=0.002, rho=7.0): + self.sigma_max = sigma_max + self.sigma_min = sigma_min + self.rho = rho + self.set_timesteps(num_inference_steps) + + + def set_timesteps(self, num_inference_steps=100, denoising_strength=1.0, **kwargs): + ramp = torch.linspace(1-denoising_strength, 1, num_inference_steps) + min_inv_rho = torch.pow(torch.tensor((self.sigma_min,)), (1 / self.rho)) + max_inv_rho = torch.pow(torch.tensor((self.sigma_max,)), (1 / self.rho)) + self.sigmas = torch.pow(max_inv_rho + ramp * (min_inv_rho - max_inv_rho), self.rho) + self.timesteps = torch.log(self.sigmas) * 0.25 + + + def step(self, model_output, timestep, sample, to_final=False): + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + sample *= (sigma*sigma + 1).sqrt() + estimated_sample = -sigma / (sigma*sigma + 1).sqrt() * model_output + 1 / (sigma*sigma + 1) * sample + if to_final or timestep_id + 1 >= len(self.timesteps): + prev_sample = estimated_sample + else: + sigma_ = self.sigmas[timestep_id + 1] + derivative = 1 / sigma * (sample - estimated_sample) + prev_sample = sample + derivative * (sigma_ - sigma) + prev_sample /= (sigma_*sigma_ + 1).sqrt() + return prev_sample + + + def return_to_timestep(self, timestep, sample, sample_stablized): + # This scheduler doesn't support this function. + pass + + + def add_noise(self, original_samples, noise, timestep): + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + sample = (original_samples + noise * sigma) / (sigma*sigma + 1).sqrt() + return sample + + + def training_target(self, sample, noise, timestep): + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + target = (-(sigma*sigma + 1).sqrt() / sigma + 1 / (sigma*sigma + 1).sqrt() / sigma) * sample + 1 / (sigma*sigma + 1).sqrt() * noise + return target + + + def training_weight(self, timestep): + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + weight = (1 + sigma*sigma).sqrt() / sigma + return weight diff --git a/diffsynth/schedulers/ddim.py b/diffsynth/schedulers/ddim.py new file mode 100644 index 0000000000000000000000000000000000000000..da524963c62f662016b1429d5047ebe7b5922604 --- /dev/null +++ b/diffsynth/schedulers/ddim.py @@ -0,0 +1,105 @@ +import torch, math + + +class EnhancedDDIMScheduler(): + + def __init__(self, num_train_timesteps=1000, beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", prediction_type="epsilon", rescale_zero_terminal_snr=False): + self.num_train_timesteps = num_train_timesteps + if beta_schedule == "scaled_linear": + betas = torch.square(torch.linspace(math.sqrt(beta_start), math.sqrt(beta_end), num_train_timesteps, dtype=torch.float32)) + elif beta_schedule == "linear": + betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) + else: + raise NotImplementedError(f"{beta_schedule} is not implemented") + self.alphas_cumprod = torch.cumprod(1.0 - betas, dim=0) + if rescale_zero_terminal_snr: + self.alphas_cumprod = self.rescale_zero_terminal_snr(self.alphas_cumprod) + self.alphas_cumprod = self.alphas_cumprod.tolist() + self.set_timesteps(10) + self.prediction_type = prediction_type + + + def rescale_zero_terminal_snr(self, alphas_cumprod): + alphas_bar_sqrt = alphas_cumprod.sqrt() + + # Store old values. + alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone() + alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone() + + # Shift so the last timestep is zero. + alphas_bar_sqrt -= alphas_bar_sqrt_T + + # Scale so the first timestep is back to the old value. + alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T) + + # Convert alphas_bar_sqrt to betas + alphas_bar = alphas_bar_sqrt.square() # Revert sqrt + + return alphas_bar + + + def set_timesteps(self, num_inference_steps, denoising_strength=1.0, **kwargs): + # The timesteps are aligned to 999...0, which is different from other implementations, + # but I think this implementation is more reasonable in theory. + max_timestep = max(round(self.num_train_timesteps * denoising_strength) - 1, 0) + num_inference_steps = min(num_inference_steps, max_timestep + 1) + if num_inference_steps == 1: + self.timesteps = torch.Tensor([max_timestep]) + else: + step_length = max_timestep / (num_inference_steps - 1) + self.timesteps = torch.Tensor([round(max_timestep - i*step_length) for i in range(num_inference_steps)]) + + + def denoise(self, model_output, sample, alpha_prod_t, alpha_prod_t_prev): + if self.prediction_type == "epsilon": + weight_e = math.sqrt(1 - alpha_prod_t_prev) - math.sqrt(alpha_prod_t_prev * (1 - alpha_prod_t) / alpha_prod_t) + weight_x = math.sqrt(alpha_prod_t_prev / alpha_prod_t) + prev_sample = sample * weight_x + model_output * weight_e + elif self.prediction_type == "v_prediction": + weight_e = -math.sqrt(alpha_prod_t_prev * (1 - alpha_prod_t)) + math.sqrt(alpha_prod_t * (1 - alpha_prod_t_prev)) + weight_x = math.sqrt(alpha_prod_t * alpha_prod_t_prev) + math.sqrt((1 - alpha_prod_t) * (1 - alpha_prod_t_prev)) + prev_sample = sample * weight_x + model_output * weight_e + else: + raise NotImplementedError(f"{self.prediction_type} is not implemented") + return prev_sample + + + def step(self, model_output, timestep, sample, to_final=False): + alpha_prod_t = self.alphas_cumprod[int(timestep.flatten().tolist()[0])] + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + if to_final or timestep_id + 1 >= len(self.timesteps): + alpha_prod_t_prev = 1.0 + else: + timestep_prev = int(self.timesteps[timestep_id + 1]) + alpha_prod_t_prev = self.alphas_cumprod[timestep_prev] + + return self.denoise(model_output, sample, alpha_prod_t, alpha_prod_t_prev) + + + def return_to_timestep(self, timestep, sample, sample_stablized): + alpha_prod_t = self.alphas_cumprod[int(timestep.flatten().tolist()[0])] + noise_pred = (sample - math.sqrt(alpha_prod_t) * sample_stablized) / math.sqrt(1 - alpha_prod_t) + return noise_pred + + + def add_noise(self, original_samples, noise, timestep): + sqrt_alpha_prod = math.sqrt(self.alphas_cumprod[int(timestep.flatten().tolist()[0])]) + sqrt_one_minus_alpha_prod = math.sqrt(1 - self.alphas_cumprod[int(timestep.flatten().tolist()[0])]) + noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise + return noisy_samples + + + def training_target(self, sample, noise, timestep): + if self.prediction_type == "epsilon": + return noise + else: + sqrt_alpha_prod = math.sqrt(self.alphas_cumprod[int(timestep.flatten().tolist()[0])]) + sqrt_one_minus_alpha_prod = math.sqrt(1 - self.alphas_cumprod[int(timestep.flatten().tolist()[0])]) + target = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample + return target + + + def training_weight(self, timestep): + return 1.0 diff --git a/diffsynth/schedulers/flow_match.py b/diffsynth/schedulers/flow_match.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d02195aac2345e1938044d8ffd310dc6c4d3b9 --- /dev/null +++ b/diffsynth/schedulers/flow_match.py @@ -0,0 +1,79 @@ +import torch + + + +class FlowMatchScheduler(): + + def __init__(self, num_inference_steps=100, num_train_timesteps=1000, shift=3.0, sigma_max=1.0, sigma_min=0.003/1.002, inverse_timesteps=False, extra_one_step=False, reverse_sigmas=False): + self.num_train_timesteps = num_train_timesteps + self.shift = shift + self.sigma_max = sigma_max + self.sigma_min = sigma_min + self.inverse_timesteps = inverse_timesteps + self.extra_one_step = extra_one_step + self.reverse_sigmas = reverse_sigmas + self.set_timesteps(num_inference_steps) + + + def set_timesteps(self, num_inference_steps=100, denoising_strength=1.0, training=False, shift=None): + if shift is not None: + self.shift = shift + sigma_start = self.sigma_min + (self.sigma_max - self.sigma_min) * denoising_strength + if self.extra_one_step: + self.sigmas = torch.linspace(sigma_start, self.sigma_min, num_inference_steps + 1)[:-1] + else: + self.sigmas = torch.linspace(sigma_start, self.sigma_min, num_inference_steps) + if self.inverse_timesteps: + self.sigmas = torch.flip(self.sigmas, dims=[0]) + self.sigmas = self.shift * self.sigmas / (1 + (self.shift - 1) * self.sigmas) + if self.reverse_sigmas: + self.sigmas = 1 - self.sigmas + self.timesteps = self.sigmas * self.num_train_timesteps + if training: + x = self.timesteps + y = torch.exp(-2 * ((x - num_inference_steps / 2) / num_inference_steps) ** 2) + y_shifted = y - y.min() + bsmntw_weighing = y_shifted * (num_inference_steps / y_shifted.sum()) + self.linear_timesteps_weights = bsmntw_weighing + + + def step(self, model_output, timestep, sample, to_final=False, **kwargs): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + if to_final or timestep_id + 1 >= len(self.timesteps): + sigma_ = 1 if (self.inverse_timesteps or self.reverse_sigmas) else 0 + else: + sigma_ = self.sigmas[timestep_id + 1] + prev_sample = sample + model_output * (sigma_ - sigma) + return prev_sample + + + def return_to_timestep(self, timestep, sample, sample_stablized): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + model_output = (sample - sample_stablized) / sigma + return model_output + + + def add_noise(self, original_samples, noise, timestep): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + sample = (1 - sigma) * original_samples + sigma * noise + return sample + + + def training_target(self, sample, noise, timestep): + target = noise - sample + return target + + + def training_weight(self, timestep): + timestep_id = torch.argmin((self.timesteps - timestep.to(self.timesteps.device)).abs()) + weights = self.linear_timesteps_weights[timestep_id] + return weights diff --git a/diffsynth/vram_management/__init__.py b/diffsynth/vram_management/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69a388db1dea2d5699b716260dfa0902c27c0ab5 --- /dev/null +++ b/diffsynth/vram_management/__init__.py @@ -0,0 +1 @@ +from .layers import * diff --git a/diffsynth/vram_management/__pycache__/__init__.cpython-311.pyc b/diffsynth/vram_management/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1e91e0e2902764bfe7954d0bb351dc853530874 Binary files /dev/null and b/diffsynth/vram_management/__pycache__/__init__.cpython-311.pyc differ diff --git a/diffsynth/vram_management/__pycache__/layers.cpython-311.pyc b/diffsynth/vram_management/__pycache__/layers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abc07054a686ee49209c4cef8b766ff236aa80a9 Binary files /dev/null and b/diffsynth/vram_management/__pycache__/layers.cpython-311.pyc differ diff --git a/diffsynth/vram_management/layers.py b/diffsynth/vram_management/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..a9df39ed224bf44a611af3ab984cb84a5d12c527 --- /dev/null +++ b/diffsynth/vram_management/layers.py @@ -0,0 +1,95 @@ +import torch, copy +from ..models.utils import init_weights_on_device + + +def cast_to(weight, dtype, device): + r = torch.empty_like(weight, dtype=dtype, device=device) + r.copy_(weight) + return r + + +class AutoWrappedModule(torch.nn.Module): + def __init__(self, module: torch.nn.Module, offload_dtype, offload_device, onload_dtype, onload_device, computation_dtype, computation_device): + super().__init__() + self.module = module.to(dtype=offload_dtype, device=offload_device) + self.offload_dtype = offload_dtype + self.offload_device = offload_device + self.onload_dtype = onload_dtype + self.onload_device = onload_device + self.computation_dtype = computation_dtype + self.computation_device = computation_device + self.state = 0 + + def offload(self): + if self.state == 1 and (self.offload_dtype != self.onload_dtype or self.offload_device != self.onload_device): + self.module.to(dtype=self.offload_dtype, device=self.offload_device) + self.state = 0 + + def onload(self): + if self.state == 0 and (self.offload_dtype != self.onload_dtype or self.offload_device != self.onload_device): + self.module.to(dtype=self.onload_dtype, device=self.onload_device) + self.state = 1 + + def forward(self, *args, **kwargs): + if self.onload_dtype == self.computation_dtype and self.onload_device == self.computation_device: + module = self.module + else: + module = copy.deepcopy(self.module).to(dtype=self.computation_dtype, device=self.computation_device) + return module(*args, **kwargs) + + +class AutoWrappedLinear(torch.nn.Linear): + def __init__(self, module: torch.nn.Linear, offload_dtype, offload_device, onload_dtype, onload_device, computation_dtype, computation_device): + with init_weights_on_device(device=torch.device("meta")): + super().__init__(in_features=module.in_features, out_features=module.out_features, bias=module.bias is not None, dtype=offload_dtype, device=offload_device) + self.weight = module.weight + self.bias = module.bias + self.offload_dtype = offload_dtype + self.offload_device = offload_device + self.onload_dtype = onload_dtype + self.onload_device = onload_device + self.computation_dtype = computation_dtype + self.computation_device = computation_device + self.state = 0 + + def offload(self): + if self.state == 1 and (self.offload_dtype != self.onload_dtype or self.offload_device != self.onload_device): + self.to(dtype=self.offload_dtype, device=self.offload_device) + self.state = 0 + + def onload(self): + if self.state == 0 and (self.offload_dtype != self.onload_dtype or self.offload_device != self.onload_device): + self.to(dtype=self.onload_dtype, device=self.onload_device) + self.state = 1 + + def forward(self, x, *args, **kwargs): + if self.onload_dtype == self.computation_dtype and self.onload_device == self.computation_device: + weight, bias = self.weight, self.bias + else: + weight = cast_to(self.weight, self.computation_dtype, self.computation_device) + bias = None if self.bias is None else cast_to(self.bias, self.computation_dtype, self.computation_device) + return torch.nn.functional.linear(x, weight, bias) + + +def enable_vram_management_recursively(model: torch.nn.Module, module_map: dict, module_config: dict, max_num_param=None, overflow_module_config: dict = None, total_num_param=0): + for name, module in model.named_children(): + for source_module, target_module in module_map.items(): + if isinstance(module, source_module): + num_param = sum(p.numel() for p in module.parameters()) + if max_num_param is not None and total_num_param + num_param > max_num_param: + module_config_ = overflow_module_config + else: + module_config_ = module_config + module_ = target_module(module, **module_config_) + setattr(model, name, module_) + total_num_param += num_param + break + else: + total_num_param = enable_vram_management_recursively(module, module_map, module_config, max_num_param, overflow_module_config, total_num_param) + return total_num_param + + +def enable_vram_management(model: torch.nn.Module, module_map: dict, module_config: dict, max_num_param=None, overflow_module_config: dict = None): + enable_vram_management_recursively(model, module_map, module_config, max_num_param, overflow_module_config, total_num_param=0) + model.vram_management_enabled = True +