Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- diffsynth/data/__init__.py +1 -0
- diffsynth/data/__pycache__/__init__.cpython-311.pyc +0 -0
- diffsynth/data/__pycache__/video.cpython-311.pyc +0 -0
- diffsynth/data/simple_text_image.py +41 -0
- diffsynth/data/video.py +148 -0
- diffsynth/distributed/__init__.py +0 -0
- diffsynth/distributed/__pycache__/__init__.cpython-311.pyc +0 -0
- diffsynth/distributed/__pycache__/xdit_context_parallel.cpython-311.pyc +0 -0
- diffsynth/distributed/xdit_context_parallel.py +129 -0
- diffsynth/pipelines/__init__.py +15 -0
- diffsynth/pipelines/__pycache__/__init__.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/base.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/cog_video.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/dancer.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/flux_image.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/hunyuan_image.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/hunyuan_video.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/omnigen_image.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/pipeline_runner.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/sd3_image.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/sd_image.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/sd_video.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/sdxl_image.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/sdxl_video.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/step_video.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/svd_video.cpython-311.pyc +0 -0
- diffsynth/pipelines/__pycache__/wan_video.cpython-311.pyc +0 -0
- diffsynth/pipelines/cog_video.py +135 -0
- diffsynth/pipelines/dancer.py +236 -0
- diffsynth/pipelines/flux_image.py +646 -0
- diffsynth/pipelines/hunyuan_image.py +288 -0
- diffsynth/pipelines/hunyuan_video.py +395 -0
- diffsynth/pipelines/omnigen_image.py +289 -0
- diffsynth/pipelines/pipeline_runner.py +105 -0
- diffsynth/pipelines/sd3_image.py +147 -0
- diffsynth/pipelines/sd_image.py +191 -0
- diffsynth/pipelines/sd_video.py +269 -0
- diffsynth/pipelines/sdxl_video.py +226 -0
- diffsynth/pipelines/step_video.py +209 -0
- diffsynth/pipelines/svd_video.py +300 -0
- diffsynth/processors/FastBlend.py +142 -0
- diffsynth/processors/PILEditor.py +28 -0
- diffsynth/processors/RIFE.py +77 -0
- diffsynth/processors/__init__.py +0 -0
- diffsynth/processors/__pycache__/__init__.cpython-311.pyc +0 -0
- diffsynth/processors/__pycache__/base.cpython-311.pyc +0 -0
- diffsynth/processors/__pycache__/sequencial_processor.cpython-311.pyc +0 -0
- diffsynth/processors/base.py +6 -0
- diffsynth/processors/sequencial_processor.py +41 -0
- diffsynth/prompters/__pycache__/sd3_prompter.cpython-311.pyc +0 -0
diffsynth/data/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .video import VideoData, save_video, save_frames
|
diffsynth/data/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (254 Bytes). View file
|
|
|
diffsynth/data/__pycache__/video.cpython-311.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
diffsynth/data/simple_text_image.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch, os, torchvision
|
| 2 |
+
from torchvision import transforms
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TextImageDataset(torch.utils.data.Dataset):
|
| 9 |
+
def __init__(self, dataset_path, steps_per_epoch=10000, height=1024, width=1024, center_crop=True, random_flip=False):
|
| 10 |
+
self.steps_per_epoch = steps_per_epoch
|
| 11 |
+
metadata = pd.read_csv(os.path.join(dataset_path, "train/metadata.csv"))
|
| 12 |
+
self.path = [os.path.join(dataset_path, "train", file_name) for file_name in metadata["file_name"]]
|
| 13 |
+
self.text = metadata["text"].to_list()
|
| 14 |
+
self.height = height
|
| 15 |
+
self.width = width
|
| 16 |
+
self.image_processor = transforms.Compose(
|
| 17 |
+
[
|
| 18 |
+
transforms.CenterCrop((height, width)) if center_crop else transforms.RandomCrop((height, width)),
|
| 19 |
+
transforms.RandomHorizontalFlip() if random_flip else transforms.Lambda(lambda x: x),
|
| 20 |
+
transforms.ToTensor(),
|
| 21 |
+
transforms.Normalize([0.5], [0.5]),
|
| 22 |
+
]
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def __getitem__(self, index):
|
| 27 |
+
data_id = torch.randint(0, len(self.path), (1,))[0]
|
| 28 |
+
data_id = (data_id + index) % len(self.path) # For fixed seed.
|
| 29 |
+
text = self.text[data_id]
|
| 30 |
+
image = Image.open(self.path[data_id]).convert("RGB")
|
| 31 |
+
target_height, target_width = self.height, self.width
|
| 32 |
+
width, height = image.size
|
| 33 |
+
scale = max(target_width / width, target_height / height)
|
| 34 |
+
shape = [round(height*scale),round(width*scale)]
|
| 35 |
+
image = torchvision.transforms.functional.resize(image,shape,interpolation=transforms.InterpolationMode.BILINEAR)
|
| 36 |
+
image = self.image_processor(image)
|
| 37 |
+
return {"text": text, "image": image}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def __len__(self):
|
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|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class LowMemoryVideo:
|
| 8 |
+
def __init__(self, file_name):
|
| 9 |
+
self.reader = imageio.get_reader(file_name)
|
| 10 |
+
|
| 11 |
+
def __len__(self):
|
| 12 |
+
return self.reader.count_frames()
|
| 13 |
+
|
| 14 |
+
def __getitem__(self, item):
|
| 15 |
+
return Image.fromarray(np.array(self.reader.get_data(item))).convert("RGB")
|
| 16 |
+
|
| 17 |
+
def __del__(self):
|
| 18 |
+
self.reader.close()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def split_file_name(file_name):
|
| 22 |
+
result = []
|
| 23 |
+
number = -1
|
| 24 |
+
for i in file_name:
|
| 25 |
+
if ord(i)>=ord("0") and ord(i)<=ord("9"):
|
| 26 |
+
if number == -1:
|
| 27 |
+
number = 0
|
| 28 |
+
number = number*10 + ord(i) - ord("0")
|
| 29 |
+
else:
|
| 30 |
+
if number != -1:
|
| 31 |
+
result.append(number)
|
| 32 |
+
number = -1
|
| 33 |
+
result.append(i)
|
| 34 |
+
if number != -1:
|
| 35 |
+
result.append(number)
|
| 36 |
+
result = tuple(result)
|
| 37 |
+
return result
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def search_for_images(folder):
|
| 41 |
+
file_list = [i for i in os.listdir(folder) if i.endswith(".jpg") or i.endswith(".png")]
|
| 42 |
+
file_list = [(split_file_name(file_name), file_name) for file_name in file_list]
|
| 43 |
+
file_list = [i[1] for i in sorted(file_list)]
|
| 44 |
+
file_list = [os.path.join(folder, i) for i in file_list]
|
| 45 |
+
return file_list
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class LowMemoryImageFolder:
|
| 49 |
+
def __init__(self, folder, file_list=None):
|
| 50 |
+
if file_list is None:
|
| 51 |
+
self.file_list = search_for_images(folder)
|
| 52 |
+
else:
|
| 53 |
+
self.file_list = [os.path.join(folder, file_name) for file_name in file_list]
|
| 54 |
+
|
| 55 |
+
def __len__(self):
|
| 56 |
+
return len(self.file_list)
|
| 57 |
+
|
| 58 |
+
def __getitem__(self, item):
|
| 59 |
+
return Image.open(self.file_list[item]).convert("RGB")
|
| 60 |
+
|
| 61 |
+
def __del__(self):
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def crop_and_resize(image, height, width):
|
| 66 |
+
image = np.array(image)
|
| 67 |
+
image_height, image_width, _ = image.shape
|
| 68 |
+
if image_height / image_width < height / width:
|
| 69 |
+
croped_width = int(image_height / height * width)
|
| 70 |
+
left = (image_width - croped_width) // 2
|
| 71 |
+
image = image[:, left: left+croped_width]
|
| 72 |
+
image = Image.fromarray(image).resize((width, height))
|
| 73 |
+
else:
|
| 74 |
+
croped_height = int(image_width / width * height)
|
| 75 |
+
left = (image_height - croped_height) // 2
|
| 76 |
+
image = image[left: left+croped_height, :]
|
| 77 |
+
image = Image.fromarray(image).resize((width, height))
|
| 78 |
+
return image
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class VideoData:
|
| 82 |
+
def __init__(self, video_file=None, image_folder=None, height=None, width=None, **kwargs):
|
| 83 |
+
if video_file is not None:
|
| 84 |
+
self.data_type = "video"
|
| 85 |
+
self.data = LowMemoryVideo(video_file, **kwargs)
|
| 86 |
+
elif image_folder is not None:
|
| 87 |
+
self.data_type = "images"
|
| 88 |
+
self.data = LowMemoryImageFolder(image_folder, **kwargs)
|
| 89 |
+
else:
|
| 90 |
+
raise ValueError("Cannot open video or image folder")
|
| 91 |
+
self.length = None
|
| 92 |
+
self.set_shape(height, width)
|
| 93 |
+
|
| 94 |
+
def raw_data(self):
|
| 95 |
+
frames = []
|
| 96 |
+
for i in range(self.__len__()):
|
| 97 |
+
frames.append(self.__getitem__(i))
|
| 98 |
+
return frames
|
| 99 |
+
|
| 100 |
+
def set_length(self, length):
|
| 101 |
+
self.length = length
|
| 102 |
+
|
| 103 |
+
def set_shape(self, height, width):
|
| 104 |
+
self.height = height
|
| 105 |
+
self.width = width
|
| 106 |
+
|
| 107 |
+
def __len__(self):
|
| 108 |
+
if self.length is None:
|
| 109 |
+
return len(self.data)
|
| 110 |
+
else:
|
| 111 |
+
return self.length
|
| 112 |
+
|
| 113 |
+
def shape(self):
|
| 114 |
+
if self.height is not None and self.width is not None:
|
| 115 |
+
return self.height, self.width
|
| 116 |
+
else:
|
| 117 |
+
height, width, _ = self.__getitem__(0).shape
|
| 118 |
+
return height, width
|
| 119 |
+
|
| 120 |
+
def __getitem__(self, item):
|
| 121 |
+
frame = self.data.__getitem__(item)
|
| 122 |
+
width, height = frame.size
|
| 123 |
+
if self.height is not None and self.width is not None:
|
| 124 |
+
if self.height != height or self.width != width:
|
| 125 |
+
frame = crop_and_resize(frame, self.height, self.width)
|
| 126 |
+
return frame
|
| 127 |
+
|
| 128 |
+
def __del__(self):
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
def save_images(self, folder):
|
| 132 |
+
os.makedirs(folder, exist_ok=True)
|
| 133 |
+
for i in tqdm(range(self.__len__()), desc="Saving images"):
|
| 134 |
+
frame = self.__getitem__(i)
|
| 135 |
+
frame.save(os.path.join(folder, f"{i}.png"))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def save_video(frames, save_path, fps, quality=9, ffmpeg_params=None):
|
| 139 |
+
writer = imageio.get_writer(save_path, fps=fps, quality=quality, ffmpeg_params=ffmpeg_params)
|
| 140 |
+
for frame in tqdm(frames, desc="Saving video"):
|
| 141 |
+
frame = np.array(frame)
|
| 142 |
+
writer.append_data(frame)
|
| 143 |
+
writer.close()
|
| 144 |
+
|
| 145 |
+
def save_frames(frames, save_path):
|
| 146 |
+
os.makedirs(save_path, exist_ok=True)
|
| 147 |
+
for i, frame in enumerate(tqdm(frames, desc="Saving images")):
|
| 148 |
+
frame.save(os.path.join(save_path, f"{i}.png"))
|
diffsynth/distributed/__init__.py
ADDED
|
File without changes
|
diffsynth/distributed/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (153 Bytes). View file
|
|
|
diffsynth/distributed/__pycache__/xdit_context_parallel.cpython-311.pyc
ADDED
|
Binary file (8.1 kB). View file
|
|
|
diffsynth/distributed/xdit_context_parallel.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from einops import rearrange
|
| 4 |
+
from xfuser.core.distributed import (get_sequence_parallel_rank,
|
| 5 |
+
get_sequence_parallel_world_size,
|
| 6 |
+
get_sp_group)
|
| 7 |
+
from xfuser.core.long_ctx_attention import xFuserLongContextAttention
|
| 8 |
+
|
| 9 |
+
def sinusoidal_embedding_1d(dim, position):
|
| 10 |
+
sinusoid = torch.outer(position.type(torch.float64), torch.pow(
|
| 11 |
+
10000, -torch.arange(dim//2, dtype=torch.float64, device=position.device).div(dim//2)))
|
| 12 |
+
x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
|
| 13 |
+
return x.to(position.dtype)
|
| 14 |
+
|
| 15 |
+
def pad_freqs(original_tensor, target_len):
|
| 16 |
+
seq_len, s1, s2 = original_tensor.shape
|
| 17 |
+
pad_size = target_len - seq_len
|
| 18 |
+
padding_tensor = torch.ones(
|
| 19 |
+
pad_size,
|
| 20 |
+
s1,
|
| 21 |
+
s2,
|
| 22 |
+
dtype=original_tensor.dtype,
|
| 23 |
+
device=original_tensor.device)
|
| 24 |
+
padded_tensor = torch.cat([original_tensor, padding_tensor], dim=0)
|
| 25 |
+
return padded_tensor
|
| 26 |
+
|
| 27 |
+
def rope_apply(x, freqs, num_heads):
|
| 28 |
+
x = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
|
| 29 |
+
s_per_rank = x.shape[1]
|
| 30 |
+
|
| 31 |
+
x_out = torch.view_as_complex(x.to(torch.float64).reshape(
|
| 32 |
+
x.shape[0], x.shape[1], x.shape[2], -1, 2))
|
| 33 |
+
|
| 34 |
+
sp_size = get_sequence_parallel_world_size()
|
| 35 |
+
sp_rank = get_sequence_parallel_rank()
|
| 36 |
+
freqs = pad_freqs(freqs, s_per_rank * sp_size)
|
| 37 |
+
freqs_rank = freqs[(sp_rank * s_per_rank):((sp_rank + 1) * s_per_rank), :, :]
|
| 38 |
+
|
| 39 |
+
x_out = torch.view_as_real(x_out * freqs_rank).flatten(2)
|
| 40 |
+
return x_out.to(x.dtype)
|
| 41 |
+
|
| 42 |
+
def usp_dit_forward(self,
|
| 43 |
+
x: torch.Tensor,
|
| 44 |
+
timestep: torch.Tensor,
|
| 45 |
+
context: torch.Tensor,
|
| 46 |
+
clip_feature: Optional[torch.Tensor] = None,
|
| 47 |
+
y: Optional[torch.Tensor] = None,
|
| 48 |
+
use_gradient_checkpointing: bool = False,
|
| 49 |
+
use_gradient_checkpointing_offload: bool = False,
|
| 50 |
+
**kwargs,
|
| 51 |
+
):
|
| 52 |
+
t = self.time_embedding(
|
| 53 |
+
sinusoidal_embedding_1d(self.freq_dim, timestep))
|
| 54 |
+
t_mod = self.time_projection(t).unflatten(1, (6, self.dim))
|
| 55 |
+
context = self.text_embedding(context)
|
| 56 |
+
|
| 57 |
+
if self.has_image_input:
|
| 58 |
+
x = torch.cat([x, y], dim=1) # (b, c_x + c_y, f, h, w)
|
| 59 |
+
clip_embdding = self.img_emb(clip_feature)
|
| 60 |
+
context = torch.cat([clip_embdding, context], dim=1)
|
| 61 |
+
|
| 62 |
+
x, (f, h, w) = self.patchify(x)
|
| 63 |
+
|
| 64 |
+
freqs = torch.cat([
|
| 65 |
+
self.freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
|
| 66 |
+
self.freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
|
| 67 |
+
self.freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
|
| 68 |
+
], dim=-1).reshape(f * h * w, 1, -1).to(x.device)
|
| 69 |
+
|
| 70 |
+
def create_custom_forward(module):
|
| 71 |
+
def custom_forward(*inputs):
|
| 72 |
+
return module(*inputs)
|
| 73 |
+
return custom_forward
|
| 74 |
+
|
| 75 |
+
# Context Parallel
|
| 76 |
+
x = torch.chunk(
|
| 77 |
+
x, get_sequence_parallel_world_size(),
|
| 78 |
+
dim=1)[get_sequence_parallel_rank()]
|
| 79 |
+
|
| 80 |
+
for block in self.blocks:
|
| 81 |
+
if self.training and use_gradient_checkpointing:
|
| 82 |
+
if use_gradient_checkpointing_offload:
|
| 83 |
+
with torch.autograd.graph.save_on_cpu():
|
| 84 |
+
x = torch.utils.checkpoint.checkpoint(
|
| 85 |
+
create_custom_forward(block),
|
| 86 |
+
x, context, t_mod, freqs,
|
| 87 |
+
use_reentrant=False,
|
| 88 |
+
)
|
| 89 |
+
else:
|
| 90 |
+
x = torch.utils.checkpoint.checkpoint(
|
| 91 |
+
create_custom_forward(block),
|
| 92 |
+
x, context, t_mod, freqs,
|
| 93 |
+
use_reentrant=False,
|
| 94 |
+
)
|
| 95 |
+
else:
|
| 96 |
+
x = block(x, context, t_mod, freqs)
|
| 97 |
+
|
| 98 |
+
x = self.head(x, t)
|
| 99 |
+
|
| 100 |
+
# Context Parallel
|
| 101 |
+
x = get_sp_group().all_gather(x, dim=1)
|
| 102 |
+
|
| 103 |
+
# unpatchify
|
| 104 |
+
x = self.unpatchify(x, (f, h, w))
|
| 105 |
+
return x
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def usp_attn_forward(self, x, freqs):
|
| 109 |
+
q = self.norm_q(self.q(x))
|
| 110 |
+
k = self.norm_k(self.k(x))
|
| 111 |
+
v = self.v(x)
|
| 112 |
+
|
| 113 |
+
q = rope_apply(q, freqs, self.num_heads)
|
| 114 |
+
k = rope_apply(k, freqs, self.num_heads)
|
| 115 |
+
q = rearrange(q, "b s (n d) -> b s n d", n=self.num_heads)
|
| 116 |
+
k = rearrange(k, "b s (n d) -> b s n d", n=self.num_heads)
|
| 117 |
+
v = rearrange(v, "b s (n d) -> b s n d", n=self.num_heads)
|
| 118 |
+
|
| 119 |
+
x = xFuserLongContextAttention()(
|
| 120 |
+
None,
|
| 121 |
+
query=q,
|
| 122 |
+
key=k,
|
| 123 |
+
value=v,
|
| 124 |
+
)
|
| 125 |
+
x = x.flatten(2)
|
| 126 |
+
|
| 127 |
+
del q, k, v
|
| 128 |
+
torch.cuda.empty_cache()
|
| 129 |
+
return self.o(x)
|
diffsynth/pipelines/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .sd_image import SDImagePipeline
|
| 2 |
+
from .sd_video import SDVideoPipeline
|
| 3 |
+
from .sdxl_image import SDXLImagePipeline
|
| 4 |
+
from .sdxl_video import SDXLVideoPipeline
|
| 5 |
+
from .sd3_image import SD3ImagePipeline
|
| 6 |
+
from .hunyuan_image import HunyuanDiTImagePipeline
|
| 7 |
+
from .svd_video import SVDVideoPipeline
|
| 8 |
+
from .flux_image import FluxImagePipeline
|
| 9 |
+
from .cog_video import CogVideoPipeline
|
| 10 |
+
from .omnigen_image import OmnigenImagePipeline
|
| 11 |
+
from .pipeline_runner import SDVideoPipelineRunner
|
| 12 |
+
from .hunyuan_video import HunyuanVideoPipeline
|
| 13 |
+
from .step_video import StepVideoPipeline
|
| 14 |
+
from .wan_video import WanVideoPipeline, WanUniAnimateVideoPipeline, WanRepalceAnyoneVideoPipeline, WanUniAnimateLongVideoPipeline
|
| 15 |
+
KolorsImagePipeline = SDXLImagePipeline
|
diffsynth/pipelines/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (1.32 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (9.74 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/cog_video.cpython-311.pyc
ADDED
|
Binary file (8.04 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/dancer.cpython-311.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/flux_image.cpython-311.pyc
ADDED
|
Binary file (34 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/hunyuan_image.cpython-311.pyc
ADDED
|
Binary file (17 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/hunyuan_video.cpython-311.pyc
ADDED
|
Binary file (25.9 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/omnigen_image.cpython-311.pyc
ADDED
|
Binary file (19.3 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/pipeline_runner.cpython-311.pyc
ADDED
|
Binary file (9.02 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/sd3_image.cpython-311.pyc
ADDED
|
Binary file (8.79 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/sd_image.cpython-311.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/sd_video.cpython-311.pyc
ADDED
|
Binary file (14.4 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/sdxl_image.cpython-311.pyc
ADDED
|
Binary file (13 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/sdxl_video.cpython-311.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/step_video.cpython-311.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/svd_video.cpython-311.pyc
ADDED
|
Binary file (17.1 kB). View file
|
|
|
diffsynth/pipelines/__pycache__/wan_video.cpython-311.pyc
ADDED
|
Binary file (78.2 kB). View file
|
|
|
diffsynth/pipelines/cog_video.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models import ModelManager, FluxTextEncoder2, CogDiT, CogVAEEncoder, CogVAEDecoder
|
| 2 |
+
from ..prompters import CogPrompter
|
| 3 |
+
from ..schedulers import EnhancedDDIMScheduler
|
| 4 |
+
from .base import BasePipeline
|
| 5 |
+
import torch
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import numpy as np
|
| 9 |
+
from einops import rearrange
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CogVideoPipeline(BasePipeline):
|
| 14 |
+
|
| 15 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 16 |
+
super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16)
|
| 17 |
+
self.scheduler = EnhancedDDIMScheduler(rescale_zero_terminal_snr=True, prediction_type="v_prediction")
|
| 18 |
+
self.prompter = CogPrompter()
|
| 19 |
+
# models
|
| 20 |
+
self.text_encoder: FluxTextEncoder2 = None
|
| 21 |
+
self.dit: CogDiT = None
|
| 22 |
+
self.vae_encoder: CogVAEEncoder = None
|
| 23 |
+
self.vae_decoder: CogVAEDecoder = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]):
|
| 27 |
+
self.text_encoder = model_manager.fetch_model("flux_text_encoder_2")
|
| 28 |
+
self.dit = model_manager.fetch_model("cog_dit")
|
| 29 |
+
self.vae_encoder = model_manager.fetch_model("cog_vae_encoder")
|
| 30 |
+
self.vae_decoder = model_manager.fetch_model("cog_vae_decoder")
|
| 31 |
+
self.prompter.fetch_models(self.text_encoder)
|
| 32 |
+
self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@staticmethod
|
| 36 |
+
def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[]):
|
| 37 |
+
pipe = CogVideoPipeline(
|
| 38 |
+
device=model_manager.device,
|
| 39 |
+
torch_dtype=model_manager.torch_dtype
|
| 40 |
+
)
|
| 41 |
+
pipe.fetch_models(model_manager, prompt_refiner_classes)
|
| 42 |
+
return pipe
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def tensor2video(self, frames):
|
| 46 |
+
frames = rearrange(frames, "C T H W -> T H W C")
|
| 47 |
+
frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8)
|
| 48 |
+
frames = [Image.fromarray(frame) for frame in frames]
|
| 49 |
+
return frames
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def encode_prompt(self, prompt, positive=True):
|
| 53 |
+
prompt_emb = self.prompter.encode_prompt(prompt, device=self.device, positive=positive)
|
| 54 |
+
return {"prompt_emb": prompt_emb}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def prepare_extra_input(self, latents):
|
| 58 |
+
return {"image_rotary_emb": self.dit.prepare_rotary_positional_embeddings(latents.shape[3], latents.shape[4], latents.shape[2], device=self.device)}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@torch.no_grad()
|
| 62 |
+
def __call__(
|
| 63 |
+
self,
|
| 64 |
+
prompt,
|
| 65 |
+
negative_prompt="",
|
| 66 |
+
input_video=None,
|
| 67 |
+
cfg_scale=7.0,
|
| 68 |
+
denoising_strength=1.0,
|
| 69 |
+
num_frames=49,
|
| 70 |
+
height=480,
|
| 71 |
+
width=720,
|
| 72 |
+
num_inference_steps=20,
|
| 73 |
+
tiled=False,
|
| 74 |
+
tile_size=(60, 90),
|
| 75 |
+
tile_stride=(30, 45),
|
| 76 |
+
seed=None,
|
| 77 |
+
progress_bar_cmd=tqdm,
|
| 78 |
+
progress_bar_st=None,
|
| 79 |
+
):
|
| 80 |
+
height, width = self.check_resize_height_width(height, width)
|
| 81 |
+
|
| 82 |
+
# Tiler parameters
|
| 83 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 84 |
+
|
| 85 |
+
# Prepare scheduler
|
| 86 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength)
|
| 87 |
+
|
| 88 |
+
# Prepare latent tensors
|
| 89 |
+
noise = self.generate_noise((1, 16, num_frames // 4 + 1, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype)
|
| 90 |
+
|
| 91 |
+
if denoising_strength == 1.0:
|
| 92 |
+
latents = noise.clone()
|
| 93 |
+
else:
|
| 94 |
+
input_video = self.preprocess_images(input_video)
|
| 95 |
+
input_video = torch.stack(input_video, dim=2)
|
| 96 |
+
latents = self.vae_encoder.encode_video(input_video, **tiler_kwargs, progress_bar=progress_bar_cmd).to(dtype=self.torch_dtype)
|
| 97 |
+
latents = self.scheduler.add_noise(latents, noise, self.scheduler.timesteps[0])
|
| 98 |
+
if not tiled: latents = latents.to(self.device)
|
| 99 |
+
|
| 100 |
+
# Encode prompt
|
| 101 |
+
prompt_emb_posi = self.encode_prompt(prompt, positive=True)
|
| 102 |
+
if cfg_scale != 1.0:
|
| 103 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False)
|
| 104 |
+
|
| 105 |
+
# Extra input
|
| 106 |
+
extra_input = self.prepare_extra_input(latents)
|
| 107 |
+
|
| 108 |
+
# Denoise
|
| 109 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 110 |
+
timestep = timestep.unsqueeze(0).to(self.device)
|
| 111 |
+
|
| 112 |
+
# Classifier-free guidance
|
| 113 |
+
noise_pred_posi = self.dit(
|
| 114 |
+
latents, timestep=timestep, **prompt_emb_posi, **tiler_kwargs, **extra_input
|
| 115 |
+
)
|
| 116 |
+
if cfg_scale != 1.0:
|
| 117 |
+
noise_pred_nega = self.dit(
|
| 118 |
+
latents, timestep=timestep, **prompt_emb_nega, **tiler_kwargs, **extra_input
|
| 119 |
+
)
|
| 120 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 121 |
+
else:
|
| 122 |
+
noise_pred = noise_pred_posi
|
| 123 |
+
|
| 124 |
+
# DDIM
|
| 125 |
+
latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
|
| 126 |
+
|
| 127 |
+
# Update progress bar
|
| 128 |
+
if progress_bar_st is not None:
|
| 129 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 130 |
+
|
| 131 |
+
# Decode image
|
| 132 |
+
video = self.vae_decoder.decode_video(latents.to("cpu"), **tiler_kwargs, progress_bar=progress_bar_cmd)
|
| 133 |
+
video = self.tensor2video(video[0])
|
| 134 |
+
|
| 135 |
+
return video
|
diffsynth/pipelines/dancer.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from ..models import SDUNet, SDMotionModel, SDXLUNet, SDXLMotionModel
|
| 3 |
+
from ..models.sd_unet import PushBlock, PopBlock
|
| 4 |
+
from ..controlnets import MultiControlNetManager
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def lets_dance(
|
| 8 |
+
unet: SDUNet,
|
| 9 |
+
motion_modules: SDMotionModel = None,
|
| 10 |
+
controlnet: MultiControlNetManager = None,
|
| 11 |
+
sample = None,
|
| 12 |
+
timestep = None,
|
| 13 |
+
encoder_hidden_states = None,
|
| 14 |
+
ipadapter_kwargs_list = {},
|
| 15 |
+
controlnet_frames = None,
|
| 16 |
+
unet_batch_size = 1,
|
| 17 |
+
controlnet_batch_size = 1,
|
| 18 |
+
cross_frame_attention = False,
|
| 19 |
+
tiled=False,
|
| 20 |
+
tile_size=64,
|
| 21 |
+
tile_stride=32,
|
| 22 |
+
device = "cuda",
|
| 23 |
+
vram_limit_level = 0,
|
| 24 |
+
):
|
| 25 |
+
# 0. Text embedding alignment (only for video processing)
|
| 26 |
+
if encoder_hidden_states.shape[0] != sample.shape[0]:
|
| 27 |
+
encoder_hidden_states = encoder_hidden_states.repeat(sample.shape[0], 1, 1, 1)
|
| 28 |
+
|
| 29 |
+
# 1. ControlNet
|
| 30 |
+
# This part will be repeated on overlapping frames if animatediff_batch_size > animatediff_stride.
|
| 31 |
+
# I leave it here because I intend to do something interesting on the ControlNets.
|
| 32 |
+
controlnet_insert_block_id = 30
|
| 33 |
+
if controlnet is not None and controlnet_frames is not None:
|
| 34 |
+
res_stacks = []
|
| 35 |
+
# process controlnet frames with batch
|
| 36 |
+
for batch_id in range(0, sample.shape[0], controlnet_batch_size):
|
| 37 |
+
batch_id_ = min(batch_id + controlnet_batch_size, sample.shape[0])
|
| 38 |
+
res_stack = controlnet(
|
| 39 |
+
sample[batch_id: batch_id_],
|
| 40 |
+
timestep,
|
| 41 |
+
encoder_hidden_states[batch_id: batch_id_],
|
| 42 |
+
controlnet_frames[:, batch_id: batch_id_],
|
| 43 |
+
tiled=tiled, tile_size=tile_size, tile_stride=tile_stride
|
| 44 |
+
)
|
| 45 |
+
if vram_limit_level >= 1:
|
| 46 |
+
res_stack = [res.cpu() for res in res_stack]
|
| 47 |
+
res_stacks.append(res_stack)
|
| 48 |
+
# concat the residual
|
| 49 |
+
additional_res_stack = []
|
| 50 |
+
for i in range(len(res_stacks[0])):
|
| 51 |
+
res = torch.concat([res_stack[i] for res_stack in res_stacks], dim=0)
|
| 52 |
+
additional_res_stack.append(res)
|
| 53 |
+
else:
|
| 54 |
+
additional_res_stack = None
|
| 55 |
+
|
| 56 |
+
# 2. time
|
| 57 |
+
time_emb = unet.time_proj(timestep).to(sample.dtype)
|
| 58 |
+
time_emb = unet.time_embedding(time_emb)
|
| 59 |
+
|
| 60 |
+
# 3. pre-process
|
| 61 |
+
height, width = sample.shape[2], sample.shape[3]
|
| 62 |
+
hidden_states = unet.conv_in(sample)
|
| 63 |
+
text_emb = encoder_hidden_states
|
| 64 |
+
res_stack = [hidden_states.cpu() if vram_limit_level>=1 else hidden_states]
|
| 65 |
+
|
| 66 |
+
# 4. blocks
|
| 67 |
+
for block_id, block in enumerate(unet.blocks):
|
| 68 |
+
# 4.1 UNet
|
| 69 |
+
if isinstance(block, PushBlock):
|
| 70 |
+
hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
|
| 71 |
+
if vram_limit_level>=1:
|
| 72 |
+
res_stack[-1] = res_stack[-1].cpu()
|
| 73 |
+
elif isinstance(block, PopBlock):
|
| 74 |
+
if vram_limit_level>=1:
|
| 75 |
+
res_stack[-1] = res_stack[-1].to(device)
|
| 76 |
+
hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
|
| 77 |
+
else:
|
| 78 |
+
hidden_states_input = hidden_states
|
| 79 |
+
hidden_states_output = []
|
| 80 |
+
for batch_id in range(0, sample.shape[0], unet_batch_size):
|
| 81 |
+
batch_id_ = min(batch_id + unet_batch_size, sample.shape[0])
|
| 82 |
+
hidden_states, _, _, _ = block(
|
| 83 |
+
hidden_states_input[batch_id: batch_id_],
|
| 84 |
+
time_emb,
|
| 85 |
+
text_emb[batch_id: batch_id_],
|
| 86 |
+
res_stack,
|
| 87 |
+
cross_frame_attention=cross_frame_attention,
|
| 88 |
+
ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id, {}),
|
| 89 |
+
tiled=tiled, tile_size=tile_size, tile_stride=tile_stride
|
| 90 |
+
)
|
| 91 |
+
hidden_states_output.append(hidden_states)
|
| 92 |
+
hidden_states = torch.concat(hidden_states_output, dim=0)
|
| 93 |
+
# 4.2 AnimateDiff
|
| 94 |
+
if motion_modules is not None:
|
| 95 |
+
if block_id in motion_modules.call_block_id:
|
| 96 |
+
motion_module_id = motion_modules.call_block_id[block_id]
|
| 97 |
+
hidden_states, time_emb, text_emb, res_stack = motion_modules.motion_modules[motion_module_id](
|
| 98 |
+
hidden_states, time_emb, text_emb, res_stack,
|
| 99 |
+
batch_size=1
|
| 100 |
+
)
|
| 101 |
+
# 4.3 ControlNet
|
| 102 |
+
if block_id == controlnet_insert_block_id and additional_res_stack is not None:
|
| 103 |
+
hidden_states += additional_res_stack.pop().to(device)
|
| 104 |
+
if vram_limit_level>=1:
|
| 105 |
+
res_stack = [(res.to(device) + additional_res.to(device)).cpu() for res, additional_res in zip(res_stack, additional_res_stack)]
|
| 106 |
+
else:
|
| 107 |
+
res_stack = [res + additional_res for res, additional_res in zip(res_stack, additional_res_stack)]
|
| 108 |
+
|
| 109 |
+
# 5. output
|
| 110 |
+
hidden_states = unet.conv_norm_out(hidden_states)
|
| 111 |
+
hidden_states = unet.conv_act(hidden_states)
|
| 112 |
+
hidden_states = unet.conv_out(hidden_states)
|
| 113 |
+
|
| 114 |
+
return hidden_states
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def lets_dance_xl(
|
| 120 |
+
unet: SDXLUNet,
|
| 121 |
+
motion_modules: SDXLMotionModel = None,
|
| 122 |
+
controlnet: MultiControlNetManager = None,
|
| 123 |
+
sample = None,
|
| 124 |
+
add_time_id = None,
|
| 125 |
+
add_text_embeds = None,
|
| 126 |
+
timestep = None,
|
| 127 |
+
encoder_hidden_states = None,
|
| 128 |
+
ipadapter_kwargs_list = {},
|
| 129 |
+
controlnet_frames = None,
|
| 130 |
+
unet_batch_size = 1,
|
| 131 |
+
controlnet_batch_size = 1,
|
| 132 |
+
cross_frame_attention = False,
|
| 133 |
+
tiled=False,
|
| 134 |
+
tile_size=64,
|
| 135 |
+
tile_stride=32,
|
| 136 |
+
device = "cuda",
|
| 137 |
+
vram_limit_level = 0,
|
| 138 |
+
):
|
| 139 |
+
# 0. Text embedding alignment (only for video processing)
|
| 140 |
+
if encoder_hidden_states.shape[0] != sample.shape[0]:
|
| 141 |
+
encoder_hidden_states = encoder_hidden_states.repeat(sample.shape[0], 1, 1, 1)
|
| 142 |
+
if add_text_embeds.shape[0] != sample.shape[0]:
|
| 143 |
+
add_text_embeds = add_text_embeds.repeat(sample.shape[0], 1)
|
| 144 |
+
|
| 145 |
+
# 1. ControlNet
|
| 146 |
+
controlnet_insert_block_id = 22
|
| 147 |
+
if controlnet is not None and controlnet_frames is not None:
|
| 148 |
+
res_stacks = []
|
| 149 |
+
# process controlnet frames with batch
|
| 150 |
+
for batch_id in range(0, sample.shape[0], controlnet_batch_size):
|
| 151 |
+
batch_id_ = min(batch_id + controlnet_batch_size, sample.shape[0])
|
| 152 |
+
res_stack = controlnet(
|
| 153 |
+
sample[batch_id: batch_id_],
|
| 154 |
+
timestep,
|
| 155 |
+
encoder_hidden_states[batch_id: batch_id_],
|
| 156 |
+
controlnet_frames[:, batch_id: batch_id_],
|
| 157 |
+
add_time_id=add_time_id,
|
| 158 |
+
add_text_embeds=add_text_embeds,
|
| 159 |
+
tiled=tiled, tile_size=tile_size, tile_stride=tile_stride,
|
| 160 |
+
unet=unet, # for Kolors, some modules in ControlNets will be replaced.
|
| 161 |
+
)
|
| 162 |
+
if vram_limit_level >= 1:
|
| 163 |
+
res_stack = [res.cpu() for res in res_stack]
|
| 164 |
+
res_stacks.append(res_stack)
|
| 165 |
+
# concat the residual
|
| 166 |
+
additional_res_stack = []
|
| 167 |
+
for i in range(len(res_stacks[0])):
|
| 168 |
+
res = torch.concat([res_stack[i] for res_stack in res_stacks], dim=0)
|
| 169 |
+
additional_res_stack.append(res)
|
| 170 |
+
else:
|
| 171 |
+
additional_res_stack = None
|
| 172 |
+
|
| 173 |
+
# 2. time
|
| 174 |
+
t_emb = unet.time_proj(timestep).to(sample.dtype)
|
| 175 |
+
t_emb = unet.time_embedding(t_emb)
|
| 176 |
+
|
| 177 |
+
time_embeds = unet.add_time_proj(add_time_id)
|
| 178 |
+
time_embeds = time_embeds.reshape((add_text_embeds.shape[0], -1))
|
| 179 |
+
add_embeds = torch.concat([add_text_embeds, time_embeds], dim=-1)
|
| 180 |
+
add_embeds = add_embeds.to(sample.dtype)
|
| 181 |
+
add_embeds = unet.add_time_embedding(add_embeds)
|
| 182 |
+
|
| 183 |
+
time_emb = t_emb + add_embeds
|
| 184 |
+
|
| 185 |
+
# 3. pre-process
|
| 186 |
+
height, width = sample.shape[2], sample.shape[3]
|
| 187 |
+
hidden_states = unet.conv_in(sample)
|
| 188 |
+
text_emb = encoder_hidden_states if unet.text_intermediate_proj is None else unet.text_intermediate_proj(encoder_hidden_states)
|
| 189 |
+
res_stack = [hidden_states]
|
| 190 |
+
|
| 191 |
+
# 4. blocks
|
| 192 |
+
for block_id, block in enumerate(unet.blocks):
|
| 193 |
+
# 4.1 UNet
|
| 194 |
+
if isinstance(block, PushBlock):
|
| 195 |
+
hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
|
| 196 |
+
if vram_limit_level>=1:
|
| 197 |
+
res_stack[-1] = res_stack[-1].cpu()
|
| 198 |
+
elif isinstance(block, PopBlock):
|
| 199 |
+
if vram_limit_level>=1:
|
| 200 |
+
res_stack[-1] = res_stack[-1].to(device)
|
| 201 |
+
hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
|
| 202 |
+
else:
|
| 203 |
+
hidden_states_input = hidden_states
|
| 204 |
+
hidden_states_output = []
|
| 205 |
+
for batch_id in range(0, sample.shape[0], unet_batch_size):
|
| 206 |
+
batch_id_ = min(batch_id + unet_batch_size, sample.shape[0])
|
| 207 |
+
hidden_states, _, _, _ = block(
|
| 208 |
+
hidden_states_input[batch_id: batch_id_],
|
| 209 |
+
time_emb[batch_id: batch_id_],
|
| 210 |
+
text_emb[batch_id: batch_id_],
|
| 211 |
+
res_stack,
|
| 212 |
+
cross_frame_attention=cross_frame_attention,
|
| 213 |
+
ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id, {}),
|
| 214 |
+
tiled=tiled, tile_size=tile_size, tile_stride=tile_stride,
|
| 215 |
+
)
|
| 216 |
+
hidden_states_output.append(hidden_states)
|
| 217 |
+
hidden_states = torch.concat(hidden_states_output, dim=0)
|
| 218 |
+
# 4.2 AnimateDiff
|
| 219 |
+
if motion_modules is not None:
|
| 220 |
+
if block_id in motion_modules.call_block_id:
|
| 221 |
+
motion_module_id = motion_modules.call_block_id[block_id]
|
| 222 |
+
hidden_states, time_emb, text_emb, res_stack = motion_modules.motion_modules[motion_module_id](
|
| 223 |
+
hidden_states, time_emb, text_emb, res_stack,
|
| 224 |
+
batch_size=1
|
| 225 |
+
)
|
| 226 |
+
# 4.3 ControlNet
|
| 227 |
+
if block_id == controlnet_insert_block_id and additional_res_stack is not None:
|
| 228 |
+
hidden_states += additional_res_stack.pop().to(device)
|
| 229 |
+
res_stack = [res + additional_res for res, additional_res in zip(res_stack, additional_res_stack)]
|
| 230 |
+
|
| 231 |
+
# 5. output
|
| 232 |
+
hidden_states = unet.conv_norm_out(hidden_states)
|
| 233 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|
+
from ..controlnets import FluxMultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator
|
| 3 |
+
from ..prompters import FluxPrompter
|
| 4 |
+
from ..schedulers import FlowMatchScheduler
|
| 5 |
+
from .base import BasePipeline
|
| 6 |
+
from typing import List
|
| 7 |
+
import torch
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
import numpy as np
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from ..models.tiler import FastTileWorker
|
| 12 |
+
from transformers import SiglipVisionModel
|
| 13 |
+
from copy import deepcopy
|
| 14 |
+
from transformers.models.t5.modeling_t5 import T5LayerNorm, T5DenseActDense, T5DenseGatedActDense
|
| 15 |
+
from ..models.flux_dit import RMSNorm
|
| 16 |
+
from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FluxImagePipeline(BasePipeline):
|
| 20 |
+
|
| 21 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 22 |
+
super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16)
|
| 23 |
+
self.scheduler = FlowMatchScheduler()
|
| 24 |
+
self.prompter = FluxPrompter()
|
| 25 |
+
# models
|
| 26 |
+
self.text_encoder_1: SD3TextEncoder1 = None
|
| 27 |
+
self.text_encoder_2: FluxTextEncoder2 = None
|
| 28 |
+
self.dit: FluxDiT = None
|
| 29 |
+
self.vae_decoder: FluxVAEDecoder = None
|
| 30 |
+
self.vae_encoder: FluxVAEEncoder = None
|
| 31 |
+
self.controlnet: FluxMultiControlNetManager = None
|
| 32 |
+
self.ipadapter: FluxIpAdapter = None
|
| 33 |
+
self.ipadapter_image_encoder: SiglipVisionModel = None
|
| 34 |
+
self.model_names = ['text_encoder_1', 'text_encoder_2', 'dit', 'vae_decoder', 'vae_encoder', 'controlnet', 'ipadapter', 'ipadapter_image_encoder']
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def enable_vram_management(self, num_persistent_param_in_dit=None):
|
| 38 |
+
dtype = next(iter(self.text_encoder_1.parameters())).dtype
|
| 39 |
+
enable_vram_management(
|
| 40 |
+
self.text_encoder_1,
|
| 41 |
+
module_map = {
|
| 42 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 43 |
+
torch.nn.Embedding: AutoWrappedModule,
|
| 44 |
+
torch.nn.LayerNorm: AutoWrappedModule,
|
| 45 |
+
},
|
| 46 |
+
module_config = dict(
|
| 47 |
+
offload_dtype=dtype,
|
| 48 |
+
offload_device="cpu",
|
| 49 |
+
onload_dtype=dtype,
|
| 50 |
+
onload_device="cpu",
|
| 51 |
+
computation_dtype=self.torch_dtype,
|
| 52 |
+
computation_device=self.device,
|
| 53 |
+
),
|
| 54 |
+
)
|
| 55 |
+
dtype = next(iter(self.text_encoder_2.parameters())).dtype
|
| 56 |
+
enable_vram_management(
|
| 57 |
+
self.text_encoder_2,
|
| 58 |
+
module_map = {
|
| 59 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 60 |
+
torch.nn.Embedding: AutoWrappedModule,
|
| 61 |
+
T5LayerNorm: AutoWrappedModule,
|
| 62 |
+
T5DenseActDense: AutoWrappedModule,
|
| 63 |
+
T5DenseGatedActDense: AutoWrappedModule,
|
| 64 |
+
},
|
| 65 |
+
module_config = dict(
|
| 66 |
+
offload_dtype=dtype,
|
| 67 |
+
offload_device="cpu",
|
| 68 |
+
onload_dtype=dtype,
|
| 69 |
+
onload_device="cpu",
|
| 70 |
+
computation_dtype=self.torch_dtype,
|
| 71 |
+
computation_device=self.device,
|
| 72 |
+
),
|
| 73 |
+
)
|
| 74 |
+
dtype = next(iter(self.dit.parameters())).dtype
|
| 75 |
+
enable_vram_management(
|
| 76 |
+
self.dit,
|
| 77 |
+
module_map = {
|
| 78 |
+
RMSNorm: AutoWrappedModule,
|
| 79 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 80 |
+
},
|
| 81 |
+
module_config = dict(
|
| 82 |
+
offload_dtype=dtype,
|
| 83 |
+
offload_device="cpu",
|
| 84 |
+
onload_dtype=dtype,
|
| 85 |
+
onload_device="cuda",
|
| 86 |
+
computation_dtype=self.torch_dtype,
|
| 87 |
+
computation_device=self.device,
|
| 88 |
+
),
|
| 89 |
+
max_num_param=num_persistent_param_in_dit,
|
| 90 |
+
overflow_module_config = dict(
|
| 91 |
+
offload_dtype=dtype,
|
| 92 |
+
offload_device="cpu",
|
| 93 |
+
onload_dtype=dtype,
|
| 94 |
+
onload_device="cpu",
|
| 95 |
+
computation_dtype=self.torch_dtype,
|
| 96 |
+
computation_device=self.device,
|
| 97 |
+
),
|
| 98 |
+
)
|
| 99 |
+
dtype = next(iter(self.vae_decoder.parameters())).dtype
|
| 100 |
+
enable_vram_management(
|
| 101 |
+
self.vae_decoder,
|
| 102 |
+
module_map = {
|
| 103 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 104 |
+
torch.nn.Conv2d: AutoWrappedModule,
|
| 105 |
+
torch.nn.GroupNorm: AutoWrappedModule,
|
| 106 |
+
},
|
| 107 |
+
module_config = dict(
|
| 108 |
+
offload_dtype=dtype,
|
| 109 |
+
offload_device="cpu",
|
| 110 |
+
onload_dtype=dtype,
|
| 111 |
+
onload_device="cpu",
|
| 112 |
+
computation_dtype=self.torch_dtype,
|
| 113 |
+
computation_device=self.device,
|
| 114 |
+
),
|
| 115 |
+
)
|
| 116 |
+
dtype = next(iter(self.vae_encoder.parameters())).dtype
|
| 117 |
+
enable_vram_management(
|
| 118 |
+
self.vae_encoder,
|
| 119 |
+
module_map = {
|
| 120 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 121 |
+
torch.nn.Conv2d: AutoWrappedModule,
|
| 122 |
+
torch.nn.GroupNorm: AutoWrappedModule,
|
| 123 |
+
},
|
| 124 |
+
module_config = dict(
|
| 125 |
+
offload_dtype=dtype,
|
| 126 |
+
offload_device="cpu",
|
| 127 |
+
onload_dtype=dtype,
|
| 128 |
+
onload_device="cpu",
|
| 129 |
+
computation_dtype=self.torch_dtype,
|
| 130 |
+
computation_device=self.device,
|
| 131 |
+
),
|
| 132 |
+
)
|
| 133 |
+
self.enable_cpu_offload()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def denoising_model(self):
|
| 137 |
+
return self.dit
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[], prompt_extender_classes=[]):
|
| 141 |
+
self.text_encoder_1 = model_manager.fetch_model("sd3_text_encoder_1")
|
| 142 |
+
self.text_encoder_2 = model_manager.fetch_model("flux_text_encoder_2")
|
| 143 |
+
self.dit = model_manager.fetch_model("flux_dit")
|
| 144 |
+
self.vae_decoder = model_manager.fetch_model("flux_vae_decoder")
|
| 145 |
+
self.vae_encoder = model_manager.fetch_model("flux_vae_encoder")
|
| 146 |
+
self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2)
|
| 147 |
+
self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes)
|
| 148 |
+
self.prompter.load_prompt_extenders(model_manager, prompt_extender_classes)
|
| 149 |
+
|
| 150 |
+
# ControlNets
|
| 151 |
+
controlnet_units = []
|
| 152 |
+
for config in controlnet_config_units:
|
| 153 |
+
controlnet_unit = ControlNetUnit(
|
| 154 |
+
Annotator(config.processor_id, device=self.device, skip_processor=config.skip_processor),
|
| 155 |
+
model_manager.fetch_model("flux_controlnet", config.model_path),
|
| 156 |
+
config.scale
|
| 157 |
+
)
|
| 158 |
+
controlnet_units.append(controlnet_unit)
|
| 159 |
+
self.controlnet = FluxMultiControlNetManager(controlnet_units)
|
| 160 |
+
|
| 161 |
+
# IP-Adapters
|
| 162 |
+
self.ipadapter = model_manager.fetch_model("flux_ipadapter")
|
| 163 |
+
self.ipadapter_image_encoder = model_manager.fetch_model("siglip_vision_model")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@staticmethod
|
| 167 |
+
def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[], prompt_extender_classes=[], device=None, torch_dtype=None):
|
| 168 |
+
pipe = FluxImagePipeline(
|
| 169 |
+
device=model_manager.device if device is None else device,
|
| 170 |
+
torch_dtype=model_manager.torch_dtype if torch_dtype is None else torch_dtype,
|
| 171 |
+
)
|
| 172 |
+
pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes, prompt_extender_classes)
|
| 173 |
+
return pipe
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32):
|
| 177 |
+
latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 178 |
+
return latents
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32):
|
| 182 |
+
image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 183 |
+
image = self.vae_output_to_image(image)
|
| 184 |
+
return image
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def encode_prompt(self, prompt, positive=True, t5_sequence_length=512):
|
| 188 |
+
prompt_emb, pooled_prompt_emb, text_ids = self.prompter.encode_prompt(
|
| 189 |
+
prompt, device=self.device, positive=positive, t5_sequence_length=t5_sequence_length
|
| 190 |
+
)
|
| 191 |
+
return {"prompt_emb": prompt_emb, "pooled_prompt_emb": pooled_prompt_emb, "text_ids": text_ids}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def prepare_extra_input(self, latents=None, guidance=1.0):
|
| 195 |
+
latent_image_ids = self.dit.prepare_image_ids(latents)
|
| 196 |
+
guidance = torch.Tensor([guidance] * latents.shape[0]).to(device=latents.device, dtype=latents.dtype)
|
| 197 |
+
return {"image_ids": latent_image_ids, "guidance": guidance}
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def apply_controlnet_mask_on_latents(self, latents, mask):
|
| 201 |
+
mask = (self.preprocess_image(mask) + 1) / 2
|
| 202 |
+
mask = mask.mean(dim=1, keepdim=True)
|
| 203 |
+
mask = mask.to(dtype=self.torch_dtype, device=self.device)
|
| 204 |
+
mask = 1 - torch.nn.functional.interpolate(mask, size=latents.shape[-2:])
|
| 205 |
+
latents = torch.concat([latents, mask], dim=1)
|
| 206 |
+
return latents
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def apply_controlnet_mask_on_image(self, image, mask):
|
| 210 |
+
mask = mask.resize(image.size)
|
| 211 |
+
mask = self.preprocess_image(mask).mean(dim=[0, 1])
|
| 212 |
+
image = np.array(image)
|
| 213 |
+
image[mask > 0] = 0
|
| 214 |
+
image = Image.fromarray(image)
|
| 215 |
+
return image
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def prepare_controlnet_input(self, controlnet_image, controlnet_inpaint_mask, tiler_kwargs):
|
| 219 |
+
if isinstance(controlnet_image, Image.Image):
|
| 220 |
+
controlnet_image = [controlnet_image] * len(self.controlnet.processors)
|
| 221 |
+
|
| 222 |
+
controlnet_frames = []
|
| 223 |
+
for i in range(len(self.controlnet.processors)):
|
| 224 |
+
# image annotator
|
| 225 |
+
image = self.controlnet.process_image(controlnet_image[i], processor_id=i)[0]
|
| 226 |
+
if controlnet_inpaint_mask is not None and self.controlnet.processors[i].processor_id == "inpaint":
|
| 227 |
+
image = self.apply_controlnet_mask_on_image(image, controlnet_inpaint_mask)
|
| 228 |
+
|
| 229 |
+
# image to tensor
|
| 230 |
+
image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype)
|
| 231 |
+
|
| 232 |
+
# vae encoder
|
| 233 |
+
image = self.encode_image(image, **tiler_kwargs)
|
| 234 |
+
if controlnet_inpaint_mask is not None and self.controlnet.processors[i].processor_id == "inpaint":
|
| 235 |
+
image = self.apply_controlnet_mask_on_latents(image, controlnet_inpaint_mask)
|
| 236 |
+
|
| 237 |
+
# store it
|
| 238 |
+
controlnet_frames.append(image)
|
| 239 |
+
return controlnet_frames
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def prepare_ipadapter_inputs(self, images, height=384, width=384):
|
| 243 |
+
images = [image.convert("RGB").resize((width, height), resample=3) for image in images]
|
| 244 |
+
images = [self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype) for image in images]
|
| 245 |
+
return torch.cat(images, dim=0)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def inpaint_fusion(self, latents, inpaint_latents, pred_noise, fg_mask, bg_mask, progress_id, background_weight=0.):
|
| 249 |
+
# inpaint noise
|
| 250 |
+
inpaint_noise = (latents - inpaint_latents) / self.scheduler.sigmas[progress_id]
|
| 251 |
+
# merge noise
|
| 252 |
+
weight = torch.ones_like(inpaint_noise)
|
| 253 |
+
inpaint_noise[fg_mask] = pred_noise[fg_mask]
|
| 254 |
+
inpaint_noise[bg_mask] += pred_noise[bg_mask] * background_weight
|
| 255 |
+
weight[bg_mask] += background_weight
|
| 256 |
+
inpaint_noise /= weight
|
| 257 |
+
return inpaint_noise
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def preprocess_masks(self, masks, height, width, dim):
|
| 261 |
+
out_masks = []
|
| 262 |
+
for mask in masks:
|
| 263 |
+
mask = self.preprocess_image(mask.resize((width, height), resample=Image.NEAREST)).mean(dim=1, keepdim=True) > 0
|
| 264 |
+
mask = mask.repeat(1, dim, 1, 1).to(device=self.device, dtype=self.torch_dtype)
|
| 265 |
+
out_masks.append(mask)
|
| 266 |
+
return out_masks
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def prepare_entity_inputs(self, entity_prompts, entity_masks, width, height, t5_sequence_length=512, enable_eligen_inpaint=False):
|
| 270 |
+
fg_mask, bg_mask = None, None
|
| 271 |
+
if enable_eligen_inpaint:
|
| 272 |
+
masks_ = deepcopy(entity_masks)
|
| 273 |
+
fg_masks = torch.cat([self.preprocess_image(mask.resize((width//8, height//8))).mean(dim=1, keepdim=True) for mask in masks_])
|
| 274 |
+
fg_masks = (fg_masks > 0).float()
|
| 275 |
+
fg_mask = fg_masks.sum(dim=0, keepdim=True).repeat(1, 16, 1, 1) > 0
|
| 276 |
+
bg_mask = ~fg_mask
|
| 277 |
+
entity_masks = self.preprocess_masks(entity_masks, height//8, width//8, 1)
|
| 278 |
+
entity_masks = torch.cat(entity_masks, dim=0).unsqueeze(0) # b, n_mask, c, h, w
|
| 279 |
+
entity_prompts = self.encode_prompt(entity_prompts, t5_sequence_length=t5_sequence_length)['prompt_emb'].unsqueeze(0)
|
| 280 |
+
return entity_prompts, entity_masks, fg_mask, bg_mask
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def prepare_latents(self, input_image, height, width, seed, tiled, tile_size, tile_stride):
|
| 284 |
+
if input_image is not None:
|
| 285 |
+
self.load_models_to_device(['vae_encoder'])
|
| 286 |
+
image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype)
|
| 287 |
+
input_latents = self.encode_image(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 288 |
+
noise = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 289 |
+
latents = self.scheduler.add_noise(input_latents, noise, timestep=self.scheduler.timesteps[0])
|
| 290 |
+
else:
|
| 291 |
+
latents = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 292 |
+
input_latents = None
|
| 293 |
+
return latents, input_latents
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def prepare_ipadapter(self, ipadapter_images, ipadapter_scale):
|
| 297 |
+
if ipadapter_images is not None:
|
| 298 |
+
self.load_models_to_device(['ipadapter_image_encoder'])
|
| 299 |
+
ipadapter_images = self.prepare_ipadapter_inputs(ipadapter_images)
|
| 300 |
+
ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images).pooler_output
|
| 301 |
+
self.load_models_to_device(['ipadapter'])
|
| 302 |
+
ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)}
|
| 303 |
+
ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))}
|
| 304 |
+
else:
|
| 305 |
+
ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}}
|
| 306 |
+
return ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def prepare_controlnet(self, controlnet_image, masks, controlnet_inpaint_mask, tiler_kwargs, enable_controlnet_on_negative):
|
| 310 |
+
if controlnet_image is not None:
|
| 311 |
+
self.load_models_to_device(['vae_encoder'])
|
| 312 |
+
controlnet_kwargs_posi = {"controlnet_frames": self.prepare_controlnet_input(controlnet_image, controlnet_inpaint_mask, tiler_kwargs)}
|
| 313 |
+
if len(masks) > 0 and controlnet_inpaint_mask is not None:
|
| 314 |
+
print("The controlnet_inpaint_mask will be overridden by masks.")
|
| 315 |
+
local_controlnet_kwargs = [{"controlnet_frames": self.prepare_controlnet_input(controlnet_image, mask, tiler_kwargs)} for mask in masks]
|
| 316 |
+
else:
|
| 317 |
+
local_controlnet_kwargs = None
|
| 318 |
+
else:
|
| 319 |
+
controlnet_kwargs_posi, local_controlnet_kwargs = {"controlnet_frames": None}, [{}] * len(masks)
|
| 320 |
+
controlnet_kwargs_nega = controlnet_kwargs_posi if enable_controlnet_on_negative else {}
|
| 321 |
+
return controlnet_kwargs_posi, controlnet_kwargs_nega, local_controlnet_kwargs
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
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):
|
| 325 |
+
if eligen_entity_masks is not None:
|
| 326 |
+
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)
|
| 327 |
+
if enable_eligen_on_negative and cfg_scale != 1.0:
|
| 328 |
+
entity_prompt_emb_nega = prompt_emb_nega['prompt_emb'].unsqueeze(1).repeat(1, entity_masks_posi.shape[1], 1, 1)
|
| 329 |
+
entity_masks_nega = entity_masks_posi
|
| 330 |
+
else:
|
| 331 |
+
entity_prompt_emb_nega, entity_masks_nega = None, None
|
| 332 |
+
else:
|
| 333 |
+
entity_prompt_emb_posi, entity_masks_posi, entity_prompt_emb_nega, entity_masks_nega = None, None, None, None
|
| 334 |
+
fg_mask, bg_mask = None, None
|
| 335 |
+
eligen_kwargs_posi = {"entity_prompt_emb": entity_prompt_emb_posi, "entity_masks": entity_masks_posi}
|
| 336 |
+
eligen_kwargs_nega = {"entity_prompt_emb": entity_prompt_emb_nega, "entity_masks": entity_masks_nega}
|
| 337 |
+
return eligen_kwargs_posi, eligen_kwargs_nega, fg_mask, bg_mask
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def prepare_prompts(self, prompt, local_prompts, masks, mask_scales, t5_sequence_length, negative_prompt, cfg_scale):
|
| 341 |
+
# Extend prompt
|
| 342 |
+
self.load_models_to_device(['text_encoder_1', 'text_encoder_2'])
|
| 343 |
+
prompt, local_prompts, masks, mask_scales = self.extend_prompt(prompt, local_prompts, masks, mask_scales)
|
| 344 |
+
|
| 345 |
+
# Encode prompts
|
| 346 |
+
prompt_emb_posi = self.encode_prompt(prompt, t5_sequence_length=t5_sequence_length)
|
| 347 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False, t5_sequence_length=t5_sequence_length) if cfg_scale != 1.0 else None
|
| 348 |
+
prompt_emb_locals = [self.encode_prompt(prompt_local, t5_sequence_length=t5_sequence_length) for prompt_local in local_prompts]
|
| 349 |
+
return prompt_emb_posi, prompt_emb_nega, prompt_emb_locals
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@torch.no_grad()
|
| 353 |
+
def __call__(
|
| 354 |
+
self,
|
| 355 |
+
# Prompt
|
| 356 |
+
prompt,
|
| 357 |
+
negative_prompt="",
|
| 358 |
+
cfg_scale=1.0,
|
| 359 |
+
embedded_guidance=3.5,
|
| 360 |
+
t5_sequence_length=512,
|
| 361 |
+
# Image
|
| 362 |
+
input_image=None,
|
| 363 |
+
denoising_strength=1.0,
|
| 364 |
+
height=1024,
|
| 365 |
+
width=1024,
|
| 366 |
+
seed=None,
|
| 367 |
+
# Steps
|
| 368 |
+
num_inference_steps=30,
|
| 369 |
+
# local prompts
|
| 370 |
+
local_prompts=(),
|
| 371 |
+
masks=(),
|
| 372 |
+
mask_scales=(),
|
| 373 |
+
# ControlNet
|
| 374 |
+
controlnet_image=None,
|
| 375 |
+
controlnet_inpaint_mask=None,
|
| 376 |
+
enable_controlnet_on_negative=False,
|
| 377 |
+
# IP-Adapter
|
| 378 |
+
ipadapter_images=None,
|
| 379 |
+
ipadapter_scale=1.0,
|
| 380 |
+
# EliGen
|
| 381 |
+
eligen_entity_prompts=None,
|
| 382 |
+
eligen_entity_masks=None,
|
| 383 |
+
enable_eligen_on_negative=False,
|
| 384 |
+
enable_eligen_inpaint=False,
|
| 385 |
+
# TeaCache
|
| 386 |
+
tea_cache_l1_thresh=None,
|
| 387 |
+
# Tile
|
| 388 |
+
tiled=False,
|
| 389 |
+
tile_size=128,
|
| 390 |
+
tile_stride=64,
|
| 391 |
+
# Progress bar
|
| 392 |
+
progress_bar_cmd=tqdm,
|
| 393 |
+
progress_bar_st=None,
|
| 394 |
+
):
|
| 395 |
+
height, width = self.check_resize_height_width(height, width)
|
| 396 |
+
|
| 397 |
+
# Tiler parameters
|
| 398 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 399 |
+
|
| 400 |
+
# Prepare scheduler
|
| 401 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 402 |
+
|
| 403 |
+
# Prepare latent tensors
|
| 404 |
+
latents, input_latents = self.prepare_latents(input_image, height, width, seed, tiled, tile_size, tile_stride)
|
| 405 |
+
|
| 406 |
+
# Prompt
|
| 407 |
+
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)
|
| 408 |
+
|
| 409 |
+
# Extra input
|
| 410 |
+
extra_input = self.prepare_extra_input(latents, guidance=embedded_guidance)
|
| 411 |
+
|
| 412 |
+
# Entity control
|
| 413 |
+
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)
|
| 414 |
+
|
| 415 |
+
# IP-Adapter
|
| 416 |
+
ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = self.prepare_ipadapter(ipadapter_images, ipadapter_scale)
|
| 417 |
+
|
| 418 |
+
# ControlNets
|
| 419 |
+
controlnet_kwargs_posi, controlnet_kwargs_nega, local_controlnet_kwargs = self.prepare_controlnet(controlnet_image, masks, controlnet_inpaint_mask, tiler_kwargs, enable_controlnet_on_negative)
|
| 420 |
+
|
| 421 |
+
# TeaCache
|
| 422 |
+
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}
|
| 423 |
+
|
| 424 |
+
# Denoise
|
| 425 |
+
self.load_models_to_device(['dit', 'controlnet'])
|
| 426 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 427 |
+
timestep = timestep.unsqueeze(0).to(self.device)
|
| 428 |
+
|
| 429 |
+
# Positive side
|
| 430 |
+
inference_callback = lambda prompt_emb_posi, controlnet_kwargs: lets_dance_flux(
|
| 431 |
+
dit=self.dit, controlnet=self.controlnet,
|
| 432 |
+
hidden_states=latents, timestep=timestep,
|
| 433 |
+
**prompt_emb_posi, **tiler_kwargs, **extra_input, **controlnet_kwargs, **ipadapter_kwargs_list_posi, **eligen_kwargs_posi, **tea_cache_kwargs,
|
| 434 |
+
)
|
| 435 |
+
noise_pred_posi = self.control_noise_via_local_prompts(
|
| 436 |
+
prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback,
|
| 437 |
+
special_kwargs=controlnet_kwargs_posi, special_local_kwargs_list=local_controlnet_kwargs
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
# Inpaint
|
| 441 |
+
if enable_eligen_inpaint:
|
| 442 |
+
noise_pred_posi = self.inpaint_fusion(latents, input_latents, noise_pred_posi, fg_mask, bg_mask, progress_id)
|
| 443 |
+
|
| 444 |
+
# Classifier-free guidance
|
| 445 |
+
if cfg_scale != 1.0:
|
| 446 |
+
# Negative side
|
| 447 |
+
noise_pred_nega = lets_dance_flux(
|
| 448 |
+
dit=self.dit, controlnet=self.controlnet,
|
| 449 |
+
hidden_states=latents, timestep=timestep,
|
| 450 |
+
**prompt_emb_nega, **tiler_kwargs, **extra_input, **controlnet_kwargs_nega, **ipadapter_kwargs_list_nega, **eligen_kwargs_nega,
|
| 451 |
+
)
|
| 452 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 453 |
+
else:
|
| 454 |
+
noise_pred = noise_pred_posi
|
| 455 |
+
|
| 456 |
+
# Iterate
|
| 457 |
+
latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
|
| 458 |
+
|
| 459 |
+
# UI
|
| 460 |
+
if progress_bar_st is not None:
|
| 461 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 462 |
+
|
| 463 |
+
# Decode image
|
| 464 |
+
self.load_models_to_device(['vae_decoder'])
|
| 465 |
+
image = self.decode_image(latents, **tiler_kwargs)
|
| 466 |
+
|
| 467 |
+
# Offload all models
|
| 468 |
+
self.load_models_to_device([])
|
| 469 |
+
return image
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class TeaCache:
|
| 473 |
+
def __init__(self, num_inference_steps, rel_l1_thresh):
|
| 474 |
+
self.num_inference_steps = num_inference_steps
|
| 475 |
+
self.step = 0
|
| 476 |
+
self.accumulated_rel_l1_distance = 0
|
| 477 |
+
self.previous_modulated_input = None
|
| 478 |
+
self.rel_l1_thresh = rel_l1_thresh
|
| 479 |
+
self.previous_residual = None
|
| 480 |
+
self.previous_hidden_states = None
|
| 481 |
+
|
| 482 |
+
def check(self, dit: FluxDiT, hidden_states, conditioning):
|
| 483 |
+
inp = hidden_states.clone()
|
| 484 |
+
temb_ = conditioning.clone()
|
| 485 |
+
modulated_inp, _, _, _, _ = dit.blocks[0].norm1_a(inp, emb=temb_)
|
| 486 |
+
if self.step == 0 or self.step == self.num_inference_steps - 1:
|
| 487 |
+
should_calc = True
|
| 488 |
+
self.accumulated_rel_l1_distance = 0
|
| 489 |
+
else:
|
| 490 |
+
coefficients = [4.98651651e+02, -2.83781631e+02, 5.58554382e+01, -3.82021401e+00, 2.64230861e-01]
|
| 491 |
+
rescale_func = np.poly1d(coefficients)
|
| 492 |
+
self.accumulated_rel_l1_distance += rescale_func(((modulated_inp-self.previous_modulated_input).abs().mean() / self.previous_modulated_input.abs().mean()).cpu().item())
|
| 493 |
+
if self.accumulated_rel_l1_distance < self.rel_l1_thresh:
|
| 494 |
+
should_calc = False
|
| 495 |
+
else:
|
| 496 |
+
should_calc = True
|
| 497 |
+
self.accumulated_rel_l1_distance = 0
|
| 498 |
+
self.previous_modulated_input = modulated_inp
|
| 499 |
+
self.step += 1
|
| 500 |
+
if self.step == self.num_inference_steps:
|
| 501 |
+
self.step = 0
|
| 502 |
+
if should_calc:
|
| 503 |
+
self.previous_hidden_states = hidden_states.clone()
|
| 504 |
+
return not should_calc
|
| 505 |
+
|
| 506 |
+
def store(self, hidden_states):
|
| 507 |
+
self.previous_residual = hidden_states - self.previous_hidden_states
|
| 508 |
+
self.previous_hidden_states = None
|
| 509 |
+
|
| 510 |
+
def update(self, hidden_states):
|
| 511 |
+
hidden_states = hidden_states + self.previous_residual
|
| 512 |
+
return hidden_states
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def lets_dance_flux(
|
| 516 |
+
dit: FluxDiT,
|
| 517 |
+
controlnet: FluxMultiControlNetManager = None,
|
| 518 |
+
hidden_states=None,
|
| 519 |
+
timestep=None,
|
| 520 |
+
prompt_emb=None,
|
| 521 |
+
pooled_prompt_emb=None,
|
| 522 |
+
guidance=None,
|
| 523 |
+
text_ids=None,
|
| 524 |
+
image_ids=None,
|
| 525 |
+
controlnet_frames=None,
|
| 526 |
+
tiled=False,
|
| 527 |
+
tile_size=128,
|
| 528 |
+
tile_stride=64,
|
| 529 |
+
entity_prompt_emb=None,
|
| 530 |
+
entity_masks=None,
|
| 531 |
+
ipadapter_kwargs_list={},
|
| 532 |
+
tea_cache: TeaCache = None,
|
| 533 |
+
**kwargs
|
| 534 |
+
):
|
| 535 |
+
if tiled:
|
| 536 |
+
def flux_forward_fn(hl, hr, wl, wr):
|
| 537 |
+
tiled_controlnet_frames = [f[:, :, hl: hr, wl: wr] for f in controlnet_frames] if controlnet_frames is not None else None
|
| 538 |
+
return lets_dance_flux(
|
| 539 |
+
dit=dit,
|
| 540 |
+
controlnet=controlnet,
|
| 541 |
+
hidden_states=hidden_states[:, :, hl: hr, wl: wr],
|
| 542 |
+
timestep=timestep,
|
| 543 |
+
prompt_emb=prompt_emb,
|
| 544 |
+
pooled_prompt_emb=pooled_prompt_emb,
|
| 545 |
+
guidance=guidance,
|
| 546 |
+
text_ids=text_ids,
|
| 547 |
+
image_ids=None,
|
| 548 |
+
controlnet_frames=tiled_controlnet_frames,
|
| 549 |
+
tiled=False,
|
| 550 |
+
**kwargs
|
| 551 |
+
)
|
| 552 |
+
return FastTileWorker().tiled_forward(
|
| 553 |
+
flux_forward_fn,
|
| 554 |
+
hidden_states,
|
| 555 |
+
tile_size=tile_size,
|
| 556 |
+
tile_stride=tile_stride,
|
| 557 |
+
tile_device=hidden_states.device,
|
| 558 |
+
tile_dtype=hidden_states.dtype
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
# ControlNet
|
| 563 |
+
if controlnet is not None and controlnet_frames is not None:
|
| 564 |
+
controlnet_extra_kwargs = {
|
| 565 |
+
"hidden_states": hidden_states,
|
| 566 |
+
"timestep": timestep,
|
| 567 |
+
"prompt_emb": prompt_emb,
|
| 568 |
+
"pooled_prompt_emb": pooled_prompt_emb,
|
| 569 |
+
"guidance": guidance,
|
| 570 |
+
"text_ids": text_ids,
|
| 571 |
+
"image_ids": image_ids,
|
| 572 |
+
"tiled": tiled,
|
| 573 |
+
"tile_size": tile_size,
|
| 574 |
+
"tile_stride": tile_stride,
|
| 575 |
+
}
|
| 576 |
+
controlnet_res_stack, controlnet_single_res_stack = controlnet(
|
| 577 |
+
controlnet_frames, **controlnet_extra_kwargs
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
if image_ids is None:
|
| 581 |
+
image_ids = dit.prepare_image_ids(hidden_states)
|
| 582 |
+
|
| 583 |
+
conditioning = dit.time_embedder(timestep, hidden_states.dtype) + dit.pooled_text_embedder(pooled_prompt_emb)
|
| 584 |
+
if dit.guidance_embedder is not None:
|
| 585 |
+
guidance = guidance * 1000
|
| 586 |
+
conditioning = conditioning + dit.guidance_embedder(guidance, hidden_states.dtype)
|
| 587 |
+
|
| 588 |
+
height, width = hidden_states.shape[-2:]
|
| 589 |
+
hidden_states = dit.patchify(hidden_states)
|
| 590 |
+
hidden_states = dit.x_embedder(hidden_states)
|
| 591 |
+
|
| 592 |
+
if entity_prompt_emb is not None and entity_masks is not None:
|
| 593 |
+
prompt_emb, image_rotary_emb, attention_mask = dit.process_entity_masks(hidden_states, prompt_emb, entity_prompt_emb, entity_masks, text_ids, image_ids)
|
| 594 |
+
else:
|
| 595 |
+
prompt_emb = dit.context_embedder(prompt_emb)
|
| 596 |
+
image_rotary_emb = dit.pos_embedder(torch.cat((text_ids, image_ids), dim=1))
|
| 597 |
+
attention_mask = None
|
| 598 |
+
|
| 599 |
+
# TeaCache
|
| 600 |
+
if tea_cache is not None:
|
| 601 |
+
tea_cache_update = tea_cache.check(dit, hidden_states, conditioning)
|
| 602 |
+
else:
|
| 603 |
+
tea_cache_update = False
|
| 604 |
+
|
| 605 |
+
if tea_cache_update:
|
| 606 |
+
hidden_states = tea_cache.update(hidden_states)
|
| 607 |
+
else:
|
| 608 |
+
# Joint Blocks
|
| 609 |
+
for block_id, block in enumerate(dit.blocks):
|
| 610 |
+
hidden_states, prompt_emb = block(
|
| 611 |
+
hidden_states,
|
| 612 |
+
prompt_emb,
|
| 613 |
+
conditioning,
|
| 614 |
+
image_rotary_emb,
|
| 615 |
+
attention_mask,
|
| 616 |
+
ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id, None)
|
| 617 |
+
)
|
| 618 |
+
# ControlNet
|
| 619 |
+
if controlnet is not None and controlnet_frames is not None:
|
| 620 |
+
hidden_states = hidden_states + controlnet_res_stack[block_id]
|
| 621 |
+
|
| 622 |
+
# Single Blocks
|
| 623 |
+
hidden_states = torch.cat([prompt_emb, hidden_states], dim=1)
|
| 624 |
+
num_joint_blocks = len(dit.blocks)
|
| 625 |
+
for block_id, block in enumerate(dit.single_blocks):
|
| 626 |
+
hidden_states, prompt_emb = block(
|
| 627 |
+
hidden_states,
|
| 628 |
+
prompt_emb,
|
| 629 |
+
conditioning,
|
| 630 |
+
image_rotary_emb,
|
| 631 |
+
attention_mask,
|
| 632 |
+
ipadapter_kwargs_list=ipadapter_kwargs_list.get(block_id + num_joint_blocks, None)
|
| 633 |
+
)
|
| 634 |
+
# ControlNet
|
| 635 |
+
if controlnet is not None and controlnet_frames is not None:
|
| 636 |
+
hidden_states[:, prompt_emb.shape[1]:] = hidden_states[:, prompt_emb.shape[1]:] + controlnet_single_res_stack[block_id]
|
| 637 |
+
hidden_states = hidden_states[:, prompt_emb.shape[1]:]
|
| 638 |
+
|
| 639 |
+
if tea_cache is not None:
|
| 640 |
+
tea_cache.store(hidden_states)
|
| 641 |
+
|
| 642 |
+
hidden_states = dit.final_norm_out(hidden_states, conditioning)
|
| 643 |
+
hidden_states = dit.final_proj_out(hidden_states)
|
| 644 |
+
hidden_states = dit.unpatchify(hidden_states, height, width)
|
| 645 |
+
|
| 646 |
+
return hidden_states
|
diffsynth/pipelines/hunyuan_image.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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AEEncoder
|
| 4 |
+
from ..models.sdxl_vae_decoder import SDXLVAEDecoder
|
| 5 |
+
from ..models import ModelManager
|
| 6 |
+
from ..prompters import HunyuanDiTPrompter
|
| 7 |
+
from ..schedulers import EnhancedDDIMScheduler
|
| 8 |
+
from .base import BasePipeline
|
| 9 |
+
import torch
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ImageSizeManager:
|
| 16 |
+
def __init__(self):
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _to_tuple(self, x):
|
| 21 |
+
if isinstance(x, int):
|
| 22 |
+
return x, x
|
| 23 |
+
else:
|
| 24 |
+
return x
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_fill_resize_and_crop(self, src, tgt):
|
| 28 |
+
th, tw = self._to_tuple(tgt)
|
| 29 |
+
h, w = self._to_tuple(src)
|
| 30 |
+
|
| 31 |
+
tr = th / tw # base 分辨率
|
| 32 |
+
r = h / w # 目标分辨率
|
| 33 |
+
|
| 34 |
+
# resize
|
| 35 |
+
if r > tr:
|
| 36 |
+
resize_height = th
|
| 37 |
+
resize_width = int(round(th / h * w))
|
| 38 |
+
else:
|
| 39 |
+
resize_width = tw
|
| 40 |
+
resize_height = int(round(tw / w * h)) # 根据base分辨率,将目标分辨率resize下来
|
| 41 |
+
|
| 42 |
+
crop_top = int(round((th - resize_height) / 2.0))
|
| 43 |
+
crop_left = int(round((tw - resize_width) / 2.0))
|
| 44 |
+
|
| 45 |
+
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_meshgrid(self, start, *args):
|
| 49 |
+
if len(args) == 0:
|
| 50 |
+
# start is grid_size
|
| 51 |
+
num = self._to_tuple(start)
|
| 52 |
+
start = (0, 0)
|
| 53 |
+
stop = num
|
| 54 |
+
elif len(args) == 1:
|
| 55 |
+
# start is start, args[0] is stop, step is 1
|
| 56 |
+
start = self._to_tuple(start)
|
| 57 |
+
stop = self._to_tuple(args[0])
|
| 58 |
+
num = (stop[0] - start[0], stop[1] - start[1])
|
| 59 |
+
elif len(args) == 2:
|
| 60 |
+
# start is start, args[0] is stop, args[1] is num
|
| 61 |
+
start = self._to_tuple(start) # 左上角 eg: 12,0
|
| 62 |
+
stop = self._to_tuple(args[0]) # 右下角 eg: 20,32
|
| 63 |
+
num = self._to_tuple(args[1]) # 目标大小 eg: 32,124
|
| 64 |
+
else:
|
| 65 |
+
raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}")
|
| 66 |
+
|
| 67 |
+
grid_h = np.linspace(start[0], stop[0], num[0], endpoint=False, dtype=np.float32) # 12-20 中间差值32份 0-32 中间差值124份
|
| 68 |
+
grid_w = np.linspace(start[1], stop[1], num[1], endpoint=False, dtype=np.float32)
|
| 69 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 70 |
+
grid = np.stack(grid, axis=0) # [2, W, H]
|
| 71 |
+
return grid
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_2d_rotary_pos_embed(self, embed_dim, start, *args, use_real=True):
|
| 75 |
+
grid = self.get_meshgrid(start, *args) # [2, H, w]
|
| 76 |
+
grid = grid.reshape([2, 1, *grid.shape[1:]]) # 返回一个采样矩阵 分辨率与目标分辨率一致
|
| 77 |
+
pos_embed = self.get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=use_real)
|
| 78 |
+
return pos_embed
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_2d_rotary_pos_embed_from_grid(self, embed_dim, grid, use_real=False):
|
| 82 |
+
assert embed_dim % 4 == 0
|
| 83 |
+
|
| 84 |
+
# use half of dimensions to encode grid_h
|
| 85 |
+
emb_h = self.get_1d_rotary_pos_embed(embed_dim // 2, grid[0].reshape(-1), use_real=use_real) # (H*W, D/4)
|
| 86 |
+
emb_w = self.get_1d_rotary_pos_embed(embed_dim // 2, grid[1].reshape(-1), use_real=use_real) # (H*W, D/4)
|
| 87 |
+
|
| 88 |
+
if use_real:
|
| 89 |
+
cos = torch.cat([emb_h[0], emb_w[0]], dim=1) # (H*W, D/2)
|
| 90 |
+
sin = torch.cat([emb_h[1], emb_w[1]], dim=1) # (H*W, D/2)
|
| 91 |
+
return cos, sin
|
| 92 |
+
else:
|
| 93 |
+
emb = torch.cat([emb_h, emb_w], dim=1) # (H*W, D/2)
|
| 94 |
+
return emb
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def get_1d_rotary_pos_embed(self, dim: int, pos, theta: float = 10000.0, use_real=False):
|
| 98 |
+
if isinstance(pos, int):
|
| 99 |
+
pos = np.arange(pos)
|
| 100 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) # [D/2]
|
| 101 |
+
t = torch.from_numpy(pos).to(freqs.device) # type: ignore # [S]
|
| 102 |
+
freqs = torch.outer(t, freqs).float() # type: ignore # [S, D/2]
|
| 103 |
+
if use_real:
|
| 104 |
+
freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]
|
| 105 |
+
freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]
|
| 106 |
+
return freqs_cos, freqs_sin
|
| 107 |
+
else:
|
| 108 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 # [S, D/2]
|
| 109 |
+
return freqs_cis
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def calc_rope(self, height, width):
|
| 113 |
+
patch_size = 2
|
| 114 |
+
head_size = 88
|
| 115 |
+
th = height // 8 // patch_size
|
| 116 |
+
tw = width // 8 // patch_size
|
| 117 |
+
base_size = 512 // 8 // patch_size
|
| 118 |
+
start, stop = self.get_fill_resize_and_crop((th, tw), base_size)
|
| 119 |
+
sub_args = [start, stop, (th, tw)]
|
| 120 |
+
rope = self.get_2d_rotary_pos_embed(head_size, *sub_args)
|
| 121 |
+
return rope
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class HunyuanDiTImagePipeline(BasePipeline):
|
| 126 |
+
|
| 127 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 128 |
+
super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16)
|
| 129 |
+
self.scheduler = EnhancedDDIMScheduler(prediction_type="v_prediction", beta_start=0.00085, beta_end=0.03)
|
| 130 |
+
self.prompter = HunyuanDiTPrompter()
|
| 131 |
+
self.image_size_manager = ImageSizeManager()
|
| 132 |
+
# models
|
| 133 |
+
self.text_encoder: HunyuanDiTCLIPTextEncoder = None
|
| 134 |
+
self.text_encoder_t5: HunyuanDiTT5TextEncoder = None
|
| 135 |
+
self.dit: HunyuanDiT = None
|
| 136 |
+
self.vae_decoder: SDXLVAEDecoder = None
|
| 137 |
+
self.vae_encoder: SDXLVAEEncoder = None
|
| 138 |
+
self.model_names = ['text_encoder', 'text_encoder_t5', 'dit', 'vae_decoder', 'vae_encoder']
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def denoising_model(self):
|
| 142 |
+
return self.dit
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]):
|
| 146 |
+
# Main models
|
| 147 |
+
self.text_encoder = model_manager.fetch_model("hunyuan_dit_clip_text_encoder")
|
| 148 |
+
self.text_encoder_t5 = model_manager.fetch_model("hunyuan_dit_t5_text_encoder")
|
| 149 |
+
self.dit = model_manager.fetch_model("hunyuan_dit")
|
| 150 |
+
self.vae_decoder = model_manager.fetch_model("sdxl_vae_decoder")
|
| 151 |
+
self.vae_encoder = model_manager.fetch_model("sdxl_vae_encoder")
|
| 152 |
+
self.prompter.fetch_models(self.text_encoder, self.text_encoder_t5)
|
| 153 |
+
self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[], device=None):
|
| 158 |
+
pipe = HunyuanDiTImagePipeline(
|
| 159 |
+
device=model_manager.device if device is None else device,
|
| 160 |
+
torch_dtype=model_manager.torch_dtype,
|
| 161 |
+
)
|
| 162 |
+
pipe.fetch_models(model_manager, prompt_refiner_classes)
|
| 163 |
+
return pipe
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32):
|
| 167 |
+
latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 168 |
+
return latents
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32):
|
| 172 |
+
image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 173 |
+
image = self.vae_output_to_image(image)
|
| 174 |
+
return image
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def encode_prompt(self, prompt, clip_skip=1, clip_skip_2=1, positive=True):
|
| 178 |
+
text_emb, text_emb_mask, text_emb_t5, text_emb_mask_t5 = self.prompter.encode_prompt(
|
| 179 |
+
prompt,
|
| 180 |
+
clip_skip=clip_skip,
|
| 181 |
+
clip_skip_2=clip_skip_2,
|
| 182 |
+
positive=positive,
|
| 183 |
+
device=self.device
|
| 184 |
+
)
|
| 185 |
+
return {
|
| 186 |
+
"text_emb": text_emb,
|
| 187 |
+
"text_emb_mask": text_emb_mask,
|
| 188 |
+
"text_emb_t5": text_emb_t5,
|
| 189 |
+
"text_emb_mask_t5": text_emb_mask_t5
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def prepare_extra_input(self, latents=None, tiled=False, tile_size=64, tile_stride=32):
|
| 194 |
+
batch_size, height, width = latents.shape[0], latents.shape[2] * 8, latents.shape[3] * 8
|
| 195 |
+
if tiled:
|
| 196 |
+
height, width = tile_size * 16, tile_size * 16
|
| 197 |
+
image_meta_size = torch.as_tensor([width, height, width, height, 0, 0]).to(device=self.device)
|
| 198 |
+
freqs_cis_img = self.image_size_manager.calc_rope(height, width)
|
| 199 |
+
image_meta_size = torch.stack([image_meta_size] * batch_size)
|
| 200 |
+
return {
|
| 201 |
+
"size_emb": image_meta_size,
|
| 202 |
+
"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)),
|
| 203 |
+
"tiled": tiled,
|
| 204 |
+
"tile_size": tile_size,
|
| 205 |
+
"tile_stride": tile_stride
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@torch.no_grad()
|
| 210 |
+
def __call__(
|
| 211 |
+
self,
|
| 212 |
+
prompt,
|
| 213 |
+
local_prompts=[],
|
| 214 |
+
masks=[],
|
| 215 |
+
mask_scales=[],
|
| 216 |
+
negative_prompt="",
|
| 217 |
+
cfg_scale=7.5,
|
| 218 |
+
clip_skip=1,
|
| 219 |
+
clip_skip_2=1,
|
| 220 |
+
input_image=None,
|
| 221 |
+
reference_strengths=[0.4],
|
| 222 |
+
denoising_strength=1.0,
|
| 223 |
+
height=1024,
|
| 224 |
+
width=1024,
|
| 225 |
+
num_inference_steps=20,
|
| 226 |
+
tiled=False,
|
| 227 |
+
tile_size=64,
|
| 228 |
+
tile_stride=32,
|
| 229 |
+
seed=None,
|
| 230 |
+
progress_bar_cmd=tqdm,
|
| 231 |
+
progress_bar_st=None,
|
| 232 |
+
):
|
| 233 |
+
height, width = self.check_resize_height_width(height, width)
|
| 234 |
+
|
| 235 |
+
# Prepare scheduler
|
| 236 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 237 |
+
|
| 238 |
+
# Prepare latent tensors
|
| 239 |
+
noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 240 |
+
if input_image is not None:
|
| 241 |
+
self.load_models_to_device(['vae_encoder'])
|
| 242 |
+
image = self.preprocess_image(input_image).to(device=self.device, dtype=torch.float32)
|
| 243 |
+
latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(self.torch_dtype)
|
| 244 |
+
latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
|
| 245 |
+
else:
|
| 246 |
+
latents = noise.clone()
|
| 247 |
+
|
| 248 |
+
# Encode prompts
|
| 249 |
+
self.load_models_to_device(['text_encoder', 'text_encoder_t5'])
|
| 250 |
+
prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, clip_skip_2=clip_skip_2, positive=True)
|
| 251 |
+
if cfg_scale != 1.0:
|
| 252 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, clip_skip_2=clip_skip_2, positive=True)
|
| 253 |
+
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]
|
| 254 |
+
|
| 255 |
+
# Prepare positional id
|
| 256 |
+
extra_input = self.prepare_extra_input(latents, tiled, tile_size)
|
| 257 |
+
|
| 258 |
+
# Denoise
|
| 259 |
+
self.load_models_to_device(['dit'])
|
| 260 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 261 |
+
timestep = torch.tensor([timestep]).to(dtype=self.torch_dtype, device=self.device)
|
| 262 |
+
|
| 263 |
+
# Positive side
|
| 264 |
+
inference_callback = lambda prompt_emb_posi: self.dit(latents, timestep=timestep, **prompt_emb_posi, **extra_input)
|
| 265 |
+
noise_pred_posi = self.control_noise_via_local_prompts(prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback)
|
| 266 |
+
|
| 267 |
+
if cfg_scale != 1.0:
|
| 268 |
+
# Negative side
|
| 269 |
+
noise_pred_nega = self.dit(
|
| 270 |
+
latents, timestep=timestep, **prompt_emb_nega, **extra_input,
|
| 271 |
+
)
|
| 272 |
+
# Classifier-free guidance
|
| 273 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 274 |
+
else:
|
| 275 |
+
noise_pred = noise_pred_posi
|
| 276 |
+
|
| 277 |
+
latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
|
| 278 |
+
|
| 279 |
+
if progress_bar_st is not None:
|
| 280 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 281 |
+
|
| 282 |
+
# Decode image
|
| 283 |
+
self.load_models_to_device(['vae_decoder'])
|
| 284 |
+
image = self.decode_image(latents.to(torch.float32), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 285 |
+
|
| 286 |
+
# Offload all models
|
| 287 |
+
self.load_models_to_device([])
|
| 288 |
+
return image
|
diffsynth/pipelines/hunyuan_video.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models import ModelManager, SD3TextEncoder1, HunyuanVideoVAEDecoder, HunyuanVideoVAEEncoder
|
| 2 |
+
from ..models.hunyuan_video_dit import HunyuanVideoDiT
|
| 3 |
+
from ..models.hunyuan_video_text_encoder import HunyuanVideoLLMEncoder
|
| 4 |
+
from ..schedulers.flow_match import FlowMatchScheduler
|
| 5 |
+
from .base import BasePipeline
|
| 6 |
+
from ..prompters import HunyuanVideoPrompter
|
| 7 |
+
import torch
|
| 8 |
+
import torchvision.transforms as transforms
|
| 9 |
+
from einops import rearrange
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class HunyuanVideoPipeline(BasePipeline):
|
| 16 |
+
|
| 17 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 18 |
+
super().__init__(device=device, torch_dtype=torch_dtype)
|
| 19 |
+
self.scheduler = FlowMatchScheduler(shift=7.0, sigma_min=0.0, extra_one_step=True)
|
| 20 |
+
self.prompter = HunyuanVideoPrompter()
|
| 21 |
+
self.text_encoder_1: SD3TextEncoder1 = None
|
| 22 |
+
self.text_encoder_2: HunyuanVideoLLMEncoder = None
|
| 23 |
+
self.dit: HunyuanVideoDiT = None
|
| 24 |
+
self.vae_decoder: HunyuanVideoVAEDecoder = None
|
| 25 |
+
self.vae_encoder: HunyuanVideoVAEEncoder = None
|
| 26 |
+
self.model_names = ['text_encoder_1', 'text_encoder_2', 'dit', 'vae_decoder', 'vae_encoder']
|
| 27 |
+
self.vram_management = False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def enable_vram_management(self):
|
| 31 |
+
self.vram_management = True
|
| 32 |
+
self.enable_cpu_offload()
|
| 33 |
+
self.text_encoder_2.enable_auto_offload(dtype=self.torch_dtype, device=self.device)
|
| 34 |
+
self.dit.enable_auto_offload(dtype=self.torch_dtype, device=self.device)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fetch_models(self, model_manager: ModelManager):
|
| 38 |
+
self.text_encoder_1 = model_manager.fetch_model("sd3_text_encoder_1")
|
| 39 |
+
self.text_encoder_2 = model_manager.fetch_model("hunyuan_video_text_encoder_2")
|
| 40 |
+
self.dit = model_manager.fetch_model("hunyuan_video_dit")
|
| 41 |
+
self.vae_decoder = model_manager.fetch_model("hunyuan_video_vae_decoder")
|
| 42 |
+
self.vae_encoder = model_manager.fetch_model("hunyuan_video_vae_encoder")
|
| 43 |
+
self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
def from_model_manager(model_manager: ModelManager, torch_dtype=None, device=None, enable_vram_management=True):
|
| 48 |
+
if device is None: device = model_manager.device
|
| 49 |
+
if torch_dtype is None: torch_dtype = model_manager.torch_dtype
|
| 50 |
+
pipe = HunyuanVideoPipeline(device=device, torch_dtype=torch_dtype)
|
| 51 |
+
pipe.fetch_models(model_manager)
|
| 52 |
+
if enable_vram_management:
|
| 53 |
+
pipe.enable_vram_management()
|
| 54 |
+
return pipe
|
| 55 |
+
|
| 56 |
+
def generate_crop_size_list(self, base_size=256, patch_size=32, max_ratio=4.0):
|
| 57 |
+
num_patches = round((base_size / patch_size)**2)
|
| 58 |
+
assert max_ratio >= 1.0
|
| 59 |
+
crop_size_list = []
|
| 60 |
+
wp, hp = num_patches, 1
|
| 61 |
+
while wp > 0:
|
| 62 |
+
if max(wp, hp) / min(wp, hp) <= max_ratio:
|
| 63 |
+
crop_size_list.append((wp * patch_size, hp * patch_size))
|
| 64 |
+
if (hp + 1) * wp <= num_patches:
|
| 65 |
+
hp += 1
|
| 66 |
+
else:
|
| 67 |
+
wp -= 1
|
| 68 |
+
return crop_size_list
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_closest_ratio(self, height: float, width: float, ratios: list, buckets: list):
|
| 72 |
+
aspect_ratio = float(height) / float(width)
|
| 73 |
+
closest_ratio_id = np.abs(ratios - aspect_ratio).argmin()
|
| 74 |
+
closest_ratio = min(ratios, key=lambda ratio: abs(float(ratio) - aspect_ratio))
|
| 75 |
+
return buckets[closest_ratio_id], float(closest_ratio)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def prepare_vae_images_inputs(self, semantic_images, i2v_resolution="720p"):
|
| 79 |
+
if i2v_resolution == "720p":
|
| 80 |
+
bucket_hw_base_size = 960
|
| 81 |
+
elif i2v_resolution == "540p":
|
| 82 |
+
bucket_hw_base_size = 720
|
| 83 |
+
elif i2v_resolution == "360p":
|
| 84 |
+
bucket_hw_base_size = 480
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError(f"i2v_resolution: {i2v_resolution} must be in [360p, 540p, 720p]")
|
| 87 |
+
origin_size = semantic_images[0].size
|
| 88 |
+
|
| 89 |
+
crop_size_list = self.generate_crop_size_list(bucket_hw_base_size, 32)
|
| 90 |
+
aspect_ratios = np.array([round(float(h) / float(w), 5) for h, w in crop_size_list])
|
| 91 |
+
closest_size, closest_ratio = self.get_closest_ratio(origin_size[1], origin_size[0], aspect_ratios, crop_size_list)
|
| 92 |
+
ref_image_transform = transforms.Compose([
|
| 93 |
+
transforms.Resize(closest_size),
|
| 94 |
+
transforms.CenterCrop(closest_size),
|
| 95 |
+
transforms.ToTensor(),
|
| 96 |
+
transforms.Normalize([0.5], [0.5])
|
| 97 |
+
])
|
| 98 |
+
|
| 99 |
+
semantic_image_pixel_values = [ref_image_transform(semantic_image) for semantic_image in semantic_images]
|
| 100 |
+
semantic_image_pixel_values = torch.cat(semantic_image_pixel_values).unsqueeze(0).unsqueeze(2).to(self.device)
|
| 101 |
+
target_height, target_width = closest_size
|
| 102 |
+
return semantic_image_pixel_values, target_height, target_width
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def encode_prompt(self, prompt, positive=True, clip_sequence_length=77, llm_sequence_length=256, input_images=None):
|
| 106 |
+
prompt_emb, pooled_prompt_emb, text_mask = self.prompter.encode_prompt(
|
| 107 |
+
prompt, device=self.device, positive=positive, clip_sequence_length=clip_sequence_length, llm_sequence_length=llm_sequence_length, images=input_images
|
| 108 |
+
)
|
| 109 |
+
return {"prompt_emb": prompt_emb, "pooled_prompt_emb": pooled_prompt_emb, "text_mask": text_mask}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def prepare_extra_input(self, latents=None, guidance=1.0):
|
| 113 |
+
freqs_cos, freqs_sin = self.dit.prepare_freqs(latents)
|
| 114 |
+
guidance = torch.Tensor([guidance] * latents.shape[0]).to(device=latents.device, dtype=latents.dtype)
|
| 115 |
+
return {"freqs_cos": freqs_cos, "freqs_sin": freqs_sin, "guidance": guidance}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def tensor2video(self, frames):
|
| 119 |
+
frames = rearrange(frames, "C T H W -> T H W C")
|
| 120 |
+
frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8)
|
| 121 |
+
frames = [Image.fromarray(frame) for frame in frames]
|
| 122 |
+
return frames
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def encode_video(self, frames, tile_size=(17, 30, 30), tile_stride=(12, 20, 20)):
|
| 126 |
+
tile_size = ((tile_size[0] - 1) * 4 + 1, tile_size[1] * 8, tile_size[2] * 8)
|
| 127 |
+
tile_stride = (tile_stride[0] * 4, tile_stride[1] * 8, tile_stride[2] * 8)
|
| 128 |
+
latents = self.vae_encoder.encode_video(frames, tile_size=tile_size, tile_stride=tile_stride)
|
| 129 |
+
return latents
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@torch.no_grad()
|
| 133 |
+
def __call__(
|
| 134 |
+
self,
|
| 135 |
+
prompt,
|
| 136 |
+
negative_prompt="",
|
| 137 |
+
input_video=None,
|
| 138 |
+
input_images=None,
|
| 139 |
+
i2v_resolution="720p",
|
| 140 |
+
i2v_stability=True,
|
| 141 |
+
denoising_strength=1.0,
|
| 142 |
+
seed=None,
|
| 143 |
+
rand_device=None,
|
| 144 |
+
height=720,
|
| 145 |
+
width=1280,
|
| 146 |
+
num_frames=129,
|
| 147 |
+
embedded_guidance=6.0,
|
| 148 |
+
cfg_scale=1.0,
|
| 149 |
+
num_inference_steps=30,
|
| 150 |
+
tea_cache_l1_thresh=None,
|
| 151 |
+
tile_size=(17, 30, 30),
|
| 152 |
+
tile_stride=(12, 20, 20),
|
| 153 |
+
step_processor=None,
|
| 154 |
+
progress_bar_cmd=lambda x: x,
|
| 155 |
+
progress_bar_st=None,
|
| 156 |
+
):
|
| 157 |
+
# Tiler parameters
|
| 158 |
+
tiler_kwargs = {"tile_size": tile_size, "tile_stride": tile_stride}
|
| 159 |
+
|
| 160 |
+
# Scheduler
|
| 161 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 162 |
+
|
| 163 |
+
# encoder input images
|
| 164 |
+
if input_images is not None:
|
| 165 |
+
self.load_models_to_device(['vae_encoder'])
|
| 166 |
+
image_pixel_values, height, width = self.prepare_vae_images_inputs(input_images, i2v_resolution=i2v_resolution)
|
| 167 |
+
with torch.autocast(device_type=self.device, dtype=torch.float16, enabled=True):
|
| 168 |
+
image_latents = self.vae_encoder(image_pixel_values)
|
| 169 |
+
|
| 170 |
+
# Initialize noise
|
| 171 |
+
rand_device = self.device if rand_device is None else rand_device
|
| 172 |
+
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)
|
| 173 |
+
if input_video is not None:
|
| 174 |
+
self.load_models_to_device(['vae_encoder'])
|
| 175 |
+
input_video = self.preprocess_images(input_video)
|
| 176 |
+
input_video = torch.stack(input_video, dim=2)
|
| 177 |
+
latents = self.encode_video(input_video, **tiler_kwargs).to(dtype=self.torch_dtype, device=self.device)
|
| 178 |
+
latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
|
| 179 |
+
elif input_images is not None and i2v_stability:
|
| 180 |
+
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)
|
| 181 |
+
t = torch.tensor([0.999]).to(device=self.device)
|
| 182 |
+
latents = noise * t + image_latents.repeat(1, 1, (num_frames - 1) // 4 + 1, 1, 1) * (1 - t)
|
| 183 |
+
latents = latents.to(dtype=image_latents.dtype)
|
| 184 |
+
else:
|
| 185 |
+
latents = noise
|
| 186 |
+
|
| 187 |
+
# Encode prompts
|
| 188 |
+
# current mllm does not support vram_management
|
| 189 |
+
self.load_models_to_device(["text_encoder_1"] if self.vram_management and input_images is None else ["text_encoder_1", "text_encoder_2"])
|
| 190 |
+
prompt_emb_posi = self.encode_prompt(prompt, positive=True, input_images=input_images)
|
| 191 |
+
if cfg_scale != 1.0:
|
| 192 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False)
|
| 193 |
+
|
| 194 |
+
# Extra input
|
| 195 |
+
extra_input = self.prepare_extra_input(latents, guidance=embedded_guidance)
|
| 196 |
+
|
| 197 |
+
# TeaCache
|
| 198 |
+
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}
|
| 199 |
+
|
| 200 |
+
# Denoise
|
| 201 |
+
self.load_models_to_device([] if self.vram_management else ["dit"])
|
| 202 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 203 |
+
timestep = timestep.unsqueeze(0).to(self.device)
|
| 204 |
+
print(f"Step {progress_id + 1} / {len(self.scheduler.timesteps)}")
|
| 205 |
+
|
| 206 |
+
forward_func = lets_dance_hunyuan_video
|
| 207 |
+
if input_images is not None:
|
| 208 |
+
latents = torch.concat([image_latents, latents[:, :, 1:, :, :]], dim=2)
|
| 209 |
+
forward_func = lets_dance_hunyuan_video_i2v
|
| 210 |
+
|
| 211 |
+
# Inference
|
| 212 |
+
with torch.autocast(device_type=self.device, dtype=self.torch_dtype):
|
| 213 |
+
noise_pred_posi = forward_func(self.dit, latents, timestep, **prompt_emb_posi, **extra_input, **tea_cache_kwargs)
|
| 214 |
+
if cfg_scale != 1.0:
|
| 215 |
+
noise_pred_nega = forward_func(self.dit, latents, timestep, **prompt_emb_nega, **extra_input)
|
| 216 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 217 |
+
else:
|
| 218 |
+
noise_pred = noise_pred_posi
|
| 219 |
+
|
| 220 |
+
# (Experimental feature, may be removed in the future)
|
| 221 |
+
if step_processor is not None:
|
| 222 |
+
self.load_models_to_device(['vae_decoder'])
|
| 223 |
+
rendered_frames = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents, to_final=True)
|
| 224 |
+
rendered_frames = self.vae_decoder.decode_video(rendered_frames, **tiler_kwargs)
|
| 225 |
+
rendered_frames = self.tensor2video(rendered_frames[0])
|
| 226 |
+
rendered_frames = step_processor(rendered_frames, original_frames=input_video)
|
| 227 |
+
self.load_models_to_device(['vae_encoder'])
|
| 228 |
+
rendered_frames = self.preprocess_images(rendered_frames)
|
| 229 |
+
rendered_frames = torch.stack(rendered_frames, dim=2)
|
| 230 |
+
target_latents = self.encode_video(rendered_frames).to(dtype=self.torch_dtype, device=self.device)
|
| 231 |
+
noise_pred = self.scheduler.return_to_timestep(self.scheduler.timesteps[progress_id], latents, target_latents)
|
| 232 |
+
self.load_models_to_device([] if self.vram_management else ["dit"])
|
| 233 |
+
|
| 234 |
+
# Scheduler
|
| 235 |
+
if input_images is not None:
|
| 236 |
+
latents = self.scheduler.step(noise_pred[:, :, 1:, :, :], self.scheduler.timesteps[progress_id], latents[:, :, 1:, :, :])
|
| 237 |
+
latents = torch.concat([image_latents, latents], dim=2)
|
| 238 |
+
else:
|
| 239 |
+
latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
|
| 240 |
+
|
| 241 |
+
# Decode
|
| 242 |
+
self.load_models_to_device(['vae_decoder'])
|
| 243 |
+
frames = self.vae_decoder.decode_video(latents, **tiler_kwargs)
|
| 244 |
+
self.load_models_to_device([])
|
| 245 |
+
frames = self.tensor2video(frames[0])
|
| 246 |
+
|
| 247 |
+
return frames
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class TeaCache:
|
| 252 |
+
def __init__(self, num_inference_steps, rel_l1_thresh):
|
| 253 |
+
self.num_inference_steps = num_inference_steps
|
| 254 |
+
self.step = 0
|
| 255 |
+
self.accumulated_rel_l1_distance = 0
|
| 256 |
+
self.previous_modulated_input = None
|
| 257 |
+
self.rel_l1_thresh = rel_l1_thresh
|
| 258 |
+
self.previous_residual = None
|
| 259 |
+
self.previous_hidden_states = None
|
| 260 |
+
|
| 261 |
+
def check(self, dit: HunyuanVideoDiT, img, vec):
|
| 262 |
+
img_ = img.clone()
|
| 263 |
+
vec_ = vec.clone()
|
| 264 |
+
img_mod1_shift, img_mod1_scale, _, _, _, _ = dit.double_blocks[0].component_a.mod(vec_).chunk(6, dim=-1)
|
| 265 |
+
normed_inp = dit.double_blocks[0].component_a.norm1(img_)
|
| 266 |
+
modulated_inp = normed_inp * (1 + img_mod1_scale.unsqueeze(1)) + img_mod1_shift.unsqueeze(1)
|
| 267 |
+
if self.step == 0 or self.step == self.num_inference_steps - 1:
|
| 268 |
+
should_calc = True
|
| 269 |
+
self.accumulated_rel_l1_distance = 0
|
| 270 |
+
else:
|
| 271 |
+
coefficients = [7.33226126e+02, -4.01131952e+02, 6.75869174e+01, -3.14987800e+00, 9.61237896e-02]
|
| 272 |
+
rescale_func = np.poly1d(coefficients)
|
| 273 |
+
self.accumulated_rel_l1_distance += rescale_func(((modulated_inp-self.previous_modulated_input).abs().mean() / self.previous_modulated_input.abs().mean()).cpu().item())
|
| 274 |
+
if self.accumulated_rel_l1_distance < self.rel_l1_thresh:
|
| 275 |
+
should_calc = False
|
| 276 |
+
else:
|
| 277 |
+
should_calc = True
|
| 278 |
+
self.accumulated_rel_l1_distance = 0
|
| 279 |
+
self.previous_modulated_input = modulated_inp
|
| 280 |
+
self.step += 1
|
| 281 |
+
if self.step == self.num_inference_steps:
|
| 282 |
+
self.step = 0
|
| 283 |
+
if should_calc:
|
| 284 |
+
self.previous_hidden_states = img.clone()
|
| 285 |
+
return not should_calc
|
| 286 |
+
|
| 287 |
+
def store(self, hidden_states):
|
| 288 |
+
self.previous_residual = hidden_states - self.previous_hidden_states
|
| 289 |
+
self.previous_hidden_states = None
|
| 290 |
+
|
| 291 |
+
def update(self, hidden_states):
|
| 292 |
+
hidden_states = hidden_states + self.previous_residual
|
| 293 |
+
return hidden_states
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def lets_dance_hunyuan_video(
|
| 298 |
+
dit: HunyuanVideoDiT,
|
| 299 |
+
x: torch.Tensor,
|
| 300 |
+
t: torch.Tensor,
|
| 301 |
+
prompt_emb: torch.Tensor = None,
|
| 302 |
+
text_mask: torch.Tensor = None,
|
| 303 |
+
pooled_prompt_emb: torch.Tensor = None,
|
| 304 |
+
freqs_cos: torch.Tensor = None,
|
| 305 |
+
freqs_sin: torch.Tensor = None,
|
| 306 |
+
guidance: torch.Tensor = None,
|
| 307 |
+
tea_cache: TeaCache = None,
|
| 308 |
+
**kwargs
|
| 309 |
+
):
|
| 310 |
+
B, C, T, H, W = x.shape
|
| 311 |
+
|
| 312 |
+
vec = dit.time_in(t, dtype=torch.float32) + dit.vector_in(pooled_prompt_emb) + dit.guidance_in(guidance * 1000, dtype=torch.float32)
|
| 313 |
+
img = dit.img_in(x)
|
| 314 |
+
txt = dit.txt_in(prompt_emb, t, text_mask)
|
| 315 |
+
|
| 316 |
+
# TeaCache
|
| 317 |
+
if tea_cache is not None:
|
| 318 |
+
tea_cache_update = tea_cache.check(dit, img, vec)
|
| 319 |
+
else:
|
| 320 |
+
tea_cache_update = False
|
| 321 |
+
|
| 322 |
+
if tea_cache_update:
|
| 323 |
+
print("TeaCache skip forward.")
|
| 324 |
+
img = tea_cache.update(img)
|
| 325 |
+
else:
|
| 326 |
+
split_token = int(text_mask.sum(dim=1))
|
| 327 |
+
txt_len = int(txt.shape[1])
|
| 328 |
+
for block in tqdm(dit.double_blocks, desc="Double stream blocks"):
|
| 329 |
+
img, txt = block(img, txt, vec, (freqs_cos, freqs_sin), split_token=split_token)
|
| 330 |
+
|
| 331 |
+
x = torch.concat([img, txt], dim=1)
|
| 332 |
+
for block in tqdm(dit.single_blocks, desc="Single stream blocks"):
|
| 333 |
+
x = block(x, vec, (freqs_cos, freqs_sin), txt_len=txt_len, split_token=split_token)
|
| 334 |
+
img = x[:, :-txt_len]
|
| 335 |
+
|
| 336 |
+
if tea_cache is not None:
|
| 337 |
+
tea_cache.store(img)
|
| 338 |
+
img = dit.final_layer(img, vec)
|
| 339 |
+
img = dit.unpatchify(img, T=T//1, H=H//2, W=W//2)
|
| 340 |
+
return img
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def lets_dance_hunyuan_video_i2v(
|
| 344 |
+
dit: HunyuanVideoDiT,
|
| 345 |
+
x: torch.Tensor,
|
| 346 |
+
t: torch.Tensor,
|
| 347 |
+
prompt_emb: torch.Tensor = None,
|
| 348 |
+
text_mask: torch.Tensor = None,
|
| 349 |
+
pooled_prompt_emb: torch.Tensor = None,
|
| 350 |
+
freqs_cos: torch.Tensor = None,
|
| 351 |
+
freqs_sin: torch.Tensor = None,
|
| 352 |
+
guidance: torch.Tensor = None,
|
| 353 |
+
tea_cache: TeaCache = None,
|
| 354 |
+
**kwargs
|
| 355 |
+
):
|
| 356 |
+
B, C, T, H, W = x.shape
|
| 357 |
+
# Uncomment below to keep same as official implementation
|
| 358 |
+
# guidance = guidance.to(dtype=torch.float32).to(torch.bfloat16)
|
| 359 |
+
vec = dit.time_in(t, dtype=torch.bfloat16)
|
| 360 |
+
vec_2 = dit.vector_in(pooled_prompt_emb)
|
| 361 |
+
vec = vec + vec_2
|
| 362 |
+
vec = vec + dit.guidance_in(guidance * 1000., dtype=torch.bfloat16)
|
| 363 |
+
|
| 364 |
+
token_replace_vec = dit.time_in(torch.zeros_like(t), dtype=torch.bfloat16)
|
| 365 |
+
tr_token = (H // 2) * (W // 2)
|
| 366 |
+
token_replace_vec = token_replace_vec + vec_2
|
| 367 |
+
|
| 368 |
+
img = dit.img_in(x)
|
| 369 |
+
txt = dit.txt_in(prompt_emb, t, text_mask)
|
| 370 |
+
|
| 371 |
+
# TeaCache
|
| 372 |
+
if tea_cache is not None:
|
| 373 |
+
tea_cache_update = tea_cache.check(dit, img, vec)
|
| 374 |
+
else:
|
| 375 |
+
tea_cache_update = False
|
| 376 |
+
|
| 377 |
+
if tea_cache_update:
|
| 378 |
+
print("TeaCache skip forward.")
|
| 379 |
+
img = tea_cache.update(img)
|
| 380 |
+
else:
|
| 381 |
+
split_token = int(text_mask.sum(dim=1))
|
| 382 |
+
txt_len = int(txt.shape[1])
|
| 383 |
+
for block in tqdm(dit.double_blocks, desc="Double stream blocks"):
|
| 384 |
+
img, txt = block(img, txt, vec, (freqs_cos, freqs_sin), token_replace_vec, tr_token, split_token)
|
| 385 |
+
|
| 386 |
+
x = torch.concat([img, txt], dim=1)
|
| 387 |
+
for block in tqdm(dit.single_blocks, desc="Single stream blocks"):
|
| 388 |
+
x = block(x, vec, (freqs_cos, freqs_sin), txt_len, token_replace_vec, tr_token, split_token)
|
| 389 |
+
img = x[:, :-txt_len]
|
| 390 |
+
|
| 391 |
+
if tea_cache is not None:
|
| 392 |
+
tea_cache.store(img)
|
| 393 |
+
img = dit.final_layer(img, vec)
|
| 394 |
+
img = dit.unpatchify(img, T=T//1, H=H//2, W=W//2)
|
| 395 |
+
return img
|
diffsynth/pipelines/omnigen_image.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models.omnigen import OmniGenTransformer
|
| 2 |
+
from ..models.sdxl_vae_encoder import SDXLVAEEncoder
|
| 3 |
+
from ..models.sdxl_vae_decoder import SDXLVAEDecoder
|
| 4 |
+
from ..models.model_manager import ModelManager
|
| 5 |
+
from ..prompters.omnigen_prompter import OmniGenPrompter
|
| 6 |
+
from ..schedulers import FlowMatchScheduler
|
| 7 |
+
from .base import BasePipeline
|
| 8 |
+
from typing import Optional, Dict, Any, Tuple, List
|
| 9 |
+
from transformers.cache_utils import DynamicCache
|
| 10 |
+
import torch, os
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class OmniGenCache(DynamicCache):
|
| 16 |
+
def __init__(self,
|
| 17 |
+
num_tokens_for_img: int, offload_kv_cache: bool=False) -> None:
|
| 18 |
+
if not torch.cuda.is_available():
|
| 19 |
+
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!!!")
|
| 20 |
+
offload_kv_cache = False
|
| 21 |
+
raise RuntimeError("OffloadedCache can only be used with a GPU")
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.original_device = []
|
| 24 |
+
self.prefetch_stream = torch.cuda.Stream()
|
| 25 |
+
self.num_tokens_for_img = num_tokens_for_img
|
| 26 |
+
self.offload_kv_cache = offload_kv_cache
|
| 27 |
+
|
| 28 |
+
def prefetch_layer(self, layer_idx: int):
|
| 29 |
+
"Starts prefetching the next layer cache"
|
| 30 |
+
if layer_idx < len(self):
|
| 31 |
+
with torch.cuda.stream(self.prefetch_stream):
|
| 32 |
+
# Prefetch next layer tensors to GPU
|
| 33 |
+
device = self.original_device[layer_idx]
|
| 34 |
+
self.key_cache[layer_idx] = self.key_cache[layer_idx].to(device, non_blocking=True)
|
| 35 |
+
self.value_cache[layer_idx] = self.value_cache[layer_idx].to(device, non_blocking=True)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def evict_previous_layer(self, layer_idx: int):
|
| 39 |
+
"Moves the previous layer cache to the CPU"
|
| 40 |
+
if len(self) > 2:
|
| 41 |
+
# We do it on the default stream so it occurs after all earlier computations on these tensors are done
|
| 42 |
+
if layer_idx == 0:
|
| 43 |
+
prev_layer_idx = -1
|
| 44 |
+
else:
|
| 45 |
+
prev_layer_idx = (layer_idx - 1) % len(self)
|
| 46 |
+
self.key_cache[prev_layer_idx] = self.key_cache[prev_layer_idx].to("cpu", non_blocking=True)
|
| 47 |
+
self.value_cache[prev_layer_idx] = self.value_cache[prev_layer_idx].to("cpu", non_blocking=True)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def __getitem__(self, layer_idx: int) -> List[Tuple[torch.Tensor]]:
|
| 51 |
+
"Gets the cache for this layer to the device. Prefetches the next and evicts the previous layer."
|
| 52 |
+
if layer_idx < len(self):
|
| 53 |
+
if self.offload_kv_cache:
|
| 54 |
+
# Evict the previous layer if necessary
|
| 55 |
+
torch.cuda.current_stream().synchronize()
|
| 56 |
+
self.evict_previous_layer(layer_idx)
|
| 57 |
+
# Load current layer cache to its original device if not already there
|
| 58 |
+
original_device = self.original_device[layer_idx]
|
| 59 |
+
# self.prefetch_stream.synchronize(original_device)
|
| 60 |
+
torch.cuda.synchronize(self.prefetch_stream)
|
| 61 |
+
key_tensor = self.key_cache[layer_idx]
|
| 62 |
+
value_tensor = self.value_cache[layer_idx]
|
| 63 |
+
|
| 64 |
+
# Prefetch the next layer
|
| 65 |
+
self.prefetch_layer((layer_idx + 1) % len(self))
|
| 66 |
+
else:
|
| 67 |
+
key_tensor = self.key_cache[layer_idx]
|
| 68 |
+
value_tensor = self.value_cache[layer_idx]
|
| 69 |
+
return (key_tensor, value_tensor)
|
| 70 |
+
else:
|
| 71 |
+
raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def update(
|
| 75 |
+
self,
|
| 76 |
+
key_states: torch.Tensor,
|
| 77 |
+
value_states: torch.Tensor,
|
| 78 |
+
layer_idx: int,
|
| 79 |
+
cache_kwargs: Optional[Dict[str, Any]] = None,
|
| 80 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 81 |
+
"""
|
| 82 |
+
Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
|
| 83 |
+
Parameters:
|
| 84 |
+
key_states (`torch.Tensor`):
|
| 85 |
+
The new key states to cache.
|
| 86 |
+
value_states (`torch.Tensor`):
|
| 87 |
+
The new value states to cache.
|
| 88 |
+
layer_idx (`int`):
|
| 89 |
+
The index of the layer to cache the states for.
|
| 90 |
+
cache_kwargs (`Dict[str, Any]`, `optional`):
|
| 91 |
+
Additional arguments for the cache subclass. No additional arguments are used in `OffloadedCache`.
|
| 92 |
+
Return:
|
| 93 |
+
A tuple containing the updated key and value states.
|
| 94 |
+
"""
|
| 95 |
+
# Update the cache
|
| 96 |
+
if len(self.key_cache) < layer_idx:
|
| 97 |
+
raise ValueError("OffloadedCache does not support model usage where layers are skipped. Use DynamicCache.")
|
| 98 |
+
elif len(self.key_cache) == layer_idx:
|
| 99 |
+
# only cache the states for condition tokens
|
| 100 |
+
key_states = key_states[..., :-(self.num_tokens_for_img+1), :]
|
| 101 |
+
value_states = value_states[..., :-(self.num_tokens_for_img+1), :]
|
| 102 |
+
|
| 103 |
+
# Update the number of seen tokens
|
| 104 |
+
if layer_idx == 0:
|
| 105 |
+
self._seen_tokens += key_states.shape[-2]
|
| 106 |
+
|
| 107 |
+
self.key_cache.append(key_states)
|
| 108 |
+
self.value_cache.append(value_states)
|
| 109 |
+
self.original_device.append(key_states.device)
|
| 110 |
+
if self.offload_kv_cache:
|
| 111 |
+
self.evict_previous_layer(layer_idx)
|
| 112 |
+
return self.key_cache[layer_idx], self.value_cache[layer_idx]
|
| 113 |
+
else:
|
| 114 |
+
# only cache the states for condition tokens
|
| 115 |
+
key_tensor, value_tensor = self[layer_idx]
|
| 116 |
+
k = torch.cat([key_tensor, key_states], dim=-2)
|
| 117 |
+
v = torch.cat([value_tensor, value_states], dim=-2)
|
| 118 |
+
return k, v
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class OmnigenImagePipeline(BasePipeline):
|
| 123 |
+
|
| 124 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 125 |
+
super().__init__(device=device, torch_dtype=torch_dtype)
|
| 126 |
+
self.scheduler = FlowMatchScheduler(num_train_timesteps=1, shift=1, inverse_timesteps=True, sigma_min=0, sigma_max=1)
|
| 127 |
+
# models
|
| 128 |
+
self.vae_decoder: SDXLVAEDecoder = None
|
| 129 |
+
self.vae_encoder: SDXLVAEEncoder = None
|
| 130 |
+
self.transformer: OmniGenTransformer = None
|
| 131 |
+
self.prompter: OmniGenPrompter = None
|
| 132 |
+
self.model_names = ['transformer', 'vae_decoder', 'vae_encoder']
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def denoising_model(self):
|
| 136 |
+
return self.transformer
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]):
|
| 140 |
+
# Main models
|
| 141 |
+
self.transformer, model_path = model_manager.fetch_model("omnigen_transformer", require_model_path=True)
|
| 142 |
+
self.vae_decoder = model_manager.fetch_model("sdxl_vae_decoder")
|
| 143 |
+
self.vae_encoder = model_manager.fetch_model("sdxl_vae_encoder")
|
| 144 |
+
self.prompter = OmniGenPrompter.from_pretrained(os.path.dirname(model_path))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[], device=None):
|
| 149 |
+
pipe = OmnigenImagePipeline(
|
| 150 |
+
device=model_manager.device if device is None else device,
|
| 151 |
+
torch_dtype=model_manager.torch_dtype,
|
| 152 |
+
)
|
| 153 |
+
pipe.fetch_models(model_manager, prompt_refiner_classes=[])
|
| 154 |
+
return pipe
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32):
|
| 158 |
+
latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 159 |
+
return latents
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def encode_images(self, images, tiled=False, tile_size=64, tile_stride=32):
|
| 163 |
+
latents = [self.encode_image(image.to(device=self.device), tiled, tile_size, tile_stride).to(self.torch_dtype) for image in images]
|
| 164 |
+
return latents
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32):
|
| 168 |
+
image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 169 |
+
image = self.vae_output_to_image(image)
|
| 170 |
+
return image
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def encode_prompt(self, prompt, clip_skip=1, positive=True):
|
| 174 |
+
prompt_emb = self.prompter.encode_prompt(prompt, clip_skip=clip_skip, device=self.device, positive=positive)
|
| 175 |
+
return {"encoder_hidden_states": prompt_emb}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def prepare_extra_input(self, latents=None):
|
| 179 |
+
return {}
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def crop_position_ids_for_cache(self, position_ids, num_tokens_for_img):
|
| 183 |
+
if isinstance(position_ids, list):
|
| 184 |
+
for i in range(len(position_ids)):
|
| 185 |
+
position_ids[i] = position_ids[i][:, -(num_tokens_for_img+1):]
|
| 186 |
+
else:
|
| 187 |
+
position_ids = position_ids[:, -(num_tokens_for_img+1):]
|
| 188 |
+
return position_ids
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def crop_attention_mask_for_cache(self, attention_mask, num_tokens_for_img):
|
| 192 |
+
if isinstance(attention_mask, list):
|
| 193 |
+
return [x[..., -(num_tokens_for_img+1):, :] for x in attention_mask]
|
| 194 |
+
return attention_mask[..., -(num_tokens_for_img+1):, :]
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@torch.no_grad()
|
| 198 |
+
def __call__(
|
| 199 |
+
self,
|
| 200 |
+
prompt,
|
| 201 |
+
reference_images=[],
|
| 202 |
+
cfg_scale=2.0,
|
| 203 |
+
image_cfg_scale=2.0,
|
| 204 |
+
use_kv_cache=True,
|
| 205 |
+
offload_kv_cache=True,
|
| 206 |
+
input_image=None,
|
| 207 |
+
denoising_strength=1.0,
|
| 208 |
+
height=1024,
|
| 209 |
+
width=1024,
|
| 210 |
+
num_inference_steps=20,
|
| 211 |
+
tiled=False,
|
| 212 |
+
tile_size=64,
|
| 213 |
+
tile_stride=32,
|
| 214 |
+
seed=None,
|
| 215 |
+
progress_bar_cmd=tqdm,
|
| 216 |
+
progress_bar_st=None,
|
| 217 |
+
):
|
| 218 |
+
height, width = self.check_resize_height_width(height, width)
|
| 219 |
+
|
| 220 |
+
# Tiler parameters
|
| 221 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 222 |
+
|
| 223 |
+
# Prepare scheduler
|
| 224 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 225 |
+
|
| 226 |
+
# Prepare latent tensors
|
| 227 |
+
if input_image is not None:
|
| 228 |
+
self.load_models_to_device(['vae_encoder'])
|
| 229 |
+
image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype)
|
| 230 |
+
latents = self.encode_image(image, **tiler_kwargs)
|
| 231 |
+
noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 232 |
+
latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
|
| 233 |
+
else:
|
| 234 |
+
latents = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 235 |
+
latents = latents.repeat(3, 1, 1, 1)
|
| 236 |
+
|
| 237 |
+
# Encode prompts
|
| 238 |
+
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)
|
| 239 |
+
|
| 240 |
+
# Encode images
|
| 241 |
+
reference_latents = [self.encode_images(images, **tiler_kwargs) for images in input_data['input_pixel_values']]
|
| 242 |
+
|
| 243 |
+
# Pack all parameters
|
| 244 |
+
model_kwargs = dict(input_ids=[input_ids.to(self.device) for input_ids in input_data['input_ids']],
|
| 245 |
+
input_img_latents=reference_latents,
|
| 246 |
+
input_image_sizes=input_data['input_image_sizes'],
|
| 247 |
+
attention_mask=[attention_mask.to(self.device) for attention_mask in input_data["attention_mask"]],
|
| 248 |
+
position_ids=[position_ids.to(self.device) for position_ids in input_data["position_ids"]],
|
| 249 |
+
cfg_scale=cfg_scale,
|
| 250 |
+
img_cfg_scale=image_cfg_scale,
|
| 251 |
+
use_img_cfg=True,
|
| 252 |
+
use_kv_cache=use_kv_cache,
|
| 253 |
+
offload_model=False,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
# Denoise
|
| 257 |
+
self.load_models_to_device(['transformer'])
|
| 258 |
+
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
|
| 259 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 260 |
+
timestep = timestep.unsqueeze(0).repeat(latents.shape[0]).to(self.device)
|
| 261 |
+
|
| 262 |
+
# Forward
|
| 263 |
+
noise_pred, cache = self.transformer.forward_with_separate_cfg(latents, timestep, past_key_values=cache, **model_kwargs)
|
| 264 |
+
|
| 265 |
+
# Scheduler
|
| 266 |
+
latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
|
| 267 |
+
|
| 268 |
+
# Update KV cache
|
| 269 |
+
if progress_id == 0 and use_kv_cache:
|
| 270 |
+
num_tokens_for_img = latents.size(-1)*latents.size(-2) // 4
|
| 271 |
+
if isinstance(cache, list):
|
| 272 |
+
model_kwargs['input_ids'] = [None] * len(cache)
|
| 273 |
+
else:
|
| 274 |
+
model_kwargs['input_ids'] = None
|
| 275 |
+
model_kwargs['position_ids'] = self.crop_position_ids_for_cache(model_kwargs['position_ids'], num_tokens_for_img)
|
| 276 |
+
model_kwargs['attention_mask'] = self.crop_attention_mask_for_cache(model_kwargs['attention_mask'], num_tokens_for_img)
|
| 277 |
+
|
| 278 |
+
# UI
|
| 279 |
+
if progress_bar_st is not None:
|
| 280 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 281 |
+
|
| 282 |
+
# Decode image
|
| 283 |
+
del cache
|
| 284 |
+
self.load_models_to_device(['vae_decoder'])
|
| 285 |
+
image = self.decode_image(latents, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 286 |
+
|
| 287 |
+
# offload all models
|
| 288 |
+
self.load_models_to_device([])
|
| 289 |
+
return image
|
diffsynth/pipelines/pipeline_runner.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, torch, json
|
| 2 |
+
from .sd_video import ModelManager, SDVideoPipeline, ControlNetConfigUnit
|
| 3 |
+
from ..processors.sequencial_processor import SequencialProcessor
|
| 4 |
+
from ..data import VideoData, save_frames, save_video
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SDVideoPipelineRunner:
|
| 9 |
+
def __init__(self, in_streamlit=False):
|
| 10 |
+
self.in_streamlit = in_streamlit
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_pipeline(self, model_list, textual_inversion_folder, device, lora_alphas, controlnet_units):
|
| 14 |
+
# Load models
|
| 15 |
+
model_manager = ModelManager(torch_dtype=torch.float16, device=device)
|
| 16 |
+
model_manager.load_models(model_list)
|
| 17 |
+
pipe = SDVideoPipeline.from_model_manager(
|
| 18 |
+
model_manager,
|
| 19 |
+
[
|
| 20 |
+
ControlNetConfigUnit(
|
| 21 |
+
processor_id=unit["processor_id"],
|
| 22 |
+
model_path=unit["model_path"],
|
| 23 |
+
scale=unit["scale"]
|
| 24 |
+
) for unit in controlnet_units
|
| 25 |
+
]
|
| 26 |
+
)
|
| 27 |
+
textual_inversion_paths = []
|
| 28 |
+
for file_name in os.listdir(textual_inversion_folder):
|
| 29 |
+
if file_name.endswith(".pt") or file_name.endswith(".bin") or file_name.endswith(".pth") or file_name.endswith(".safetensors"):
|
| 30 |
+
textual_inversion_paths.append(os.path.join(textual_inversion_folder, file_name))
|
| 31 |
+
pipe.prompter.load_textual_inversions(textual_inversion_paths)
|
| 32 |
+
return model_manager, pipe
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def load_smoother(self, model_manager, smoother_configs):
|
| 36 |
+
smoother = SequencialProcessor.from_model_manager(model_manager, smoother_configs)
|
| 37 |
+
return smoother
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def synthesize_video(self, model_manager, pipe, seed, smoother, **pipeline_inputs):
|
| 41 |
+
torch.manual_seed(seed)
|
| 42 |
+
if self.in_streamlit:
|
| 43 |
+
import streamlit as st
|
| 44 |
+
progress_bar_st = st.progress(0.0)
|
| 45 |
+
output_video = pipe(**pipeline_inputs, smoother=smoother, progress_bar_st=progress_bar_st)
|
| 46 |
+
progress_bar_st.progress(1.0)
|
| 47 |
+
else:
|
| 48 |
+
output_video = pipe(**pipeline_inputs, smoother=smoother)
|
| 49 |
+
model_manager.to("cpu")
|
| 50 |
+
return output_video
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def load_video(self, video_file, image_folder, height, width, start_frame_id, end_frame_id):
|
| 54 |
+
video = VideoData(video_file=video_file, image_folder=image_folder, height=height, width=width)
|
| 55 |
+
if start_frame_id is None:
|
| 56 |
+
start_frame_id = 0
|
| 57 |
+
if end_frame_id is None:
|
| 58 |
+
end_frame_id = len(video)
|
| 59 |
+
frames = [video[i] for i in range(start_frame_id, end_frame_id)]
|
| 60 |
+
return frames
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def add_data_to_pipeline_inputs(self, data, pipeline_inputs):
|
| 64 |
+
pipeline_inputs["input_frames"] = self.load_video(**data["input_frames"])
|
| 65 |
+
pipeline_inputs["num_frames"] = len(pipeline_inputs["input_frames"])
|
| 66 |
+
pipeline_inputs["width"], pipeline_inputs["height"] = pipeline_inputs["input_frames"][0].size
|
| 67 |
+
if len(data["controlnet_frames"]) > 0:
|
| 68 |
+
pipeline_inputs["controlnet_frames"] = [self.load_video(**unit) for unit in data["controlnet_frames"]]
|
| 69 |
+
return pipeline_inputs
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def save_output(self, video, output_folder, fps, config):
|
| 73 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 74 |
+
save_frames(video, os.path.join(output_folder, "frames"))
|
| 75 |
+
save_video(video, os.path.join(output_folder, "video.mp4"), fps=fps)
|
| 76 |
+
config["pipeline"]["pipeline_inputs"]["input_frames"] = []
|
| 77 |
+
config["pipeline"]["pipeline_inputs"]["controlnet_frames"] = []
|
| 78 |
+
with open(os.path.join(output_folder, "config.json"), 'w') as file:
|
| 79 |
+
json.dump(config, file, indent=4)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def run(self, config):
|
| 83 |
+
if self.in_streamlit:
|
| 84 |
+
import streamlit as st
|
| 85 |
+
if self.in_streamlit: st.markdown("Loading videos ...")
|
| 86 |
+
config["pipeline"]["pipeline_inputs"] = self.add_data_to_pipeline_inputs(config["data"], config["pipeline"]["pipeline_inputs"])
|
| 87 |
+
if self.in_streamlit: st.markdown("Loading videos ... done!")
|
| 88 |
+
if self.in_streamlit: st.markdown("Loading models ...")
|
| 89 |
+
model_manager, pipe = self.load_pipeline(**config["models"])
|
| 90 |
+
if self.in_streamlit: st.markdown("Loading models ... done!")
|
| 91 |
+
if "smoother_configs" in config:
|
| 92 |
+
if self.in_streamlit: st.markdown("Loading smoother ...")
|
| 93 |
+
smoother = self.load_smoother(model_manager, config["smoother_configs"])
|
| 94 |
+
if self.in_streamlit: st.markdown("Loading smoother ... done!")
|
| 95 |
+
else:
|
| 96 |
+
smoother = None
|
| 97 |
+
if self.in_streamlit: st.markdown("Synthesizing videos ...")
|
| 98 |
+
output_video = self.synthesize_video(model_manager, pipe, config["pipeline"]["seed"], smoother, **config["pipeline"]["pipeline_inputs"])
|
| 99 |
+
if self.in_streamlit: st.markdown("Synthesizing videos ... done!")
|
| 100 |
+
if self.in_streamlit: st.markdown("Saving videos ...")
|
| 101 |
+
self.save_output(output_video, config["data"]["output_folder"], config["data"]["fps"], config)
|
| 102 |
+
if self.in_streamlit: st.markdown("Saving videos ... done!")
|
| 103 |
+
if self.in_streamlit: st.markdown("Finished!")
|
| 104 |
+
video_file = open(os.path.join(os.path.join(config["data"]["output_folder"], "video.mp4")), 'rb')
|
| 105 |
+
if self.in_streamlit: st.video(video_file.read())
|
diffsynth/pipelines/sd3_image.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models import ModelManager, SD3TextEncoder1, SD3TextEncoder2, SD3TextEncoder3, SD3DiT, SD3VAEDecoder, SD3VAEEncoder
|
| 2 |
+
from ..prompters import SD3Prompter
|
| 3 |
+
from ..schedulers import FlowMatchScheduler
|
| 4 |
+
from .base import BasePipeline
|
| 5 |
+
import torch
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class SD3ImagePipeline(BasePipeline):
|
| 11 |
+
|
| 12 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 13 |
+
super().__init__(device=device, torch_dtype=torch_dtype, height_division_factor=16, width_division_factor=16)
|
| 14 |
+
self.scheduler = FlowMatchScheduler()
|
| 15 |
+
self.prompter = SD3Prompter()
|
| 16 |
+
# models
|
| 17 |
+
self.text_encoder_1: SD3TextEncoder1 = None
|
| 18 |
+
self.text_encoder_2: SD3TextEncoder2 = None
|
| 19 |
+
self.text_encoder_3: SD3TextEncoder3 = None
|
| 20 |
+
self.dit: SD3DiT = None
|
| 21 |
+
self.vae_decoder: SD3VAEDecoder = None
|
| 22 |
+
self.vae_encoder: SD3VAEEncoder = None
|
| 23 |
+
self.model_names = ['text_encoder_1', 'text_encoder_2', 'text_encoder_3', 'dit', 'vae_decoder', 'vae_encoder']
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def denoising_model(self):
|
| 27 |
+
return self.dit
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def fetch_models(self, model_manager: ModelManager, prompt_refiner_classes=[]):
|
| 31 |
+
self.text_encoder_1 = model_manager.fetch_model("sd3_text_encoder_1")
|
| 32 |
+
self.text_encoder_2 = model_manager.fetch_model("sd3_text_encoder_2")
|
| 33 |
+
self.text_encoder_3 = model_manager.fetch_model("sd3_text_encoder_3")
|
| 34 |
+
self.dit = model_manager.fetch_model("sd3_dit")
|
| 35 |
+
self.vae_decoder = model_manager.fetch_model("sd3_vae_decoder")
|
| 36 |
+
self.vae_encoder = model_manager.fetch_model("sd3_vae_encoder")
|
| 37 |
+
self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2, self.text_encoder_3)
|
| 38 |
+
self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
def from_model_manager(model_manager: ModelManager, prompt_refiner_classes=[], device=None):
|
| 43 |
+
pipe = SD3ImagePipeline(
|
| 44 |
+
device=model_manager.device if device is None else device,
|
| 45 |
+
torch_dtype=model_manager.torch_dtype,
|
| 46 |
+
)
|
| 47 |
+
pipe.fetch_models(model_manager, prompt_refiner_classes)
|
| 48 |
+
return pipe
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32):
|
| 52 |
+
latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 53 |
+
return latents
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32):
|
| 57 |
+
image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 58 |
+
image = self.vae_output_to_image(image)
|
| 59 |
+
return image
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def encode_prompt(self, prompt, positive=True, t5_sequence_length=77):
|
| 63 |
+
prompt_emb, pooled_prompt_emb = self.prompter.encode_prompt(
|
| 64 |
+
prompt, device=self.device, positive=positive, t5_sequence_length=t5_sequence_length
|
| 65 |
+
)
|
| 66 |
+
return {"prompt_emb": prompt_emb, "pooled_prompt_emb": pooled_prompt_emb}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def prepare_extra_input(self, latents=None):
|
| 70 |
+
return {}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@torch.no_grad()
|
| 74 |
+
def __call__(
|
| 75 |
+
self,
|
| 76 |
+
prompt,
|
| 77 |
+
local_prompts=[],
|
| 78 |
+
masks=[],
|
| 79 |
+
mask_scales=[],
|
| 80 |
+
negative_prompt="",
|
| 81 |
+
cfg_scale=7.5,
|
| 82 |
+
input_image=None,
|
| 83 |
+
denoising_strength=1.0,
|
| 84 |
+
height=1024,
|
| 85 |
+
width=1024,
|
| 86 |
+
num_inference_steps=20,
|
| 87 |
+
t5_sequence_length=77,
|
| 88 |
+
tiled=False,
|
| 89 |
+
tile_size=128,
|
| 90 |
+
tile_stride=64,
|
| 91 |
+
seed=None,
|
| 92 |
+
progress_bar_cmd=tqdm,
|
| 93 |
+
progress_bar_st=None,
|
| 94 |
+
):
|
| 95 |
+
height, width = self.check_resize_height_width(height, width)
|
| 96 |
+
|
| 97 |
+
# Tiler parameters
|
| 98 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 99 |
+
|
| 100 |
+
# Prepare scheduler
|
| 101 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 102 |
+
|
| 103 |
+
# Prepare latent tensors
|
| 104 |
+
if input_image is not None:
|
| 105 |
+
self.load_models_to_device(['vae_encoder'])
|
| 106 |
+
image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype)
|
| 107 |
+
latents = self.encode_image(image, **tiler_kwargs)
|
| 108 |
+
noise = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 109 |
+
latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
|
| 110 |
+
else:
|
| 111 |
+
latents = self.generate_noise((1, 16, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 112 |
+
|
| 113 |
+
# Encode prompts
|
| 114 |
+
self.load_models_to_device(['text_encoder_1', 'text_encoder_2', 'text_encoder_3'])
|
| 115 |
+
prompt_emb_posi = self.encode_prompt(prompt, positive=True, t5_sequence_length=t5_sequence_length)
|
| 116 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False, t5_sequence_length=t5_sequence_length)
|
| 117 |
+
prompt_emb_locals = [self.encode_prompt(prompt_local, t5_sequence_length=t5_sequence_length) for prompt_local in local_prompts]
|
| 118 |
+
|
| 119 |
+
# Denoise
|
| 120 |
+
self.load_models_to_device(['dit'])
|
| 121 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 122 |
+
timestep = timestep.unsqueeze(0).to(self.device)
|
| 123 |
+
|
| 124 |
+
# Classifier-free guidance
|
| 125 |
+
inference_callback = lambda prompt_emb_posi: self.dit(
|
| 126 |
+
latents, timestep=timestep, **prompt_emb_posi, **tiler_kwargs,
|
| 127 |
+
)
|
| 128 |
+
noise_pred_posi = self.control_noise_via_local_prompts(prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback)
|
| 129 |
+
noise_pred_nega = self.dit(
|
| 130 |
+
latents, timestep=timestep, **prompt_emb_nega, **tiler_kwargs,
|
| 131 |
+
)
|
| 132 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 133 |
+
|
| 134 |
+
# DDIM
|
| 135 |
+
latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
|
| 136 |
+
|
| 137 |
+
# UI
|
| 138 |
+
if progress_bar_st is not None:
|
| 139 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 140 |
+
|
| 141 |
+
# Decode image
|
| 142 |
+
self.load_models_to_device(['vae_decoder'])
|
| 143 |
+
image = self.decode_image(latents, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 144 |
+
|
| 145 |
+
# offload all models
|
| 146 |
+
self.load_models_to_device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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models import SDTextEncoder, SDUNet, SDVAEDecoder, SDVAEEncoder, SDIpAdapter, IpAdapterCLIPImageEmbedder
|
| 2 |
+
from ..models.model_manager import ModelManager
|
| 3 |
+
from ..controlnets import MultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator
|
| 4 |
+
from ..prompters import SDPrompter
|
| 5 |
+
from ..schedulers import EnhancedDDIMScheduler
|
| 6 |
+
from .base import BasePipeline
|
| 7 |
+
from .dancer import lets_dance
|
| 8 |
+
from typing import List
|
| 9 |
+
import torch
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class SDImagePipeline(BasePipeline):
|
| 15 |
+
|
| 16 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 17 |
+
super().__init__(device=device, torch_dtype=torch_dtype)
|
| 18 |
+
self.scheduler = EnhancedDDIMScheduler()
|
| 19 |
+
self.prompter = SDPrompter()
|
| 20 |
+
# models
|
| 21 |
+
self.text_encoder: SDTextEncoder = None
|
| 22 |
+
self.unet: SDUNet = None
|
| 23 |
+
self.vae_decoder: SDVAEDecoder = None
|
| 24 |
+
self.vae_encoder: SDVAEEncoder = None
|
| 25 |
+
self.controlnet: MultiControlNetManager = None
|
| 26 |
+
self.ipadapter_image_encoder: IpAdapterCLIPImageEmbedder = None
|
| 27 |
+
self.ipadapter: SDIpAdapter = None
|
| 28 |
+
self.model_names = ['text_encoder', 'unet', 'vae_decoder', 'vae_encoder', 'controlnet', 'ipadapter_image_encoder', 'ipadapter']
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def denoising_model(self):
|
| 32 |
+
return self.unet
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]):
|
| 36 |
+
# Main models
|
| 37 |
+
self.text_encoder = model_manager.fetch_model("sd_text_encoder")
|
| 38 |
+
self.unet = model_manager.fetch_model("sd_unet")
|
| 39 |
+
self.vae_decoder = model_manager.fetch_model("sd_vae_decoder")
|
| 40 |
+
self.vae_encoder = model_manager.fetch_model("sd_vae_encoder")
|
| 41 |
+
self.prompter.fetch_models(self.text_encoder)
|
| 42 |
+
self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes)
|
| 43 |
+
|
| 44 |
+
# ControlNets
|
| 45 |
+
controlnet_units = []
|
| 46 |
+
for config in controlnet_config_units:
|
| 47 |
+
controlnet_unit = ControlNetUnit(
|
| 48 |
+
Annotator(config.processor_id, device=self.device),
|
| 49 |
+
model_manager.fetch_model("sd_controlnet", config.model_path),
|
| 50 |
+
config.scale
|
| 51 |
+
)
|
| 52 |
+
controlnet_units.append(controlnet_unit)
|
| 53 |
+
self.controlnet = MultiControlNetManager(controlnet_units)
|
| 54 |
+
|
| 55 |
+
# IP-Adapters
|
| 56 |
+
self.ipadapter = model_manager.fetch_model("sd_ipadapter")
|
| 57 |
+
self.ipadapter_image_encoder = model_manager.fetch_model("sd_ipadapter_clip_image_encoder")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[], device=None):
|
| 62 |
+
pipe = SDImagePipeline(
|
| 63 |
+
device=model_manager.device if device is None else device,
|
| 64 |
+
torch_dtype=model_manager.torch_dtype,
|
| 65 |
+
)
|
| 66 |
+
pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes=[])
|
| 67 |
+
return pipe
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def encode_image(self, image, tiled=False, tile_size=64, tile_stride=32):
|
| 71 |
+
latents = self.vae_encoder(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 72 |
+
return latents
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def decode_image(self, latent, tiled=False, tile_size=64, tile_stride=32):
|
| 76 |
+
image = self.vae_decoder(latent.to(self.device), tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 77 |
+
image = self.vae_output_to_image(image)
|
| 78 |
+
return image
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def encode_prompt(self, prompt, clip_skip=1, positive=True):
|
| 82 |
+
prompt_emb = self.prompter.encode_prompt(prompt, clip_skip=clip_skip, device=self.device, positive=positive)
|
| 83 |
+
return {"encoder_hidden_states": prompt_emb}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def prepare_extra_input(self, latents=None):
|
| 87 |
+
return {}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@torch.no_grad()
|
| 91 |
+
def __call__(
|
| 92 |
+
self,
|
| 93 |
+
prompt,
|
| 94 |
+
local_prompts=[],
|
| 95 |
+
masks=[],
|
| 96 |
+
mask_scales=[],
|
| 97 |
+
negative_prompt="",
|
| 98 |
+
cfg_scale=7.5,
|
| 99 |
+
clip_skip=1,
|
| 100 |
+
input_image=None,
|
| 101 |
+
ipadapter_images=None,
|
| 102 |
+
ipadapter_scale=1.0,
|
| 103 |
+
controlnet_image=None,
|
| 104 |
+
denoising_strength=1.0,
|
| 105 |
+
height=512,
|
| 106 |
+
width=512,
|
| 107 |
+
num_inference_steps=20,
|
| 108 |
+
tiled=False,
|
| 109 |
+
tile_size=64,
|
| 110 |
+
tile_stride=32,
|
| 111 |
+
seed=None,
|
| 112 |
+
progress_bar_cmd=tqdm,
|
| 113 |
+
progress_bar_st=None,
|
| 114 |
+
):
|
| 115 |
+
height, width = self.check_resize_height_width(height, width)
|
| 116 |
+
|
| 117 |
+
# Tiler parameters
|
| 118 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 119 |
+
|
| 120 |
+
# Prepare scheduler
|
| 121 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 122 |
+
|
| 123 |
+
# Prepare latent tensors
|
| 124 |
+
if input_image is not None:
|
| 125 |
+
self.load_models_to_device(['vae_encoder'])
|
| 126 |
+
image = self.preprocess_image(input_image).to(device=self.device, dtype=self.torch_dtype)
|
| 127 |
+
latents = self.encode_image(image, **tiler_kwargs)
|
| 128 |
+
noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 129 |
+
latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
|
| 130 |
+
else:
|
| 131 |
+
latents = self.generate_noise((1, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 132 |
+
|
| 133 |
+
# Encode prompts
|
| 134 |
+
self.load_models_to_device(['text_encoder'])
|
| 135 |
+
prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, positive=True)
|
| 136 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, positive=False)
|
| 137 |
+
prompt_emb_locals = [self.encode_prompt(prompt_local, clip_skip=clip_skip, positive=True) for prompt_local in local_prompts]
|
| 138 |
+
|
| 139 |
+
# IP-Adapter
|
| 140 |
+
if ipadapter_images is not None:
|
| 141 |
+
self.load_models_to_device(['ipadapter_image_encoder'])
|
| 142 |
+
ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images)
|
| 143 |
+
self.load_models_to_device(['ipadapter'])
|
| 144 |
+
ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)}
|
| 145 |
+
ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))}
|
| 146 |
+
else:
|
| 147 |
+
ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}}
|
| 148 |
+
|
| 149 |
+
# Prepare ControlNets
|
| 150 |
+
if controlnet_image is not None:
|
| 151 |
+
self.load_models_to_device(['controlnet'])
|
| 152 |
+
controlnet_image = self.controlnet.process_image(controlnet_image).to(device=self.device, dtype=self.torch_dtype)
|
| 153 |
+
controlnet_image = controlnet_image.unsqueeze(1)
|
| 154 |
+
controlnet_kwargs = {"controlnet_frames": controlnet_image}
|
| 155 |
+
else:
|
| 156 |
+
controlnet_kwargs = {"controlnet_frames": None}
|
| 157 |
+
|
| 158 |
+
# Denoise
|
| 159 |
+
self.load_models_to_device(['controlnet', 'unet'])
|
| 160 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 161 |
+
timestep = timestep.unsqueeze(0).to(self.device)
|
| 162 |
+
|
| 163 |
+
# Classifier-free guidance
|
| 164 |
+
inference_callback = lambda prompt_emb_posi: lets_dance(
|
| 165 |
+
self.unet, motion_modules=None, controlnet=self.controlnet,
|
| 166 |
+
sample=latents, timestep=timestep,
|
| 167 |
+
**prompt_emb_posi, **controlnet_kwargs, **tiler_kwargs, **ipadapter_kwargs_list_posi,
|
| 168 |
+
device=self.device,
|
| 169 |
+
)
|
| 170 |
+
noise_pred_posi = self.control_noise_via_local_prompts(prompt_emb_posi, prompt_emb_locals, masks, mask_scales, inference_callback)
|
| 171 |
+
noise_pred_nega = lets_dance(
|
| 172 |
+
self.unet, motion_modules=None, controlnet=self.controlnet,
|
| 173 |
+
sample=latents, timestep=timestep, **prompt_emb_nega, **controlnet_kwargs, **tiler_kwargs, **ipadapter_kwargs_list_nega,
|
| 174 |
+
device=self.device,
|
| 175 |
+
)
|
| 176 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 177 |
+
|
| 178 |
+
# DDIM
|
| 179 |
+
latents = self.scheduler.step(noise_pred, timestep, latents)
|
| 180 |
+
|
| 181 |
+
# UI
|
| 182 |
+
if progress_bar_st is not None:
|
| 183 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 184 |
+
|
| 185 |
+
# Decode image
|
| 186 |
+
self.load_models_to_device(['vae_decoder'])
|
| 187 |
+
image = self.decode_image(latents, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 188 |
+
|
| 189 |
+
# offload all models
|
| 190 |
+
self.load_models_to_device([])
|
| 191 |
+
return image
|
diffsynth/pipelines/sd_video.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from ..controlnets import MultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator
|
| 4 |
+
from ..prompters import SDPrompter
|
| 5 |
+
from ..schedulers import EnhancedDDIMScheduler
|
| 6 |
+
from .sd_image import SDImagePipeline
|
| 7 |
+
from .dancer import lets_dance
|
| 8 |
+
from typing import List
|
| 9 |
+
import torch
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def lets_dance_with_long_video(
|
| 15 |
+
unet: SDUNet,
|
| 16 |
+
motion_modules: SDMotionModel = None,
|
| 17 |
+
controlnet: MultiControlNetManager = None,
|
| 18 |
+
sample = None,
|
| 19 |
+
timestep = None,
|
| 20 |
+
encoder_hidden_states = None,
|
| 21 |
+
ipadapter_kwargs_list = {},
|
| 22 |
+
controlnet_frames = None,
|
| 23 |
+
unet_batch_size = 1,
|
| 24 |
+
controlnet_batch_size = 1,
|
| 25 |
+
cross_frame_attention = False,
|
| 26 |
+
tiled=False,
|
| 27 |
+
tile_size=64,
|
| 28 |
+
tile_stride=32,
|
| 29 |
+
device="cuda",
|
| 30 |
+
animatediff_batch_size=16,
|
| 31 |
+
animatediff_stride=8,
|
| 32 |
+
):
|
| 33 |
+
num_frames = sample.shape[0]
|
| 34 |
+
hidden_states_output = [(torch.zeros(sample[0].shape, dtype=sample[0].dtype), 0) for i in range(num_frames)]
|
| 35 |
+
|
| 36 |
+
for batch_id in range(0, num_frames, animatediff_stride):
|
| 37 |
+
batch_id_ = min(batch_id + animatediff_batch_size, num_frames)
|
| 38 |
+
|
| 39 |
+
# process this batch
|
| 40 |
+
hidden_states_batch = lets_dance(
|
| 41 |
+
unet, motion_modules, controlnet,
|
| 42 |
+
sample[batch_id: batch_id_].to(device),
|
| 43 |
+
timestep,
|
| 44 |
+
encoder_hidden_states,
|
| 45 |
+
ipadapter_kwargs_list=ipadapter_kwargs_list,
|
| 46 |
+
controlnet_frames=controlnet_frames[:, batch_id: batch_id_].to(device) if controlnet_frames is not None else None,
|
| 47 |
+
unet_batch_size=unet_batch_size, controlnet_batch_size=controlnet_batch_size,
|
| 48 |
+
cross_frame_attention=cross_frame_attention,
|
| 49 |
+
tiled=tiled, tile_size=tile_size, tile_stride=tile_stride, device=device
|
| 50 |
+
).cpu()
|
| 51 |
+
|
| 52 |
+
# update hidden_states
|
| 53 |
+
for i, hidden_states_updated in zip(range(batch_id, batch_id_), hidden_states_batch):
|
| 54 |
+
bias = max(1 - abs(i - (batch_id + batch_id_ - 1) / 2) / ((batch_id_ - batch_id - 1 + 1e-2) / 2), 1e-2)
|
| 55 |
+
hidden_states, num = hidden_states_output[i]
|
| 56 |
+
hidden_states = hidden_states * (num / (num + bias)) + hidden_states_updated * (bias / (num + bias))
|
| 57 |
+
hidden_states_output[i] = (hidden_states, num + bias)
|
| 58 |
+
|
| 59 |
+
if batch_id_ == num_frames:
|
| 60 |
+
break
|
| 61 |
+
|
| 62 |
+
# output
|
| 63 |
+
hidden_states = torch.stack([h for h, _ in hidden_states_output])
|
| 64 |
+
return hidden_states
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class SDVideoPipeline(SDImagePipeline):
|
| 69 |
+
|
| 70 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16, use_original_animatediff=True):
|
| 71 |
+
super().__init__(device=device, torch_dtype=torch_dtype)
|
| 72 |
+
self.scheduler = EnhancedDDIMScheduler(beta_schedule="linear" if use_original_animatediff else "scaled_linear")
|
| 73 |
+
self.prompter = SDPrompter()
|
| 74 |
+
# models
|
| 75 |
+
self.text_encoder: SDTextEncoder = None
|
| 76 |
+
self.unet: SDUNet = None
|
| 77 |
+
self.vae_decoder: SDVAEDecoder = None
|
| 78 |
+
self.vae_encoder: SDVAEEncoder = None
|
| 79 |
+
self.controlnet: MultiControlNetManager = None
|
| 80 |
+
self.ipadapter_image_encoder: IpAdapterCLIPImageEmbedder = None
|
| 81 |
+
self.ipadapter: SDIpAdapter = None
|
| 82 |
+
self.motion_modules: SDMotionModel = None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]):
|
| 86 |
+
# Main models
|
| 87 |
+
self.text_encoder = model_manager.fetch_model("sd_text_encoder")
|
| 88 |
+
self.unet = model_manager.fetch_model("sd_unet")
|
| 89 |
+
self.vae_decoder = model_manager.fetch_model("sd_vae_decoder")
|
| 90 |
+
self.vae_encoder = model_manager.fetch_model("sd_vae_encoder")
|
| 91 |
+
self.prompter.fetch_models(self.text_encoder)
|
| 92 |
+
self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes)
|
| 93 |
+
|
| 94 |
+
# ControlNets
|
| 95 |
+
controlnet_units = []
|
| 96 |
+
for config in controlnet_config_units:
|
| 97 |
+
controlnet_unit = ControlNetUnit(
|
| 98 |
+
Annotator(config.processor_id, device=self.device),
|
| 99 |
+
model_manager.fetch_model("sd_controlnet", config.model_path),
|
| 100 |
+
config.scale
|
| 101 |
+
)
|
| 102 |
+
controlnet_units.append(controlnet_unit)
|
| 103 |
+
self.controlnet = MultiControlNetManager(controlnet_units)
|
| 104 |
+
|
| 105 |
+
# IP-Adapters
|
| 106 |
+
self.ipadapter = model_manager.fetch_model("sd_ipadapter")
|
| 107 |
+
self.ipadapter_image_encoder = model_manager.fetch_model("sd_ipadapter_clip_image_encoder")
|
| 108 |
+
|
| 109 |
+
# Motion Modules
|
| 110 |
+
self.motion_modules = model_manager.fetch_model("sd_motion_modules")
|
| 111 |
+
if self.motion_modules is None:
|
| 112 |
+
self.scheduler = EnhancedDDIMScheduler(beta_schedule="scaled_linear")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]):
|
| 117 |
+
pipe = SDVideoPipeline(
|
| 118 |
+
device=model_manager.device,
|
| 119 |
+
torch_dtype=model_manager.torch_dtype,
|
| 120 |
+
)
|
| 121 |
+
pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes)
|
| 122 |
+
return pipe
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def decode_video(self, latents, tiled=False, tile_size=64, tile_stride=32):
|
| 126 |
+
images = [
|
| 127 |
+
self.decode_image(latents[frame_id: frame_id+1], tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 128 |
+
for frame_id in range(latents.shape[0])
|
| 129 |
+
]
|
| 130 |
+
return images
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def encode_video(self, processed_images, tiled=False, tile_size=64, tile_stride=32):
|
| 134 |
+
latents = []
|
| 135 |
+
for image in processed_images:
|
| 136 |
+
image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype)
|
| 137 |
+
latent = self.encode_image(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 138 |
+
latents.append(latent.cpu())
|
| 139 |
+
latents = torch.concat(latents, dim=0)
|
| 140 |
+
return latents
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@torch.no_grad()
|
| 144 |
+
def __call__(
|
| 145 |
+
self,
|
| 146 |
+
prompt,
|
| 147 |
+
negative_prompt="",
|
| 148 |
+
cfg_scale=7.5,
|
| 149 |
+
clip_skip=1,
|
| 150 |
+
num_frames=None,
|
| 151 |
+
input_frames=None,
|
| 152 |
+
ipadapter_images=None,
|
| 153 |
+
ipadapter_scale=1.0,
|
| 154 |
+
controlnet_frames=None,
|
| 155 |
+
denoising_strength=1.0,
|
| 156 |
+
height=512,
|
| 157 |
+
width=512,
|
| 158 |
+
num_inference_steps=20,
|
| 159 |
+
animatediff_batch_size = 16,
|
| 160 |
+
animatediff_stride = 8,
|
| 161 |
+
unet_batch_size = 1,
|
| 162 |
+
controlnet_batch_size = 1,
|
| 163 |
+
cross_frame_attention = False,
|
| 164 |
+
smoother=None,
|
| 165 |
+
smoother_progress_ids=[],
|
| 166 |
+
tiled=False,
|
| 167 |
+
tile_size=64,
|
| 168 |
+
tile_stride=32,
|
| 169 |
+
seed=None,
|
| 170 |
+
progress_bar_cmd=tqdm,
|
| 171 |
+
progress_bar_st=None,
|
| 172 |
+
):
|
| 173 |
+
height, width = self.check_resize_height_width(height, width)
|
| 174 |
+
|
| 175 |
+
# Tiler parameters, batch size ...
|
| 176 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 177 |
+
other_kwargs = {
|
| 178 |
+
"animatediff_batch_size": animatediff_batch_size, "animatediff_stride": animatediff_stride,
|
| 179 |
+
"unet_batch_size": unet_batch_size, "controlnet_batch_size": controlnet_batch_size,
|
| 180 |
+
"cross_frame_attention": cross_frame_attention,
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
# Prepare scheduler
|
| 184 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 185 |
+
|
| 186 |
+
# Prepare latent tensors
|
| 187 |
+
if self.motion_modules is None:
|
| 188 |
+
noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype).repeat(num_frames, 1, 1, 1)
|
| 189 |
+
else:
|
| 190 |
+
noise = self.generate_noise((num_frames, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype)
|
| 191 |
+
if input_frames is None or denoising_strength == 1.0:
|
| 192 |
+
latents = noise
|
| 193 |
+
else:
|
| 194 |
+
latents = self.encode_video(input_frames, **tiler_kwargs)
|
| 195 |
+
latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
|
| 196 |
+
|
| 197 |
+
# Encode prompts
|
| 198 |
+
prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, positive=True)
|
| 199 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, positive=False)
|
| 200 |
+
|
| 201 |
+
# IP-Adapter
|
| 202 |
+
if ipadapter_images is not None:
|
| 203 |
+
ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images)
|
| 204 |
+
ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)}
|
| 205 |
+
ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))}
|
| 206 |
+
else:
|
| 207 |
+
ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}}
|
| 208 |
+
|
| 209 |
+
# Prepare ControlNets
|
| 210 |
+
if controlnet_frames is not None:
|
| 211 |
+
if isinstance(controlnet_frames[0], list):
|
| 212 |
+
controlnet_frames_ = []
|
| 213 |
+
for processor_id in range(len(controlnet_frames)):
|
| 214 |
+
controlnet_frames_.append(
|
| 215 |
+
torch.stack([
|
| 216 |
+
self.controlnet.process_image(controlnet_frame, processor_id=processor_id).to(self.torch_dtype)
|
| 217 |
+
for controlnet_frame in progress_bar_cmd(controlnet_frames[processor_id])
|
| 218 |
+
], dim=1)
|
| 219 |
+
)
|
| 220 |
+
controlnet_frames = torch.concat(controlnet_frames_, dim=0)
|
| 221 |
+
else:
|
| 222 |
+
controlnet_frames = torch.stack([
|
| 223 |
+
self.controlnet.process_image(controlnet_frame).to(self.torch_dtype)
|
| 224 |
+
for controlnet_frame in progress_bar_cmd(controlnet_frames)
|
| 225 |
+
], dim=1)
|
| 226 |
+
controlnet_kwargs = {"controlnet_frames": controlnet_frames}
|
| 227 |
+
else:
|
| 228 |
+
controlnet_kwargs = {"controlnet_frames": None}
|
| 229 |
+
|
| 230 |
+
# Denoise
|
| 231 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 232 |
+
timestep = timestep.unsqueeze(0).to(self.device)
|
| 233 |
+
|
| 234 |
+
# Classifier-free guidance
|
| 235 |
+
noise_pred_posi = lets_dance_with_long_video(
|
| 236 |
+
self.unet, motion_modules=self.motion_modules, controlnet=self.controlnet,
|
| 237 |
+
sample=latents, timestep=timestep,
|
| 238 |
+
**prompt_emb_posi, **controlnet_kwargs, **ipadapter_kwargs_list_posi, **other_kwargs, **tiler_kwargs,
|
| 239 |
+
device=self.device,
|
| 240 |
+
)
|
| 241 |
+
noise_pred_nega = lets_dance_with_long_video(
|
| 242 |
+
self.unet, motion_modules=self.motion_modules, controlnet=self.controlnet,
|
| 243 |
+
sample=latents, timestep=timestep,
|
| 244 |
+
**prompt_emb_nega, **controlnet_kwargs, **ipadapter_kwargs_list_nega, **other_kwargs, **tiler_kwargs,
|
| 245 |
+
device=self.device,
|
| 246 |
+
)
|
| 247 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 248 |
+
|
| 249 |
+
# DDIM and smoother
|
| 250 |
+
if smoother is not None and progress_id in smoother_progress_ids:
|
| 251 |
+
rendered_frames = self.scheduler.step(noise_pred, timestep, latents, to_final=True)
|
| 252 |
+
rendered_frames = self.decode_video(rendered_frames)
|
| 253 |
+
rendered_frames = smoother(rendered_frames, original_frames=input_frames)
|
| 254 |
+
target_latents = self.encode_video(rendered_frames)
|
| 255 |
+
noise_pred = self.scheduler.return_to_timestep(timestep, latents, target_latents)
|
| 256 |
+
latents = self.scheduler.step(noise_pred, timestep, latents)
|
| 257 |
+
|
| 258 |
+
# UI
|
| 259 |
+
if progress_bar_st is not None:
|
| 260 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 261 |
+
|
| 262 |
+
# Decode image
|
| 263 |
+
output_frames = self.decode_video(latents, **tiler_kwargs)
|
| 264 |
+
|
| 265 |
+
# Post-process
|
| 266 |
+
if smoother is not None and (num_inference_steps in smoother_progress_ids or -1 in smoother_progress_ids):
|
| 267 |
+
output_frames = smoother(output_frames, original_frames=input_frames)
|
| 268 |
+
|
| 269 |
+
return output_frames
|
diffsynth/pipelines/sdxl_video.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models import SDXLTextEncoder, SDXLTextEncoder2, SDXLUNet, SDXLVAEDecoder, SDXLVAEEncoder, SDXLIpAdapter, IpAdapterXLCLIPImageEmbedder, SDXLMotionModel
|
| 2 |
+
from ..models.kolors_text_encoder import ChatGLMModel
|
| 3 |
+
from ..models.model_manager import ModelManager
|
| 4 |
+
from ..controlnets import MultiControlNetManager, ControlNetUnit, ControlNetConfigUnit, Annotator
|
| 5 |
+
from ..prompters import SDXLPrompter, KolorsPrompter
|
| 6 |
+
from ..schedulers import EnhancedDDIMScheduler
|
| 7 |
+
from .sdxl_image import SDXLImagePipeline
|
| 8 |
+
from .dancer import lets_dance_xl
|
| 9 |
+
from typing import List
|
| 10 |
+
import torch
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class SDXLVideoPipeline(SDXLImagePipeline):
|
| 16 |
+
|
| 17 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16, use_original_animatediff=True):
|
| 18 |
+
super().__init__(device=device, torch_dtype=torch_dtype)
|
| 19 |
+
self.scheduler = EnhancedDDIMScheduler(beta_schedule="linear" if use_original_animatediff else "scaled_linear")
|
| 20 |
+
self.prompter = SDXLPrompter()
|
| 21 |
+
# models
|
| 22 |
+
self.text_encoder: SDXLTextEncoder = None
|
| 23 |
+
self.text_encoder_2: SDXLTextEncoder2 = None
|
| 24 |
+
self.text_encoder_kolors: ChatGLMModel = None
|
| 25 |
+
self.unet: SDXLUNet = None
|
| 26 |
+
self.vae_decoder: SDXLVAEDecoder = None
|
| 27 |
+
self.vae_encoder: SDXLVAEEncoder = None
|
| 28 |
+
# self.controlnet: MultiControlNetManager = None (TODO)
|
| 29 |
+
self.ipadapter_image_encoder: IpAdapterXLCLIPImageEmbedder = None
|
| 30 |
+
self.ipadapter: SDXLIpAdapter = None
|
| 31 |
+
self.motion_modules: SDXLMotionModel = None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def fetch_models(self, model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]):
|
| 35 |
+
# Main models
|
| 36 |
+
self.text_encoder = model_manager.fetch_model("sdxl_text_encoder")
|
| 37 |
+
self.text_encoder_2 = model_manager.fetch_model("sdxl_text_encoder_2")
|
| 38 |
+
self.text_encoder_kolors = model_manager.fetch_model("kolors_text_encoder")
|
| 39 |
+
self.unet = model_manager.fetch_model("sdxl_unet")
|
| 40 |
+
self.vae_decoder = model_manager.fetch_model("sdxl_vae_decoder")
|
| 41 |
+
self.vae_encoder = model_manager.fetch_model("sdxl_vae_encoder")
|
| 42 |
+
self.prompter.fetch_models(self.text_encoder)
|
| 43 |
+
self.prompter.load_prompt_refiners(model_manager, prompt_refiner_classes)
|
| 44 |
+
|
| 45 |
+
# ControlNets (TODO)
|
| 46 |
+
|
| 47 |
+
# IP-Adapters
|
| 48 |
+
self.ipadapter = model_manager.fetch_model("sdxl_ipadapter")
|
| 49 |
+
self.ipadapter_image_encoder = model_manager.fetch_model("sdxl_ipadapter_clip_image_encoder")
|
| 50 |
+
|
| 51 |
+
# Motion Modules
|
| 52 |
+
self.motion_modules = model_manager.fetch_model("sdxl_motion_modules")
|
| 53 |
+
if self.motion_modules is None:
|
| 54 |
+
self.scheduler = EnhancedDDIMScheduler(beta_schedule="scaled_linear")
|
| 55 |
+
|
| 56 |
+
# Kolors
|
| 57 |
+
if self.text_encoder_kolors is not None:
|
| 58 |
+
print("Switch to Kolors. The prompter will be replaced.")
|
| 59 |
+
self.prompter = KolorsPrompter()
|
| 60 |
+
self.prompter.fetch_models(self.text_encoder_kolors)
|
| 61 |
+
# The schedulers of AniamteDiff and Kolors are incompatible. We align it with AniamteDiff.
|
| 62 |
+
if self.motion_modules is None:
|
| 63 |
+
self.scheduler = EnhancedDDIMScheduler(beta_end=0.014, num_train_timesteps=1100)
|
| 64 |
+
else:
|
| 65 |
+
self.prompter.fetch_models(self.text_encoder, self.text_encoder_2)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
def from_model_manager(model_manager: ModelManager, controlnet_config_units: List[ControlNetConfigUnit]=[], prompt_refiner_classes=[]):
|
| 70 |
+
pipe = SDXLVideoPipeline(
|
| 71 |
+
device=model_manager.device,
|
| 72 |
+
torch_dtype=model_manager.torch_dtype,
|
| 73 |
+
)
|
| 74 |
+
pipe.fetch_models(model_manager, controlnet_config_units, prompt_refiner_classes)
|
| 75 |
+
return pipe
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def decode_video(self, latents, tiled=False, tile_size=64, tile_stride=32):
|
| 79 |
+
images = [
|
| 80 |
+
self.decode_image(latents[frame_id: frame_id+1], tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 81 |
+
for frame_id in range(latents.shape[0])
|
| 82 |
+
]
|
| 83 |
+
return images
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def encode_video(self, processed_images, tiled=False, tile_size=64, tile_stride=32):
|
| 87 |
+
latents = []
|
| 88 |
+
for image in processed_images:
|
| 89 |
+
image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype)
|
| 90 |
+
latent = self.encode_image(image, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
|
| 91 |
+
latents.append(latent.cpu())
|
| 92 |
+
latents = torch.concat(latents, dim=0)
|
| 93 |
+
return latents
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@torch.no_grad()
|
| 97 |
+
def __call__(
|
| 98 |
+
self,
|
| 99 |
+
prompt,
|
| 100 |
+
negative_prompt="",
|
| 101 |
+
cfg_scale=7.5,
|
| 102 |
+
clip_skip=1,
|
| 103 |
+
num_frames=None,
|
| 104 |
+
input_frames=None,
|
| 105 |
+
ipadapter_images=None,
|
| 106 |
+
ipadapter_scale=1.0,
|
| 107 |
+
ipadapter_use_instant_style=False,
|
| 108 |
+
controlnet_frames=None,
|
| 109 |
+
denoising_strength=1.0,
|
| 110 |
+
height=512,
|
| 111 |
+
width=512,
|
| 112 |
+
num_inference_steps=20,
|
| 113 |
+
animatediff_batch_size = 16,
|
| 114 |
+
animatediff_stride = 8,
|
| 115 |
+
unet_batch_size = 1,
|
| 116 |
+
controlnet_batch_size = 1,
|
| 117 |
+
cross_frame_attention = False,
|
| 118 |
+
smoother=None,
|
| 119 |
+
smoother_progress_ids=[],
|
| 120 |
+
tiled=False,
|
| 121 |
+
tile_size=64,
|
| 122 |
+
tile_stride=32,
|
| 123 |
+
seed=None,
|
| 124 |
+
progress_bar_cmd=tqdm,
|
| 125 |
+
progress_bar_st=None,
|
| 126 |
+
):
|
| 127 |
+
height, width = self.check_resize_height_width(height, width)
|
| 128 |
+
|
| 129 |
+
# Tiler parameters, batch size ...
|
| 130 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 131 |
+
|
| 132 |
+
# Prepare scheduler
|
| 133 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 134 |
+
|
| 135 |
+
# Prepare latent tensors
|
| 136 |
+
if self.motion_modules is None:
|
| 137 |
+
noise = self.generate_noise((1, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype).repeat(num_frames, 1, 1, 1)
|
| 138 |
+
else:
|
| 139 |
+
noise = self.generate_noise((num_frames, 4, height//8, width//8), seed=seed, device="cpu", dtype=self.torch_dtype)
|
| 140 |
+
if input_frames is None or denoising_strength == 1.0:
|
| 141 |
+
latents = noise
|
| 142 |
+
else:
|
| 143 |
+
latents = self.encode_video(input_frames, **tiler_kwargs)
|
| 144 |
+
latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
|
| 145 |
+
latents = latents.to(self.device) # will be deleted for supporting long videos
|
| 146 |
+
|
| 147 |
+
# Encode prompts
|
| 148 |
+
prompt_emb_posi = self.encode_prompt(prompt, clip_skip=clip_skip, positive=True)
|
| 149 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, clip_skip=clip_skip, positive=False)
|
| 150 |
+
|
| 151 |
+
# IP-Adapter
|
| 152 |
+
if ipadapter_images is not None:
|
| 153 |
+
if ipadapter_use_instant_style:
|
| 154 |
+
self.ipadapter.set_less_adapter()
|
| 155 |
+
else:
|
| 156 |
+
self.ipadapter.set_full_adapter()
|
| 157 |
+
ipadapter_image_encoding = self.ipadapter_image_encoder(ipadapter_images)
|
| 158 |
+
ipadapter_kwargs_list_posi = {"ipadapter_kwargs_list": self.ipadapter(ipadapter_image_encoding, scale=ipadapter_scale)}
|
| 159 |
+
ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": self.ipadapter(torch.zeros_like(ipadapter_image_encoding))}
|
| 160 |
+
else:
|
| 161 |
+
ipadapter_kwargs_list_posi, ipadapter_kwargs_list_nega = {"ipadapter_kwargs_list": {}}, {"ipadapter_kwargs_list": {}}
|
| 162 |
+
|
| 163 |
+
# Prepare ControlNets
|
| 164 |
+
if controlnet_frames is not None:
|
| 165 |
+
if isinstance(controlnet_frames[0], list):
|
| 166 |
+
controlnet_frames_ = []
|
| 167 |
+
for processor_id in range(len(controlnet_frames)):
|
| 168 |
+
controlnet_frames_.append(
|
| 169 |
+
torch.stack([
|
| 170 |
+
self.controlnet.process_image(controlnet_frame, processor_id=processor_id).to(self.torch_dtype)
|
| 171 |
+
for controlnet_frame in progress_bar_cmd(controlnet_frames[processor_id])
|
| 172 |
+
], dim=1)
|
| 173 |
+
)
|
| 174 |
+
controlnet_frames = torch.concat(controlnet_frames_, dim=0)
|
| 175 |
+
else:
|
| 176 |
+
controlnet_frames = torch.stack([
|
| 177 |
+
self.controlnet.process_image(controlnet_frame).to(self.torch_dtype)
|
| 178 |
+
for controlnet_frame in progress_bar_cmd(controlnet_frames)
|
| 179 |
+
], dim=1)
|
| 180 |
+
controlnet_kwargs = {"controlnet_frames": controlnet_frames}
|
| 181 |
+
else:
|
| 182 |
+
controlnet_kwargs = {"controlnet_frames": None}
|
| 183 |
+
|
| 184 |
+
# Prepare extra input
|
| 185 |
+
extra_input = self.prepare_extra_input(latents)
|
| 186 |
+
|
| 187 |
+
# Denoise
|
| 188 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 189 |
+
timestep = timestep.unsqueeze(0).to(self.device)
|
| 190 |
+
|
| 191 |
+
# Classifier-free guidance
|
| 192 |
+
noise_pred_posi = lets_dance_xl(
|
| 193 |
+
self.unet, motion_modules=self.motion_modules, controlnet=None,
|
| 194 |
+
sample=latents, timestep=timestep,
|
| 195 |
+
**prompt_emb_posi, **controlnet_kwargs, **ipadapter_kwargs_list_posi, **extra_input, **tiler_kwargs,
|
| 196 |
+
device=self.device,
|
| 197 |
+
)
|
| 198 |
+
noise_pred_nega = lets_dance_xl(
|
| 199 |
+
self.unet, motion_modules=self.motion_modules, controlnet=None,
|
| 200 |
+
sample=latents, timestep=timestep,
|
| 201 |
+
**prompt_emb_nega, **controlnet_kwargs, **ipadapter_kwargs_list_nega, **extra_input, **tiler_kwargs,
|
| 202 |
+
device=self.device,
|
| 203 |
+
)
|
| 204 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 205 |
+
|
| 206 |
+
# DDIM and smoother
|
| 207 |
+
if smoother is not None and progress_id in smoother_progress_ids:
|
| 208 |
+
rendered_frames = self.scheduler.step(noise_pred, timestep, latents, to_final=True)
|
| 209 |
+
rendered_frames = self.decode_video(rendered_frames)
|
| 210 |
+
rendered_frames = smoother(rendered_frames, original_frames=input_frames)
|
| 211 |
+
target_latents = self.encode_video(rendered_frames)
|
| 212 |
+
noise_pred = self.scheduler.return_to_timestep(timestep, latents, target_latents)
|
| 213 |
+
latents = self.scheduler.step(noise_pred, timestep, latents)
|
| 214 |
+
|
| 215 |
+
# UI
|
| 216 |
+
if progress_bar_st is not None:
|
| 217 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 218 |
+
|
| 219 |
+
# Decode image
|
| 220 |
+
output_frames = self.decode_video(latents, **tiler_kwargs)
|
| 221 |
+
|
| 222 |
+
# Post-process
|
| 223 |
+
if smoother is not None and (num_inference_steps in smoother_progress_ids or -1 in smoother_progress_ids):
|
| 224 |
+
output_frames = smoother(output_frames, original_frames=input_frames)
|
| 225 |
+
|
| 226 |
+
return output_frames
|
diffsynth/pipelines/step_video.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models import ModelManager
|
| 2 |
+
from ..models.hunyuan_dit_text_encoder import HunyuanDiTCLIPTextEncoder
|
| 3 |
+
from ..models.stepvideo_text_encoder import STEP1TextEncoder
|
| 4 |
+
from ..models.stepvideo_dit import StepVideoModel
|
| 5 |
+
from ..models.stepvideo_vae import StepVideoVAE
|
| 6 |
+
from ..schedulers.flow_match import FlowMatchScheduler
|
| 7 |
+
from .base import BasePipeline
|
| 8 |
+
from ..prompters import StepVideoPrompter
|
| 9 |
+
import torch
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
import numpy as np
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear
|
| 14 |
+
from transformers.models.bert.modeling_bert import BertEmbeddings
|
| 15 |
+
from ..models.stepvideo_dit import RMSNorm
|
| 16 |
+
from ..models.stepvideo_vae import CausalConv, CausalConvAfterNorm, Upsample2D, BaseGroupNorm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class StepVideoPipeline(BasePipeline):
|
| 21 |
+
|
| 22 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 23 |
+
super().__init__(device=device, torch_dtype=torch_dtype)
|
| 24 |
+
self.scheduler = FlowMatchScheduler(sigma_min=0.0, extra_one_step=True, shift=13.0, reverse_sigmas=True, num_train_timesteps=1)
|
| 25 |
+
self.prompter = StepVideoPrompter()
|
| 26 |
+
self.text_encoder_1: HunyuanDiTCLIPTextEncoder = None
|
| 27 |
+
self.text_encoder_2: STEP1TextEncoder = None
|
| 28 |
+
self.dit: StepVideoModel = None
|
| 29 |
+
self.vae: StepVideoVAE = None
|
| 30 |
+
self.model_names = ['text_encoder_1', 'text_encoder_2', 'dit', 'vae']
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def enable_vram_management(self, num_persistent_param_in_dit=None):
|
| 34 |
+
dtype = next(iter(self.text_encoder_1.parameters())).dtype
|
| 35 |
+
enable_vram_management(
|
| 36 |
+
self.text_encoder_1,
|
| 37 |
+
module_map = {
|
| 38 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 39 |
+
BertEmbeddings: AutoWrappedModule,
|
| 40 |
+
torch.nn.LayerNorm: AutoWrappedModule,
|
| 41 |
+
},
|
| 42 |
+
module_config = dict(
|
| 43 |
+
offload_dtype=dtype,
|
| 44 |
+
offload_device="cpu",
|
| 45 |
+
onload_dtype=dtype,
|
| 46 |
+
onload_device="cpu",
|
| 47 |
+
computation_dtype=torch.float32,
|
| 48 |
+
computation_device=self.device,
|
| 49 |
+
),
|
| 50 |
+
)
|
| 51 |
+
dtype = next(iter(self.text_encoder_2.parameters())).dtype
|
| 52 |
+
enable_vram_management(
|
| 53 |
+
self.text_encoder_2,
|
| 54 |
+
module_map = {
|
| 55 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 56 |
+
RMSNorm: AutoWrappedModule,
|
| 57 |
+
torch.nn.Embedding: AutoWrappedModule,
|
| 58 |
+
},
|
| 59 |
+
module_config = dict(
|
| 60 |
+
offload_dtype=dtype,
|
| 61 |
+
offload_device="cpu",
|
| 62 |
+
onload_dtype=dtype,
|
| 63 |
+
onload_device="cpu",
|
| 64 |
+
computation_dtype=self.torch_dtype,
|
| 65 |
+
computation_device=self.device,
|
| 66 |
+
),
|
| 67 |
+
)
|
| 68 |
+
dtype = next(iter(self.dit.parameters())).dtype
|
| 69 |
+
enable_vram_management(
|
| 70 |
+
self.dit,
|
| 71 |
+
module_map = {
|
| 72 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 73 |
+
torch.nn.Conv2d: AutoWrappedModule,
|
| 74 |
+
torch.nn.LayerNorm: AutoWrappedModule,
|
| 75 |
+
RMSNorm: AutoWrappedModule,
|
| 76 |
+
},
|
| 77 |
+
module_config = dict(
|
| 78 |
+
offload_dtype=dtype,
|
| 79 |
+
offload_device="cpu",
|
| 80 |
+
onload_dtype=dtype,
|
| 81 |
+
onload_device=self.device,
|
| 82 |
+
computation_dtype=self.torch_dtype,
|
| 83 |
+
computation_device=self.device,
|
| 84 |
+
),
|
| 85 |
+
max_num_param=num_persistent_param_in_dit,
|
| 86 |
+
overflow_module_config = dict(
|
| 87 |
+
offload_dtype=dtype,
|
| 88 |
+
offload_device="cpu",
|
| 89 |
+
onload_dtype=dtype,
|
| 90 |
+
onload_device="cpu",
|
| 91 |
+
computation_dtype=self.torch_dtype,
|
| 92 |
+
computation_device=self.device,
|
| 93 |
+
),
|
| 94 |
+
)
|
| 95 |
+
dtype = next(iter(self.vae.parameters())).dtype
|
| 96 |
+
enable_vram_management(
|
| 97 |
+
self.vae,
|
| 98 |
+
module_map = {
|
| 99 |
+
torch.nn.Linear: AutoWrappedLinear,
|
| 100 |
+
torch.nn.Conv3d: AutoWrappedModule,
|
| 101 |
+
CausalConv: AutoWrappedModule,
|
| 102 |
+
CausalConvAfterNorm: AutoWrappedModule,
|
| 103 |
+
Upsample2D: AutoWrappedModule,
|
| 104 |
+
BaseGroupNorm: AutoWrappedModule,
|
| 105 |
+
},
|
| 106 |
+
module_config = dict(
|
| 107 |
+
offload_dtype=dtype,
|
| 108 |
+
offload_device="cpu",
|
| 109 |
+
onload_dtype=dtype,
|
| 110 |
+
onload_device="cpu",
|
| 111 |
+
computation_dtype=self.torch_dtype,
|
| 112 |
+
computation_device=self.device,
|
| 113 |
+
),
|
| 114 |
+
)
|
| 115 |
+
self.enable_cpu_offload()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def fetch_models(self, model_manager: ModelManager):
|
| 119 |
+
self.text_encoder_1 = model_manager.fetch_model("hunyuan_dit_clip_text_encoder")
|
| 120 |
+
self.text_encoder_2 = model_manager.fetch_model("stepvideo_text_encoder_2")
|
| 121 |
+
self.dit = model_manager.fetch_model("stepvideo_dit")
|
| 122 |
+
self.vae = model_manager.fetch_model("stepvideo_vae")
|
| 123 |
+
self.prompter.fetch_models(self.text_encoder_1, self.text_encoder_2)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def from_model_manager(model_manager: ModelManager, torch_dtype=None, device=None):
|
| 128 |
+
if device is None: device = model_manager.device
|
| 129 |
+
if torch_dtype is None: torch_dtype = model_manager.torch_dtype
|
| 130 |
+
pipe = StepVideoPipeline(device=device, torch_dtype=torch_dtype)
|
| 131 |
+
pipe.fetch_models(model_manager)
|
| 132 |
+
return pipe
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def encode_prompt(self, prompt, positive=True):
|
| 136 |
+
clip_embeds, llm_embeds, llm_mask = self.prompter.encode_prompt(prompt, device=self.device, positive=positive)
|
| 137 |
+
clip_embeds = clip_embeds.to(dtype=self.torch_dtype, device=self.device)
|
| 138 |
+
llm_embeds = llm_embeds.to(dtype=self.torch_dtype, device=self.device)
|
| 139 |
+
llm_mask = llm_mask.to(dtype=self.torch_dtype, device=self.device)
|
| 140 |
+
return {"encoder_hidden_states_2": clip_embeds, "encoder_hidden_states": llm_embeds, "encoder_attention_mask": llm_mask}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def tensor2video(self, frames):
|
| 144 |
+
frames = rearrange(frames, "C T H W -> T H W C")
|
| 145 |
+
frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8)
|
| 146 |
+
frames = [Image.fromarray(frame) for frame in frames]
|
| 147 |
+
return frames
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@torch.no_grad()
|
| 151 |
+
def __call__(
|
| 152 |
+
self,
|
| 153 |
+
prompt,
|
| 154 |
+
negative_prompt="",
|
| 155 |
+
input_video=None,
|
| 156 |
+
denoising_strength=1.0,
|
| 157 |
+
seed=None,
|
| 158 |
+
rand_device="cpu",
|
| 159 |
+
height=544,
|
| 160 |
+
width=992,
|
| 161 |
+
num_frames=204,
|
| 162 |
+
cfg_scale=9.0,
|
| 163 |
+
num_inference_steps=30,
|
| 164 |
+
tiled=True,
|
| 165 |
+
tile_size=(34, 34),
|
| 166 |
+
tile_stride=(16, 16),
|
| 167 |
+
smooth_scale=0.6,
|
| 168 |
+
progress_bar_cmd=lambda x: x,
|
| 169 |
+
progress_bar_st=None,
|
| 170 |
+
):
|
| 171 |
+
# Tiler parameters
|
| 172 |
+
tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
|
| 173 |
+
|
| 174 |
+
# Scheduler
|
| 175 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength)
|
| 176 |
+
|
| 177 |
+
# Initialize noise
|
| 178 |
+
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)
|
| 179 |
+
|
| 180 |
+
# Encode prompts
|
| 181 |
+
self.load_models_to_device(["text_encoder_1", "text_encoder_2"])
|
| 182 |
+
prompt_emb_posi = self.encode_prompt(prompt, positive=True)
|
| 183 |
+
if cfg_scale != 1.0:
|
| 184 |
+
prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False)
|
| 185 |
+
|
| 186 |
+
# Denoise
|
| 187 |
+
self.load_models_to_device(["dit"])
|
| 188 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 189 |
+
timestep = timestep.unsqueeze(0).to(dtype=self.torch_dtype, device=self.device)
|
| 190 |
+
print(f"Step {progress_id + 1} / {len(self.scheduler.timesteps)}")
|
| 191 |
+
|
| 192 |
+
# Inference
|
| 193 |
+
noise_pred_posi = self.dit(latents, timestep=timestep, **prompt_emb_posi)
|
| 194 |
+
if cfg_scale != 1.0:
|
| 195 |
+
noise_pred_nega = self.dit(latents, timestep=timestep, **prompt_emb_nega)
|
| 196 |
+
noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
|
| 197 |
+
else:
|
| 198 |
+
noise_pred = noise_pred_posi
|
| 199 |
+
|
| 200 |
+
# Scheduler
|
| 201 |
+
latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
|
| 202 |
+
|
| 203 |
+
# Decode
|
| 204 |
+
self.load_models_to_device(['vae'])
|
| 205 |
+
frames = self.vae.decode(latents, device=self.device, smooth_scale=smooth_scale, **tiler_kwargs)
|
| 206 |
+
self.load_models_to_device([])
|
| 207 |
+
frames = self.tensor2video(frames[0])
|
| 208 |
+
|
| 209 |
+
return frames
|
diffsynth/pipelines/svd_video.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..models import ModelManager, SVDImageEncoder, SVDUNet, SVDVAEEncoder, SVDVAEDecoder
|
| 2 |
+
from ..schedulers import ContinuousODEScheduler
|
| 3 |
+
from .base import BasePipeline
|
| 4 |
+
import torch
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import numpy as np
|
| 8 |
+
from einops import rearrange, repeat
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SVDVideoPipeline(BasePipeline):
|
| 13 |
+
|
| 14 |
+
def __init__(self, device="cuda", torch_dtype=torch.float16):
|
| 15 |
+
super().__init__(device=device, torch_dtype=torch_dtype)
|
| 16 |
+
self.scheduler = ContinuousODEScheduler()
|
| 17 |
+
# models
|
| 18 |
+
self.image_encoder: SVDImageEncoder = None
|
| 19 |
+
self.unet: SVDUNet = None
|
| 20 |
+
self.vae_encoder: SVDVAEEncoder = None
|
| 21 |
+
self.vae_decoder: SVDVAEDecoder = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def fetch_models(self, model_manager: ModelManager):
|
| 25 |
+
self.image_encoder = model_manager.fetch_model("svd_image_encoder")
|
| 26 |
+
self.unet = model_manager.fetch_model("svd_unet")
|
| 27 |
+
self.vae_encoder = model_manager.fetch_model("svd_vae_encoder")
|
| 28 |
+
self.vae_decoder = model_manager.fetch_model("svd_vae_decoder")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@staticmethod
|
| 32 |
+
def from_model_manager(model_manager: ModelManager, **kwargs):
|
| 33 |
+
pipe = SVDVideoPipeline(
|
| 34 |
+
device=model_manager.device,
|
| 35 |
+
torch_dtype=model_manager.torch_dtype
|
| 36 |
+
)
|
| 37 |
+
pipe.fetch_models(model_manager)
|
| 38 |
+
return pipe
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def encode_image_with_clip(self, image):
|
| 42 |
+
image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype)
|
| 43 |
+
image = SVDCLIPImageProcessor().resize_with_antialiasing(image, (224, 224))
|
| 44 |
+
image = (image + 1.0) / 2.0
|
| 45 |
+
mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).reshape(1, 3, 1, 1).to(device=self.device, dtype=self.torch_dtype)
|
| 46 |
+
std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).reshape(1, 3, 1, 1).to(device=self.device, dtype=self.torch_dtype)
|
| 47 |
+
image = (image - mean) / std
|
| 48 |
+
image_emb = self.image_encoder(image)
|
| 49 |
+
return image_emb
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def encode_image_with_vae(self, image, noise_aug_strength, seed=None):
|
| 53 |
+
image = self.preprocess_image(image).to(device=self.device, dtype=self.torch_dtype)
|
| 54 |
+
noise = self.generate_noise(image.shape, seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 55 |
+
image = image + noise_aug_strength * noise
|
| 56 |
+
image_emb = self.vae_encoder(image) / self.vae_encoder.scaling_factor
|
| 57 |
+
return image_emb
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def encode_video_with_vae(self, video):
|
| 61 |
+
video = torch.concat([self.preprocess_image(frame) for frame in video], dim=0)
|
| 62 |
+
video = rearrange(video, "T C H W -> 1 C T H W")
|
| 63 |
+
video = video.to(device=self.device, dtype=self.torch_dtype)
|
| 64 |
+
latents = self.vae_encoder.encode_video(video)
|
| 65 |
+
latents = rearrange(latents[0], "C T H W -> T C H W")
|
| 66 |
+
return latents
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def tensor2video(self, frames):
|
| 70 |
+
frames = rearrange(frames, "C T H W -> T H W C")
|
| 71 |
+
frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8)
|
| 72 |
+
frames = [Image.fromarray(frame) for frame in frames]
|
| 73 |
+
return frames
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def calculate_noise_pred(
|
| 77 |
+
self,
|
| 78 |
+
latents,
|
| 79 |
+
timestep,
|
| 80 |
+
add_time_id,
|
| 81 |
+
cfg_scales,
|
| 82 |
+
image_emb_vae_posi, image_emb_clip_posi,
|
| 83 |
+
image_emb_vae_nega, image_emb_clip_nega
|
| 84 |
+
):
|
| 85 |
+
# Positive side
|
| 86 |
+
noise_pred_posi = self.unet(
|
| 87 |
+
torch.cat([latents, image_emb_vae_posi], dim=1),
|
| 88 |
+
timestep, image_emb_clip_posi, add_time_id
|
| 89 |
+
)
|
| 90 |
+
# Negative side
|
| 91 |
+
noise_pred_nega = self.unet(
|
| 92 |
+
torch.cat([latents, image_emb_vae_nega], dim=1),
|
| 93 |
+
timestep, image_emb_clip_nega, add_time_id
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# Classifier-free guidance
|
| 97 |
+
noise_pred = noise_pred_nega + cfg_scales * (noise_pred_posi - noise_pred_nega)
|
| 98 |
+
|
| 99 |
+
return noise_pred
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def post_process_latents(self, latents, post_normalize=True, contrast_enhance_scale=1.0):
|
| 103 |
+
if post_normalize:
|
| 104 |
+
mean, std = latents.mean(), latents.std()
|
| 105 |
+
latents = (latents - latents.mean(dim=[1, 2, 3], keepdim=True)) / latents.std(dim=[1, 2, 3], keepdim=True) * std + mean
|
| 106 |
+
latents = latents * contrast_enhance_scale
|
| 107 |
+
return latents
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@torch.no_grad()
|
| 111 |
+
def __call__(
|
| 112 |
+
self,
|
| 113 |
+
input_image=None,
|
| 114 |
+
input_video=None,
|
| 115 |
+
mask_frames=[],
|
| 116 |
+
mask_frame_ids=[],
|
| 117 |
+
min_cfg_scale=1.0,
|
| 118 |
+
max_cfg_scale=3.0,
|
| 119 |
+
denoising_strength=1.0,
|
| 120 |
+
num_frames=25,
|
| 121 |
+
height=576,
|
| 122 |
+
width=1024,
|
| 123 |
+
fps=7,
|
| 124 |
+
motion_bucket_id=127,
|
| 125 |
+
noise_aug_strength=0.02,
|
| 126 |
+
num_inference_steps=20,
|
| 127 |
+
post_normalize=True,
|
| 128 |
+
contrast_enhance_scale=1.2,
|
| 129 |
+
seed=None,
|
| 130 |
+
progress_bar_cmd=tqdm,
|
| 131 |
+
progress_bar_st=None,
|
| 132 |
+
):
|
| 133 |
+
height, width = self.check_resize_height_width(height, width)
|
| 134 |
+
|
| 135 |
+
# Prepare scheduler
|
| 136 |
+
self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength)
|
| 137 |
+
|
| 138 |
+
# Prepare latent tensors
|
| 139 |
+
noise = self.generate_noise((num_frames, 4, height//8, width//8), seed=seed, device=self.device, dtype=self.torch_dtype)
|
| 140 |
+
if denoising_strength == 1.0:
|
| 141 |
+
latents = noise.clone()
|
| 142 |
+
else:
|
| 143 |
+
latents = self.encode_video_with_vae(input_video)
|
| 144 |
+
latents = self.scheduler.add_noise(latents, noise, self.scheduler.timesteps[0])
|
| 145 |
+
|
| 146 |
+
# Prepare mask frames
|
| 147 |
+
if len(mask_frames) > 0:
|
| 148 |
+
mask_latents = self.encode_video_with_vae(mask_frames)
|
| 149 |
+
|
| 150 |
+
# Encode image
|
| 151 |
+
image_emb_clip_posi = self.encode_image_with_clip(input_image)
|
| 152 |
+
image_emb_clip_nega = torch.zeros_like(image_emb_clip_posi)
|
| 153 |
+
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)
|
| 154 |
+
image_emb_vae_nega = torch.zeros_like(image_emb_vae_posi)
|
| 155 |
+
|
| 156 |
+
# Prepare classifier-free guidance
|
| 157 |
+
cfg_scales = torch.linspace(min_cfg_scale, max_cfg_scale, num_frames)
|
| 158 |
+
cfg_scales = cfg_scales.reshape(num_frames, 1, 1, 1).to(device=self.device, dtype=self.torch_dtype)
|
| 159 |
+
|
| 160 |
+
# Prepare positional id
|
| 161 |
+
add_time_id = torch.tensor([[fps-1, motion_bucket_id, noise_aug_strength]], device=self.device)
|
| 162 |
+
|
| 163 |
+
# Denoise
|
| 164 |
+
for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
|
| 165 |
+
|
| 166 |
+
# Mask frames
|
| 167 |
+
for frame_id, mask_frame_id in enumerate(mask_frame_ids):
|
| 168 |
+
latents[mask_frame_id] = self.scheduler.add_noise(mask_latents[frame_id], noise[mask_frame_id], timestep)
|
| 169 |
+
|
| 170 |
+
# Fetch model output
|
| 171 |
+
noise_pred = self.calculate_noise_pred(
|
| 172 |
+
latents, timestep, add_time_id, cfg_scales,
|
| 173 |
+
image_emb_vae_posi, image_emb_clip_posi, image_emb_vae_nega, image_emb_clip_nega
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# Forward Euler
|
| 177 |
+
latents = self.scheduler.step(noise_pred, timestep, latents)
|
| 178 |
+
|
| 179 |
+
# Update progress bar
|
| 180 |
+
if progress_bar_st is not None:
|
| 181 |
+
progress_bar_st.progress(progress_id / len(self.scheduler.timesteps))
|
| 182 |
+
|
| 183 |
+
# Decode image
|
| 184 |
+
latents = self.post_process_latents(latents, post_normalize=post_normalize, contrast_enhance_scale=contrast_enhance_scale)
|
| 185 |
+
video = self.vae_decoder.decode_video(latents, progress_bar=progress_bar_cmd)
|
| 186 |
+
video = self.tensor2video(video)
|
| 187 |
+
|
| 188 |
+
return video
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class SVDCLIPImageProcessor:
|
| 193 |
+
def __init__(self):
|
| 194 |
+
pass
|
| 195 |
+
|
| 196 |
+
def resize_with_antialiasing(self, input, size, interpolation="bicubic", align_corners=True):
|
| 197 |
+
h, w = input.shape[-2:]
|
| 198 |
+
factors = (h / size[0], w / size[1])
|
| 199 |
+
|
| 200 |
+
# First, we have to determine sigma
|
| 201 |
+
# Taken from skimage: https://github.com/scikit-image/scikit-image/blob/v0.19.2/skimage/transform/_warps.py#L171
|
| 202 |
+
sigmas = (
|
| 203 |
+
max((factors[0] - 1.0) / 2.0, 0.001),
|
| 204 |
+
max((factors[1] - 1.0) / 2.0, 0.001),
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Now kernel size. Good results are for 3 sigma, but that is kind of slow. Pillow uses 1 sigma
|
| 208 |
+
# https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206
|
| 209 |
+
# But they do it in the 2 passes, which gives better results. Let's try 2 sigmas for now
|
| 210 |
+
ks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3))
|
| 211 |
+
|
| 212 |
+
# Make sure it is odd
|
| 213 |
+
if (ks[0] % 2) == 0:
|
| 214 |
+
ks = ks[0] + 1, ks[1]
|
| 215 |
+
|
| 216 |
+
if (ks[1] % 2) == 0:
|
| 217 |
+
ks = ks[0], ks[1] + 1
|
| 218 |
+
|
| 219 |
+
input = self._gaussian_blur2d(input, ks, sigmas)
|
| 220 |
+
|
| 221 |
+
output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)
|
| 222 |
+
return output
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _compute_padding(self, kernel_size):
|
| 226 |
+
"""Compute padding tuple."""
|
| 227 |
+
# 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)
|
| 228 |
+
# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad
|
| 229 |
+
if len(kernel_size) < 2:
|
| 230 |
+
raise AssertionError(kernel_size)
|
| 231 |
+
computed = [k - 1 for k in kernel_size]
|
| 232 |
+
|
| 233 |
+
# for even kernels we need to do asymmetric padding :(
|
| 234 |
+
out_padding = 2 * len(kernel_size) * [0]
|
| 235 |
+
|
| 236 |
+
for i in range(len(kernel_size)):
|
| 237 |
+
computed_tmp = computed[-(i + 1)]
|
| 238 |
+
|
| 239 |
+
pad_front = computed_tmp // 2
|
| 240 |
+
pad_rear = computed_tmp - pad_front
|
| 241 |
+
|
| 242 |
+
out_padding[2 * i + 0] = pad_front
|
| 243 |
+
out_padding[2 * i + 1] = pad_rear
|
| 244 |
+
|
| 245 |
+
return out_padding
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _filter2d(self, input, kernel):
|
| 249 |
+
# prepare kernel
|
| 250 |
+
b, c, h, w = input.shape
|
| 251 |
+
tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
|
| 252 |
+
|
| 253 |
+
tmp_kernel = tmp_kernel.expand(-1, c, -1, -1)
|
| 254 |
+
|
| 255 |
+
height, width = tmp_kernel.shape[-2:]
|
| 256 |
+
|
| 257 |
+
padding_shape: list[int] = self._compute_padding([height, width])
|
| 258 |
+
input = torch.nn.functional.pad(input, padding_shape, mode="reflect")
|
| 259 |
+
|
| 260 |
+
# kernel and input tensor reshape to align element-wise or batch-wise params
|
| 261 |
+
tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)
|
| 262 |
+
input = input.view(-1, tmp_kernel.size(0), input.size(-2), input.size(-1))
|
| 263 |
+
|
| 264 |
+
# convolve the tensor with the kernel.
|
| 265 |
+
output = torch.nn.functional.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
|
| 266 |
+
|
| 267 |
+
out = output.view(b, c, h, w)
|
| 268 |
+
return out
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _gaussian(self, window_size: int, sigma):
|
| 272 |
+
if isinstance(sigma, float):
|
| 273 |
+
sigma = torch.tensor([[sigma]])
|
| 274 |
+
|
| 275 |
+
batch_size = sigma.shape[0]
|
| 276 |
+
|
| 277 |
+
x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)
|
| 278 |
+
|
| 279 |
+
if window_size % 2 == 0:
|
| 280 |
+
x = x + 0.5
|
| 281 |
+
|
| 282 |
+
gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0)))
|
| 283 |
+
|
| 284 |
+
return gauss / gauss.sum(-1, keepdim=True)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _gaussian_blur2d(self, input, kernel_size, sigma):
|
| 288 |
+
if isinstance(sigma, tuple):
|
| 289 |
+
sigma = torch.tensor([sigma], dtype=input.dtype)
|
| 290 |
+
else:
|
| 291 |
+
sigma = sigma.to(dtype=input.dtype)
|
| 292 |
+
|
| 293 |
+
ky, kx = int(kernel_size[0]), int(kernel_size[1])
|
| 294 |
+
bs = sigma.shape[0]
|
| 295 |
+
kernel_x = self._gaussian(kx, sigma[:, 1].view(bs, 1))
|
| 296 |
+
kernel_y = self._gaussian(ky, sigma[:, 0].view(bs, 1))
|
| 297 |
+
out_x = self._filter2d(input, kernel_x[..., None, :])
|
| 298 |
+
out = self._filter2d(out_x, k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FastBlend.patch_match import PyramidPatchMatcher
|
| 6 |
+
from ..extensions.FastBlend.runners.fast import TableManager
|
| 7 |
+
from .base import VideoProcessor
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class FastBlendSmoother(VideoProcessor):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
inference_mode="fast", batch_size=8, window_size=60,
|
| 14 |
+
minimum_patch_size=5, threads_per_block=8, num_iter=5, gpu_id=0, guide_weight=10.0, initialize="identity", tracking_window_size=0
|
| 15 |
+
):
|
| 16 |
+
self.inference_mode = inference_mode
|
| 17 |
+
self.batch_size = batch_size
|
| 18 |
+
self.window_size = window_size
|
| 19 |
+
self.ebsynth_config = {
|
| 20 |
+
"minimum_patch_size": minimum_patch_size,
|
| 21 |
+
"threads_per_block": threads_per_block,
|
| 22 |
+
"num_iter": num_iter,
|
| 23 |
+
"gpu_id": gpu_id,
|
| 24 |
+
"guide_weight": guide_weight,
|
| 25 |
+
"initialize": initialize,
|
| 26 |
+
"tracking_window_size": tracking_window_size
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
@staticmethod
|
| 30 |
+
def from_model_manager(model_manager, **kwargs):
|
| 31 |
+
# TODO: fetch GPU ID from model_manager
|
| 32 |
+
return FastBlendSmoother(**kwargs)
|
| 33 |
+
|
| 34 |
+
def inference_fast(self, frames_guide, frames_style):
|
| 35 |
+
table_manager = TableManager()
|
| 36 |
+
patch_match_engine = PyramidPatchMatcher(
|
| 37 |
+
image_height=frames_style[0].shape[0],
|
| 38 |
+
image_width=frames_style[0].shape[1],
|
| 39 |
+
channel=3,
|
| 40 |
+
**self.ebsynth_config
|
| 41 |
+
)
|
| 42 |
+
# left part
|
| 43 |
+
table_l = table_manager.build_remapping_table(frames_guide, frames_style, patch_match_engine, self.batch_size, desc="Fast Mode Step 1/4")
|
| 44 |
+
table_l = table_manager.remapping_table_to_blending_table(table_l)
|
| 45 |
+
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")
|
| 46 |
+
# right part
|
| 47 |
+
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")
|
| 48 |
+
table_r = table_manager.remapping_table_to_blending_table(table_r)
|
| 49 |
+
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]
|
| 50 |
+
# merge
|
| 51 |
+
frames = []
|
| 52 |
+
for (frame_l, weight_l), frame_m, (frame_r, weight_r) in zip(table_l, frames_style, table_r):
|
| 53 |
+
weight_m = -1
|
| 54 |
+
weight = weight_l + weight_m + weight_r
|
| 55 |
+
frame = frame_l * (weight_l / weight) + frame_m * (weight_m / weight) + frame_r * (weight_r / weight)
|
| 56 |
+
frames.append(frame)
|
| 57 |
+
frames = [frame.clip(0, 255).astype("uint8") for frame in frames]
|
| 58 |
+
frames = [Image.fromarray(frame) for frame in frames]
|
| 59 |
+
return frames
|
| 60 |
+
|
| 61 |
+
def inference_balanced(self, frames_guide, frames_style):
|
| 62 |
+
patch_match_engine = PyramidPatchMatcher(
|
| 63 |
+
image_height=frames_style[0].shape[0],
|
| 64 |
+
image_width=frames_style[0].shape[1],
|
| 65 |
+
channel=3,
|
| 66 |
+
**self.ebsynth_config
|
| 67 |
+
)
|
| 68 |
+
output_frames = []
|
| 69 |
+
# tasks
|
| 70 |
+
n = len(frames_style)
|
| 71 |
+
tasks = []
|
| 72 |
+
for target in range(n):
|
| 73 |
+
for source in range(target - self.window_size, target + self.window_size + 1):
|
| 74 |
+
if source >= 0 and source < n and source != target:
|
| 75 |
+
tasks.append((source, target))
|
| 76 |
+
# run
|
| 77 |
+
frames = [(None, 1) for i in range(n)]
|
| 78 |
+
for batch_id in tqdm(range(0, len(tasks), self.batch_size), desc="Balanced Mode"):
|
| 79 |
+
tasks_batch = tasks[batch_id: min(batch_id+self.batch_size, len(tasks))]
|
| 80 |
+
source_guide = np.stack([frames_guide[source] for source, target in tasks_batch])
|
| 81 |
+
target_guide = np.stack([frames_guide[target] for source, target in tasks_batch])
|
| 82 |
+
source_style = np.stack([frames_style[source] for source, target in tasks_batch])
|
| 83 |
+
_, target_style = patch_match_engine.estimate_nnf(source_guide, target_guide, source_style)
|
| 84 |
+
for (source, target), result in zip(tasks_batch, target_style):
|
| 85 |
+
frame, weight = frames[target]
|
| 86 |
+
if frame is None:
|
| 87 |
+
frame = frames_style[target]
|
| 88 |
+
frames[target] = (
|
| 89 |
+
frame * (weight / (weight + 1)) + result / (weight + 1),
|
| 90 |
+
weight + 1
|
| 91 |
+
)
|
| 92 |
+
if weight + 1 == min(n, target + self.window_size + 1) - max(0, target - self.window_size):
|
| 93 |
+
frame = frame.clip(0, 255).astype("uint8")
|
| 94 |
+
output_frames.append(Image.fromarray(frame))
|
| 95 |
+
frames[target] = (None, 1)
|
| 96 |
+
return output_frames
|
| 97 |
+
|
| 98 |
+
def inference_accurate(self, frames_guide, frames_style):
|
| 99 |
+
patch_match_engine = PyramidPatchMatcher(
|
| 100 |
+
image_height=frames_style[0].shape[0],
|
| 101 |
+
image_width=frames_style[0].shape[1],
|
| 102 |
+
channel=3,
|
| 103 |
+
use_mean_target_style=True,
|
| 104 |
+
**self.ebsynth_config
|
| 105 |
+
)
|
| 106 |
+
output_frames = []
|
| 107 |
+
# run
|
| 108 |
+
n = len(frames_style)
|
| 109 |
+
for target in tqdm(range(n), desc="Accurate Mode"):
|
| 110 |
+
l, r = max(target - self.window_size, 0), min(target + self.window_size + 1, n)
|
| 111 |
+
remapped_frames = []
|
| 112 |
+
for i in range(l, r, self.batch_size):
|
| 113 |
+
j = min(i + self.batch_size, r)
|
| 114 |
+
source_guide = np.stack([frames_guide[source] for source in range(i, j)])
|
| 115 |
+
target_guide = np.stack([frames_guide[target]] * (j - i))
|
| 116 |
+
source_style = np.stack([frames_style[source] for source in range(i, j)])
|
| 117 |
+
_, target_style = patch_match_engine.estimate_nnf(source_guide, target_guide, source_style)
|
| 118 |
+
remapped_frames.append(target_style)
|
| 119 |
+
frame = np.concatenate(remapped_frames, axis=0).mean(axis=0)
|
| 120 |
+
frame = frame.clip(0, 255).astype("uint8")
|
| 121 |
+
output_frames.append(Image.fromarray(frame))
|
| 122 |
+
return output_frames
|
| 123 |
+
|
| 124 |
+
def release_vram(self):
|
| 125 |
+
mempool = cp.get_default_memory_pool()
|
| 126 |
+
pinned_mempool = cp.get_default_pinned_memory_pool()
|
| 127 |
+
mempool.free_all_blocks()
|
| 128 |
+
pinned_mempool.free_all_blocks()
|
| 129 |
+
|
| 130 |
+
def __call__(self, rendered_frames, original_frames=None, **kwargs):
|
| 131 |
+
rendered_frames = [np.array(frame) for frame in rendered_frames]
|
| 132 |
+
original_frames = [np.array(frame) for frame in original_frames]
|
| 133 |
+
if self.inference_mode == "fast":
|
| 134 |
+
output_frames = self.inference_fast(original_frames, rendered_frames)
|
| 135 |
+
elif self.inference_mode == "balanced":
|
| 136 |
+
output_frames = self.inference_balanced(original_frames, rendered_frames)
|
| 137 |
+
elif self.inference_mode == "accurate":
|
| 138 |
+
output_frames = self.inference_accurate(original_frames, rendered_frames)
|
| 139 |
+
else:
|
| 140 |
+
raise ValueError("inference_mode must be fast, balanced or accurate")
|
| 141 |
+
self.release_vram()
|
| 142 |
+
return output_frames
|
diffsynth/processors/PILEditor.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import ImageEnhance
|
| 2 |
+
from .base import VideoProcessor
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ContrastEditor(VideoProcessor):
|
| 6 |
+
def __init__(self, rate=1.5):
|
| 7 |
+
self.rate = rate
|
| 8 |
+
|
| 9 |
+
@staticmethod
|
| 10 |
+
def from_model_manager(model_manager, **kwargs):
|
| 11 |
+
return ContrastEditor(**kwargs)
|
| 12 |
+
|
| 13 |
+
def __call__(self, rendered_frames, **kwargs):
|
| 14 |
+
rendered_frames = [ImageEnhance.Contrast(i).enhance(self.rate) for i in rendered_frames]
|
| 15 |
+
return rendered_frames
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SharpnessEditor(VideoProcessor):
|
| 19 |
+
def __init__(self, rate=1.5):
|
| 20 |
+
self.rate = rate
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def from_model_manager(model_manager, **kwargs):
|
| 24 |
+
return SharpnessEditor(**kwargs)
|
| 25 |
+
|
| 26 |
+
def __call__(self, rendered_frames, **kwargs):
|
| 27 |
+
rendered_frames = [ImageEnhance.Sharpness(i).enhance(self.rate) for i in rendered_frames]
|
| 28 |
+
return rendered_frames
|
diffsynth/processors/RIFE.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from .base import VideoProcessor
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class RIFESmoother(VideoProcessor):
|
| 8 |
+
def __init__(self, model, device="cuda", scale=1.0, batch_size=4, interpolate=True):
|
| 9 |
+
self.model = model
|
| 10 |
+
self.device = device
|
| 11 |
+
|
| 12 |
+
# IFNet only does not support float16
|
| 13 |
+
self.torch_dtype = torch.float32
|
| 14 |
+
|
| 15 |
+
# Other parameters
|
| 16 |
+
self.scale = scale
|
| 17 |
+
self.batch_size = batch_size
|
| 18 |
+
self.interpolate = interpolate
|
| 19 |
+
|
| 20 |
+
@staticmethod
|
| 21 |
+
def from_model_manager(model_manager, **kwargs):
|
| 22 |
+
return RIFESmoother(model_manager.RIFE, device=model_manager.device, **kwargs)
|
| 23 |
+
|
| 24 |
+
def process_image(self, image):
|
| 25 |
+
width, height = image.size
|
| 26 |
+
if width % 32 != 0 or height % 32 != 0:
|
| 27 |
+
width = (width + 31) // 32
|
| 28 |
+
height = (height + 31) // 32
|
| 29 |
+
image = image.resize((width, height))
|
| 30 |
+
image = torch.Tensor(np.array(image, dtype=np.float32)[:, :, [2,1,0]] / 255).permute(2, 0, 1)
|
| 31 |
+
return image
|
| 32 |
+
|
| 33 |
+
def process_images(self, images):
|
| 34 |
+
images = [self.process_image(image) for image in images]
|
| 35 |
+
images = torch.stack(images)
|
| 36 |
+
return images
|
| 37 |
+
|
| 38 |
+
def decode_images(self, images):
|
| 39 |
+
images = (images[:, [2,1,0]].permute(0, 2, 3, 1) * 255).clip(0, 255).numpy().astype(np.uint8)
|
| 40 |
+
images = [Image.fromarray(image) for image in images]
|
| 41 |
+
return images
|
| 42 |
+
|
| 43 |
+
def process_tensors(self, input_tensor, scale=1.0, batch_size=4):
|
| 44 |
+
output_tensor = []
|
| 45 |
+
for batch_id in range(0, input_tensor.shape[0], batch_size):
|
| 46 |
+
batch_id_ = min(batch_id + batch_size, input_tensor.shape[0])
|
| 47 |
+
batch_input_tensor = input_tensor[batch_id: batch_id_]
|
| 48 |
+
batch_input_tensor = batch_input_tensor.to(device=self.device, dtype=self.torch_dtype)
|
| 49 |
+
flow, mask, merged = self.model(batch_input_tensor, [4/scale, 2/scale, 1/scale])
|
| 50 |
+
output_tensor.append(merged[2].cpu())
|
| 51 |
+
output_tensor = torch.concat(output_tensor, dim=0)
|
| 52 |
+
return output_tensor
|
| 53 |
+
|
| 54 |
+
@torch.no_grad()
|
| 55 |
+
def __call__(self, rendered_frames, **kwargs):
|
| 56 |
+
# Preprocess
|
| 57 |
+
processed_images = self.process_images(rendered_frames)
|
| 58 |
+
|
| 59 |
+
# Input
|
| 60 |
+
input_tensor = torch.cat((processed_images[:-2], processed_images[2:]), dim=1)
|
| 61 |
+
|
| 62 |
+
# Interpolate
|
| 63 |
+
output_tensor = self.process_tensors(input_tensor, scale=self.scale, batch_size=self.batch_size)
|
| 64 |
+
|
| 65 |
+
if self.interpolate:
|
| 66 |
+
# Blend
|
| 67 |
+
input_tensor = torch.cat((processed_images[1:-1], output_tensor), dim=1)
|
| 68 |
+
output_tensor = self.process_tensors(input_tensor, scale=self.scale, batch_size=self.batch_size)
|
| 69 |
+
processed_images[1:-1] = output_tensor
|
| 70 |
+
else:
|
| 71 |
+
processed_images[1:-1] = (processed_images[1:-1] + output_tensor) / 2
|
| 72 |
+
|
| 73 |
+
# To images
|
| 74 |
+
output_images = self.decode_images(processed_images)
|
| 75 |
+
if output_images[0].size != rendered_frames[0].size:
|
| 76 |
+
output_images = [image.resize(rendered_frames[0].size) for image in output_images]
|
| 77 |
+
return output_images
|
diffsynth/processors/__init__.py
ADDED
|
File without changes
|
diffsynth/processors/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (152 Bytes). View file
|
|
|
diffsynth/processors/__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (687 Bytes). View file
|
|
|
diffsynth/processors/__pycache__/sequencial_processor.cpython-311.pyc
ADDED
|
Binary file (2.88 kB). View file
|
|
|
diffsynth/processors/base.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class VideoProcessor:
|
| 2 |
+
def __init__(self):
|
| 3 |
+
pass
|
| 4 |
+
|
| 5 |
+
def __call__(self):
|
| 6 |
+
raise NotImplementedError
|
diffsynth/processors/sequencial_processor.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base import VideoProcessor
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class AutoVideoProcessor(VideoProcessor):
|
| 5 |
+
def __init__(self):
|
| 6 |
+
pass
|
| 7 |
+
|
| 8 |
+
@staticmethod
|
| 9 |
+
def from_model_manager(model_manager, processor_type, **kwargs):
|
| 10 |
+
if processor_type == "FastBlend":
|
| 11 |
+
from .FastBlend import FastBlendSmoother
|
| 12 |
+
return FastBlendSmoother.from_model_manager(model_manager, **kwargs)
|
| 13 |
+
elif processor_type == "Contrast":
|
| 14 |
+
from .PILEditor import ContrastEditor
|
| 15 |
+
return ContrastEditor.from_model_manager(model_manager, **kwargs)
|
| 16 |
+
elif processor_type == "Sharpness":
|
| 17 |
+
from .PILEditor import SharpnessEditor
|
| 18 |
+
return SharpnessEditor.from_model_manager(model_manager, **kwargs)
|
| 19 |
+
elif processor_type == "RIFE":
|
| 20 |
+
from .RIFE import RIFESmoother
|
| 21 |
+
return RIFESmoother.from_model_manager(model_manager, **kwargs)
|
| 22 |
+
else:
|
| 23 |
+
raise ValueError(f"invalid processor_type: {processor_type}")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class SequencialProcessor(VideoProcessor):
|
| 27 |
+
def __init__(self, processors=[]):
|
| 28 |
+
self.processors = processors
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def from_model_manager(model_manager, configs):
|
| 32 |
+
processors = [
|
| 33 |
+
AutoVideoProcessor.from_model_manager(model_manager, config["processor_type"], **config["config"])
|
| 34 |
+
for config in configs
|
| 35 |
+
]
|
| 36 |
+
return SequencialProcessor(processors)
|
| 37 |
+
|
| 38 |
+
def __call__(self, rendered_frames, **kwargs):
|
| 39 |
+
for processor in self.processors:
|
| 40 |
+
rendered_frames = processor(rendered_frames, **kwargs)
|
| 41 |
+
return rendered_frames
|
diffsynth/prompters/__pycache__/sd3_prompter.cpython-311.pyc
ADDED
|
Binary file (5.59 kB). View file
|
|
|