Spaces:
Running
on
Zero
Running
on
Zero
Upload 7 files
Browse files- app.py +183 -4
- src/__init__.py +0 -0
- src/layers_cache.py +368 -0
- src/lora_helper.py +196 -0
- src/pipeline.py +722 -0
- src/prompt_helper.py +205 -0
- src/transformer_flux.py +583 -0
app.py
CHANGED
@@ -1,7 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import time
|
4 |
+
import torch
|
5 |
+
from PIL import Image
|
6 |
+
from tqdm import tqdm
|
7 |
import gradio as gr
|
8 |
|
9 |
+
from safetensors.torch import save_file
|
10 |
+
from src.pipeline import FluxPipeline
|
11 |
+
from src.transformer_flux import FluxTransformer2DModel
|
12 |
+
from src.lora_helper import set_single_lora, set_multi_lora, unset_lora
|
13 |
|
14 |
+
class ImageProcessor:
|
15 |
+
def __init__(self, path):
|
16 |
+
device = "cuda"
|
17 |
+
self.pipe = FluxPipeline.from_pretrained(path, torch_dtype=torch.bfloat16, device=device)
|
18 |
+
transformer = FluxTransformer2DModel.from_pretrained(path, subfolder="transformer", torch_dtype=torch.bfloat16, device=device)
|
19 |
+
self.pipe.transformer = transformer
|
20 |
+
self.pipe.to(device)
|
21 |
+
|
22 |
+
def clear_cache(self, transformer):
|
23 |
+
for name, attn_processor in transformer.attn_processors.items():
|
24 |
+
attn_processor.bank_kv.clear()
|
25 |
+
|
26 |
+
def process_image(self, prompt='', subject_imgs=[], spatial_imgs=[], height=768, width=768, output_path=None, seed=42):
|
27 |
+
image = self.pipe(
|
28 |
+
prompt,
|
29 |
+
height=int(height),
|
30 |
+
width=int(width),
|
31 |
+
guidance_scale=3.5,
|
32 |
+
num_inference_steps=25,
|
33 |
+
max_sequence_length=512,
|
34 |
+
generator=torch.Generator("cpu").manual_seed(seed),
|
35 |
+
subject_images=subject_imgs,
|
36 |
+
spatial_images=spatial_imgs,
|
37 |
+
cond_size=512,
|
38 |
+
).images[0]
|
39 |
+
self.clear_cache(self.pipe.transformer)
|
40 |
+
if output_path:
|
41 |
+
image.save(output_path)
|
42 |
+
return image
|
43 |
+
|
44 |
+
# Initialize the image processor
|
45 |
+
base_path = "/opt/liblibai-models/model-weights/black-forest-labs/FLUX.1-dev"
|
46 |
+
lora_base_path = "/opt/liblibai-models/user-workspace/rey/projects/opensource/github/EasyControl/models"
|
47 |
+
style_lora_base_path = "/opt/liblibai-models/user-workspace/zhangyuxuan/models/Shakker-Labs"
|
48 |
+
processor = ImageProcessor(base_path)
|
49 |
+
|
50 |
+
# Define the Gradio interface
|
51 |
+
def single_condition_generate_image(prompt, subject_img, spatial_img, height, width, seed, control_type, style_lora=None):
|
52 |
+
# Set the control type
|
53 |
+
if control_type == "subject":
|
54 |
+
lora_path = os.path.join(lora_base_path, "subject.safetensors")
|
55 |
+
elif control_type == "depth":
|
56 |
+
lora_path = os.path.join(lora_base_path, "depth.safetensors")
|
57 |
+
elif control_type == "seg":
|
58 |
+
lora_path = os.path.join(lora_base_path, "seg.safetensors")
|
59 |
+
elif control_type == "pose":
|
60 |
+
lora_path = os.path.join(lora_base_path, "pose.safetensors")
|
61 |
+
elif control_type == "inpainting":
|
62 |
+
lora_path = os.path.join(lora_base_path, "inpainting.safetensors")
|
63 |
+
elif control_type == "hedsketch":
|
64 |
+
lora_path = os.path.join(lora_base_path, "hedsketch.safetensors")
|
65 |
+
elif control_type == "canny":
|
66 |
+
lora_path = os.path.join(lora_base_path, "canny.safetensors")
|
67 |
+
set_single_lora(processor.pipe.transformer, lora_path, lora_weights=[1], cond_size=512)
|
68 |
+
|
69 |
+
# Set the style LoRA
|
70 |
+
if style_lora=="None":
|
71 |
+
pass
|
72 |
+
else:
|
73 |
+
if style_lora == "Simple_Sketch":
|
74 |
+
processor.pipe.unload_lora_weights()
|
75 |
+
style_lora_path = os.path.join(style_lora_base_path, "FLUX.1-dev-LoRA-Children-Simple-Sketch/pytorch_lora_weights.safetensors")
|
76 |
+
processor.pipe.load_lora_weights(self.lora_path, weight_name="pytorch_lora_weights.safetensors")
|
77 |
+
if style_lora == "Text_Poster":
|
78 |
+
processor.pipe.unload_lora_weights()
|
79 |
+
style_lora_path = os.path.join(style_lora_base_path, "FLUX.1-dev-LoRA-Text-Poster/pytorch_lora_weights.safetensors")
|
80 |
+
processor.pipe.load_lora_weights(self.lora_path, weight_name="pytorch_lora_weights.safetensors")
|
81 |
+
if style_lora == "Vector_Style":
|
82 |
+
processor.pipe.unload_lora_weights()
|
83 |
+
style_lora_path = os.path.join(style_lora_base_path, "FLUX.1-dev-LoRA-Vector-Journey/pytorch_lora_weights.safetensors")
|
84 |
+
processor.pipe.load_lora_weights(style_lora_path, weight_name="pytorch_lora_weights.safetensors")
|
85 |
+
|
86 |
+
# Process the image
|
87 |
+
subject_imgs = [subject_img] if subject_img else []
|
88 |
+
spatial_imgs = [spatial_img] if spatial_img else []
|
89 |
+
image = processor.process_image(prompt=prompt, subject_imgs=subject_imgs, spatial_imgs=spatial_imgs, height=height, width=width, seed=seed)
|
90 |
+
return image
|
91 |
+
|
92 |
+
# Define the Gradio interface
|
93 |
+
def multi_condition_generate_image(prompt, subject_img, spatial_img, height, width, seed):
|
94 |
+
subject_path = os.path.join(lora_base_path, "subject.safetensors")
|
95 |
+
inpainting_path = os.path.join(lora_base_path, "inpainting.safetensors")
|
96 |
+
set_multi_lora(processor.pipe.transformer, [subject_path, inpainting_path], lora_weights=[[1],[1]],cond_size=512)
|
97 |
+
|
98 |
+
# Process the image
|
99 |
+
subject_imgs = [subject_img] if subject_img else []
|
100 |
+
spatial_imgs = [spatial_img] if spatial_img else []
|
101 |
+
image = processor.process_image(prompt=prompt, subject_imgs=subject_imgs, spatial_imgs=spatial_imgs, height=height, width=width, seed=seed)
|
102 |
+
return image
|
103 |
+
|
104 |
+
# Define the Gradio interface components
|
105 |
+
control_types = ["subject", "depth", "pose", "inpainting", "hedsketch", "seg", "canny"]
|
106 |
+
style_loras = ["Simple_Sketch", "Text_Poster", "Vector_Style", "None"]
|
107 |
+
|
108 |
+
# Example data
|
109 |
+
single_examples = [
|
110 |
+
["A SKS in the library", Image.open("/opt/liblibai-models/user-workspace/zhangyuxuan/project/easycontrol/inference0310/test_imgs/subject3.jpg"), None, 1024, 1024, 5, "subject", None],
|
111 |
+
["In a picturesque village, a narrow cobblestone street with rustic stone buildings, colorful blinds, and lush green spaces, a cartoon man drawn with simple lines and solid colors stands in the foreground, wearing a red shirt, beige work pants, and brown shoes, carrying a strap on his shoulder. The scene features warm and enticing colors, a pleasant fusion of nature and architecture, and the camera's perspective on the street clearly shows the charming and quaint environment., Integrating elements of reality and cartoon.", None, Image.open("/opt/liblibai-models/user-workspace/zhangyuxuan/project/easycontrol/inference0310/test_imgs/openpose.png"), 1024, 1024, 1, "pose", "Vector_Style"],
|
112 |
+
]
|
113 |
+
multi_examples = [
|
114 |
+
["A SKS on the car", Image.open("/opt/liblibai-models/user-workspace/zhangyuxuan/project/easycontrol/code0221/test_imgs/subject/s17.png"), Image.open("/opt/liblibai-models/user-workspace/zhangyuxuan/project/easycontrol/code0221/test_imgs/inpainting.png"), 1024, 1024, 7],
|
115 |
+
]
|
116 |
+
|
117 |
+
|
118 |
+
# Create the Gradio Blocks interface
|
119 |
+
with gr.Blocks() as demo:
|
120 |
+
gr.Markdown("# Image Generation with EasyControl")
|
121 |
+
gr.Markdown("Generate images using EasyControl with different control types and style LoRAs.")
|
122 |
+
|
123 |
+
with gr.Tab("Single Condition Generation"):
|
124 |
+
with gr.Row():
|
125 |
+
with gr.Column():
|
126 |
+
prompt = gr.Textbox(label="Prompt")
|
127 |
+
subject_img = gr.Image(label="Subject Image", type="pil") # 上传图像文件
|
128 |
+
spatial_img = gr.Image(label="Spatial Image", type="pil") # 上传图像文件
|
129 |
+
height = gr.Slider(minimum=256, maximum=1536, step=64, label="Height", value=768)
|
130 |
+
width = gr.Slider(minimum=256, maximum=1536, step=64, label="Width", value=768)
|
131 |
+
seed = gr.Number(label="Seed", value=42)
|
132 |
+
control_type = gr.Dropdown(choices=control_types, label="Control Type")
|
133 |
+
style_lora = gr.Dropdown(choices=style_loras, label="Style LoRA")
|
134 |
+
single_generate_btn = gr.Button("Generate Image")
|
135 |
+
with gr.Column():
|
136 |
+
single_output_image = gr.Image(label="Generated Image")
|
137 |
+
|
138 |
+
# Add examples for Single Condition Generation
|
139 |
+
gr.Examples(
|
140 |
+
examples=single_examples,
|
141 |
+
inputs=[prompt, subject_img, spatial_img, height, width, seed, control_type, style_lora],
|
142 |
+
outputs=single_output_image,
|
143 |
+
fn=single_condition_generate_image,
|
144 |
+
cache_examples=True, # 缓存示例结果以加快加载速度
|
145 |
+
label="Single Condition Examples"
|
146 |
+
)
|
147 |
+
|
148 |
+
|
149 |
+
with gr.Tab("Multi-Condition Generation"):
|
150 |
+
with gr.Row():
|
151 |
+
with gr.Column():
|
152 |
+
multi_prompt = gr.Textbox(label="Prompt")
|
153 |
+
multi_subject_img = gr.Image(label="Subject Image", type="pil") # 上传图像文件
|
154 |
+
multi_spatial_img = gr.Image(label="Spatial Image", type="pil") # 上传图像文件
|
155 |
+
multi_height = gr.Slider(minimum=256, maximum=1536, step=64, label="Height", value=768)
|
156 |
+
multi_width = gr.Slider(minimum=256, maximum=1536, step=64, label="Width", value=768)
|
157 |
+
multi_seed = gr.Number(label="Seed", value=42)
|
158 |
+
multi_generate_btn = gr.Button("Generate Image")
|
159 |
+
with gr.Column():
|
160 |
+
multi_output_image = gr.Image(label="Generated Image")
|
161 |
+
|
162 |
+
# Add examples for Multi-Condition Generation
|
163 |
+
gr.Examples(
|
164 |
+
examples=multi_examples,
|
165 |
+
inputs=[multi_prompt, multi_subject_img, multi_spatial_img, multi_height, multi_width, multi_seed],
|
166 |
+
outputs=multi_output_image,
|
167 |
+
fn=multi_condition_generate_image,
|
168 |
+
cache_examples=True, # 缓存示例结果以加快加载速度
|
169 |
+
label="Multi-Condition Examples"
|
170 |
+
)
|
171 |
+
|
172 |
+
|
173 |
+
# Link the buttons to the functions
|
174 |
+
single_generate_btn.click(
|
175 |
+
single_condition_generate_image,
|
176 |
+
inputs=[prompt, subject_img, spatial_img, height, width, seed, control_type, style_lora],
|
177 |
+
outputs=single_output_image
|
178 |
+
)
|
179 |
+
multi_generate_btn.click(
|
180 |
+
multi_condition_generate_image,
|
181 |
+
inputs=[multi_prompt, multi_subject_img, multi_spatial_img, multi_height, multi_width, multi_seed],
|
182 |
+
outputs=multi_output_image
|
183 |
+
)
|
184 |
+
|
185 |
+
# Launch the Gradio app
|
186 |
+
demo.queue().launch(server_name='0.0.0.0',server_port=7861)
|
src/__init__.py
ADDED
File without changes
|
src/layers_cache.py
ADDED
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import math
|
3 |
+
from typing import Callable, List, Optional, Tuple, Union
|
4 |
+
from einops import rearrange
|
5 |
+
import torch
|
6 |
+
from torch import nn
|
7 |
+
import torch.nn.functional as F
|
8 |
+
from torch import Tensor
|
9 |
+
from diffusers.models.attention_processor import Attention
|
10 |
+
|
11 |
+
class LoRALinearLayer(nn.Module):
|
12 |
+
def __init__(
|
13 |
+
self,
|
14 |
+
in_features: int,
|
15 |
+
out_features: int,
|
16 |
+
rank: int = 4,
|
17 |
+
network_alpha: Optional[float] = None,
|
18 |
+
device: Optional[Union[torch.device, str]] = None,
|
19 |
+
dtype: Optional[torch.dtype] = None,
|
20 |
+
cond_width=512,
|
21 |
+
cond_height=512,
|
22 |
+
number=0,
|
23 |
+
n_loras=1
|
24 |
+
):
|
25 |
+
super().__init__()
|
26 |
+
self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype)
|
27 |
+
self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype)
|
28 |
+
# This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
|
29 |
+
# See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
|
30 |
+
self.network_alpha = network_alpha
|
31 |
+
self.rank = rank
|
32 |
+
self.out_features = out_features
|
33 |
+
self.in_features = in_features
|
34 |
+
|
35 |
+
nn.init.normal_(self.down.weight, std=1 / rank)
|
36 |
+
nn.init.zeros_(self.up.weight)
|
37 |
+
|
38 |
+
self.cond_height = cond_height
|
39 |
+
self.cond_width = cond_width
|
40 |
+
self.number = number
|
41 |
+
self.n_loras = n_loras
|
42 |
+
|
43 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
44 |
+
orig_dtype = hidden_states.dtype
|
45 |
+
dtype = self.down.weight.dtype
|
46 |
+
|
47 |
+
####
|
48 |
+
batch_size = hidden_states.shape[0]
|
49 |
+
cond_size = self.cond_width // 8 * self.cond_height // 8 * 16 // 64
|
50 |
+
block_size = hidden_states.shape[1] - cond_size * self.n_loras
|
51 |
+
shape = (batch_size, hidden_states.shape[1], 3072)
|
52 |
+
mask = torch.ones(shape, device=hidden_states.device, dtype=dtype)
|
53 |
+
mask[:, :block_size+self.number*cond_size, :] = 0
|
54 |
+
mask[:, block_size+(self.number+1)*cond_size:, :] = 0
|
55 |
+
hidden_states = mask * hidden_states
|
56 |
+
####
|
57 |
+
|
58 |
+
down_hidden_states = self.down(hidden_states.to(dtype))
|
59 |
+
up_hidden_states = self.up(down_hidden_states)
|
60 |
+
|
61 |
+
if self.network_alpha is not None:
|
62 |
+
up_hidden_states *= self.network_alpha / self.rank
|
63 |
+
|
64 |
+
return up_hidden_states.to(orig_dtype)
|
65 |
+
|
66 |
+
|
67 |
+
class MultiSingleStreamBlockLoraProcessor(nn.Module):
|
68 |
+
def __init__(self, dim: int, ranks=[], lora_weights=[], network_alphas=[], device=None, dtype=None, cond_width=512, cond_height=512, n_loras=1):
|
69 |
+
super().__init__()
|
70 |
+
# Initialize a list to store the LoRA layers
|
71 |
+
self.n_loras = n_loras
|
72 |
+
self.cond_width = cond_width
|
73 |
+
self.cond_height = cond_height
|
74 |
+
|
75 |
+
self.q_loras = nn.ModuleList([
|
76 |
+
LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
|
77 |
+
for i in range(n_loras)
|
78 |
+
])
|
79 |
+
self.k_loras = nn.ModuleList([
|
80 |
+
LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
|
81 |
+
for i in range(n_loras)
|
82 |
+
])
|
83 |
+
self.v_loras = nn.ModuleList([
|
84 |
+
LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
|
85 |
+
for i in range(n_loras)
|
86 |
+
])
|
87 |
+
self.lora_weights = lora_weights
|
88 |
+
self.bank_attn = None
|
89 |
+
self.bank_kv = []
|
90 |
+
|
91 |
+
|
92 |
+
def __call__(self,
|
93 |
+
attn: Attention,
|
94 |
+
hidden_states: torch.FloatTensor,
|
95 |
+
encoder_hidden_states: torch.FloatTensor = None,
|
96 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
97 |
+
image_rotary_emb: Optional[torch.Tensor] = None,
|
98 |
+
use_cond = False
|
99 |
+
) -> torch.FloatTensor:
|
100 |
+
|
101 |
+
batch_size, seq_len, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
102 |
+
scaled_seq_len = hidden_states.shape[1]
|
103 |
+
cond_size = self.cond_width // 8 * self.cond_height // 8 * 16 // 64
|
104 |
+
block_size = scaled_seq_len - cond_size * self.n_loras
|
105 |
+
scaled_cond_size = cond_size
|
106 |
+
scaled_block_size = block_size
|
107 |
+
|
108 |
+
if len(self.bank_kv)== 0:
|
109 |
+
cache = True
|
110 |
+
else:
|
111 |
+
cache = False
|
112 |
+
|
113 |
+
if cache:
|
114 |
+
query = attn.to_q(hidden_states)
|
115 |
+
key = attn.to_k(hidden_states)
|
116 |
+
value = attn.to_v(hidden_states)
|
117 |
+
for i in range(self.n_loras):
|
118 |
+
query = query + self.lora_weights[i] * self.q_loras[i](hidden_states)
|
119 |
+
key = key + self.lora_weights[i] * self.k_loras[i](hidden_states)
|
120 |
+
value = value + self.lora_weights[i] * self.v_loras[i](hidden_states)
|
121 |
+
|
122 |
+
inner_dim = key.shape[-1]
|
123 |
+
head_dim = inner_dim // attn.heads
|
124 |
+
|
125 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
126 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
127 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
128 |
+
|
129 |
+
self.bank_kv.append(key[:, :, scaled_block_size:, :])
|
130 |
+
self.bank_kv.append(value[:, :, scaled_block_size:, :])
|
131 |
+
|
132 |
+
if attn.norm_q is not None:
|
133 |
+
query = attn.norm_q(query)
|
134 |
+
if attn.norm_k is not None:
|
135 |
+
key = attn.norm_k(key)
|
136 |
+
|
137 |
+
if image_rotary_emb is not None:
|
138 |
+
from diffusers.models.embeddings import apply_rotary_emb
|
139 |
+
query = apply_rotary_emb(query, image_rotary_emb)
|
140 |
+
key = apply_rotary_emb(key, image_rotary_emb)
|
141 |
+
|
142 |
+
num_cond_blocks = self.n_loras
|
143 |
+
mask = torch.ones((scaled_seq_len, scaled_seq_len), device=hidden_states.device)
|
144 |
+
mask[ :scaled_block_size, :] = 0 # First block_size row
|
145 |
+
for i in range(num_cond_blocks):
|
146 |
+
start = i * scaled_cond_size + scaled_block_size
|
147 |
+
end = (i + 1) * scaled_cond_size + scaled_block_size
|
148 |
+
mask[start:end, start:end] = 0 # Diagonal blocks
|
149 |
+
mask = mask * -1e20
|
150 |
+
mask = mask.to(query.dtype)
|
151 |
+
|
152 |
+
hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=mask)
|
153 |
+
self.bank_attn = hidden_states[:, :, scaled_block_size:, :]
|
154 |
+
|
155 |
+
else:
|
156 |
+
query = attn.to_q(hidden_states)
|
157 |
+
key = attn.to_k(hidden_states)
|
158 |
+
value = attn.to_v(hidden_states)
|
159 |
+
|
160 |
+
inner_dim = query.shape[-1]
|
161 |
+
head_dim = inner_dim // attn.heads
|
162 |
+
|
163 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
164 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
165 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
166 |
+
|
167 |
+
key = torch.concat([key[:, :, :scaled_block_size, :], self.bank_kv[0]], dim=-2)
|
168 |
+
value = torch.concat([value[:, :, :scaled_block_size, :], self.bank_kv[1]], dim=-2)
|
169 |
+
|
170 |
+
if attn.norm_q is not None:
|
171 |
+
query = attn.norm_q(query)
|
172 |
+
if attn.norm_k is not None:
|
173 |
+
key = attn.norm_k(key)
|
174 |
+
|
175 |
+
if image_rotary_emb is not None:
|
176 |
+
from diffusers.models.embeddings import apply_rotary_emb
|
177 |
+
query = apply_rotary_emb(query, image_rotary_emb)
|
178 |
+
key = apply_rotary_emb(key, image_rotary_emb)
|
179 |
+
|
180 |
+
query = query[:, :, :scaled_block_size, :]
|
181 |
+
|
182 |
+
hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=None)
|
183 |
+
hidden_states = torch.concat([hidden_states, self.bank_attn], dim=-2)
|
184 |
+
|
185 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
186 |
+
hidden_states = hidden_states.to(query.dtype)
|
187 |
+
|
188 |
+
cond_hidden_states = hidden_states[:, block_size:,:]
|
189 |
+
hidden_states = hidden_states[:, : block_size,:]
|
190 |
+
|
191 |
+
return hidden_states if not use_cond else (hidden_states, cond_hidden_states)
|
192 |
+
|
193 |
+
|
194 |
+
class MultiDoubleStreamBlockLoraProcessor(nn.Module):
|
195 |
+
def __init__(self, dim: int, ranks=[], lora_weights=[], network_alphas=[], device=None, dtype=None, cond_width=512, cond_height=512, n_loras=1):
|
196 |
+
super().__init__()
|
197 |
+
|
198 |
+
# Initialize a list to store the LoRA layers
|
199 |
+
self.n_loras = n_loras
|
200 |
+
self.cond_width = cond_width
|
201 |
+
self.cond_height = cond_height
|
202 |
+
self.q_loras = nn.ModuleList([
|
203 |
+
LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
|
204 |
+
for i in range(n_loras)
|
205 |
+
])
|
206 |
+
self.k_loras = nn.ModuleList([
|
207 |
+
LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
|
208 |
+
for i in range(n_loras)
|
209 |
+
])
|
210 |
+
self.v_loras = nn.ModuleList([
|
211 |
+
LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
|
212 |
+
for i in range(n_loras)
|
213 |
+
])
|
214 |
+
self.proj_loras = nn.ModuleList([
|
215 |
+
LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
|
216 |
+
for i in range(n_loras)
|
217 |
+
])
|
218 |
+
self.lora_weights = lora_weights
|
219 |
+
self.bank_attn = None
|
220 |
+
self.bank_kv = []
|
221 |
+
|
222 |
+
|
223 |
+
def __call__(self,
|
224 |
+
attn: Attention,
|
225 |
+
hidden_states: torch.FloatTensor,
|
226 |
+
encoder_hidden_states: torch.FloatTensor = None,
|
227 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
228 |
+
image_rotary_emb: Optional[torch.Tensor] = None,
|
229 |
+
use_cond=False,
|
230 |
+
) -> torch.FloatTensor:
|
231 |
+
|
232 |
+
batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
233 |
+
cond_size = self.cond_width // 8 * self.cond_height // 8 * 16 // 64
|
234 |
+
block_size = hidden_states.shape[1] - cond_size * self.n_loras
|
235 |
+
scaled_seq_len = encoder_hidden_states.shape[1] + hidden_states.shape[1]
|
236 |
+
scaled_cond_size = cond_size
|
237 |
+
scaled_block_size = scaled_seq_len - scaled_cond_size * self.n_loras
|
238 |
+
|
239 |
+
# `context` projections.
|
240 |
+
inner_dim = 3072
|
241 |
+
head_dim = inner_dim // attn.heads
|
242 |
+
encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
|
243 |
+
encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
|
244 |
+
encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
|
245 |
+
|
246 |
+
encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
|
247 |
+
batch_size, -1, attn.heads, head_dim
|
248 |
+
).transpose(1, 2)
|
249 |
+
encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
|
250 |
+
batch_size, -1, attn.heads, head_dim
|
251 |
+
).transpose(1, 2)
|
252 |
+
encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
|
253 |
+
batch_size, -1, attn.heads, head_dim
|
254 |
+
).transpose(1, 2)
|
255 |
+
|
256 |
+
if attn.norm_added_q is not None:
|
257 |
+
encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
|
258 |
+
if attn.norm_added_k is not None:
|
259 |
+
encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
|
260 |
+
|
261 |
+
if len(self.bank_kv)== 0:
|
262 |
+
cache = True
|
263 |
+
else:
|
264 |
+
cache = False
|
265 |
+
|
266 |
+
if cache:
|
267 |
+
|
268 |
+
query = attn.to_q(hidden_states)
|
269 |
+
key = attn.to_k(hidden_states)
|
270 |
+
value = attn.to_v(hidden_states)
|
271 |
+
for i in range(self.n_loras):
|
272 |
+
query = query + self.lora_weights[i] * self.q_loras[i](hidden_states)
|
273 |
+
key = key + self.lora_weights[i] * self.k_loras[i](hidden_states)
|
274 |
+
value = value + self.lora_weights[i] * self.v_loras[i](hidden_states)
|
275 |
+
|
276 |
+
inner_dim = key.shape[-1]
|
277 |
+
head_dim = inner_dim // attn.heads
|
278 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
279 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
280 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
281 |
+
|
282 |
+
|
283 |
+
self.bank_kv.append(key[:, :, block_size:, :])
|
284 |
+
self.bank_kv.append(value[:, :, block_size:, :])
|
285 |
+
|
286 |
+
if attn.norm_q is not None:
|
287 |
+
query = attn.norm_q(query)
|
288 |
+
if attn.norm_k is not None:
|
289 |
+
key = attn.norm_k(key)
|
290 |
+
|
291 |
+
# attention
|
292 |
+
query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
|
293 |
+
key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
|
294 |
+
value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
|
295 |
+
|
296 |
+
if image_rotary_emb is not None:
|
297 |
+
from diffusers.models.embeddings import apply_rotary_emb
|
298 |
+
query = apply_rotary_emb(query, image_rotary_emb)
|
299 |
+
key = apply_rotary_emb(key, image_rotary_emb)
|
300 |
+
|
301 |
+
num_cond_blocks = self.n_loras
|
302 |
+
mask = torch.ones((scaled_seq_len, scaled_seq_len), device=hidden_states.device)
|
303 |
+
mask[ :scaled_block_size, :] = 0 # First block_size row
|
304 |
+
for i in range(num_cond_blocks):
|
305 |
+
start = i * scaled_cond_size + scaled_block_size
|
306 |
+
end = (i + 1) * scaled_cond_size + scaled_block_size
|
307 |
+
mask[start:end, start:end] = 0 # Diagonal blocks
|
308 |
+
mask = mask * -1e20
|
309 |
+
mask = mask.to(query.dtype)
|
310 |
+
|
311 |
+
hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=mask)
|
312 |
+
self.bank_attn = hidden_states[:, :, scaled_block_size:, :]
|
313 |
+
|
314 |
+
else:
|
315 |
+
query = attn.to_q(hidden_states)
|
316 |
+
key = attn.to_k(hidden_states)
|
317 |
+
value = attn.to_v(hidden_states)
|
318 |
+
|
319 |
+
inner_dim = query.shape[-1]
|
320 |
+
head_dim = inner_dim // attn.heads
|
321 |
+
|
322 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
323 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
324 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
325 |
+
|
326 |
+
key = torch.concat([key[:, :, :block_size, :], self.bank_kv[0]], dim=-2)
|
327 |
+
value = torch.concat([value[:, :, :block_size, :], self.bank_kv[1]], dim=-2)
|
328 |
+
|
329 |
+
if attn.norm_q is not None:
|
330 |
+
query = attn.norm_q(query)
|
331 |
+
if attn.norm_k is not None:
|
332 |
+
key = attn.norm_k(key)
|
333 |
+
|
334 |
+
# attention
|
335 |
+
query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
|
336 |
+
key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
|
337 |
+
value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
|
338 |
+
|
339 |
+
if image_rotary_emb is not None:
|
340 |
+
from diffusers.models.embeddings import apply_rotary_emb
|
341 |
+
query = apply_rotary_emb(query, image_rotary_emb)
|
342 |
+
key = apply_rotary_emb(key, image_rotary_emb)
|
343 |
+
|
344 |
+
query = query[:, :, :scaled_block_size, :]
|
345 |
+
|
346 |
+
hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=None)
|
347 |
+
hidden_states = torch.concat([hidden_states, self.bank_attn], dim=-2)
|
348 |
+
|
349 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
350 |
+
hidden_states = hidden_states.to(query.dtype)
|
351 |
+
|
352 |
+
encoder_hidden_states, hidden_states = (
|
353 |
+
hidden_states[:, : encoder_hidden_states.shape[1]],
|
354 |
+
hidden_states[:, encoder_hidden_states.shape[1] :],
|
355 |
+
)
|
356 |
+
|
357 |
+
# Linear projection (with LoRA weight applied to each proj layer)
|
358 |
+
hidden_states = attn.to_out[0](hidden_states)
|
359 |
+
for i in range(self.n_loras):
|
360 |
+
hidden_states = hidden_states + self.lora_weights[i] * self.proj_loras[i](hidden_states)
|
361 |
+
# dropout
|
362 |
+
hidden_states = attn.to_out[1](hidden_states)
|
363 |
+
encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
|
364 |
+
|
365 |
+
cond_hidden_states = hidden_states[:, block_size:,:]
|
366 |
+
hidden_states = hidden_states[:, :block_size,:]
|
367 |
+
|
368 |
+
return (hidden_states, encoder_hidden_states, cond_hidden_states) if use_cond else (encoder_hidden_states, hidden_states)
|
src/lora_helper.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers.models.attention_processor import FluxAttnProcessor2_0
|
2 |
+
from safetensors import safe_open
|
3 |
+
import re
|
4 |
+
import torch
|
5 |
+
from .layers_cache import MultiDoubleStreamBlockLoraProcessor, MultiSingleStreamBlockLoraProcessor
|
6 |
+
|
7 |
+
device = "cuda"
|
8 |
+
|
9 |
+
def load_safetensors(path):
|
10 |
+
tensors = {}
|
11 |
+
with safe_open(path, framework="pt", device="cpu") as f:
|
12 |
+
for key in f.keys():
|
13 |
+
tensors[key] = f.get_tensor(key)
|
14 |
+
return tensors
|
15 |
+
|
16 |
+
def get_lora_rank(checkpoint):
|
17 |
+
for k in checkpoint.keys():
|
18 |
+
if k.endswith(".down.weight"):
|
19 |
+
return checkpoint[k].shape[0]
|
20 |
+
|
21 |
+
def load_checkpoint(local_path):
|
22 |
+
if local_path is not None:
|
23 |
+
if '.safetensors' in local_path:
|
24 |
+
print(f"Loading .safetensors checkpoint from {local_path}")
|
25 |
+
checkpoint = load_safetensors(local_path)
|
26 |
+
else:
|
27 |
+
print(f"Loading checkpoint from {local_path}")
|
28 |
+
checkpoint = torch.load(local_path, map_location='cpu')
|
29 |
+
return checkpoint
|
30 |
+
|
31 |
+
def update_model_with_lora(checkpoint, lora_weights, transformer, cond_size):
|
32 |
+
number = len(lora_weights)
|
33 |
+
ranks = [get_lora_rank(checkpoint) for _ in range(number)]
|
34 |
+
lora_attn_procs = {}
|
35 |
+
double_blocks_idx = list(range(19))
|
36 |
+
single_blocks_idx = list(range(38))
|
37 |
+
for name, attn_processor in transformer.attn_processors.items():
|
38 |
+
match = re.search(r'\.(\d+)\.', name)
|
39 |
+
if match:
|
40 |
+
layer_index = int(match.group(1))
|
41 |
+
|
42 |
+
if name.startswith("transformer_blocks") and layer_index in double_blocks_idx:
|
43 |
+
|
44 |
+
lora_state_dicts = {}
|
45 |
+
for key, value in checkpoint.items():
|
46 |
+
# Match based on the layer index in the key (assuming the key contains layer index)
|
47 |
+
if re.search(r'\.(\d+)\.', key):
|
48 |
+
checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
|
49 |
+
if checkpoint_layer_index == layer_index and key.startswith("transformer_blocks"):
|
50 |
+
lora_state_dicts[key] = value
|
51 |
+
|
52 |
+
lora_attn_procs[name] = MultiDoubleStreamBlockLoraProcessor(
|
53 |
+
dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=lora_weights, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=number
|
54 |
+
)
|
55 |
+
|
56 |
+
# Load the weights from the checkpoint dictionary into the corresponding layers
|
57 |
+
for n in range(number):
|
58 |
+
lora_attn_procs[name].q_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.down.weight', None)
|
59 |
+
lora_attn_procs[name].q_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.up.weight', None)
|
60 |
+
lora_attn_procs[name].k_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.down.weight', None)
|
61 |
+
lora_attn_procs[name].k_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.up.weight', None)
|
62 |
+
lora_attn_procs[name].v_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.down.weight', None)
|
63 |
+
lora_attn_procs[name].v_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.up.weight', None)
|
64 |
+
lora_attn_procs[name].proj_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.proj_loras.{n}.down.weight', None)
|
65 |
+
lora_attn_procs[name].proj_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.proj_loras.{n}.up.weight', None)
|
66 |
+
lora_attn_procs[name].to(device)
|
67 |
+
|
68 |
+
elif name.startswith("single_transformer_blocks") and layer_index in single_blocks_idx:
|
69 |
+
|
70 |
+
lora_state_dicts = {}
|
71 |
+
for key, value in checkpoint.items():
|
72 |
+
# Match based on the layer index in the key (assuming the key contains layer index)
|
73 |
+
if re.search(r'\.(\d+)\.', key):
|
74 |
+
checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
|
75 |
+
if checkpoint_layer_index == layer_index and key.startswith("single_transformer_blocks"):
|
76 |
+
lora_state_dicts[key] = value
|
77 |
+
|
78 |
+
lora_attn_procs[name] = MultiSingleStreamBlockLoraProcessor(
|
79 |
+
dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=lora_weights, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=number
|
80 |
+
)
|
81 |
+
# Load the weights from the checkpoint dictionary into the corresponding layers
|
82 |
+
for n in range(number):
|
83 |
+
lora_attn_procs[name].q_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.down.weight', None)
|
84 |
+
lora_attn_procs[name].q_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.up.weight', None)
|
85 |
+
lora_attn_procs[name].k_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.down.weight', None)
|
86 |
+
lora_attn_procs[name].k_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.up.weight', None)
|
87 |
+
lora_attn_procs[name].v_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.down.weight', None)
|
88 |
+
lora_attn_procs[name].v_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.up.weight', None)
|
89 |
+
lora_attn_procs[name].to(device)
|
90 |
+
else:
|
91 |
+
lora_attn_procs[name] = FluxAttnProcessor2_0()
|
92 |
+
|
93 |
+
transformer.set_attn_processor(lora_attn_procs)
|
94 |
+
|
95 |
+
|
96 |
+
def update_model_with_multi_lora(checkpoints, lora_weights, transformer, cond_size):
|
97 |
+
ck_number = len(checkpoints)
|
98 |
+
cond_lora_number = [len(ls) for ls in lora_weights]
|
99 |
+
cond_number = sum(cond_lora_number)
|
100 |
+
ranks = [get_lora_rank(checkpoint) for checkpoint in checkpoints]
|
101 |
+
multi_lora_weight = []
|
102 |
+
for ls in lora_weights:
|
103 |
+
for n in ls:
|
104 |
+
multi_lora_weight.append(n)
|
105 |
+
|
106 |
+
lora_attn_procs = {}
|
107 |
+
double_blocks_idx = list(range(19))
|
108 |
+
single_blocks_idx = list(range(38))
|
109 |
+
for name, attn_processor in transformer.attn_processors.items():
|
110 |
+
match = re.search(r'\.(\d+)\.', name)
|
111 |
+
if match:
|
112 |
+
layer_index = int(match.group(1))
|
113 |
+
|
114 |
+
if name.startswith("transformer_blocks") and layer_index in double_blocks_idx:
|
115 |
+
lora_state_dicts = [{} for _ in range(ck_number)]
|
116 |
+
for idx, checkpoint in enumerate(checkpoints):
|
117 |
+
for key, value in checkpoint.items():
|
118 |
+
# Match based on the layer index in the key (assuming the key contains layer index)
|
119 |
+
if re.search(r'\.(\d+)\.', key):
|
120 |
+
checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
|
121 |
+
if checkpoint_layer_index == layer_index and key.startswith("transformer_blocks"):
|
122 |
+
lora_state_dicts[idx][key] = value
|
123 |
+
|
124 |
+
lora_attn_procs[name] = MultiDoubleStreamBlockLoraProcessor(
|
125 |
+
dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=multi_lora_weight, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=cond_number
|
126 |
+
)
|
127 |
+
|
128 |
+
# Load the weights from the checkpoint dictionary into the corresponding layers
|
129 |
+
num = 0
|
130 |
+
for idx in range(ck_number):
|
131 |
+
for n in range(cond_lora_number[idx]):
|
132 |
+
lora_attn_procs[name].q_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.down.weight', None)
|
133 |
+
lora_attn_procs[name].q_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.up.weight', None)
|
134 |
+
lora_attn_procs[name].k_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.down.weight', None)
|
135 |
+
lora_attn_procs[name].k_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.up.weight', None)
|
136 |
+
lora_attn_procs[name].v_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.down.weight', None)
|
137 |
+
lora_attn_procs[name].v_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.up.weight', None)
|
138 |
+
lora_attn_procs[name].proj_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.proj_loras.{n}.down.weight', None)
|
139 |
+
lora_attn_procs[name].proj_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.proj_loras.{n}.up.weight', None)
|
140 |
+
lora_attn_procs[name].to(device)
|
141 |
+
num += 1
|
142 |
+
|
143 |
+
elif name.startswith("single_transformer_blocks") and layer_index in single_blocks_idx:
|
144 |
+
|
145 |
+
lora_state_dicts = [{} for _ in range(ck_number)]
|
146 |
+
for idx, checkpoint in enumerate(checkpoints):
|
147 |
+
for key, value in checkpoint.items():
|
148 |
+
# Match based on the layer index in the key (assuming the key contains layer index)
|
149 |
+
if re.search(r'\.(\d+)\.', key):
|
150 |
+
checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
|
151 |
+
if checkpoint_layer_index == layer_index and key.startswith("single_transformer_blocks"):
|
152 |
+
lora_state_dicts[idx][key] = value
|
153 |
+
|
154 |
+
lora_attn_procs[name] = MultiSingleStreamBlockLoraProcessor(
|
155 |
+
dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=multi_lora_weight, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=cond_number
|
156 |
+
)
|
157 |
+
# Load the weights from the checkpoint dictionary into the corresponding layers
|
158 |
+
num = 0
|
159 |
+
for idx in range(ck_number):
|
160 |
+
for n in range(cond_lora_number[idx]):
|
161 |
+
lora_attn_procs[name].q_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.down.weight', None)
|
162 |
+
lora_attn_procs[name].q_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.up.weight', None)
|
163 |
+
lora_attn_procs[name].k_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.down.weight', None)
|
164 |
+
lora_attn_procs[name].k_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.up.weight', None)
|
165 |
+
lora_attn_procs[name].v_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.down.weight', None)
|
166 |
+
lora_attn_procs[name].v_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.up.weight', None)
|
167 |
+
lora_attn_procs[name].to(device)
|
168 |
+
num += 1
|
169 |
+
|
170 |
+
else:
|
171 |
+
lora_attn_procs[name] = FluxAttnProcessor2_0()
|
172 |
+
|
173 |
+
transformer.set_attn_processor(lora_attn_procs)
|
174 |
+
|
175 |
+
|
176 |
+
def set_single_lora(transformer, local_path, lora_weights=[], cond_size=512):
|
177 |
+
checkpoint = load_checkpoint(local_path)
|
178 |
+
update_model_with_lora(checkpoint, lora_weights, transformer, cond_size)
|
179 |
+
|
180 |
+
def set_multi_lora(transformer, local_paths, lora_weights=[[]], cond_size=512):
|
181 |
+
checkpoints = [load_checkpoint(local_path) for local_path in local_paths]
|
182 |
+
update_model_with_multi_lora(checkpoints, lora_weights, transformer, cond_size)
|
183 |
+
|
184 |
+
def unset_lora(transformer):
|
185 |
+
lora_attn_procs = {}
|
186 |
+
for name, attn_processor in transformer.attn_processors.items():
|
187 |
+
lora_attn_procs[name] = FluxAttnProcessor2_0()
|
188 |
+
transformer.set_attn_processor(lora_attn_procs)
|
189 |
+
|
190 |
+
|
191 |
+
'''
|
192 |
+
unset_lora(pipe.transformer)
|
193 |
+
lora_path = "./lora.safetensors"
|
194 |
+
lora_weights = [1, 1]
|
195 |
+
set_lora(pipe.transformer, local_path=lora_path, lora_weights=lora_weights, cond_size=512)
|
196 |
+
'''
|
src/pipeline.py
ADDED
@@ -0,0 +1,722 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
7 |
+
|
8 |
+
from diffusers.image_processor import (VaeImageProcessor)
|
9 |
+
from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin
|
10 |
+
from diffusers.models.autoencoders import AutoencoderKL
|
11 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
12 |
+
from diffusers.utils import (
|
13 |
+
USE_PEFT_BACKEND,
|
14 |
+
is_torch_xla_available,
|
15 |
+
logging,
|
16 |
+
scale_lora_layers,
|
17 |
+
unscale_lora_layers,
|
18 |
+
)
|
19 |
+
from diffusers.utils.torch_utils import randn_tensor
|
20 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
21 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
22 |
+
from torchvision.transforms.functional import pad
|
23 |
+
from .transformer_flux import FluxTransformer2DModel
|
24 |
+
|
25 |
+
if is_torch_xla_available():
|
26 |
+
import torch_xla.core.xla_model as xm
|
27 |
+
|
28 |
+
XLA_AVAILABLE = True
|
29 |
+
else:
|
30 |
+
XLA_AVAILABLE = False
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
33 |
+
|
34 |
+
def calculate_shift(
|
35 |
+
image_seq_len,
|
36 |
+
base_seq_len: int = 256,
|
37 |
+
max_seq_len: int = 4096,
|
38 |
+
base_shift: float = 0.5,
|
39 |
+
max_shift: float = 1.16,
|
40 |
+
):
|
41 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
42 |
+
b = base_shift - m * base_seq_len
|
43 |
+
mu = image_seq_len * m + b
|
44 |
+
return mu
|
45 |
+
|
46 |
+
def prepare_latent_image_ids_(height, width, device, dtype):
|
47 |
+
latent_image_ids = torch.zeros(height//2, width//2, 3, device=device, dtype=dtype)
|
48 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height//2, device=device)[:, None] # y
|
49 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width//2, device=device)[None, :] # x
|
50 |
+
return latent_image_ids
|
51 |
+
|
52 |
+
def prepare_latent_subject_ids(height, width, device, dtype):
|
53 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3, device=device, dtype=dtype)
|
54 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2, device=device)[:, None]
|
55 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2, device=device)[None, :]
|
56 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
57 |
+
latent_image_ids = latent_image_ids.reshape(
|
58 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
59 |
+
)
|
60 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
61 |
+
|
62 |
+
def resize_position_encoding(batch_size, original_height, original_width, target_height, target_width, device, dtype):
|
63 |
+
latent_image_ids = prepare_latent_image_ids_(original_height, original_width, device, dtype)
|
64 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
65 |
+
latent_image_ids = latent_image_ids.reshape(
|
66 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
67 |
+
)
|
68 |
+
|
69 |
+
scale_h = original_height / target_height
|
70 |
+
scale_w = original_width / target_width
|
71 |
+
latent_image_ids_resized = torch.zeros(target_height//2, target_width//2, 3, device=device, dtype=dtype)
|
72 |
+
latent_image_ids_resized[..., 1] = latent_image_ids_resized[..., 1] + torch.arange(target_height//2, device=device)[:, None] * scale_h
|
73 |
+
latent_image_ids_resized[..., 2] = latent_image_ids_resized[..., 2] + torch.arange(target_width//2, device=device)[None, :] * scale_w
|
74 |
+
|
75 |
+
cond_latent_image_id_height, cond_latent_image_id_width, cond_latent_image_id_channels = latent_image_ids_resized.shape
|
76 |
+
cond_latent_image_ids = latent_image_ids_resized.reshape(
|
77 |
+
cond_latent_image_id_height * cond_latent_image_id_width, cond_latent_image_id_channels
|
78 |
+
)
|
79 |
+
return latent_image_ids, cond_latent_image_ids
|
80 |
+
|
81 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
82 |
+
def retrieve_latents(
|
83 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
84 |
+
):
|
85 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
86 |
+
return encoder_output.latent_dist.sample(generator)
|
87 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
88 |
+
return encoder_output.latent_dist.mode()
|
89 |
+
elif hasattr(encoder_output, "latents"):
|
90 |
+
return encoder_output.latents
|
91 |
+
else:
|
92 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
93 |
+
|
94 |
+
|
95 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
96 |
+
def retrieve_timesteps(
|
97 |
+
scheduler,
|
98 |
+
num_inference_steps: Optional[int] = None,
|
99 |
+
device: Optional[Union[str, torch.device]] = None,
|
100 |
+
timesteps: Optional[List[int]] = None,
|
101 |
+
sigmas: Optional[List[float]] = None,
|
102 |
+
**kwargs,
|
103 |
+
):
|
104 |
+
if timesteps is not None and sigmas is not None:
|
105 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
106 |
+
if timesteps is not None:
|
107 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
108 |
+
if not accepts_timesteps:
|
109 |
+
raise ValueError(
|
110 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
111 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
112 |
+
)
|
113 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
114 |
+
timesteps = scheduler.timesteps
|
115 |
+
num_inference_steps = len(timesteps)
|
116 |
+
elif sigmas is not None:
|
117 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
118 |
+
if not accept_sigmas:
|
119 |
+
raise ValueError(
|
120 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
121 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
122 |
+
)
|
123 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
124 |
+
timesteps = scheduler.timesteps
|
125 |
+
num_inference_steps = len(timesteps)
|
126 |
+
else:
|
127 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
128 |
+
timesteps = scheduler.timesteps
|
129 |
+
return timesteps, num_inference_steps
|
130 |
+
|
131 |
+
|
132 |
+
class FluxPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
|
133 |
+
def __init__(
|
134 |
+
self,
|
135 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
136 |
+
vae: AutoencoderKL,
|
137 |
+
text_encoder: CLIPTextModel,
|
138 |
+
tokenizer: CLIPTokenizer,
|
139 |
+
text_encoder_2: T5EncoderModel,
|
140 |
+
tokenizer_2: T5TokenizerFast,
|
141 |
+
transformer: FluxTransformer2DModel,
|
142 |
+
):
|
143 |
+
super().__init__()
|
144 |
+
|
145 |
+
self.register_modules(
|
146 |
+
vae=vae,
|
147 |
+
text_encoder=text_encoder,
|
148 |
+
text_encoder_2=text_encoder_2,
|
149 |
+
tokenizer=tokenizer,
|
150 |
+
tokenizer_2=tokenizer_2,
|
151 |
+
transformer=transformer,
|
152 |
+
scheduler=scheduler,
|
153 |
+
)
|
154 |
+
self.vae_scale_factor = (
|
155 |
+
2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
|
156 |
+
)
|
157 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
158 |
+
self.tokenizer_max_length = (
|
159 |
+
self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
|
160 |
+
)
|
161 |
+
self.default_sample_size = 64
|
162 |
+
|
163 |
+
def _get_t5_prompt_embeds(
|
164 |
+
self,
|
165 |
+
prompt: Union[str, List[str]] = None,
|
166 |
+
num_images_per_prompt: int = 1,
|
167 |
+
max_sequence_length: int = 512,
|
168 |
+
device: Optional[torch.device] = None,
|
169 |
+
dtype: Optional[torch.dtype] = None,
|
170 |
+
):
|
171 |
+
device = device or self._execution_device
|
172 |
+
dtype = dtype or self.text_encoder.dtype
|
173 |
+
|
174 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
175 |
+
batch_size = len(prompt)
|
176 |
+
|
177 |
+
text_inputs = self.tokenizer_2(
|
178 |
+
prompt,
|
179 |
+
padding="max_length",
|
180 |
+
max_length=max_sequence_length,
|
181 |
+
truncation=True,
|
182 |
+
return_length=False,
|
183 |
+
return_overflowing_tokens=False,
|
184 |
+
return_tensors="pt",
|
185 |
+
)
|
186 |
+
text_input_ids = text_inputs.input_ids
|
187 |
+
untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
|
188 |
+
|
189 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
190 |
+
removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1: -1])
|
191 |
+
logger.warning(
|
192 |
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
193 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
194 |
+
)
|
195 |
+
|
196 |
+
prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
|
197 |
+
|
198 |
+
dtype = self.text_encoder_2.dtype
|
199 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
200 |
+
|
201 |
+
_, seq_len, _ = prompt_embeds.shape
|
202 |
+
|
203 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
204 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
205 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
206 |
+
|
207 |
+
return prompt_embeds
|
208 |
+
|
209 |
+
def _get_clip_prompt_embeds(
|
210 |
+
self,
|
211 |
+
prompt: Union[str, List[str]],
|
212 |
+
num_images_per_prompt: int = 1,
|
213 |
+
device: Optional[torch.device] = None,
|
214 |
+
):
|
215 |
+
device = device or self._execution_device
|
216 |
+
|
217 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
218 |
+
batch_size = len(prompt)
|
219 |
+
|
220 |
+
text_inputs = self.tokenizer(
|
221 |
+
prompt,
|
222 |
+
padding="max_length",
|
223 |
+
max_length=self.tokenizer_max_length,
|
224 |
+
truncation=True,
|
225 |
+
return_overflowing_tokens=False,
|
226 |
+
return_length=False,
|
227 |
+
return_tensors="pt",
|
228 |
+
)
|
229 |
+
|
230 |
+
text_input_ids = text_inputs.input_ids
|
231 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
232 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
233 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1: -1])
|
234 |
+
logger.warning(
|
235 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
236 |
+
f" {self.tokenizer_max_length} tokens: {removed_text}"
|
237 |
+
)
|
238 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
|
239 |
+
|
240 |
+
# Use pooled output of CLIPTextModel
|
241 |
+
prompt_embeds = prompt_embeds.pooler_output
|
242 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
243 |
+
|
244 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
245 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
|
246 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
247 |
+
|
248 |
+
return prompt_embeds
|
249 |
+
|
250 |
+
def encode_prompt(
|
251 |
+
self,
|
252 |
+
prompt: Union[str, List[str]],
|
253 |
+
prompt_2: Union[str, List[str]],
|
254 |
+
device: Optional[torch.device] = None,
|
255 |
+
num_images_per_prompt: int = 1,
|
256 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
257 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
258 |
+
max_sequence_length: int = 512,
|
259 |
+
lora_scale: Optional[float] = None,
|
260 |
+
):
|
261 |
+
device = device or self._execution_device
|
262 |
+
|
263 |
+
# set lora scale so that monkey patched LoRA
|
264 |
+
# function of text encoder can correctly access it
|
265 |
+
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
|
266 |
+
self._lora_scale = lora_scale
|
267 |
+
|
268 |
+
# dynamically adjust the LoRA scale
|
269 |
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
270 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
271 |
+
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
|
272 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
273 |
+
|
274 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
275 |
+
|
276 |
+
if prompt_embeds is None:
|
277 |
+
prompt_2 = prompt_2 or prompt
|
278 |
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
279 |
+
|
280 |
+
# We only use the pooled prompt output from the CLIPTextModel
|
281 |
+
pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
282 |
+
prompt=prompt,
|
283 |
+
device=device,
|
284 |
+
num_images_per_prompt=num_images_per_prompt,
|
285 |
+
)
|
286 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
287 |
+
prompt=prompt_2,
|
288 |
+
num_images_per_prompt=num_images_per_prompt,
|
289 |
+
max_sequence_length=max_sequence_length,
|
290 |
+
device=device,
|
291 |
+
)
|
292 |
+
|
293 |
+
if self.text_encoder is not None:
|
294 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
295 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
296 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
297 |
+
|
298 |
+
if self.text_encoder_2 is not None:
|
299 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
300 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
301 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
302 |
+
|
303 |
+
dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
|
304 |
+
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
|
305 |
+
|
306 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
307 |
+
|
308 |
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
|
309 |
+
def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
|
310 |
+
if isinstance(generator, list):
|
311 |
+
image_latents = [
|
312 |
+
retrieve_latents(self.vae.encode(image[i: i + 1]), generator=generator[i])
|
313 |
+
for i in range(image.shape[0])
|
314 |
+
]
|
315 |
+
image_latents = torch.cat(image_latents, dim=0)
|
316 |
+
else:
|
317 |
+
image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
318 |
+
|
319 |
+
image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
320 |
+
|
321 |
+
return image_latents
|
322 |
+
|
323 |
+
def check_inputs(
|
324 |
+
self,
|
325 |
+
prompt,
|
326 |
+
prompt_2,
|
327 |
+
height,
|
328 |
+
width,
|
329 |
+
prompt_embeds=None,
|
330 |
+
pooled_prompt_embeds=None,
|
331 |
+
callback_on_step_end_tensor_inputs=None,
|
332 |
+
max_sequence_length=None,
|
333 |
+
):
|
334 |
+
if height % 8 != 0 or width % 8 != 0:
|
335 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
336 |
+
|
337 |
+
if prompt is not None and prompt_embeds is not None:
|
338 |
+
raise ValueError(
|
339 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
340 |
+
" only forward one of the two."
|
341 |
+
)
|
342 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
343 |
+
raise ValueError(
|
344 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
345 |
+
" only forward one of the two."
|
346 |
+
)
|
347 |
+
elif prompt is None and prompt_embeds is None:
|
348 |
+
raise ValueError(
|
349 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
350 |
+
)
|
351 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
352 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
353 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
354 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
355 |
+
|
356 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
357 |
+
raise ValueError(
|
358 |
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
359 |
+
)
|
360 |
+
|
361 |
+
if max_sequence_length is not None and max_sequence_length > 512:
|
362 |
+
raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
|
363 |
+
|
364 |
+
@staticmethod
|
365 |
+
def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
|
366 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3)
|
367 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
|
368 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
|
369 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
370 |
+
latent_image_ids = latent_image_ids.reshape(
|
371 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
372 |
+
)
|
373 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
374 |
+
|
375 |
+
@staticmethod
|
376 |
+
def _pack_latents(latents, batch_size, num_channels_latents, height, width):
|
377 |
+
latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
|
378 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5)
|
379 |
+
latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
|
380 |
+
return latents
|
381 |
+
|
382 |
+
@staticmethod
|
383 |
+
def _unpack_latents(latents, height, width, vae_scale_factor):
|
384 |
+
batch_size, num_patches, channels = latents.shape
|
385 |
+
|
386 |
+
height = height // vae_scale_factor
|
387 |
+
width = width // vae_scale_factor
|
388 |
+
|
389 |
+
latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
|
390 |
+
latents = latents.permute(0, 3, 1, 4, 2, 5)
|
391 |
+
|
392 |
+
latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
|
393 |
+
|
394 |
+
return latents
|
395 |
+
|
396 |
+
def enable_vae_slicing(self):
|
397 |
+
r"""
|
398 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
399 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
400 |
+
"""
|
401 |
+
self.vae.enable_slicing()
|
402 |
+
|
403 |
+
def disable_vae_slicing(self):
|
404 |
+
r"""
|
405 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
406 |
+
computing decoding in one step.
|
407 |
+
"""
|
408 |
+
self.vae.disable_slicing()
|
409 |
+
|
410 |
+
def enable_vae_tiling(self):
|
411 |
+
r"""
|
412 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
413 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
414 |
+
processing larger images.
|
415 |
+
"""
|
416 |
+
self.vae.enable_tiling()
|
417 |
+
|
418 |
+
def disable_vae_tiling(self):
|
419 |
+
r"""
|
420 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
421 |
+
computing decoding in one step.
|
422 |
+
"""
|
423 |
+
self.vae.disable_tiling()
|
424 |
+
|
425 |
+
def prepare_latents(
|
426 |
+
self,
|
427 |
+
batch_size,
|
428 |
+
num_channels_latents,
|
429 |
+
height,
|
430 |
+
width,
|
431 |
+
dtype,
|
432 |
+
device,
|
433 |
+
generator,
|
434 |
+
subject_image,
|
435 |
+
condition_image,
|
436 |
+
latents=None,
|
437 |
+
cond_number=1,
|
438 |
+
sub_number=1
|
439 |
+
):
|
440 |
+
height_cond = 2 * (self.cond_size // self.vae_scale_factor)
|
441 |
+
width_cond = 2 * (self.cond_size // self.vae_scale_factor)
|
442 |
+
height = 2 * (int(height) // self.vae_scale_factor)
|
443 |
+
width = 2 * (int(width) // self.vae_scale_factor)
|
444 |
+
|
445 |
+
shape = (batch_size, num_channels_latents, height, width) # 1 16 106 80
|
446 |
+
noise_latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
447 |
+
noise_latents = self._pack_latents(noise_latents, batch_size, num_channels_latents, height, width)
|
448 |
+
noise_latent_image_ids, cond_latent_image_ids = resize_position_encoding(
|
449 |
+
batch_size,
|
450 |
+
height,
|
451 |
+
width,
|
452 |
+
height_cond,
|
453 |
+
width_cond,
|
454 |
+
device,
|
455 |
+
dtype,
|
456 |
+
)
|
457 |
+
|
458 |
+
latents_to_concat = []
|
459 |
+
latents_ids_to_concat = [noise_latent_image_ids]
|
460 |
+
|
461 |
+
# subject
|
462 |
+
if subject_image is not None:
|
463 |
+
shape_subject = (batch_size, num_channels_latents, height_cond*sub_number, width_cond)
|
464 |
+
subject_image = subject_image.to(device=device, dtype=dtype)
|
465 |
+
subject_image_latents = self._encode_vae_image(image=subject_image, generator=generator)
|
466 |
+
subject_latents = self._pack_latents(subject_image_latents, batch_size, num_channels_latents, height_cond*sub_number, width_cond)
|
467 |
+
mask2 = torch.zeros(shape_subject, device=device, dtype=dtype)
|
468 |
+
mask2 = self._pack_latents(mask2, batch_size, num_channels_latents, height_cond*sub_number, width_cond)
|
469 |
+
latent_subject_ids = prepare_latent_subject_ids(height_cond, width_cond, device, dtype)
|
470 |
+
latent_subject_ids[:, 1] += 64 # fixed offset
|
471 |
+
subject_latent_image_ids = torch.concat([latent_subject_ids for _ in range(sub_number)], dim=-2)
|
472 |
+
latents_to_concat.append(subject_latents)
|
473 |
+
latents_ids_to_concat.append(subject_latent_image_ids)
|
474 |
+
|
475 |
+
# spatial
|
476 |
+
if condition_image is not None:
|
477 |
+
shape_cond = (batch_size, num_channels_latents, height_cond*cond_number, width_cond)
|
478 |
+
condition_image = condition_image.to(device=device, dtype=dtype)
|
479 |
+
image_latents = self._encode_vae_image(image=condition_image, generator=generator)
|
480 |
+
cond_latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height_cond*cond_number, width_cond)
|
481 |
+
mask3 = torch.zeros(shape_cond, device=device, dtype=dtype)
|
482 |
+
mask3 = self._pack_latents(mask3, batch_size, num_channels_latents, height_cond*cond_number, width_cond)
|
483 |
+
cond_latent_image_ids = cond_latent_image_ids
|
484 |
+
cond_latent_image_ids = torch.concat([cond_latent_image_ids for _ in range(cond_number)], dim=-2)
|
485 |
+
latents_ids_to_concat.append(cond_latent_image_ids)
|
486 |
+
latents_to_concat.append(cond_latents)
|
487 |
+
|
488 |
+
cond_latents = torch.concat(latents_to_concat, dim=-2)
|
489 |
+
latent_image_ids = torch.concat(latents_ids_to_concat, dim=-2)
|
490 |
+
return cond_latents, latent_image_ids, noise_latents
|
491 |
+
|
492 |
+
@property
|
493 |
+
def guidance_scale(self):
|
494 |
+
return self._guidance_scale
|
495 |
+
|
496 |
+
@property
|
497 |
+
def joint_attention_kwargs(self):
|
498 |
+
return self._joint_attention_kwargs
|
499 |
+
|
500 |
+
@property
|
501 |
+
def num_timesteps(self):
|
502 |
+
return self._num_timesteps
|
503 |
+
|
504 |
+
@property
|
505 |
+
def interrupt(self):
|
506 |
+
return self._interrupt
|
507 |
+
|
508 |
+
@torch.no_grad()
|
509 |
+
def __call__(
|
510 |
+
self,
|
511 |
+
prompt: Union[str, List[str]] = None,
|
512 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
513 |
+
height: Optional[int] = None,
|
514 |
+
width: Optional[int] = None,
|
515 |
+
num_inference_steps: int = 28,
|
516 |
+
timesteps: List[int] = None,
|
517 |
+
guidance_scale: float = 3.5,
|
518 |
+
num_images_per_prompt: Optional[int] = 1,
|
519 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
520 |
+
latents: Optional[torch.FloatTensor] = None,
|
521 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
522 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
523 |
+
output_type: Optional[str] = "pil",
|
524 |
+
return_dict: bool = True,
|
525 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
526 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
527 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
528 |
+
max_sequence_length: int = 512,
|
529 |
+
spatial_images=None,
|
530 |
+
subject_images=None,
|
531 |
+
cond_size=512,
|
532 |
+
):
|
533 |
+
|
534 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
535 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
536 |
+
self.cond_size = cond_size
|
537 |
+
|
538 |
+
# 1. Check inputs. Raise error if not correct
|
539 |
+
self.check_inputs(
|
540 |
+
prompt,
|
541 |
+
prompt_2,
|
542 |
+
height,
|
543 |
+
width,
|
544 |
+
prompt_embeds=prompt_embeds,
|
545 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
546 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
547 |
+
max_sequence_length=max_sequence_length,
|
548 |
+
)
|
549 |
+
|
550 |
+
self._guidance_scale = guidance_scale
|
551 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
552 |
+
self._interrupt = False
|
553 |
+
|
554 |
+
cond_number = len(spatial_images)
|
555 |
+
sub_number = len(subject_images)
|
556 |
+
|
557 |
+
if sub_number > 0:
|
558 |
+
subject_image_ls = []
|
559 |
+
for subject_image in subject_images:
|
560 |
+
w, h = subject_image.size[:2]
|
561 |
+
scale = self.cond_size / max(h, w)
|
562 |
+
new_h, new_w = int(h * scale), int(w * scale)
|
563 |
+
subject_image = self.image_processor.preprocess(subject_image, height=new_h, width=new_w)
|
564 |
+
subject_image = subject_image.to(dtype=torch.float32)
|
565 |
+
pad_h = cond_size - subject_image.shape[-2]
|
566 |
+
pad_w = cond_size - subject_image.shape[-1]
|
567 |
+
subject_image = pad(
|
568 |
+
subject_image,
|
569 |
+
padding=(int(pad_w / 2), int(pad_h / 2), int(pad_w / 2), int(pad_h / 2)),
|
570 |
+
fill=0
|
571 |
+
)
|
572 |
+
subject_image_ls.append(subject_image)
|
573 |
+
subject_image = torch.concat(subject_image_ls, dim=-2)
|
574 |
+
else:
|
575 |
+
subject_image = None
|
576 |
+
|
577 |
+
if cond_number > 0:
|
578 |
+
condition_image_ls = []
|
579 |
+
for img in spatial_images:
|
580 |
+
condition_image = self.image_processor.preprocess(img, height=self.cond_size, width=self.cond_size)
|
581 |
+
condition_image = condition_image.to(dtype=torch.float32)
|
582 |
+
condition_image_ls.append(condition_image)
|
583 |
+
condition_image = torch.concat(condition_image_ls, dim=-2)
|
584 |
+
else:
|
585 |
+
condition_image = None
|
586 |
+
|
587 |
+
# 2. Define call parameters
|
588 |
+
if prompt is not None and isinstance(prompt, str):
|
589 |
+
batch_size = 1
|
590 |
+
elif prompt is not None and isinstance(prompt, list):
|
591 |
+
batch_size = len(prompt)
|
592 |
+
else:
|
593 |
+
batch_size = prompt_embeds.shape[0]
|
594 |
+
|
595 |
+
device = self._execution_device
|
596 |
+
|
597 |
+
lora_scale = (
|
598 |
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
599 |
+
)
|
600 |
+
(
|
601 |
+
prompt_embeds,
|
602 |
+
pooled_prompt_embeds,
|
603 |
+
text_ids,
|
604 |
+
) = self.encode_prompt(
|
605 |
+
prompt=prompt,
|
606 |
+
prompt_2=prompt_2,
|
607 |
+
prompt_embeds=prompt_embeds,
|
608 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
609 |
+
device=device,
|
610 |
+
num_images_per_prompt=num_images_per_prompt,
|
611 |
+
max_sequence_length=max_sequence_length,
|
612 |
+
lora_scale=lora_scale,
|
613 |
+
)
|
614 |
+
|
615 |
+
# 4. Prepare latent variables
|
616 |
+
num_channels_latents = self.transformer.config.in_channels // 4 # 16
|
617 |
+
cond_latents, latent_image_ids, noise_latents = self.prepare_latents(
|
618 |
+
batch_size * num_images_per_prompt,
|
619 |
+
num_channels_latents,
|
620 |
+
height,
|
621 |
+
width,
|
622 |
+
prompt_embeds.dtype,
|
623 |
+
device,
|
624 |
+
generator,
|
625 |
+
subject_image,
|
626 |
+
condition_image,
|
627 |
+
latents,
|
628 |
+
cond_number,
|
629 |
+
sub_number
|
630 |
+
)
|
631 |
+
latents = noise_latents
|
632 |
+
# 5. Prepare timesteps
|
633 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
634 |
+
image_seq_len = latents.shape[1]
|
635 |
+
mu = calculate_shift(
|
636 |
+
image_seq_len,
|
637 |
+
self.scheduler.config.base_image_seq_len,
|
638 |
+
self.scheduler.config.max_image_seq_len,
|
639 |
+
self.scheduler.config.base_shift,
|
640 |
+
self.scheduler.config.max_shift,
|
641 |
+
)
|
642 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
643 |
+
self.scheduler,
|
644 |
+
num_inference_steps,
|
645 |
+
device,
|
646 |
+
timesteps,
|
647 |
+
sigmas,
|
648 |
+
mu=mu,
|
649 |
+
)
|
650 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
651 |
+
self._num_timesteps = len(timesteps)
|
652 |
+
|
653 |
+
# handle guidance
|
654 |
+
if self.transformer.config.guidance_embeds:
|
655 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
|
656 |
+
guidance = guidance.expand(latents.shape[0])
|
657 |
+
else:
|
658 |
+
guidance = None
|
659 |
+
|
660 |
+
# 6. Denoising loop
|
661 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
662 |
+
for i, t in enumerate(timesteps):
|
663 |
+
if self.interrupt:
|
664 |
+
continue
|
665 |
+
|
666 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
667 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
668 |
+
noise_pred = self.transformer(
|
669 |
+
hidden_states=latents,
|
670 |
+
cond_hidden_states=cond_latents,
|
671 |
+
timestep=timestep / 1000,
|
672 |
+
guidance=guidance,
|
673 |
+
pooled_projections=pooled_prompt_embeds,
|
674 |
+
encoder_hidden_states=prompt_embeds,
|
675 |
+
txt_ids=text_ids,
|
676 |
+
img_ids=latent_image_ids,
|
677 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
678 |
+
return_dict=False,
|
679 |
+
)[0]
|
680 |
+
|
681 |
+
# compute the previous noisy sample x_t -> x_t-1
|
682 |
+
latents_dtype = latents.dtype
|
683 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
684 |
+
latents = latents
|
685 |
+
|
686 |
+
if latents.dtype != latents_dtype:
|
687 |
+
if torch.backends.mps.is_available():
|
688 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
689 |
+
latents = latents.to(latents_dtype)
|
690 |
+
|
691 |
+
if callback_on_step_end is not None:
|
692 |
+
callback_kwargs = {}
|
693 |
+
for k in callback_on_step_end_tensor_inputs:
|
694 |
+
callback_kwargs[k] = locals()[k]
|
695 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
696 |
+
|
697 |
+
latents = callback_outputs.pop("latents", latents)
|
698 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
699 |
+
|
700 |
+
# call the callback, if provided
|
701 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
702 |
+
progress_bar.update()
|
703 |
+
|
704 |
+
if XLA_AVAILABLE:
|
705 |
+
xm.mark_step()
|
706 |
+
|
707 |
+
if output_type == "latent":
|
708 |
+
image = latents
|
709 |
+
|
710 |
+
else:
|
711 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
712 |
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
713 |
+
image = self.vae.decode(latents.to(dtype=self.vae.dtype), return_dict=False)[0]
|
714 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
715 |
+
|
716 |
+
# Offload all models
|
717 |
+
self.maybe_free_model_hooks()
|
718 |
+
|
719 |
+
if not return_dict:
|
720 |
+
return (image,)
|
721 |
+
|
722 |
+
return FluxPipelineOutput(images=image)
|
src/prompt_helper.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
|
4 |
+
def load_text_encoders(args, class_one, class_two):
|
5 |
+
text_encoder_one = class_one.from_pretrained(
|
6 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
7 |
+
)
|
8 |
+
text_encoder_two = class_two.from_pretrained(
|
9 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
|
10 |
+
)
|
11 |
+
return text_encoder_one, text_encoder_two
|
12 |
+
|
13 |
+
|
14 |
+
def tokenize_prompt(tokenizer, prompt, max_sequence_length):
|
15 |
+
text_inputs = tokenizer(
|
16 |
+
prompt,
|
17 |
+
padding="max_length",
|
18 |
+
max_length=max_sequence_length,
|
19 |
+
truncation=True,
|
20 |
+
return_length=False,
|
21 |
+
return_overflowing_tokens=False,
|
22 |
+
return_tensors="pt",
|
23 |
+
)
|
24 |
+
text_input_ids = text_inputs.input_ids
|
25 |
+
return text_input_ids
|
26 |
+
|
27 |
+
|
28 |
+
def tokenize_prompt_clip(tokenizer, prompt):
|
29 |
+
text_inputs = tokenizer(
|
30 |
+
prompt,
|
31 |
+
padding="max_length",
|
32 |
+
max_length=77,
|
33 |
+
truncation=True,
|
34 |
+
return_length=False,
|
35 |
+
return_overflowing_tokens=False,
|
36 |
+
return_tensors="pt",
|
37 |
+
)
|
38 |
+
text_input_ids = text_inputs.input_ids
|
39 |
+
return text_input_ids
|
40 |
+
|
41 |
+
|
42 |
+
def tokenize_prompt_t5(tokenizer, prompt):
|
43 |
+
text_inputs = tokenizer(
|
44 |
+
prompt,
|
45 |
+
padding="max_length",
|
46 |
+
max_length=512,
|
47 |
+
truncation=True,
|
48 |
+
return_length=False,
|
49 |
+
return_overflowing_tokens=False,
|
50 |
+
return_tensors="pt",
|
51 |
+
)
|
52 |
+
text_input_ids = text_inputs.input_ids
|
53 |
+
return text_input_ids
|
54 |
+
|
55 |
+
|
56 |
+
def _encode_prompt_with_t5(
|
57 |
+
text_encoder,
|
58 |
+
tokenizer,
|
59 |
+
max_sequence_length=512,
|
60 |
+
prompt=None,
|
61 |
+
num_images_per_prompt=1,
|
62 |
+
device=None,
|
63 |
+
text_input_ids=None,
|
64 |
+
):
|
65 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
66 |
+
batch_size = len(prompt)
|
67 |
+
|
68 |
+
if tokenizer is not None:
|
69 |
+
text_inputs = tokenizer(
|
70 |
+
prompt,
|
71 |
+
padding="max_length",
|
72 |
+
max_length=max_sequence_length,
|
73 |
+
truncation=True,
|
74 |
+
return_length=False,
|
75 |
+
return_overflowing_tokens=False,
|
76 |
+
return_tensors="pt",
|
77 |
+
)
|
78 |
+
text_input_ids = text_inputs.input_ids
|
79 |
+
else:
|
80 |
+
if text_input_ids is None:
|
81 |
+
raise ValueError("text_input_ids must be provided when the tokenizer is not specified")
|
82 |
+
|
83 |
+
prompt_embeds = text_encoder(text_input_ids.to(device))[0]
|
84 |
+
|
85 |
+
dtype = text_encoder.dtype
|
86 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
87 |
+
|
88 |
+
_, seq_len, _ = prompt_embeds.shape
|
89 |
+
|
90 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
91 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
92 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
93 |
+
|
94 |
+
return prompt_embeds
|
95 |
+
|
96 |
+
|
97 |
+
def _encode_prompt_with_clip(
|
98 |
+
text_encoder,
|
99 |
+
tokenizer,
|
100 |
+
prompt: str,
|
101 |
+
device=None,
|
102 |
+
text_input_ids=None,
|
103 |
+
num_images_per_prompt: int = 1,
|
104 |
+
):
|
105 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
106 |
+
batch_size = len(prompt)
|
107 |
+
|
108 |
+
if tokenizer is not None:
|
109 |
+
text_inputs = tokenizer(
|
110 |
+
prompt,
|
111 |
+
padding="max_length",
|
112 |
+
max_length=77,
|
113 |
+
truncation=True,
|
114 |
+
return_overflowing_tokens=False,
|
115 |
+
return_length=False,
|
116 |
+
return_tensors="pt",
|
117 |
+
)
|
118 |
+
|
119 |
+
text_input_ids = text_inputs.input_ids
|
120 |
+
else:
|
121 |
+
if text_input_ids is None:
|
122 |
+
raise ValueError("text_input_ids must be provided when the tokenizer is not specified")
|
123 |
+
|
124 |
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=False)
|
125 |
+
|
126 |
+
# Use pooled output of CLIPTextModel
|
127 |
+
prompt_embeds = prompt_embeds.pooler_output
|
128 |
+
prompt_embeds = prompt_embeds.to(dtype=text_encoder.dtype, device=device)
|
129 |
+
|
130 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
131 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
132 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
133 |
+
|
134 |
+
return prompt_embeds
|
135 |
+
|
136 |
+
|
137 |
+
def encode_prompt(
|
138 |
+
text_encoders,
|
139 |
+
tokenizers,
|
140 |
+
prompt: str,
|
141 |
+
max_sequence_length,
|
142 |
+
device=None,
|
143 |
+
num_images_per_prompt: int = 1,
|
144 |
+
text_input_ids_list=None,
|
145 |
+
):
|
146 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
147 |
+
dtype = text_encoders[0].dtype
|
148 |
+
|
149 |
+
pooled_prompt_embeds = _encode_prompt_with_clip(
|
150 |
+
text_encoder=text_encoders[0],
|
151 |
+
tokenizer=tokenizers[0],
|
152 |
+
prompt=prompt,
|
153 |
+
device=device if device is not None else text_encoders[0].device,
|
154 |
+
num_images_per_prompt=num_images_per_prompt,
|
155 |
+
text_input_ids=text_input_ids_list[0] if text_input_ids_list else None,
|
156 |
+
)
|
157 |
+
|
158 |
+
prompt_embeds = _encode_prompt_with_t5(
|
159 |
+
text_encoder=text_encoders[1],
|
160 |
+
tokenizer=tokenizers[1],
|
161 |
+
max_sequence_length=max_sequence_length,
|
162 |
+
prompt=prompt,
|
163 |
+
num_images_per_prompt=num_images_per_prompt,
|
164 |
+
device=device if device is not None else text_encoders[1].device,
|
165 |
+
text_input_ids=text_input_ids_list[1] if text_input_ids_list else None,
|
166 |
+
)
|
167 |
+
|
168 |
+
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
|
169 |
+
|
170 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
171 |
+
|
172 |
+
|
173 |
+
def encode_token_ids(text_encoders, tokens, accelerator, num_images_per_prompt=1, device=None):
|
174 |
+
text_encoder_clip = text_encoders[0]
|
175 |
+
text_encoder_t5 = text_encoders[1]
|
176 |
+
tokens_clip, tokens_t5 = tokens[0], tokens[1]
|
177 |
+
batch_size = tokens_clip.shape[0]
|
178 |
+
|
179 |
+
if device == "cpu":
|
180 |
+
device = "cpu"
|
181 |
+
else:
|
182 |
+
device = accelerator.device
|
183 |
+
|
184 |
+
# clip
|
185 |
+
prompt_embeds = text_encoder_clip(tokens_clip.to(device), output_hidden_states=False)
|
186 |
+
# Use pooled output of CLIPTextModel
|
187 |
+
prompt_embeds = prompt_embeds.pooler_output
|
188 |
+
prompt_embeds = prompt_embeds.to(dtype=text_encoder_clip.dtype, device=accelerator.device)
|
189 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
190 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
191 |
+
pooled_prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
192 |
+
pooled_prompt_embeds = pooled_prompt_embeds.to(dtype=text_encoder_clip.dtype, device=accelerator.device)
|
193 |
+
|
194 |
+
# t5
|
195 |
+
prompt_embeds = text_encoder_t5(tokens_t5.to(device))[0]
|
196 |
+
dtype = text_encoder_t5.dtype
|
197 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=accelerator.device)
|
198 |
+
_, seq_len, _ = prompt_embeds.shape
|
199 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
200 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
201 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
202 |
+
|
203 |
+
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=accelerator.device, dtype=dtype)
|
204 |
+
|
205 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
src/transformer_flux.py
ADDED
@@ -0,0 +1,583 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
|
8 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
9 |
+
from diffusers.loaders import FluxTransformer2DLoadersMixin, FromOriginalModelMixin, PeftAdapterMixin
|
10 |
+
from diffusers.models.attention import FeedForward
|
11 |
+
from diffusers.models.attention_processor import (
|
12 |
+
Attention,
|
13 |
+
AttentionProcessor,
|
14 |
+
FluxAttnProcessor2_0,
|
15 |
+
FluxAttnProcessor2_0_NPU,
|
16 |
+
FusedFluxAttnProcessor2_0,
|
17 |
+
)
|
18 |
+
from diffusers.models.modeling_utils import ModelMixin
|
19 |
+
from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
|
20 |
+
from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
|
21 |
+
from diffusers.utils.import_utils import is_torch_npu_available
|
22 |
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
23 |
+
from diffusers.models.embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
|
24 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
27 |
+
|
28 |
+
@maybe_allow_in_graph
|
29 |
+
class FluxSingleTransformerBlock(nn.Module):
|
30 |
+
|
31 |
+
def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
|
32 |
+
super().__init__()
|
33 |
+
self.mlp_hidden_dim = int(dim * mlp_ratio)
|
34 |
+
|
35 |
+
self.norm = AdaLayerNormZeroSingle(dim)
|
36 |
+
self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
|
37 |
+
self.act_mlp = nn.GELU(approximate="tanh")
|
38 |
+
self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
|
39 |
+
|
40 |
+
if is_torch_npu_available():
|
41 |
+
processor = FluxAttnProcessor2_0_NPU()
|
42 |
+
else:
|
43 |
+
processor = FluxAttnProcessor2_0()
|
44 |
+
self.attn = Attention(
|
45 |
+
query_dim=dim,
|
46 |
+
cross_attention_dim=None,
|
47 |
+
dim_head=attention_head_dim,
|
48 |
+
heads=num_attention_heads,
|
49 |
+
out_dim=dim,
|
50 |
+
bias=True,
|
51 |
+
processor=processor,
|
52 |
+
qk_norm="rms_norm",
|
53 |
+
eps=1e-6,
|
54 |
+
pre_only=True,
|
55 |
+
)
|
56 |
+
|
57 |
+
def forward(
|
58 |
+
self,
|
59 |
+
hidden_states: torch.Tensor,
|
60 |
+
cond_hidden_states: torch.Tensor,
|
61 |
+
temb: torch.Tensor,
|
62 |
+
cond_temb: torch.Tensor,
|
63 |
+
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
64 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
65 |
+
) -> torch.Tensor:
|
66 |
+
use_cond = cond_hidden_states is not None
|
67 |
+
|
68 |
+
residual = hidden_states
|
69 |
+
norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
|
70 |
+
mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
|
71 |
+
|
72 |
+
if use_cond:
|
73 |
+
residual_cond = cond_hidden_states
|
74 |
+
norm_cond_hidden_states, cond_gate = self.norm(cond_hidden_states, emb=cond_temb)
|
75 |
+
mlp_cond_hidden_states = self.act_mlp(self.proj_mlp(norm_cond_hidden_states))
|
76 |
+
|
77 |
+
norm_hidden_states_concat = torch.concat([norm_hidden_states, norm_cond_hidden_states], dim=-2)
|
78 |
+
|
79 |
+
joint_attention_kwargs = joint_attention_kwargs or {}
|
80 |
+
attn_output = self.attn(
|
81 |
+
hidden_states=norm_hidden_states_concat,
|
82 |
+
image_rotary_emb=image_rotary_emb,
|
83 |
+
use_cond=use_cond,
|
84 |
+
**joint_attention_kwargs,
|
85 |
+
)
|
86 |
+
if use_cond:
|
87 |
+
attn_output, cond_attn_output = attn_output
|
88 |
+
|
89 |
+
hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
|
90 |
+
gate = gate.unsqueeze(1)
|
91 |
+
hidden_states = gate * self.proj_out(hidden_states)
|
92 |
+
hidden_states = residual + hidden_states
|
93 |
+
|
94 |
+
if use_cond:
|
95 |
+
condition_latents = torch.cat([cond_attn_output, mlp_cond_hidden_states], dim=2)
|
96 |
+
cond_gate = cond_gate.unsqueeze(1)
|
97 |
+
condition_latents = cond_gate * self.proj_out(condition_latents)
|
98 |
+
condition_latents = residual_cond + condition_latents
|
99 |
+
|
100 |
+
if hidden_states.dtype == torch.float16:
|
101 |
+
hidden_states = hidden_states.clip(-65504, 65504)
|
102 |
+
|
103 |
+
return hidden_states, condition_latents if use_cond else None
|
104 |
+
|
105 |
+
|
106 |
+
@maybe_allow_in_graph
|
107 |
+
class FluxTransformerBlock(nn.Module):
|
108 |
+
def __init__(
|
109 |
+
self, dim: int, num_attention_heads: int, attention_head_dim: int, qk_norm: str = "rms_norm", eps: float = 1e-6
|
110 |
+
):
|
111 |
+
super().__init__()
|
112 |
+
|
113 |
+
self.norm1 = AdaLayerNormZero(dim)
|
114 |
+
|
115 |
+
self.norm1_context = AdaLayerNormZero(dim)
|
116 |
+
|
117 |
+
if hasattr(F, "scaled_dot_product_attention"):
|
118 |
+
processor = FluxAttnProcessor2_0()
|
119 |
+
else:
|
120 |
+
raise ValueError(
|
121 |
+
"The current PyTorch version does not support the `scaled_dot_product_attention` function."
|
122 |
+
)
|
123 |
+
self.attn = Attention(
|
124 |
+
query_dim=dim,
|
125 |
+
cross_attention_dim=None,
|
126 |
+
added_kv_proj_dim=dim,
|
127 |
+
dim_head=attention_head_dim,
|
128 |
+
heads=num_attention_heads,
|
129 |
+
out_dim=dim,
|
130 |
+
context_pre_only=False,
|
131 |
+
bias=True,
|
132 |
+
processor=processor,
|
133 |
+
qk_norm=qk_norm,
|
134 |
+
eps=eps,
|
135 |
+
)
|
136 |
+
|
137 |
+
self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
138 |
+
self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
|
139 |
+
|
140 |
+
self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
141 |
+
self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
|
142 |
+
|
143 |
+
# let chunk size default to None
|
144 |
+
self._chunk_size = None
|
145 |
+
self._chunk_dim = 0
|
146 |
+
|
147 |
+
def forward(
|
148 |
+
self,
|
149 |
+
hidden_states: torch.Tensor,
|
150 |
+
cond_hidden_states: torch.Tensor,
|
151 |
+
encoder_hidden_states: torch.Tensor,
|
152 |
+
temb: torch.Tensor,
|
153 |
+
cond_temb: torch.Tensor,
|
154 |
+
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
155 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
156 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
157 |
+
use_cond = cond_hidden_states is not None
|
158 |
+
|
159 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
|
160 |
+
if use_cond:
|
161 |
+
(
|
162 |
+
norm_cond_hidden_states,
|
163 |
+
cond_gate_msa,
|
164 |
+
cond_shift_mlp,
|
165 |
+
cond_scale_mlp,
|
166 |
+
cond_gate_mlp,
|
167 |
+
) = self.norm1(cond_hidden_states, emb=cond_temb)
|
168 |
+
|
169 |
+
norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
|
170 |
+
encoder_hidden_states, emb=temb
|
171 |
+
)
|
172 |
+
|
173 |
+
norm_hidden_states = torch.concat([norm_hidden_states, norm_cond_hidden_states], dim=-2)
|
174 |
+
|
175 |
+
joint_attention_kwargs = joint_attention_kwargs or {}
|
176 |
+
# Attention.
|
177 |
+
attention_outputs = self.attn(
|
178 |
+
hidden_states=norm_hidden_states,
|
179 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
180 |
+
image_rotary_emb=image_rotary_emb,
|
181 |
+
use_cond=use_cond,
|
182 |
+
**joint_attention_kwargs,
|
183 |
+
)
|
184 |
+
|
185 |
+
attn_output, context_attn_output = attention_outputs[:2]
|
186 |
+
cond_attn_output = attention_outputs[2] if use_cond else None
|
187 |
+
|
188 |
+
# Process attention outputs for the `hidden_states`.
|
189 |
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
190 |
+
hidden_states = hidden_states + attn_output
|
191 |
+
|
192 |
+
if use_cond:
|
193 |
+
cond_attn_output = cond_gate_msa.unsqueeze(1) * cond_attn_output
|
194 |
+
cond_hidden_states = cond_hidden_states + cond_attn_output
|
195 |
+
|
196 |
+
norm_hidden_states = self.norm2(hidden_states)
|
197 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
198 |
+
|
199 |
+
if use_cond:
|
200 |
+
norm_cond_hidden_states = self.norm2(cond_hidden_states)
|
201 |
+
norm_cond_hidden_states = (
|
202 |
+
norm_cond_hidden_states * (1 + cond_scale_mlp[:, None])
|
203 |
+
+ cond_shift_mlp[:, None]
|
204 |
+
)
|
205 |
+
|
206 |
+
ff_output = self.ff(norm_hidden_states)
|
207 |
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
208 |
+
hidden_states = hidden_states + ff_output
|
209 |
+
|
210 |
+
if use_cond:
|
211 |
+
cond_ff_output = self.ff(norm_cond_hidden_states)
|
212 |
+
cond_ff_output = cond_gate_mlp.unsqueeze(1) * cond_ff_output
|
213 |
+
cond_hidden_states = cond_hidden_states + cond_ff_output
|
214 |
+
|
215 |
+
# Process attention outputs for the `encoder_hidden_states`.
|
216 |
+
|
217 |
+
context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
|
218 |
+
encoder_hidden_states = encoder_hidden_states + context_attn_output
|
219 |
+
|
220 |
+
norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
|
221 |
+
norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
|
222 |
+
|
223 |
+
context_ff_output = self.ff_context(norm_encoder_hidden_states)
|
224 |
+
encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
|
225 |
+
if encoder_hidden_states.dtype == torch.float16:
|
226 |
+
encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
|
227 |
+
|
228 |
+
return encoder_hidden_states, hidden_states, cond_hidden_states if use_cond else None
|
229 |
+
|
230 |
+
|
231 |
+
class FluxTransformer2DModel(
|
232 |
+
ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, FluxTransformer2DLoadersMixin
|
233 |
+
):
|
234 |
+
_supports_gradient_checkpointing = True
|
235 |
+
_no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
|
236 |
+
|
237 |
+
@register_to_config
|
238 |
+
def __init__(
|
239 |
+
self,
|
240 |
+
patch_size: int = 1,
|
241 |
+
in_channels: int = 64,
|
242 |
+
out_channels: Optional[int] = None,
|
243 |
+
num_layers: int = 19,
|
244 |
+
num_single_layers: int = 38,
|
245 |
+
attention_head_dim: int = 128,
|
246 |
+
num_attention_heads: int = 24,
|
247 |
+
joint_attention_dim: int = 4096,
|
248 |
+
pooled_projection_dim: int = 768,
|
249 |
+
guidance_embeds: bool = False,
|
250 |
+
axes_dims_rope: Tuple[int] = (16, 56, 56),
|
251 |
+
):
|
252 |
+
super().__init__()
|
253 |
+
self.out_channels = out_channels or in_channels
|
254 |
+
self.inner_dim = num_attention_heads * attention_head_dim
|
255 |
+
|
256 |
+
self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
|
257 |
+
|
258 |
+
text_time_guidance_cls = (
|
259 |
+
CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
|
260 |
+
)
|
261 |
+
self.time_text_embed = text_time_guidance_cls(
|
262 |
+
embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
|
263 |
+
)
|
264 |
+
|
265 |
+
self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
|
266 |
+
self.x_embedder = nn.Linear(in_channels, self.inner_dim)
|
267 |
+
|
268 |
+
self.transformer_blocks = nn.ModuleList(
|
269 |
+
[
|
270 |
+
FluxTransformerBlock(
|
271 |
+
dim=self.inner_dim,
|
272 |
+
num_attention_heads=num_attention_heads,
|
273 |
+
attention_head_dim=attention_head_dim,
|
274 |
+
)
|
275 |
+
for _ in range(num_layers)
|
276 |
+
]
|
277 |
+
)
|
278 |
+
|
279 |
+
self.single_transformer_blocks = nn.ModuleList(
|
280 |
+
[
|
281 |
+
FluxSingleTransformerBlock(
|
282 |
+
dim=self.inner_dim,
|
283 |
+
num_attention_heads=num_attention_heads,
|
284 |
+
attention_head_dim=attention_head_dim,
|
285 |
+
)
|
286 |
+
for _ in range(num_single_layers)
|
287 |
+
]
|
288 |
+
)
|
289 |
+
|
290 |
+
self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
|
291 |
+
self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
|
292 |
+
|
293 |
+
self.gradient_checkpointing = False
|
294 |
+
|
295 |
+
@property
|
296 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
|
297 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
298 |
+
r"""
|
299 |
+
Returns:
|
300 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
301 |
+
indexed by its weight name.
|
302 |
+
"""
|
303 |
+
# set recursively
|
304 |
+
processors = {}
|
305 |
+
|
306 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
307 |
+
if hasattr(module, "get_processor"):
|
308 |
+
processors[f"{name}.processor"] = module.get_processor()
|
309 |
+
|
310 |
+
for sub_name, child in module.named_children():
|
311 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
312 |
+
|
313 |
+
return processors
|
314 |
+
|
315 |
+
for name, module in self.named_children():
|
316 |
+
fn_recursive_add_processors(name, module, processors)
|
317 |
+
|
318 |
+
return processors
|
319 |
+
|
320 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
321 |
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
322 |
+
r"""
|
323 |
+
Sets the attention processor to use to compute attention.
|
324 |
+
|
325 |
+
Parameters:
|
326 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
327 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
328 |
+
for **all** `Attention` layers.
|
329 |
+
|
330 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
331 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
332 |
+
|
333 |
+
"""
|
334 |
+
count = len(self.attn_processors.keys())
|
335 |
+
|
336 |
+
if isinstance(processor, dict) and len(processor) != count:
|
337 |
+
raise ValueError(
|
338 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
339 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
340 |
+
)
|
341 |
+
|
342 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
343 |
+
if hasattr(module, "set_processor"):
|
344 |
+
if not isinstance(processor, dict):
|
345 |
+
module.set_processor(processor)
|
346 |
+
else:
|
347 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
348 |
+
|
349 |
+
for sub_name, child in module.named_children():
|
350 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
351 |
+
|
352 |
+
for name, module in self.named_children():
|
353 |
+
fn_recursive_attn_processor(name, module, processor)
|
354 |
+
|
355 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0
|
356 |
+
def fuse_qkv_projections(self):
|
357 |
+
"""
|
358 |
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
|
359 |
+
are fused. For cross-attention modules, key and value projection matrices are fused.
|
360 |
+
|
361 |
+
<Tip warning={true}>
|
362 |
+
|
363 |
+
This API is 🧪 experimental.
|
364 |
+
|
365 |
+
</Tip>
|
366 |
+
"""
|
367 |
+
self.original_attn_processors = None
|
368 |
+
|
369 |
+
for _, attn_processor in self.attn_processors.items():
|
370 |
+
if "Added" in str(attn_processor.__class__.__name__):
|
371 |
+
raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
|
372 |
+
|
373 |
+
self.original_attn_processors = self.attn_processors
|
374 |
+
|
375 |
+
for module in self.modules():
|
376 |
+
if isinstance(module, Attention):
|
377 |
+
module.fuse_projections(fuse=True)
|
378 |
+
|
379 |
+
self.set_attn_processor(FusedFluxAttnProcessor2_0())
|
380 |
+
|
381 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
|
382 |
+
def unfuse_qkv_projections(self):
|
383 |
+
"""Disables the fused QKV projection if enabled.
|
384 |
+
|
385 |
+
<Tip warning={true}>
|
386 |
+
|
387 |
+
This API is 🧪 experimental.
|
388 |
+
|
389 |
+
</Tip>
|
390 |
+
|
391 |
+
"""
|
392 |
+
if self.original_attn_processors is not None:
|
393 |
+
self.set_attn_processor(self.original_attn_processors)
|
394 |
+
|
395 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
396 |
+
if hasattr(module, "gradient_checkpointing"):
|
397 |
+
module.gradient_checkpointing = value
|
398 |
+
|
399 |
+
def forward(
|
400 |
+
self,
|
401 |
+
hidden_states: torch.Tensor,
|
402 |
+
cond_hidden_states: torch.Tensor = None,
|
403 |
+
encoder_hidden_states: torch.Tensor = None,
|
404 |
+
pooled_projections: torch.Tensor = None,
|
405 |
+
timestep: torch.LongTensor = None,
|
406 |
+
img_ids: torch.Tensor = None,
|
407 |
+
txt_ids: torch.Tensor = None,
|
408 |
+
guidance: torch.Tensor = None,
|
409 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
410 |
+
controlnet_block_samples=None,
|
411 |
+
controlnet_single_block_samples=None,
|
412 |
+
return_dict: bool = True,
|
413 |
+
controlnet_blocks_repeat: bool = False,
|
414 |
+
) -> Union[torch.Tensor, Transformer2DModelOutput]:
|
415 |
+
if cond_hidden_states is not None:
|
416 |
+
use_condition = True
|
417 |
+
else:
|
418 |
+
use_condition = False
|
419 |
+
|
420 |
+
if joint_attention_kwargs is not None:
|
421 |
+
joint_attention_kwargs = joint_attention_kwargs.copy()
|
422 |
+
lora_scale = joint_attention_kwargs.pop("scale", 1.0)
|
423 |
+
else:
|
424 |
+
lora_scale = 1.0
|
425 |
+
|
426 |
+
if USE_PEFT_BACKEND:
|
427 |
+
# weight the lora layers by setting `lora_scale` for each PEFT layer
|
428 |
+
scale_lora_layers(self, lora_scale)
|
429 |
+
else:
|
430 |
+
if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
|
431 |
+
logger.warning(
|
432 |
+
"Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
|
433 |
+
)
|
434 |
+
|
435 |
+
hidden_states = self.x_embedder(hidden_states)
|
436 |
+
cond_hidden_states = self.x_embedder(cond_hidden_states)
|
437 |
+
|
438 |
+
timestep = timestep.to(hidden_states.dtype) * 1000
|
439 |
+
if guidance is not None:
|
440 |
+
guidance = guidance.to(hidden_states.dtype) * 1000
|
441 |
+
else:
|
442 |
+
guidance = None
|
443 |
+
|
444 |
+
temb = (
|
445 |
+
self.time_text_embed(timestep, pooled_projections)
|
446 |
+
if guidance is None
|
447 |
+
else self.time_text_embed(timestep, guidance, pooled_projections)
|
448 |
+
)
|
449 |
+
|
450 |
+
cond_temb = (
|
451 |
+
self.time_text_embed(torch.ones_like(timestep) * 0, pooled_projections)
|
452 |
+
if guidance is None
|
453 |
+
else self.time_text_embed(
|
454 |
+
torch.ones_like(timestep) * 0, guidance, pooled_projections
|
455 |
+
)
|
456 |
+
)
|
457 |
+
|
458 |
+
encoder_hidden_states = self.context_embedder(encoder_hidden_states)
|
459 |
+
|
460 |
+
if txt_ids.ndim == 3:
|
461 |
+
logger.warning(
|
462 |
+
"Passing `txt_ids` 3d torch.Tensor is deprecated."
|
463 |
+
"Please remove the batch dimension and pass it as a 2d torch Tensor"
|
464 |
+
)
|
465 |
+
txt_ids = txt_ids[0]
|
466 |
+
if img_ids.ndim == 3:
|
467 |
+
logger.warning(
|
468 |
+
"Passing `img_ids` 3d torch.Tensor is deprecated."
|
469 |
+
"Please remove the batch dimension and pass it as a 2d torch Tensor"
|
470 |
+
)
|
471 |
+
img_ids = img_ids[0]
|
472 |
+
|
473 |
+
ids = torch.cat((txt_ids, img_ids), dim=0)
|
474 |
+
image_rotary_emb = self.pos_embed(ids)
|
475 |
+
|
476 |
+
if joint_attention_kwargs is not None and "ip_adapter_image_embeds" in joint_attention_kwargs:
|
477 |
+
ip_adapter_image_embeds = joint_attention_kwargs.pop("ip_adapter_image_embeds")
|
478 |
+
ip_hidden_states = self.encoder_hid_proj(ip_adapter_image_embeds)
|
479 |
+
joint_attention_kwargs.update({"ip_hidden_states": ip_hidden_states})
|
480 |
+
|
481 |
+
for index_block, block in enumerate(self.transformer_blocks):
|
482 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
483 |
+
|
484 |
+
def create_custom_forward(module, return_dict=None):
|
485 |
+
def custom_forward(*inputs):
|
486 |
+
if return_dict is not None:
|
487 |
+
return module(*inputs, return_dict=return_dict)
|
488 |
+
else:
|
489 |
+
return module(*inputs)
|
490 |
+
|
491 |
+
return custom_forward
|
492 |
+
|
493 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
494 |
+
encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
|
495 |
+
create_custom_forward(block),
|
496 |
+
hidden_states,
|
497 |
+
encoder_hidden_states,
|
498 |
+
temb,
|
499 |
+
image_rotary_emb,
|
500 |
+
cond_temb=cond_temb if use_condition else None,
|
501 |
+
cond_hidden_states=cond_hidden_states if use_condition else None,
|
502 |
+
**ckpt_kwargs,
|
503 |
+
)
|
504 |
+
|
505 |
+
else:
|
506 |
+
encoder_hidden_states, hidden_states, cond_hidden_states = block(
|
507 |
+
hidden_states=hidden_states,
|
508 |
+
encoder_hidden_states=encoder_hidden_states,
|
509 |
+
cond_hidden_states=cond_hidden_states if use_condition else None,
|
510 |
+
temb=temb,
|
511 |
+
cond_temb=cond_temb if use_condition else None,
|
512 |
+
image_rotary_emb=image_rotary_emb,
|
513 |
+
joint_attention_kwargs=joint_attention_kwargs,
|
514 |
+
)
|
515 |
+
|
516 |
+
# controlnet residual
|
517 |
+
if controlnet_block_samples is not None:
|
518 |
+
interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
|
519 |
+
interval_control = int(np.ceil(interval_control))
|
520 |
+
# For Xlabs ControlNet.
|
521 |
+
if controlnet_blocks_repeat:
|
522 |
+
hidden_states = (
|
523 |
+
hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
|
524 |
+
)
|
525 |
+
else:
|
526 |
+
hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
|
527 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
528 |
+
|
529 |
+
for index_block, block in enumerate(self.single_transformer_blocks):
|
530 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
531 |
+
|
532 |
+
def create_custom_forward(module, return_dict=None):
|
533 |
+
def custom_forward(*inputs):
|
534 |
+
if return_dict is not None:
|
535 |
+
return module(*inputs, return_dict=return_dict)
|
536 |
+
else:
|
537 |
+
return module(*inputs)
|
538 |
+
|
539 |
+
return custom_forward
|
540 |
+
|
541 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
542 |
+
hidden_states, cond_hidden_states = torch.utils.checkpoint.checkpoint(
|
543 |
+
create_custom_forward(block),
|
544 |
+
hidden_states,
|
545 |
+
temb,
|
546 |
+
image_rotary_emb,
|
547 |
+
cond_temb=cond_temb if use_condition else None,
|
548 |
+
cond_hidden_states=cond_hidden_states if use_condition else None,
|
549 |
+
**ckpt_kwargs,
|
550 |
+
)
|
551 |
+
|
552 |
+
else:
|
553 |
+
hidden_states, cond_hidden_states = block(
|
554 |
+
hidden_states=hidden_states,
|
555 |
+
cond_hidden_states=cond_hidden_states if use_condition else None,
|
556 |
+
temb=temb,
|
557 |
+
cond_temb=cond_temb if use_condition else None,
|
558 |
+
image_rotary_emb=image_rotary_emb,
|
559 |
+
joint_attention_kwargs=joint_attention_kwargs,
|
560 |
+
)
|
561 |
+
|
562 |
+
# controlnet residual
|
563 |
+
if controlnet_single_block_samples is not None:
|
564 |
+
interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
|
565 |
+
interval_control = int(np.ceil(interval_control))
|
566 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
|
567 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
568 |
+
+ controlnet_single_block_samples[index_block // interval_control]
|
569 |
+
)
|
570 |
+
|
571 |
+
hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
572 |
+
|
573 |
+
hidden_states = self.norm_out(hidden_states, temb)
|
574 |
+
output = self.proj_out(hidden_states)
|
575 |
+
|
576 |
+
if USE_PEFT_BACKEND:
|
577 |
+
# remove `lora_scale` from each PEFT layer
|
578 |
+
unscale_lora_layers(self, lora_scale)
|
579 |
+
|
580 |
+
if not return_dict:
|
581 |
+
return (output,)
|
582 |
+
|
583 |
+
return Transformer2DModelOutput(sample=output)
|