Spaces:
Running
on
Zero
Running
on
Zero
XuDongZhou
commited on
Commit
•
96bea52
1
Parent(s):
dfa4ebb
Upload 9 files
Browse files- pipeline_controlnet_xs_sd_xl_instantid.py +1914 -0
- utils/attention_processor.py +888 -0
- utils/callbacks.py +156 -0
- utils/controlnet_xs.py +2066 -0
- utils/modules.py +159 -0
- utils/resampler.py +159 -0
- utils/resize.py +107 -0
- utils/tools.py +124 -0
- utils/utils.py +94 -0
pipeline_controlnet_xs_sd_xl_instantid.py
ADDED
@@ -0,0 +1,1914 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
import inspect
|
4 |
+
import copy, os
|
5 |
+
from safetensors.torch import load_file
|
6 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
7 |
+
import collections
|
8 |
+
import numpy as np
|
9 |
+
import PIL.Image
|
10 |
+
import torch
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from transformers import (
|
13 |
+
CLIPImageProcessor,
|
14 |
+
CLIPTextModel,
|
15 |
+
CLIPTextModelWithProjection,
|
16 |
+
CLIPTokenizer,
|
17 |
+
)
|
18 |
+
import gc
|
19 |
+
from diffusers.utils.import_utils import is_xformers_available
|
20 |
+
from diffusers.utils.import_utils import is_invisible_watermark_available
|
21 |
+
|
22 |
+
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
23 |
+
from diffusers.loaders import FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin
|
24 |
+
from diffusers.models import AutoencoderKL
|
25 |
+
from diffusers.models.attention_processor import (
|
26 |
+
AttnProcessor2_0,
|
27 |
+
LoRAAttnProcessor2_0,
|
28 |
+
LoRAXFormersAttnProcessor,
|
29 |
+
XFormersAttnProcessor,
|
30 |
+
)
|
31 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
32 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
33 |
+
|
34 |
+
from diffusers.utils import (
|
35 |
+
USE_PEFT_BACKEND,
|
36 |
+
is_torch_version,
|
37 |
+
logging,
|
38 |
+
replace_example_docstring,
|
39 |
+
scale_lora_layers,
|
40 |
+
unscale_lora_layers,
|
41 |
+
delete_adapter_layers,
|
42 |
+
set_adapter_layers,
|
43 |
+
set_weights_and_activate_adapters,
|
44 |
+
)
|
45 |
+
|
46 |
+
from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
|
47 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
48 |
+
from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
|
49 |
+
|
50 |
+
|
51 |
+
from utils.callbacks import MultiPipelineCallbacks, PipelineCallback
|
52 |
+
|
53 |
+
# lora
|
54 |
+
from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
|
55 |
+
from controlnet_xs import ControlNetXSAdapter, UNetControlNetXSModel
|
56 |
+
from diffusers.loaders.lora_conversion_utils import _maybe_map_sgm_blocks_to_diffusers, _convert_non_diffusers_lora_to_diffusers
|
57 |
+
from utils.tools import get_module_kohya_state_dict_xs
|
58 |
+
|
59 |
+
|
60 |
+
#ipa
|
61 |
+
from ip_adapter.resampler import Resampler
|
62 |
+
from ip_adapter.utils import is_torch2_available
|
63 |
+
if is_torch2_available():
|
64 |
+
from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor
|
65 |
+
else:
|
66 |
+
from ip_adapter.attention_processor import IPAttnProcessor, AttnProcessor
|
67 |
+
from ip_adapter.attention_processor import region_control
|
68 |
+
|
69 |
+
|
70 |
+
if is_invisible_watermark_available():
|
71 |
+
from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
|
72 |
+
|
73 |
+
|
74 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
75 |
+
|
76 |
+
|
77 |
+
EXAMPLE_DOC_STRING = """
|
78 |
+
Examples:
|
79 |
+
```py
|
80 |
+
>>> # !pip install opencv-python transformers accelerate
|
81 |
+
>>> from diffusers import StableDiffusionXLControlNetXSPipeline, ControlNetXSAdapter, AutoencoderKL
|
82 |
+
>>> from diffusers.utils import load_image
|
83 |
+
>>> import numpy as np
|
84 |
+
>>> import torch
|
85 |
+
|
86 |
+
>>> import cv2
|
87 |
+
>>> from PIL import Image
|
88 |
+
|
89 |
+
>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
|
90 |
+
>>> negative_prompt = "low quality, bad quality, sketches"
|
91 |
+
|
92 |
+
>>> # download an image
|
93 |
+
>>> image = load_image(
|
94 |
+
... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
|
95 |
+
... )
|
96 |
+
|
97 |
+
>>> # initialize the models and pipeline
|
98 |
+
>>> controlnet_conditioning_scale = 0.5
|
99 |
+
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
|
100 |
+
>>> controlnet = ControlNetXSAdapter.from_pretrained(
|
101 |
+
... "UmerHA/Testing-ConrolNetXS-SDXL-canny", torch_dtype=torch.float16
|
102 |
+
... )
|
103 |
+
>>> pipe = StableDiffusionXLControlNetXSPipeline.from_pretrained(
|
104 |
+
... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
|
105 |
+
... )
|
106 |
+
>>> pipe.enable_model_cpu_offload()
|
107 |
+
|
108 |
+
>>> # get canny image
|
109 |
+
>>> image = np.array(image)
|
110 |
+
>>> image = cv2.Canny(image, 100, 200)
|
111 |
+
>>> image = image[:, :, None]
|
112 |
+
>>> image = np.concatenate([image, image, image], axis=2)
|
113 |
+
>>> canny_image = Image.fromarray(image)
|
114 |
+
|
115 |
+
>>> # generate image
|
116 |
+
>>> image = pipe(
|
117 |
+
... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
|
118 |
+
... ).images[0]
|
119 |
+
```
|
120 |
+
"""
|
121 |
+
|
122 |
+
|
123 |
+
from transformers import CLIPTokenizer
|
124 |
+
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipeline
|
125 |
+
|
126 |
+
class LongPromptWeight(object):
|
127 |
+
"""
|
128 |
+
Copied from https://github.com/huggingface/diffusers/blob/main/examples/community/lpw_stable_diffusion_xl.py
|
129 |
+
"""
|
130 |
+
|
131 |
+
def __init__(self) -> None:
|
132 |
+
pass
|
133 |
+
|
134 |
+
def parse_prompt_attention(self, text):
|
135 |
+
"""
|
136 |
+
Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
|
137 |
+
Accepted tokens are:
|
138 |
+
(abc) - increases attention to abc by a multiplier of 1.1
|
139 |
+
(abc:3.12) - increases attention to abc by a multiplier of 3.12
|
140 |
+
[abc] - decreases attention to abc by a multiplier of 1.1
|
141 |
+
\( - literal character '('
|
142 |
+
\[ - literal character '['
|
143 |
+
\) - literal character ')'
|
144 |
+
\] - literal character ']'
|
145 |
+
\\ - literal character '\'
|
146 |
+
anything else - just text
|
147 |
+
|
148 |
+
>>> parse_prompt_attention('normal text')
|
149 |
+
[['normal text', 1.0]]
|
150 |
+
>>> parse_prompt_attention('an (important) word')
|
151 |
+
[['an ', 1.0], ['important', 1.1], [' word', 1.0]]
|
152 |
+
>>> parse_prompt_attention('(unbalanced')
|
153 |
+
[['unbalanced', 1.1]]
|
154 |
+
>>> parse_prompt_attention('\(literal\]')
|
155 |
+
[['(literal]', 1.0]]
|
156 |
+
>>> parse_prompt_attention('(unnecessary)(parens)')
|
157 |
+
[['unnecessaryparens', 1.1]]
|
158 |
+
>>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
|
159 |
+
[['a ', 1.0],
|
160 |
+
['house', 1.5730000000000004],
|
161 |
+
[' ', 1.1],
|
162 |
+
['on', 1.0],
|
163 |
+
[' a ', 1.1],
|
164 |
+
['hill', 0.55],
|
165 |
+
[', sun, ', 1.1],
|
166 |
+
['sky', 1.4641000000000006],
|
167 |
+
['.', 1.1]]
|
168 |
+
"""
|
169 |
+
import re
|
170 |
+
|
171 |
+
re_attention = re.compile(
|
172 |
+
r"""
|
173 |
+
\\\(|\\\)|\\\[|\\]|\\\\|\\|\(|\[|:([+-]?[.\d]+)\)|
|
174 |
+
\)|]|[^\\()\[\]:]+|:
|
175 |
+
""",
|
176 |
+
re.X,
|
177 |
+
)
|
178 |
+
|
179 |
+
re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
|
180 |
+
|
181 |
+
res = []
|
182 |
+
round_brackets = []
|
183 |
+
square_brackets = []
|
184 |
+
|
185 |
+
round_bracket_multiplier = 1.1
|
186 |
+
square_bracket_multiplier = 1 / 1.1
|
187 |
+
|
188 |
+
def multiply_range(start_position, multiplier):
|
189 |
+
for p in range(start_position, len(res)):
|
190 |
+
res[p][1] *= multiplier
|
191 |
+
|
192 |
+
for m in re_attention.finditer(text):
|
193 |
+
text = m.group(0)
|
194 |
+
weight = m.group(1)
|
195 |
+
|
196 |
+
if text.startswith("\\"):
|
197 |
+
res.append([text[1:], 1.0])
|
198 |
+
elif text == "(":
|
199 |
+
round_brackets.append(len(res))
|
200 |
+
elif text == "[":
|
201 |
+
square_brackets.append(len(res))
|
202 |
+
elif weight is not None and len(round_brackets) > 0:
|
203 |
+
multiply_range(round_brackets.pop(), float(weight))
|
204 |
+
elif text == ")" and len(round_brackets) > 0:
|
205 |
+
multiply_range(round_brackets.pop(), round_bracket_multiplier)
|
206 |
+
elif text == "]" and len(square_brackets) > 0:
|
207 |
+
multiply_range(square_brackets.pop(), square_bracket_multiplier)
|
208 |
+
else:
|
209 |
+
parts = re.split(re_break, text)
|
210 |
+
for i, part in enumerate(parts):
|
211 |
+
if i > 0:
|
212 |
+
res.append(["BREAK", -1])
|
213 |
+
res.append([part, 1.0])
|
214 |
+
|
215 |
+
for pos in round_brackets:
|
216 |
+
multiply_range(pos, round_bracket_multiplier)
|
217 |
+
|
218 |
+
for pos in square_brackets:
|
219 |
+
multiply_range(pos, square_bracket_multiplier)
|
220 |
+
|
221 |
+
if len(res) == 0:
|
222 |
+
res = [["", 1.0]]
|
223 |
+
|
224 |
+
# merge runs of identical weights
|
225 |
+
i = 0
|
226 |
+
while i + 1 < len(res):
|
227 |
+
if res[i][1] == res[i + 1][1]:
|
228 |
+
res[i][0] += res[i + 1][0]
|
229 |
+
res.pop(i + 1)
|
230 |
+
else:
|
231 |
+
i += 1
|
232 |
+
|
233 |
+
return res
|
234 |
+
|
235 |
+
def get_prompts_tokens_with_weights(self, clip_tokenizer: CLIPTokenizer, prompt: str):
|
236 |
+
"""
|
237 |
+
Get prompt token ids and weights, this function works for both prompt and negative prompt
|
238 |
+
|
239 |
+
Args:
|
240 |
+
pipe (CLIPTokenizer)
|
241 |
+
A CLIPTokenizer
|
242 |
+
prompt (str)
|
243 |
+
A prompt string with weights
|
244 |
+
|
245 |
+
Returns:
|
246 |
+
text_tokens (list)
|
247 |
+
A list contains token ids
|
248 |
+
text_weight (list)
|
249 |
+
A list contains the correspodent weight of token ids
|
250 |
+
|
251 |
+
Example:
|
252 |
+
import torch
|
253 |
+
from transformers import CLIPTokenizer
|
254 |
+
|
255 |
+
clip_tokenizer = CLIPTokenizer.from_pretrained(
|
256 |
+
"stablediffusionapi/deliberate-v2"
|
257 |
+
, subfolder = "tokenizer"
|
258 |
+
, dtype = torch.float16
|
259 |
+
)
|
260 |
+
|
261 |
+
token_id_list, token_weight_list = get_prompts_tokens_with_weights(
|
262 |
+
clip_tokenizer = clip_tokenizer
|
263 |
+
,prompt = "a (red:1.5) cat"*70
|
264 |
+
)
|
265 |
+
"""
|
266 |
+
texts_and_weights = self.parse_prompt_attention(prompt)
|
267 |
+
text_tokens, text_weights = [], []
|
268 |
+
for word, weight in texts_and_weights:
|
269 |
+
# tokenize and discard the starting and the ending token
|
270 |
+
token = clip_tokenizer(word, truncation=False).input_ids[1:-1] # so that tokenize whatever length prompt
|
271 |
+
# the returned token is a 1d list: [320, 1125, 539, 320]
|
272 |
+
|
273 |
+
# merge the new tokens to the all tokens holder: text_tokens
|
274 |
+
text_tokens = [*text_tokens, *token]
|
275 |
+
|
276 |
+
# each token chunk will come with one weight, like ['red cat', 2.0]
|
277 |
+
# need to expand weight for each token.
|
278 |
+
chunk_weights = [weight] * len(token)
|
279 |
+
|
280 |
+
# append the weight back to the weight holder: text_weights
|
281 |
+
text_weights = [*text_weights, *chunk_weights]
|
282 |
+
return text_tokens, text_weights
|
283 |
+
|
284 |
+
def group_tokens_and_weights(self, token_ids: list, weights: list, pad_last_block=False):
|
285 |
+
"""
|
286 |
+
Produce tokens and weights in groups and pad the missing tokens
|
287 |
+
|
288 |
+
Args:
|
289 |
+
token_ids (list)
|
290 |
+
The token ids from tokenizer
|
291 |
+
weights (list)
|
292 |
+
The weights list from function get_prompts_tokens_with_weights
|
293 |
+
pad_last_block (bool)
|
294 |
+
Control if fill the last token list to 75 tokens with eos
|
295 |
+
Returns:
|
296 |
+
new_token_ids (2d list)
|
297 |
+
new_weights (2d list)
|
298 |
+
|
299 |
+
Example:
|
300 |
+
token_groups,weight_groups = group_tokens_and_weights(
|
301 |
+
token_ids = token_id_list
|
302 |
+
, weights = token_weight_list
|
303 |
+
)
|
304 |
+
"""
|
305 |
+
bos, eos = 49406, 49407
|
306 |
+
|
307 |
+
# this will be a 2d list
|
308 |
+
new_token_ids = []
|
309 |
+
new_weights = []
|
310 |
+
while len(token_ids) >= 75:
|
311 |
+
# get the first 75 tokens
|
312 |
+
head_75_tokens = [token_ids.pop(0) for _ in range(75)]
|
313 |
+
head_75_weights = [weights.pop(0) for _ in range(75)]
|
314 |
+
|
315 |
+
# extract token ids and weights
|
316 |
+
temp_77_token_ids = [bos] + head_75_tokens + [eos]
|
317 |
+
temp_77_weights = [1.0] + head_75_weights + [1.0]
|
318 |
+
|
319 |
+
# add 77 token and weights chunk to the holder list
|
320 |
+
new_token_ids.append(temp_77_token_ids)
|
321 |
+
new_weights.append(temp_77_weights)
|
322 |
+
|
323 |
+
# padding the left
|
324 |
+
if len(token_ids) >= 0:
|
325 |
+
padding_len = 75 - len(token_ids) if pad_last_block else 0
|
326 |
+
|
327 |
+
temp_77_token_ids = [bos] + token_ids + [eos] * padding_len + [eos]
|
328 |
+
new_token_ids.append(temp_77_token_ids)
|
329 |
+
|
330 |
+
temp_77_weights = [1.0] + weights + [1.0] * padding_len + [1.0]
|
331 |
+
new_weights.append(temp_77_weights)
|
332 |
+
|
333 |
+
return new_token_ids, new_weights
|
334 |
+
|
335 |
+
def get_weighted_text_embeddings_sdxl(
|
336 |
+
self,
|
337 |
+
pipe: StableDiffusionXLPipeline,
|
338 |
+
prompt: str = "",
|
339 |
+
prompt_2: str = None,
|
340 |
+
neg_prompt: str = "",
|
341 |
+
neg_prompt_2: str = None,
|
342 |
+
prompt_embeds=None,
|
343 |
+
negative_prompt_embeds=None,
|
344 |
+
pooled_prompt_embeds=None,
|
345 |
+
negative_pooled_prompt_embeds=None,
|
346 |
+
extra_emb=None,
|
347 |
+
extra_emb_alpha=0.6,
|
348 |
+
):
|
349 |
+
"""
|
350 |
+
This function can process long prompt with weights, no length limitation
|
351 |
+
for Stable Diffusion XL
|
352 |
+
|
353 |
+
Args:
|
354 |
+
pipe (StableDiffusionPipeline)
|
355 |
+
prompt (str)
|
356 |
+
prompt_2 (str)
|
357 |
+
neg_prompt (str)
|
358 |
+
neg_prompt_2 (str)
|
359 |
+
Returns:
|
360 |
+
prompt_embeds (torch.Tensor)
|
361 |
+
neg_prompt_embeds (torch.Tensor)
|
362 |
+
"""
|
363 |
+
#
|
364 |
+
if prompt_embeds is not None and \
|
365 |
+
negative_prompt_embeds is not None and \
|
366 |
+
pooled_prompt_embeds is not None and \
|
367 |
+
negative_pooled_prompt_embeds is not None:
|
368 |
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
369 |
+
|
370 |
+
if prompt_2:
|
371 |
+
prompt = f"{prompt} {prompt_2}"
|
372 |
+
|
373 |
+
if neg_prompt_2:
|
374 |
+
neg_prompt = f"{neg_prompt} {neg_prompt_2}"
|
375 |
+
|
376 |
+
eos = pipe.tokenizer.eos_token_id
|
377 |
+
|
378 |
+
# tokenizer 1
|
379 |
+
prompt_tokens, prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt)
|
380 |
+
neg_prompt_tokens, neg_prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
|
381 |
+
|
382 |
+
# tokenizer 2
|
383 |
+
# prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, prompt)
|
384 |
+
# neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, neg_prompt)
|
385 |
+
# tokenizer 2 遇到 !! !!!! 等多感叹号和tokenizer 1的效果不一致
|
386 |
+
prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt)
|
387 |
+
neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
|
388 |
+
|
389 |
+
# padding the shorter one for prompt set 1
|
390 |
+
prompt_token_len = len(prompt_tokens)
|
391 |
+
neg_prompt_token_len = len(neg_prompt_tokens)
|
392 |
+
|
393 |
+
if prompt_token_len > neg_prompt_token_len:
|
394 |
+
# padding the neg_prompt with eos token
|
395 |
+
neg_prompt_tokens = neg_prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
|
396 |
+
neg_prompt_weights = neg_prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
|
397 |
+
else:
|
398 |
+
# padding the prompt
|
399 |
+
prompt_tokens = prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
|
400 |
+
prompt_weights = prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
|
401 |
+
|
402 |
+
# padding the shorter one for token set 2
|
403 |
+
prompt_token_len_2 = len(prompt_tokens_2)
|
404 |
+
neg_prompt_token_len_2 = len(neg_prompt_tokens_2)
|
405 |
+
|
406 |
+
if prompt_token_len_2 > neg_prompt_token_len_2:
|
407 |
+
# padding the neg_prompt with eos token
|
408 |
+
neg_prompt_tokens_2 = neg_prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
|
409 |
+
neg_prompt_weights_2 = neg_prompt_weights_2 + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
|
410 |
+
else:
|
411 |
+
# padding the prompt
|
412 |
+
prompt_tokens_2 = prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
|
413 |
+
prompt_weights_2 = prompt_weights + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
|
414 |
+
|
415 |
+
embeds = []
|
416 |
+
neg_embeds = []
|
417 |
+
|
418 |
+
prompt_token_groups, prompt_weight_groups = self.group_tokens_and_weights(prompt_tokens.copy(),
|
419 |
+
prompt_weights.copy())
|
420 |
+
|
421 |
+
neg_prompt_token_groups, neg_prompt_weight_groups = self.group_tokens_and_weights(
|
422 |
+
neg_prompt_tokens.copy(), neg_prompt_weights.copy()
|
423 |
+
)
|
424 |
+
|
425 |
+
prompt_token_groups_2, prompt_weight_groups_2 = self.group_tokens_and_weights(
|
426 |
+
prompt_tokens_2.copy(), prompt_weights_2.copy()
|
427 |
+
)
|
428 |
+
|
429 |
+
neg_prompt_token_groups_2, neg_prompt_weight_groups_2 = self.group_tokens_and_weights(
|
430 |
+
neg_prompt_tokens_2.copy(), neg_prompt_weights_2.copy()
|
431 |
+
)
|
432 |
+
|
433 |
+
# get prompt embeddings one by one is not working.
|
434 |
+
for i in range(len(prompt_token_groups)):
|
435 |
+
# get positive prompt embeddings with weights
|
436 |
+
token_tensor = torch.tensor([prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
|
437 |
+
weight_tensor = torch.tensor(prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
|
438 |
+
|
439 |
+
token_tensor_2 = torch.tensor([prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
|
440 |
+
|
441 |
+
# use first text encoder
|
442 |
+
prompt_embeds_1 = pipe.text_encoder(token_tensor.to(pipe.device), output_hidden_states=True)
|
443 |
+
prompt_embeds_1_hidden_states = prompt_embeds_1.hidden_states[-2]
|
444 |
+
|
445 |
+
# use second text encoder
|
446 |
+
prompt_embeds_2 = pipe.text_encoder_2(token_tensor_2.to(pipe.device), output_hidden_states=True)
|
447 |
+
prompt_embeds_2_hidden_states = prompt_embeds_2.hidden_states[-2]
|
448 |
+
pooled_prompt_embeds = prompt_embeds_2[0]
|
449 |
+
|
450 |
+
prompt_embeds_list = [prompt_embeds_1_hidden_states, prompt_embeds_2_hidden_states]
|
451 |
+
token_embedding = torch.concat(prompt_embeds_list, dim=-1).squeeze(0)
|
452 |
+
|
453 |
+
for j in range(len(weight_tensor)):
|
454 |
+
if weight_tensor[j] != 1.0:
|
455 |
+
token_embedding[j] = (
|
456 |
+
token_embedding[-1] + (token_embedding[j] - token_embedding[-1]) * weight_tensor[j]
|
457 |
+
)
|
458 |
+
|
459 |
+
token_embedding = token_embedding.unsqueeze(0)
|
460 |
+
embeds.append(token_embedding)
|
461 |
+
|
462 |
+
# get negative prompt embeddings with weights
|
463 |
+
neg_token_tensor = torch.tensor([neg_prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
|
464 |
+
neg_token_tensor_2 = torch.tensor([neg_prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
|
465 |
+
neg_weight_tensor = torch.tensor(neg_prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
|
466 |
+
|
467 |
+
# use first text encoder
|
468 |
+
neg_prompt_embeds_1 = pipe.text_encoder(neg_token_tensor.to(pipe.device), output_hidden_states=True)
|
469 |
+
neg_prompt_embeds_1_hidden_states = neg_prompt_embeds_1.hidden_states[-2]
|
470 |
+
|
471 |
+
# use second text encoder
|
472 |
+
neg_prompt_embeds_2 = pipe.text_encoder_2(neg_token_tensor_2.to(pipe.device), output_hidden_states=True)
|
473 |
+
neg_prompt_embeds_2_hidden_states = neg_prompt_embeds_2.hidden_states[-2]
|
474 |
+
negative_pooled_prompt_embeds = neg_prompt_embeds_2[0]
|
475 |
+
|
476 |
+
neg_prompt_embeds_list = [neg_prompt_embeds_1_hidden_states, neg_prompt_embeds_2_hidden_states]
|
477 |
+
neg_token_embedding = torch.concat(neg_prompt_embeds_list, dim=-1).squeeze(0)
|
478 |
+
|
479 |
+
for z in range(len(neg_weight_tensor)):
|
480 |
+
if neg_weight_tensor[z] != 1.0:
|
481 |
+
neg_token_embedding[z] = (
|
482 |
+
neg_token_embedding[-1] + (neg_token_embedding[z] - neg_token_embedding[-1]) *
|
483 |
+
neg_weight_tensor[z]
|
484 |
+
)
|
485 |
+
|
486 |
+
neg_token_embedding = neg_token_embedding.unsqueeze(0)
|
487 |
+
neg_embeds.append(neg_token_embedding)
|
488 |
+
|
489 |
+
prompt_embeds = torch.cat(embeds, dim=1)
|
490 |
+
negative_prompt_embeds = torch.cat(neg_embeds, dim=1)
|
491 |
+
|
492 |
+
if extra_emb is not None:
|
493 |
+
extra_emb = extra_emb.to(prompt_embeds.device, dtype=prompt_embeds.dtype) * extra_emb_alpha
|
494 |
+
prompt_embeds = torch.cat([prompt_embeds, extra_emb], 1)
|
495 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, torch.zeros_like(extra_emb)], 1)
|
496 |
+
print(f'fix prompt_embeds, extra_emb_alpha={extra_emb_alpha}')
|
497 |
+
|
498 |
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
499 |
+
|
500 |
+
def get_prompt_embeds(self, *args, **kwargs):
|
501 |
+
prompt_embeds, negative_prompt_embeds, _, _ = self.get_weighted_text_embeddings_sdxl(*args, **kwargs)
|
502 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
503 |
+
return prompt_embeds
|
504 |
+
|
505 |
+
|
506 |
+
class StableDiffusionXLControlNetXSPipeline(
|
507 |
+
DiffusionPipeline,
|
508 |
+
TextualInversionLoaderMixin,
|
509 |
+
StableDiffusionXLLoraLoaderMixin,
|
510 |
+
FromSingleFileMixin,
|
511 |
+
):
|
512 |
+
r"""
|
513 |
+
Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet-XS guidance.
|
514 |
+
|
515 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
516 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
517 |
+
|
518 |
+
The pipeline also inherits the following loading methods:
|
519 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
520 |
+
- [`loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
521 |
+
- [`loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
522 |
+
|
523 |
+
Args:
|
524 |
+
vae ([`AutoencoderKL`]):
|
525 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
526 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
527 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
528 |
+
text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
|
529 |
+
Second frozen text-encoder
|
530 |
+
([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
|
531 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
532 |
+
A `CLIPTokenizer` to tokenize text.
|
533 |
+
tokenizer_2 ([`~transformers.CLIPTokenizer`]):
|
534 |
+
A `CLIPTokenizer` to tokenize text.
|
535 |
+
unet ([`UNet2DConditionModel`]):
|
536 |
+
A [`UNet2DConditionModel`] used to create a UNetControlNetXSModel to denoise the encoded image latents.
|
537 |
+
controlnet ([`ControlNetXSAdapter`]):
|
538 |
+
A [`ControlNetXSAdapter`] to be used in combination with `unet` to denoise the encoded image latents.
|
539 |
+
scheduler ([`SchedulerMixin`]):
|
540 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
541 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
542 |
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
543 |
+
Whether the negative prompt embeddings should always be set to 0. Also see the config of
|
544 |
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
545 |
+
add_watermarker (`bool`, *optional*):
|
546 |
+
Whether to use the [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) library to
|
547 |
+
watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
|
548 |
+
watermarker is used.
|
549 |
+
"""
|
550 |
+
|
551 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
|
552 |
+
_optional_components = [
|
553 |
+
"tokenizer",
|
554 |
+
"tokenizer_2",
|
555 |
+
"text_encoder",
|
556 |
+
"text_encoder_2",
|
557 |
+
"feature_extractor",
|
558 |
+
]
|
559 |
+
_callback_tensor_inputs = [
|
560 |
+
"latents",
|
561 |
+
"prompt_embeds",
|
562 |
+
"negative_prompt_embeds",
|
563 |
+
"add_text_embeds",
|
564 |
+
"add_time_ids",
|
565 |
+
"negative_pooled_prompt_embeds",
|
566 |
+
"negative_add_time_ids",
|
567 |
+
]
|
568 |
+
|
569 |
+
def __init__(
|
570 |
+
self,
|
571 |
+
vae: AutoencoderKL,
|
572 |
+
text_encoder: CLIPTextModel,
|
573 |
+
text_encoder_2: CLIPTextModelWithProjection,
|
574 |
+
tokenizer: CLIPTokenizer,
|
575 |
+
tokenizer_2: CLIPTokenizer,
|
576 |
+
unet: Union[UNet2DConditionModel, UNetControlNetXSModel],
|
577 |
+
controlnet: ControlNetXSAdapter,
|
578 |
+
scheduler: KarrasDiffusionSchedulers,
|
579 |
+
force_zeros_for_empty_prompt: bool = True,
|
580 |
+
add_watermarker: Optional[bool] = None,
|
581 |
+
feature_extractor: CLIPImageProcessor = None,
|
582 |
+
):
|
583 |
+
super().__init__()
|
584 |
+
# self.org_unet_config = copy.deepcopy(unet.config)
|
585 |
+
if isinstance(unet, UNet2DConditionModel):
|
586 |
+
unet = UNetControlNetXSModel.from_unet(unet, controlnet)
|
587 |
+
|
588 |
+
self.register_modules(
|
589 |
+
vae=vae,
|
590 |
+
text_encoder=text_encoder,
|
591 |
+
text_encoder_2=text_encoder_2,
|
592 |
+
tokenizer=tokenizer,
|
593 |
+
tokenizer_2=tokenizer_2,
|
594 |
+
unet=unet,
|
595 |
+
controlnet=controlnet,
|
596 |
+
scheduler=scheduler,
|
597 |
+
feature_extractor=feature_extractor,
|
598 |
+
)
|
599 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
600 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
601 |
+
self.control_image_processor = VaeImageProcessor(
|
602 |
+
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
|
603 |
+
)
|
604 |
+
add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
|
605 |
+
|
606 |
+
if add_watermarker:
|
607 |
+
self.watermark = StableDiffusionXLWatermarker()
|
608 |
+
else:
|
609 |
+
self.watermark = None
|
610 |
+
|
611 |
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
612 |
+
|
613 |
+
def cuda(self, org_unet_config=None, device='cuda', dtype=torch.float16, use_xformers=False):
|
614 |
+
self.org_unet_config = org_unet_config
|
615 |
+
self.to(device, dtype)
|
616 |
+
|
617 |
+
if hasattr(self, 'image_proj_model'):
|
618 |
+
self.image_proj_model.to(device).to(dtype)
|
619 |
+
|
620 |
+
if use_xformers:
|
621 |
+
if is_xformers_available():
|
622 |
+
import xformers
|
623 |
+
from packaging import version
|
624 |
+
|
625 |
+
xformers_version = version.parse(xformers.__version__)
|
626 |
+
if xformers_version == version.parse("0.0.16"):
|
627 |
+
logger.warn(
|
628 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
629 |
+
)
|
630 |
+
self.enable_xformers_memory_efficient_attention()
|
631 |
+
else:
|
632 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
633 |
+
|
634 |
+
def encode_prompt(
|
635 |
+
self,
|
636 |
+
prompt: str,
|
637 |
+
prompt_2: Optional[str] = None,
|
638 |
+
device: Optional[torch.device] = None,
|
639 |
+
num_images_per_prompt: int = 1,
|
640 |
+
do_classifier_free_guidance: bool = True,
|
641 |
+
negative_prompt: Optional[str] = None,
|
642 |
+
negative_prompt_2: Optional[str] = None,
|
643 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
644 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
645 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
646 |
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
647 |
+
lora_scale: Optional[float] = None,
|
648 |
+
clip_skip: Optional[int] = None,
|
649 |
+
):
|
650 |
+
r"""
|
651 |
+
Encodes the prompt into text encoder hidden states.
|
652 |
+
|
653 |
+
Args:
|
654 |
+
prompt (`str` or `List[str]`, *optional*):
|
655 |
+
prompt to be encoded
|
656 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
657 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
658 |
+
used in both text-encoders
|
659 |
+
device: (`torch.device`):
|
660 |
+
torch device
|
661 |
+
num_images_per_prompt (`int`):
|
662 |
+
number of images that should be generated per prompt
|
663 |
+
do_classifier_free_guidance (`bool`):
|
664 |
+
whether to use classifier free guidance or not
|
665 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
666 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
667 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
668 |
+
less than `1`).
|
669 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
670 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
671 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
672 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
673 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
674 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
675 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
676 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
677 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
678 |
+
argument.
|
679 |
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
680 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
681 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
682 |
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
683 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
684 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
685 |
+
input argument.
|
686 |
+
lora_scale (`float`, *optional*):
|
687 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
688 |
+
clip_skip (`int`, *optional*):
|
689 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
690 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
691 |
+
"""
|
692 |
+
device = device or self._execution_device
|
693 |
+
|
694 |
+
# set lora scale so that monkey patched LoRA
|
695 |
+
# function of text encoder can correctly access it
|
696 |
+
if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
|
697 |
+
self._lora_scale = lora_scale
|
698 |
+
|
699 |
+
# dynamically adjust the LoRA scale
|
700 |
+
if self.text_encoder is not None:
|
701 |
+
if not USE_PEFT_BACKEND:
|
702 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
703 |
+
else:
|
704 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
705 |
+
|
706 |
+
if self.text_encoder_2 is not None:
|
707 |
+
if not USE_PEFT_BACKEND:
|
708 |
+
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
709 |
+
else:
|
710 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
711 |
+
|
712 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
713 |
+
|
714 |
+
if prompt is not None:
|
715 |
+
batch_size = len(prompt)
|
716 |
+
else:
|
717 |
+
batch_size = prompt_embeds.shape[0]
|
718 |
+
|
719 |
+
# Define tokenizers and text encoders
|
720 |
+
tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
|
721 |
+
text_encoders = (
|
722 |
+
[self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
|
723 |
+
)
|
724 |
+
|
725 |
+
if prompt_embeds is None:
|
726 |
+
prompt_2 = prompt_2 or prompt
|
727 |
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
728 |
+
|
729 |
+
# textual inversion: process multi-vector tokens if necessary
|
730 |
+
prompt_embeds_list = []
|
731 |
+
prompts = [prompt, prompt_2]
|
732 |
+
for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
|
733 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
734 |
+
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
735 |
+
|
736 |
+
text_inputs = tokenizer(
|
737 |
+
prompt,
|
738 |
+
padding="max_length",
|
739 |
+
max_length=tokenizer.model_max_length,
|
740 |
+
truncation=True,
|
741 |
+
return_tensors="pt",
|
742 |
+
)
|
743 |
+
|
744 |
+
text_input_ids = text_inputs.input_ids
|
745 |
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
746 |
+
|
747 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
748 |
+
text_input_ids, untruncated_ids
|
749 |
+
):
|
750 |
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
|
751 |
+
logger.warning(
|
752 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
753 |
+
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
754 |
+
)
|
755 |
+
|
756 |
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
|
757 |
+
|
758 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
759 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
760 |
+
if clip_skip is None:
|
761 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
762 |
+
else:
|
763 |
+
# "2" because SDXL always indexes from the penultimate layer.
|
764 |
+
prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
|
765 |
+
|
766 |
+
prompt_embeds_list.append(prompt_embeds)
|
767 |
+
|
768 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
769 |
+
|
770 |
+
# get unconditional embeddings for classifier free guidance
|
771 |
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
772 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
773 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
774 |
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
775 |
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
776 |
+
negative_prompt = negative_prompt or ""
|
777 |
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
778 |
+
|
779 |
+
# normalize str to list
|
780 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
781 |
+
negative_prompt_2 = (
|
782 |
+
batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
|
783 |
+
)
|
784 |
+
|
785 |
+
uncond_tokens: List[str]
|
786 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
787 |
+
raise TypeError(
|
788 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
789 |
+
f" {type(prompt)}."
|
790 |
+
)
|
791 |
+
elif batch_size != len(negative_prompt):
|
792 |
+
raise ValueError(
|
793 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
794 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
795 |
+
" the batch size of `prompt`."
|
796 |
+
)
|
797 |
+
else:
|
798 |
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
799 |
+
|
800 |
+
negative_prompt_embeds_list = []
|
801 |
+
for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
|
802 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
803 |
+
negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
|
804 |
+
|
805 |
+
max_length = prompt_embeds.shape[1]
|
806 |
+
uncond_input = tokenizer(
|
807 |
+
negative_prompt,
|
808 |
+
padding="max_length",
|
809 |
+
max_length=max_length,
|
810 |
+
truncation=True,
|
811 |
+
return_tensors="pt",
|
812 |
+
)
|
813 |
+
|
814 |
+
negative_prompt_embeds = text_encoder(
|
815 |
+
uncond_input.input_ids.to(device),
|
816 |
+
output_hidden_states=True,
|
817 |
+
)
|
818 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
819 |
+
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
820 |
+
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
821 |
+
|
822 |
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
823 |
+
|
824 |
+
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
825 |
+
|
826 |
+
if self.text_encoder_2 is not None:
|
827 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
828 |
+
else:
|
829 |
+
prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
830 |
+
|
831 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
832 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
833 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
834 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
835 |
+
|
836 |
+
if do_classifier_free_guidance:
|
837 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
838 |
+
seq_len = negative_prompt_embeds.shape[1]
|
839 |
+
|
840 |
+
if self.text_encoder_2 is not None:
|
841 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
842 |
+
else:
|
843 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
844 |
+
|
845 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
846 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
847 |
+
|
848 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
849 |
+
bs_embed * num_images_per_prompt, -1
|
850 |
+
)
|
851 |
+
if do_classifier_free_guidance:
|
852 |
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
853 |
+
bs_embed * num_images_per_prompt, -1
|
854 |
+
)
|
855 |
+
|
856 |
+
if self.text_encoder is not None:
|
857 |
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
858 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
859 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
860 |
+
|
861 |
+
if self.text_encoder_2 is not None:
|
862 |
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
863 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
864 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
865 |
+
|
866 |
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
867 |
+
|
868 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
869 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
870 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
871 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
872 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
873 |
+
# and should be between [0, 1]
|
874 |
+
|
875 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
876 |
+
extra_step_kwargs = {}
|
877 |
+
if accepts_eta:
|
878 |
+
extra_step_kwargs["eta"] = eta
|
879 |
+
|
880 |
+
# check if the scheduler accepts generator
|
881 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
882 |
+
if accepts_generator:
|
883 |
+
extra_step_kwargs["generator"] = generator
|
884 |
+
return extra_step_kwargs
|
885 |
+
|
886 |
+
def check_inputs(
|
887 |
+
self,
|
888 |
+
prompt,
|
889 |
+
prompt_2,
|
890 |
+
image,
|
891 |
+
negative_prompt=None,
|
892 |
+
negative_prompt_2=None,
|
893 |
+
prompt_embeds=None,
|
894 |
+
negative_prompt_embeds=None,
|
895 |
+
pooled_prompt_embeds=None,
|
896 |
+
negative_pooled_prompt_embeds=None,
|
897 |
+
controlnet_conditioning_scale=1.0,
|
898 |
+
control_guidance_start=0.0,
|
899 |
+
control_guidance_end=1.0,
|
900 |
+
callback_on_step_end_tensor_inputs=None,
|
901 |
+
):
|
902 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
903 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
904 |
+
):
|
905 |
+
raise ValueError(
|
906 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
907 |
+
)
|
908 |
+
|
909 |
+
if prompt is not None and prompt_embeds is not None:
|
910 |
+
raise ValueError(
|
911 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
912 |
+
" only forward one of the two."
|
913 |
+
)
|
914 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
915 |
+
raise ValueError(
|
916 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
917 |
+
" only forward one of the two."
|
918 |
+
)
|
919 |
+
elif prompt is None and prompt_embeds is None:
|
920 |
+
raise ValueError(
|
921 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
922 |
+
)
|
923 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
924 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
925 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
926 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
927 |
+
|
928 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
929 |
+
raise ValueError(
|
930 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
931 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
932 |
+
)
|
933 |
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
934 |
+
raise ValueError(
|
935 |
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
936 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
937 |
+
)
|
938 |
+
|
939 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
940 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
941 |
+
raise ValueError(
|
942 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
943 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
944 |
+
f" {negative_prompt_embeds.shape}."
|
945 |
+
)
|
946 |
+
|
947 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
948 |
+
raise ValueError(
|
949 |
+
"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`."
|
950 |
+
)
|
951 |
+
|
952 |
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
953 |
+
raise ValueError(
|
954 |
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
955 |
+
)
|
956 |
+
|
957 |
+
# Check `image` and ``controlnet_conditioning_scale``
|
958 |
+
is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
|
959 |
+
self.unet, torch._dynamo.eval_frame.OptimizedModule
|
960 |
+
)
|
961 |
+
if (
|
962 |
+
isinstance(self.unet, UNetControlNetXSModel)
|
963 |
+
or is_compiled
|
964 |
+
and isinstance(self.unet._orig_mod, UNetControlNetXSModel)
|
965 |
+
):
|
966 |
+
self.check_image(image, prompt, prompt_embeds)
|
967 |
+
if not isinstance(controlnet_conditioning_scale, float):
|
968 |
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
969 |
+
else:
|
970 |
+
assert False
|
971 |
+
|
972 |
+
start, end = control_guidance_start, control_guidance_end
|
973 |
+
if start >= end:
|
974 |
+
raise ValueError(
|
975 |
+
f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
|
976 |
+
)
|
977 |
+
if start < 0.0:
|
978 |
+
raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
|
979 |
+
if end > 1.0:
|
980 |
+
raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
|
981 |
+
|
982 |
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
|
983 |
+
def check_image(self, image, prompt, prompt_embeds):
|
984 |
+
image_is_pil = isinstance(image, PIL.Image.Image)
|
985 |
+
image_is_tensor = isinstance(image, torch.Tensor)
|
986 |
+
image_is_np = isinstance(image, np.ndarray)
|
987 |
+
image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
|
988 |
+
image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
|
989 |
+
image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
|
990 |
+
|
991 |
+
if (
|
992 |
+
not image_is_pil
|
993 |
+
and not image_is_tensor
|
994 |
+
and not image_is_np
|
995 |
+
and not image_is_pil_list
|
996 |
+
and not image_is_tensor_list
|
997 |
+
and not image_is_np_list
|
998 |
+
):
|
999 |
+
raise TypeError(
|
1000 |
+
f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
|
1001 |
+
)
|
1002 |
+
|
1003 |
+
if image_is_pil:
|
1004 |
+
image_batch_size = 1
|
1005 |
+
else:
|
1006 |
+
image_batch_size = len(image)
|
1007 |
+
|
1008 |
+
if prompt is not None and isinstance(prompt, str):
|
1009 |
+
prompt_batch_size = 1
|
1010 |
+
elif prompt is not None and isinstance(prompt, list):
|
1011 |
+
prompt_batch_size = len(prompt)
|
1012 |
+
elif prompt_embeds is not None:
|
1013 |
+
prompt_batch_size = prompt_embeds.shape[0]
|
1014 |
+
|
1015 |
+
if image_batch_size != 1 and image_batch_size != prompt_batch_size:
|
1016 |
+
raise ValueError(
|
1017 |
+
f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
|
1018 |
+
)
|
1019 |
+
|
1020 |
+
def prepare_image(
|
1021 |
+
self,
|
1022 |
+
image,
|
1023 |
+
width,
|
1024 |
+
height,
|
1025 |
+
batch_size,
|
1026 |
+
num_images_per_prompt,
|
1027 |
+
device,
|
1028 |
+
dtype,
|
1029 |
+
do_classifier_free_guidance=False,
|
1030 |
+
):
|
1031 |
+
image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
1032 |
+
image_batch_size = image.shape[0]
|
1033 |
+
|
1034 |
+
if image_batch_size == 1:
|
1035 |
+
repeat_by = batch_size
|
1036 |
+
else:
|
1037 |
+
# image batch size is the same as prompt batch size
|
1038 |
+
repeat_by = num_images_per_prompt
|
1039 |
+
|
1040 |
+
image = image.repeat_interleave(repeat_by, dim=0)
|
1041 |
+
|
1042 |
+
image = image.to(device=device, dtype=dtype)
|
1043 |
+
|
1044 |
+
if do_classifier_free_guidance:
|
1045 |
+
image = torch.cat([image] * 2)
|
1046 |
+
|
1047 |
+
return image
|
1048 |
+
|
1049 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
1050 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
1051 |
+
shape = (
|
1052 |
+
batch_size,
|
1053 |
+
num_channels_latents,
|
1054 |
+
int(height) // self.vae_scale_factor,
|
1055 |
+
int(width) // self.vae_scale_factor,
|
1056 |
+
)
|
1057 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
1058 |
+
raise ValueError(
|
1059 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
1060 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
1061 |
+
)
|
1062 |
+
|
1063 |
+
if latents is None:
|
1064 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
1065 |
+
else:
|
1066 |
+
latents = latents.to(device)
|
1067 |
+
|
1068 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
1069 |
+
latents = latents * self.scheduler.init_noise_sigma
|
1070 |
+
return latents
|
1071 |
+
|
1072 |
+
def _get_add_time_ids(
|
1073 |
+
self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
|
1074 |
+
):
|
1075 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
1076 |
+
|
1077 |
+
passed_add_embed_dim = (
|
1078 |
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
|
1079 |
+
)
|
1080 |
+
expected_add_embed_dim = self.unet.base_add_embedding.linear_1.in_features
|
1081 |
+
|
1082 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
1083 |
+
raise ValueError(
|
1084 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
1085 |
+
)
|
1086 |
+
|
1087 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
1088 |
+
return add_time_ids
|
1089 |
+
|
1090 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
1091 |
+
def upcast_vae(self):
|
1092 |
+
dtype = self.vae.dtype
|
1093 |
+
self.vae.to(dtype=torch.float32)
|
1094 |
+
use_torch_2_0_or_xformers = isinstance(
|
1095 |
+
self.vae.decoder.mid_block.attentions[0].processor,
|
1096 |
+
(
|
1097 |
+
AttnProcessor2_0,
|
1098 |
+
XFormersAttnProcessor,
|
1099 |
+
LoRAXFormersAttnProcessor,
|
1100 |
+
LoRAAttnProcessor2_0,
|
1101 |
+
),
|
1102 |
+
)
|
1103 |
+
# if xformers or torch_2_0 is used attention block does not need
|
1104 |
+
# to be in float32 which can save lots of memory
|
1105 |
+
if use_torch_2_0_or_xformers:
|
1106 |
+
self.vae.post_quant_conv.to(dtype)
|
1107 |
+
self.vae.decoder.conv_in.to(dtype)
|
1108 |
+
self.vae.decoder.mid_block.to(dtype)
|
1109 |
+
|
1110 |
+
@property
|
1111 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.guidance_scale
|
1112 |
+
def guidance_scale(self):
|
1113 |
+
return self._guidance_scale
|
1114 |
+
|
1115 |
+
@property
|
1116 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.clip_skip
|
1117 |
+
def clip_skip(self):
|
1118 |
+
return self._clip_skip
|
1119 |
+
|
1120 |
+
@property
|
1121 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.do_classifier_free_guidance
|
1122 |
+
def do_classifier_free_guidance(self):
|
1123 |
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
1124 |
+
|
1125 |
+
@property
|
1126 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.cross_attention_kwargs
|
1127 |
+
def cross_attention_kwargs(self):
|
1128 |
+
return self._cross_attention_kwargs
|
1129 |
+
|
1130 |
+
@property
|
1131 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.num_timesteps
|
1132 |
+
def num_timesteps(self):
|
1133 |
+
return self._num_timesteps
|
1134 |
+
|
1135 |
+
def load_ip_adapter(self, image_proj_model, cross_attn_path=None, image_emb_dim=512, num_tokens=16, device='cuda', dtype=torch.float16):
|
1136 |
+
self.set_image_proj_model(image_proj_model, image_emb_dim, num_tokens, device=device, dtype=dtype)
|
1137 |
+
if cross_attn_path != None:
|
1138 |
+
self.set_cross_attn(cross_attn_path, num_tokens)
|
1139 |
+
|
1140 |
+
def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16, device='cuda', dtype=torch.float16):
|
1141 |
+
|
1142 |
+
image_proj_model = Resampler(
|
1143 |
+
dim=1280,
|
1144 |
+
depth=4,
|
1145 |
+
dim_head=64,
|
1146 |
+
heads=20,
|
1147 |
+
num_queries=num_tokens,
|
1148 |
+
embedding_dim=image_emb_dim,
|
1149 |
+
output_dim=self.unet.config.cross_attention_dim,
|
1150 |
+
ff_mult=4,
|
1151 |
+
)
|
1152 |
+
|
1153 |
+
image_proj_model.eval()
|
1154 |
+
|
1155 |
+
self.image_proj_model = image_proj_model.to(device, dtype=dtype)
|
1156 |
+
|
1157 |
+
print('**************************** Loading image projection Model ***************************')
|
1158 |
+
if isinstance(model_ckpt, collections.OrderedDict):
|
1159 |
+
# print('Loading from state dict...')
|
1160 |
+
state_dict = model_ckpt
|
1161 |
+
elif isinstance(model_ckpt, str):
|
1162 |
+
# print(f'Loading state dict from {model_ckpt} ...')
|
1163 |
+
# state_dict = torch.load(model_ckpt, map_location="cpu", weights_only=True)
|
1164 |
+
state_dict = torch.load(model_ckpt, map_location="cpu", weights_only=True)
|
1165 |
+
else:
|
1166 |
+
raise TypeError("model_ckpt must be either an OrderedDict or a string (file path).")
|
1167 |
+
|
1168 |
+
if isinstance(state_dict, tuple):
|
1169 |
+
print("\n\n\n state_dict is a tuple \n\n\n")
|
1170 |
+
state_dict = state_dict[0]
|
1171 |
+
|
1172 |
+
self.image_proj_model.load_state_dict(state_dict)
|
1173 |
+
|
1174 |
+
self.image_proj_model_in_features = image_emb_dim
|
1175 |
+
|
1176 |
+
del state_dict
|
1177 |
+
gc.collect()
|
1178 |
+
|
1179 |
+
def set_cross_attn(self, cross_attn_path, num_tokens):
|
1180 |
+
|
1181 |
+
print('**************************** Setting cross attention processors to UNet ***************************')
|
1182 |
+
|
1183 |
+
# self.unet # 此时unet就是cnxs
|
1184 |
+
datatype = self.unet.dtype
|
1185 |
+
|
1186 |
+
state_dict = torch.load(cross_attn_path, map_location="cpu", weights_only=True)
|
1187 |
+
attn_state_dict = {}
|
1188 |
+
for key, value in state_dict.items():
|
1189 |
+
if 'attn2.processor' in key:
|
1190 |
+
attn_state_dict[key] = value
|
1191 |
+
|
1192 |
+
attn_procs = {}
|
1193 |
+
for name in self.unet.attn_processors.keys():
|
1194 |
+
if 'ctrl' in name:
|
1195 |
+
continue
|
1196 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else self.unet.config.cross_attention_dim
|
1197 |
+
if name.startswith("mid_block"):
|
1198 |
+
hidden_size = self.unet.config.block_out_channels[-1]
|
1199 |
+
elif name.startswith("up_blocks"):
|
1200 |
+
block_id = int(name[len("up_blocks.")])
|
1201 |
+
hidden_size = list(reversed(self.unet.config.block_out_channels))[block_id]
|
1202 |
+
elif name.startswith("down_blocks"):
|
1203 |
+
block_id = int(name[len("down_blocks.")])
|
1204 |
+
hidden_size = self.unet.config.block_out_channels[block_id]
|
1205 |
+
|
1206 |
+
if cross_attention_dim is None:
|
1207 |
+
attn_procs[name] = AttnProcessor()
|
1208 |
+
else:
|
1209 |
+
weights = {
|
1210 |
+
"to_k_ip.weight": attn_state_dict[name + ".to_k_ip.weight"],
|
1211 |
+
"to_v_ip.weight": attn_state_dict[name + ".to_v_ip.weight"],
|
1212 |
+
}
|
1213 |
+
attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_tokens=num_tokens)
|
1214 |
+
attn_procs[name].load_state_dict(weights)
|
1215 |
+
|
1216 |
+
# print('length of attn_procs:', len(attn_procs)) # 140
|
1217 |
+
self.unet.set_attn_processor_unet(attn_procs)
|
1218 |
+
self.unet.to(dtype=datatype)
|
1219 |
+
|
1220 |
+
del attn_state_dict
|
1221 |
+
del attn_procs
|
1222 |
+
gc.collect()
|
1223 |
+
|
1224 |
+
def set_ip_adapter_scale(self, scale):
|
1225 |
+
unet = self.unet
|
1226 |
+
for attn_processor in unet.attn_processors_unet.values():
|
1227 |
+
# print(attn_processor)
|
1228 |
+
'''
|
1229 |
+
Attention(
|
1230 |
+
(to_q): Linear(in_features=640, out_features=640, bias=False)
|
1231 |
+
(to_k): Linear(in_features=2048, out_features=640, bias=False)
|
1232 |
+
(to_v): Linear(in_features=2048, out_features=640, bias=False)
|
1233 |
+
(to_out): ModuleList(
|
1234 |
+
(0): Linear(in_features=640, out_features=640, bias=True)
|
1235 |
+
(1): Dropout(p=0.0, inplace=False)
|
1236 |
+
)
|
1237 |
+
(processor): IPAttnProcessor2_0(
|
1238 |
+
(to_k_ip): Linear(in_features=2048, out_features=640, bias=False)
|
1239 |
+
(to_v_ip): Linear(in_features=2048, out_features=640, bias=False)
|
1240 |
+
)
|
1241 |
+
)
|
1242 |
+
'''
|
1243 |
+
if isinstance(attn_processor, IPAttnProcessor):
|
1244 |
+
# print('set_ip_adapter_scale: ',scale)
|
1245 |
+
attn_processor.scale = scale
|
1246 |
+
|
1247 |
+
def _encode_prompt_image_emb(self, prompt_image_emb, device, num_images_per_prompt, dtype, do_classifier_free_guidance):
|
1248 |
+
|
1249 |
+
if isinstance(prompt_image_emb, torch.Tensor):
|
1250 |
+
prompt_image_emb = prompt_image_emb.clone().detach()
|
1251 |
+
else:
|
1252 |
+
prompt_image_emb = torch.tensor(prompt_image_emb)
|
1253 |
+
|
1254 |
+
prompt_image_emb = prompt_image_emb.reshape([1, -1, self.image_proj_model_in_features])
|
1255 |
+
|
1256 |
+
if do_classifier_free_guidance:
|
1257 |
+
prompt_image_emb = torch.cat([torch.zeros_like(prompt_image_emb), prompt_image_emb], dim=0)
|
1258 |
+
else:
|
1259 |
+
prompt_image_emb = torch.cat([prompt_image_emb], dim=0)
|
1260 |
+
|
1261 |
+
prompt_image_emb = prompt_image_emb.to(device=self.image_proj_model.latents.device,
|
1262 |
+
dtype=self.image_proj_model.latents.dtype)
|
1263 |
+
prompt_image_emb = self.image_proj_model(prompt_image_emb)
|
1264 |
+
|
1265 |
+
bs_embed, seq_len, _ = prompt_image_emb.shape
|
1266 |
+
prompt_image_emb = prompt_image_emb.repeat(1, num_images_per_prompt, 1)
|
1267 |
+
prompt_image_emb = prompt_image_emb.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
1268 |
+
|
1269 |
+
return prompt_image_emb.to(device=device, dtype=dtype)
|
1270 |
+
|
1271 |
+
def load_lora_weights(
|
1272 |
+
self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
|
1273 |
+
):
|
1274 |
+
if not USE_PEFT_BACKEND:
|
1275 |
+
raise ValueError("PEFT backend is required for this method.")
|
1276 |
+
|
1277 |
+
# if a dict is passed, copy it instead of modifying it inplace
|
1278 |
+
if isinstance(pretrained_model_name_or_path_or_dict, dict):
|
1279 |
+
pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
|
1280 |
+
|
1281 |
+
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
|
1282 |
+
if isinstance(pretrained_model_name_or_path_or_dict, str):
|
1283 |
+
filename = os.path.basename(pretrained_model_name_or_path_or_dict)
|
1284 |
+
extension = os.path.splitext(filename)[1]
|
1285 |
+
extension = extension[1:]
|
1286 |
+
if extension == "safetensors":
|
1287 |
+
lora_weight = load_file(pretrained_model_name_or_path_or_dict)
|
1288 |
+
else:
|
1289 |
+
lora_weight = torch.load(pretrained_model_name_or_path_or_dict, map_location="cpu")
|
1290 |
+
|
1291 |
+
if all(
|
1292 |
+
(
|
1293 |
+
k.startswith("lora_te_")
|
1294 |
+
or k.startswith("lora_unet_")
|
1295 |
+
or k.startswith("lora_te1_")
|
1296 |
+
or k.startswith("lora_te2_")
|
1297 |
+
)
|
1298 |
+
for k in lora_weight.keys()
|
1299 |
+
):
|
1300 |
+
state_dict = _maybe_map_sgm_blocks_to_diffusers(lora_weight, self.org_unet_config)
|
1301 |
+
state_dict, network_alphas = _convert_non_diffusers_lora_to_diffusers(state_dict)
|
1302 |
+
state_dict = get_module_kohya_state_dict_xs(state_dict, torch.float16)
|
1303 |
+
state_dict, _ = self.lora_state_dict(state_dict, **kwargs)
|
1304 |
+
else:
|
1305 |
+
state_dict = get_module_kohya_state_dict_xs(lora_weight, torch.float16)
|
1306 |
+
state_dict, network_alphas = self.lora_state_dict(state_dict, **kwargs)
|
1307 |
+
else:
|
1308 |
+
state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
|
1309 |
+
|
1310 |
+
|
1311 |
+
is_correct_format = all("lora" in key for key in state_dict.keys())
|
1312 |
+
if not is_correct_format:
|
1313 |
+
raise ValueError("Invalid LoRA checkpoint.")
|
1314 |
+
|
1315 |
+
low_cpu_mem_usage = False
|
1316 |
+
is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
|
1317 |
+
|
1318 |
+
if is_torch_higher_equal_2_1:
|
1319 |
+
from diffusers.models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT
|
1320 |
+
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
1321 |
+
|
1322 |
+
assert is_torch_higher_equal_2_1 == low_cpu_mem_usage
|
1323 |
+
|
1324 |
+
self.load_lora_into_unet(
|
1325 |
+
state_dict,
|
1326 |
+
network_alphas=network_alphas,
|
1327 |
+
unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
|
1328 |
+
adapter_name=adapter_name,
|
1329 |
+
_pipeline=self,
|
1330 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
1331 |
+
)
|
1332 |
+
self.load_lora_into_text_encoder(
|
1333 |
+
state_dict,
|
1334 |
+
network_alphas=network_alphas,
|
1335 |
+
text_encoder=getattr(self, self.text_encoder_name) if not hasattr(self, "text_encoder") else self.text_encoder,
|
1336 |
+
lora_scale=self.lora_scale,
|
1337 |
+
adapter_name=adapter_name,
|
1338 |
+
_pipeline=self,
|
1339 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
1340 |
+
)
|
1341 |
+
|
1342 |
+
def set_adapters(
|
1343 |
+
self,
|
1344 |
+
adapter_names: Union[List[str], str],
|
1345 |
+
adapter_weights: Optional[Union[List[float], float]] = None,
|
1346 |
+
):
|
1347 |
+
"""
|
1348 |
+
Set the currently active adapters for use in the UNet.
|
1349 |
+
|
1350 |
+
Args:
|
1351 |
+
adapter_names (`List[str]` or `str`):
|
1352 |
+
The names of the adapters to use.
|
1353 |
+
adapter_weights (`Union[List[float], float]`, *optional*):
|
1354 |
+
The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
|
1355 |
+
adapters.
|
1356 |
+
|
1357 |
+
Example:
|
1358 |
+
|
1359 |
+
```py
|
1360 |
+
from diffusers import AutoPipelineForText2Image
|
1361 |
+
import torch
|
1362 |
+
|
1363 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
1364 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
1365 |
+
).to("cuda")
|
1366 |
+
pipeline.load_lora_weights(
|
1367 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
|
1368 |
+
)
|
1369 |
+
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
|
1370 |
+
pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
|
1371 |
+
```
|
1372 |
+
"""
|
1373 |
+
|
1374 |
+
if not USE_PEFT_BACKEND:
|
1375 |
+
raise ValueError("PEFT backend is required for `set_adapters()`.")
|
1376 |
+
|
1377 |
+
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
1378 |
+
|
1379 |
+
if adapter_weights is None:
|
1380 |
+
adapter_weights = [1.0] * len(adapter_names)
|
1381 |
+
elif isinstance(adapter_weights, float):
|
1382 |
+
adapter_weights = [adapter_weights] * len(adapter_names)
|
1383 |
+
|
1384 |
+
if len(adapter_names) != len(adapter_weights):
|
1385 |
+
raise ValueError(
|
1386 |
+
f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(adapter_weights)}."
|
1387 |
+
)
|
1388 |
+
|
1389 |
+
set_weights_and_activate_adapters(self.unet, adapter_names, adapter_weights)
|
1390 |
+
|
1391 |
+
'''
|
1392 |
+
def disable_lora(self):
|
1393 |
+
"""
|
1394 |
+
Disable the UNet's active LoRA layers.
|
1395 |
+
|
1396 |
+
Example:
|
1397 |
+
|
1398 |
+
```py
|
1399 |
+
from diffusers import AutoPipelineForText2Image
|
1400 |
+
import torch
|
1401 |
+
|
1402 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
1403 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
1404 |
+
).to("cuda")
|
1405 |
+
pipeline.load_lora_weights(
|
1406 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
|
1407 |
+
)
|
1408 |
+
pipeline.disable_lora()
|
1409 |
+
```
|
1410 |
+
"""
|
1411 |
+
if not USE_PEFT_BACKEND:
|
1412 |
+
raise ValueError("PEFT backend is required for this method.")
|
1413 |
+
set_adapter_layers(self.unet, enabled=False)
|
1414 |
+
|
1415 |
+
def enable_lora(self):
|
1416 |
+
"""
|
1417 |
+
Enable the UNet's active LoRA layers.
|
1418 |
+
|
1419 |
+
Example:
|
1420 |
+
|
1421 |
+
```py
|
1422 |
+
from diffusers import AutoPipelineForText2Image
|
1423 |
+
import torch
|
1424 |
+
|
1425 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
1426 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
1427 |
+
).to("cuda")
|
1428 |
+
pipeline.load_lora_weights(
|
1429 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
|
1430 |
+
)
|
1431 |
+
pipeline.enable_lora()
|
1432 |
+
```
|
1433 |
+
"""
|
1434 |
+
if not USE_PEFT_BACKEND:
|
1435 |
+
raise ValueError("PEFT backend is required for this method.")
|
1436 |
+
set_adapter_layers(self.unet, enabled=True)
|
1437 |
+
|
1438 |
+
def delete_adapters(self, adapter_names: Union[List[str], str]):
|
1439 |
+
"""
|
1440 |
+
Delete an adapter's LoRA layers from the UNet.
|
1441 |
+
|
1442 |
+
Args:
|
1443 |
+
adapter_names (`Union[List[str], str]`):
|
1444 |
+
The names (single string or list of strings) of the adapter to delete.
|
1445 |
+
|
1446 |
+
Example:
|
1447 |
+
|
1448 |
+
```py
|
1449 |
+
from diffusers import AutoPipelineForText2Image
|
1450 |
+
import torch
|
1451 |
+
|
1452 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
1453 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
1454 |
+
).to("cuda")
|
1455 |
+
pipeline.load_lora_weights(
|
1456 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
|
1457 |
+
)
|
1458 |
+
pipeline.delete_adapters("cinematic")
|
1459 |
+
```
|
1460 |
+
"""
|
1461 |
+
if not USE_PEFT_BACKEND:
|
1462 |
+
raise ValueError("PEFT backend is required for this method.")
|
1463 |
+
|
1464 |
+
if isinstance(adapter_names, str):
|
1465 |
+
adapter_names = [adapter_names]
|
1466 |
+
|
1467 |
+
for adapter_name in adapter_names:
|
1468 |
+
delete_adapter_layers(self.unet, adapter_name)
|
1469 |
+
|
1470 |
+
# Pop also the corresponding adapter from the config
|
1471 |
+
if hasattr(self.unet, "peft_config"):
|
1472 |
+
self.unet.peft_config.pop(adapter_name, None)
|
1473 |
+
'''
|
1474 |
+
|
1475 |
+
@torch.no_grad()
|
1476 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
1477 |
+
def __call__(
|
1478 |
+
self,
|
1479 |
+
prompt: Union[str, List[str]] = None,
|
1480 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
1481 |
+
image: PipelineImageInput = None,
|
1482 |
+
face_emb: Optional[torch.Tensor] = None,
|
1483 |
+
height: Optional[int] = None,
|
1484 |
+
width: Optional[int] = None,
|
1485 |
+
num_inference_steps: int = 50,
|
1486 |
+
guidance_scale: float = 5.0,
|
1487 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
1488 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
1489 |
+
num_images_per_prompt: Optional[int] = 1,
|
1490 |
+
eta: float = 0.0,
|
1491 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
1492 |
+
latents: Optional[torch.Tensor] = None,
|
1493 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
1494 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
1495 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
1496 |
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
1497 |
+
output_type: Optional[str] = "pil",
|
1498 |
+
return_dict: bool = True,
|
1499 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1500 |
+
controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
|
1501 |
+
control_guidance_start: float = 0.0,
|
1502 |
+
control_guidance_end: float = 1.0,
|
1503 |
+
original_size: Tuple[int, int] = None,
|
1504 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
1505 |
+
target_size: Tuple[int, int] = None,
|
1506 |
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
1507 |
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
1508 |
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
1509 |
+
clip_skip: Optional[int] = None,
|
1510 |
+
callback_on_step_end: Optional[
|
1511 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
1512 |
+
] = None,
|
1513 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
1514 |
+
|
1515 |
+
# IP adapter
|
1516 |
+
ip_adapter_scale=None,
|
1517 |
+
):
|
1518 |
+
r"""
|
1519 |
+
The call function to the pipeline for generation.
|
1520 |
+
|
1521 |
+
Args:
|
1522 |
+
prompt (`str` or `List[str]`, *optional*):
|
1523 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
1524 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
1525 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
1526 |
+
used in both text-encoders.
|
1527 |
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
1528 |
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
1529 |
+
The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
|
1530 |
+
specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
|
1531 |
+
as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
|
1532 |
+
width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
|
1533 |
+
images must be passed as a list such that each element of the list can be correctly batched for input
|
1534 |
+
to a single ControlNet.
|
1535 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
1536 |
+
The height in pixels of the generated image. Anything below 512 pixels won't work well for
|
1537 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
1538 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
1539 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
1540 |
+
The width in pixels of the generated image. Anything below 512 pixels won't work well for
|
1541 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
1542 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
1543 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
1544 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
1545 |
+
expense of slower inference.
|
1546 |
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
1547 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
1548 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
1549 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
1550 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
1551 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
1552 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
1553 |
+
The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
|
1554 |
+
and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
|
1555 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
1556 |
+
The number of images to generate per prompt.
|
1557 |
+
eta (`float`, *optional*, defaults to 0.0):
|
1558 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
1559 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
1560 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
1561 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
1562 |
+
generation deterministic.
|
1563 |
+
latents (`torch.Tensor`, *optional*):
|
1564 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
1565 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
1566 |
+
tensor is generated by sampling using the supplied random `generator`.
|
1567 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
1568 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
1569 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
1570 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
1571 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
1572 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
1573 |
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
1574 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
1575 |
+
not provided, pooled text embeddings are generated from `prompt` input argument.
|
1576 |
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
1577 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
|
1578 |
+
weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
|
1579 |
+
argument.
|
1580 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
1581 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
1582 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
1583 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
1584 |
+
plain tuple.
|
1585 |
+
cross_attention_kwargs (`dict`, *optional*):
|
1586 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
1587 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
1588 |
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
1589 |
+
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
|
1590 |
+
to the residual in the original `unet`.
|
1591 |
+
control_guidance_start (`float`, *optional*, defaults to 0.0):
|
1592 |
+
The percentage of total steps at which the ControlNet starts applying.
|
1593 |
+
control_guidance_end (`float`, *optional*, defaults to 1.0):
|
1594 |
+
The percentage of total steps at which the ControlNet stops applying.
|
1595 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1596 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
1597 |
+
`original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
|
1598 |
+
explained in section 2.2 of
|
1599 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1600 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
1601 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
1602 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
1603 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1604 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1605 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1606 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
1607 |
+
not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
|
1608 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1609 |
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1610 |
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
1611 |
+
micro-conditioning as explained in section 2.2 of
|
1612 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1613 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1614 |
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
1615 |
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
1616 |
+
micro-conditioning as explained in section 2.2 of
|
1617 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1618 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1619 |
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1620 |
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
1621 |
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1622 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1623 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1624 |
+
clip_skip (`int`, *optional*):
|
1625 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
1626 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
1627 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
1628 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
1629 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
1630 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
1631 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
1632 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
1633 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
1634 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
1635 |
+
`._callback_tensor_inputs` attribute of your pipeine class.
|
1636 |
+
|
1637 |
+
Examples:
|
1638 |
+
|
1639 |
+
Returns:
|
1640 |
+
[`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
|
1641 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] is
|
1642 |
+
returned, otherwise a `tuple` is returned containing the output images.
|
1643 |
+
"""
|
1644 |
+
|
1645 |
+
lpw = LongPromptWeight()
|
1646 |
+
|
1647 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
1648 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
1649 |
+
|
1650 |
+
unet = self.unet._orig_mod if is_compiled_module(self.unet) else self.unet
|
1651 |
+
|
1652 |
+
# 0. set ip_adapter_scale
|
1653 |
+
if ip_adapter_scale is not None:
|
1654 |
+
self.set_ip_adapter_scale(ip_adapter_scale)
|
1655 |
+
|
1656 |
+
# 1. Check inputs. Raise error if not correct
|
1657 |
+
self.check_inputs(
|
1658 |
+
prompt,
|
1659 |
+
prompt_2,
|
1660 |
+
image,
|
1661 |
+
negative_prompt,
|
1662 |
+
negative_prompt_2,
|
1663 |
+
prompt_embeds,
|
1664 |
+
negative_prompt_embeds,
|
1665 |
+
pooled_prompt_embeds,
|
1666 |
+
negative_pooled_prompt_embeds,
|
1667 |
+
controlnet_conditioning_scale,
|
1668 |
+
control_guidance_start,
|
1669 |
+
control_guidance_end,
|
1670 |
+
callback_on_step_end_tensor_inputs,
|
1671 |
+
)
|
1672 |
+
|
1673 |
+
self._guidance_scale = guidance_scale
|
1674 |
+
self._clip_skip = clip_skip
|
1675 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
1676 |
+
self._interrupt = False
|
1677 |
+
|
1678 |
+
# 2. Define call parameters
|
1679 |
+
if prompt is not None and isinstance(prompt, str):
|
1680 |
+
batch_size = 1
|
1681 |
+
elif prompt is not None and isinstance(prompt, list):
|
1682 |
+
batch_size = len(prompt)
|
1683 |
+
else:
|
1684 |
+
batch_size = prompt_embeds.shape[0]
|
1685 |
+
|
1686 |
+
device = self._execution_device
|
1687 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
1688 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
1689 |
+
# corresponds to doing no classifier free guidance.
|
1690 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
1691 |
+
|
1692 |
+
# 3. Encode input prompt
|
1693 |
+
|
1694 |
+
# text_encoder_lora_scale = (
|
1695 |
+
# self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
1696 |
+
# )
|
1697 |
+
# (
|
1698 |
+
# prompt_embeds,
|
1699 |
+
# negative_prompt_embeds,
|
1700 |
+
# pooled_prompt_embeds,
|
1701 |
+
# negative_pooled_prompt_embeds,
|
1702 |
+
# ) = self.encode_prompt(
|
1703 |
+
# prompt,
|
1704 |
+
# prompt_2,
|
1705 |
+
# device,
|
1706 |
+
# num_images_per_prompt,
|
1707 |
+
# do_classifier_free_guidance,
|
1708 |
+
# negative_prompt,
|
1709 |
+
# negative_prompt_2,
|
1710 |
+
# prompt_embeds=prompt_embeds,
|
1711 |
+
# negative_prompt_embeds=negative_prompt_embeds,
|
1712 |
+
# pooled_prompt_embeds=pooled_prompt_embeds,
|
1713 |
+
# negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
1714 |
+
# lora_scale=text_encoder_lora_scale,
|
1715 |
+
# clip_skip=clip_skip,
|
1716 |
+
# )
|
1717 |
+
|
1718 |
+
(
|
1719 |
+
prompt_embeds,
|
1720 |
+
negative_prompt_embeds,
|
1721 |
+
pooled_prompt_embeds,
|
1722 |
+
negative_pooled_prompt_embeds,
|
1723 |
+
) = lpw.get_weighted_text_embeddings_sdxl(
|
1724 |
+
pipe=self,
|
1725 |
+
prompt=prompt,
|
1726 |
+
neg_prompt=negative_prompt,
|
1727 |
+
prompt_embeds=prompt_embeds,
|
1728 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
1729 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
1730 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
1731 |
+
)
|
1732 |
+
prompt_image_emb = self._encode_prompt_image_emb(
|
1733 |
+
face_emb,
|
1734 |
+
device,
|
1735 |
+
num_images_per_prompt,
|
1736 |
+
unet.dtype,
|
1737 |
+
do_classifier_free_guidance
|
1738 |
+
)
|
1739 |
+
|
1740 |
+
# 4. Prepare image
|
1741 |
+
if isinstance(unet, UNetControlNetXSModel):
|
1742 |
+
image = self.prepare_image(
|
1743 |
+
image=image,
|
1744 |
+
width=width,
|
1745 |
+
height=height,
|
1746 |
+
batch_size=batch_size * num_images_per_prompt,
|
1747 |
+
num_images_per_prompt=num_images_per_prompt,
|
1748 |
+
device=device,
|
1749 |
+
dtype=unet.dtype,
|
1750 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
1751 |
+
)
|
1752 |
+
height, width = image.shape[-2:]
|
1753 |
+
else:
|
1754 |
+
assert False
|
1755 |
+
|
1756 |
+
# 5. Prepare timesteps
|
1757 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
1758 |
+
timesteps = self.scheduler.timesteps
|
1759 |
+
|
1760 |
+
# 6. Prepare latent variables
|
1761 |
+
num_channels_latents = self.unet.in_channels
|
1762 |
+
latents = self.prepare_latents(
|
1763 |
+
batch_size * num_images_per_prompt,
|
1764 |
+
num_channels_latents,
|
1765 |
+
height,
|
1766 |
+
width,
|
1767 |
+
prompt_embeds.dtype,
|
1768 |
+
device,
|
1769 |
+
generator,
|
1770 |
+
latents,
|
1771 |
+
)
|
1772 |
+
|
1773 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
1774 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1775 |
+
|
1776 |
+
# 7.1 Prepare added time ids & embeddings
|
1777 |
+
if isinstance(image, list):
|
1778 |
+
original_size = original_size or image[0].shape[-2:]
|
1779 |
+
else:
|
1780 |
+
original_size = original_size or image.shape[-2:]
|
1781 |
+
target_size = target_size or (height, width)
|
1782 |
+
|
1783 |
+
add_text_embeds = pooled_prompt_embeds
|
1784 |
+
if self.text_encoder_2 is None:
|
1785 |
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
1786 |
+
else:
|
1787 |
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
1788 |
+
|
1789 |
+
add_time_ids = self._get_add_time_ids(
|
1790 |
+
original_size,
|
1791 |
+
crops_coords_top_left,
|
1792 |
+
target_size,
|
1793 |
+
dtype=prompt_embeds.dtype,
|
1794 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1795 |
+
)
|
1796 |
+
|
1797 |
+
if negative_original_size is not None and negative_target_size is not None:
|
1798 |
+
negative_add_time_ids = self._get_add_time_ids(
|
1799 |
+
negative_original_size,
|
1800 |
+
negative_crops_coords_top_left,
|
1801 |
+
negative_target_size,
|
1802 |
+
dtype=prompt_embeds.dtype,
|
1803 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1804 |
+
)
|
1805 |
+
else:
|
1806 |
+
negative_add_time_ids = add_time_ids
|
1807 |
+
|
1808 |
+
if do_classifier_free_guidance:
|
1809 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1810 |
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
1811 |
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
1812 |
+
|
1813 |
+
prompt_embeds = prompt_embeds.to(device, dtype=unet.dtype)
|
1814 |
+
add_text_embeds = add_text_embeds.to(device, dtype=unet.dtype)
|
1815 |
+
add_time_ids = add_time_ids.to(device, dtype=unet.dtype).repeat(batch_size * num_images_per_prompt, 1)
|
1816 |
+
|
1817 |
+
prompt_image_emb = prompt_image_emb.to(device, dtype=unet.dtype)
|
1818 |
+
encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
|
1819 |
+
encoder_hidden_states = encoder_hidden_states.to(device, dtype=unet.dtype)
|
1820 |
+
|
1821 |
+
|
1822 |
+
# 8. Denoising loop
|
1823 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
1824 |
+
self._num_timesteps = len(timesteps)
|
1825 |
+
is_controlnet_compiled = is_compiled_module(self.unet)
|
1826 |
+
is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
|
1827 |
+
|
1828 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1829 |
+
for i, t in enumerate(timesteps):
|
1830 |
+
# Relevant thread:
|
1831 |
+
# https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
|
1832 |
+
if is_controlnet_compiled and is_torch_higher_equal_2_1:
|
1833 |
+
torch._inductor.cudagraph_mark_step_begin()
|
1834 |
+
# expand the latents if we are doing classifier free guidance
|
1835 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
1836 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1837 |
+
|
1838 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
1839 |
+
|
1840 |
+
# predict the noise residual
|
1841 |
+
apply_control = (
|
1842 |
+
i / len(timesteps) >= control_guidance_start and (i + 1) / len(timesteps) <= control_guidance_end
|
1843 |
+
)
|
1844 |
+
|
1845 |
+
noise_pred = self.unet(
|
1846 |
+
sample=latent_model_input,
|
1847 |
+
timestep=t,
|
1848 |
+
unet_encoder_hidden_states=encoder_hidden_states,
|
1849 |
+
cnxs_encoder_hidden_states=prompt_image_emb,
|
1850 |
+
controlnet_cond=image,
|
1851 |
+
conditioning_scale=controlnet_conditioning_scale,
|
1852 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
1853 |
+
added_cond_kwargs=added_cond_kwargs,
|
1854 |
+
return_dict=True,
|
1855 |
+
apply_control=apply_control,
|
1856 |
+
).sample
|
1857 |
+
|
1858 |
+
# perform guidance
|
1859 |
+
if do_classifier_free_guidance:
|
1860 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1861 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1862 |
+
|
1863 |
+
# compute the previous noisy sample x_t -> x_t-1
|
1864 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1865 |
+
|
1866 |
+
if callback_on_step_end is not None:
|
1867 |
+
callback_kwargs = {}
|
1868 |
+
for k in callback_on_step_end_tensor_inputs:
|
1869 |
+
callback_kwargs[k] = locals()[k]
|
1870 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1871 |
+
|
1872 |
+
latents = callback_outputs.pop("latents", latents)
|
1873 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1874 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1875 |
+
|
1876 |
+
# call the callback, if provided
|
1877 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1878 |
+
progress_bar.update()
|
1879 |
+
|
1880 |
+
# manually for max memory savings
|
1881 |
+
if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
|
1882 |
+
self.upcast_vae()
|
1883 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
1884 |
+
|
1885 |
+
if not output_type == "latent":
|
1886 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
1887 |
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1888 |
+
|
1889 |
+
if needs_upcasting:
|
1890 |
+
self.upcast_vae()
|
1891 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
1892 |
+
|
1893 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
1894 |
+
|
1895 |
+
# cast back to fp16 if needed
|
1896 |
+
if needs_upcasting:
|
1897 |
+
self.vae.to(dtype=torch.float16)
|
1898 |
+
else:
|
1899 |
+
image = latents
|
1900 |
+
|
1901 |
+
if not output_type == "latent":
|
1902 |
+
# apply watermark if available
|
1903 |
+
if self.watermark is not None:
|
1904 |
+
image = self.watermark.apply_watermark(image)
|
1905 |
+
|
1906 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1907 |
+
|
1908 |
+
# Offload all models
|
1909 |
+
self.maybe_free_model_hooks()
|
1910 |
+
|
1911 |
+
if not return_dict:
|
1912 |
+
return (image,)
|
1913 |
+
|
1914 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
utils/attention_processor.py
ADDED
@@ -0,0 +1,888 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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4 |
+
import torch.nn.functional as F
|
5 |
+
from diffusers.models.attention_processor import AttnProcessor2_0
|
6 |
+
from diffusers.models.attention_processor import XFormersAttnProcessor
|
7 |
+
try:
|
8 |
+
import xformers
|
9 |
+
import xformers.ops
|
10 |
+
xformers_available = True
|
11 |
+
except Exception as e:
|
12 |
+
xformers_available = False
|
13 |
+
|
14 |
+
class RegionControler(object):
|
15 |
+
def __init__(self) -> None:
|
16 |
+
self.prompt_image_conditioning = []
|
17 |
+
region_control = RegionControler()
|
18 |
+
|
19 |
+
class AttnProcessor(nn.Module):
|
20 |
+
r"""
|
21 |
+
Default processor for performing attention-related computations.
|
22 |
+
"""
|
23 |
+
def __init__(
|
24 |
+
self,
|
25 |
+
hidden_size=None,
|
26 |
+
cross_attention_dim=None,
|
27 |
+
):
|
28 |
+
super().__init__()
|
29 |
+
|
30 |
+
def forward(
|
31 |
+
self,
|
32 |
+
attn,
|
33 |
+
hidden_states,
|
34 |
+
encoder_hidden_states=None,
|
35 |
+
attention_mask=None,
|
36 |
+
temb=None,
|
37 |
+
):
|
38 |
+
residual = hidden_states
|
39 |
+
|
40 |
+
if attn.spatial_norm is not None:
|
41 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
42 |
+
|
43 |
+
input_ndim = hidden_states.ndim
|
44 |
+
|
45 |
+
if input_ndim == 4:
|
46 |
+
batch_size, channel, height, width = hidden_states.shape
|
47 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
48 |
+
|
49 |
+
batch_size, sequence_length, _ = (
|
50 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
51 |
+
)
|
52 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
53 |
+
|
54 |
+
if attn.group_norm is not None:
|
55 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
56 |
+
|
57 |
+
query = attn.to_q(hidden_states)
|
58 |
+
|
59 |
+
if encoder_hidden_states is None:
|
60 |
+
encoder_hidden_states = hidden_states
|
61 |
+
elif attn.norm_cross:
|
62 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
63 |
+
|
64 |
+
key = attn.to_k(encoder_hidden_states)
|
65 |
+
value = attn.to_v(encoder_hidden_states)
|
66 |
+
|
67 |
+
query = attn.head_to_batch_dim(query)
|
68 |
+
key = attn.head_to_batch_dim(key)
|
69 |
+
value = attn.head_to_batch_dim(value)
|
70 |
+
|
71 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
72 |
+
hidden_states = torch.bmm(attention_probs, value)
|
73 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
74 |
+
|
75 |
+
# linear proj
|
76 |
+
hidden_states = attn.to_out[0](hidden_states)
|
77 |
+
# dropout
|
78 |
+
hidden_states = attn.to_out[1](hidden_states)
|
79 |
+
|
80 |
+
if input_ndim == 4:
|
81 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
82 |
+
|
83 |
+
if attn.residual_connection:
|
84 |
+
hidden_states = hidden_states + residual
|
85 |
+
|
86 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
87 |
+
|
88 |
+
return hidden_states
|
89 |
+
|
90 |
+
|
91 |
+
class IPAttnProcessor(nn.Module):
|
92 |
+
r"""
|
93 |
+
Attention processor for IP-Adapater.
|
94 |
+
Args:
|
95 |
+
hidden_size (`int`):
|
96 |
+
The hidden size of the attention layer.
|
97 |
+
cross_attention_dim (`int`):
|
98 |
+
The number of channels in the `encoder_hidden_states`.
|
99 |
+
scale (`float`, defaults to 1.0):
|
100 |
+
the weight scale of image prompt.
|
101 |
+
num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
|
102 |
+
The context length of the image features.
|
103 |
+
"""
|
104 |
+
|
105 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
|
106 |
+
super().__init__()
|
107 |
+
|
108 |
+
self.hidden_size = hidden_size
|
109 |
+
self.cross_attention_dim = cross_attention_dim
|
110 |
+
self.scale = scale
|
111 |
+
self.num_tokens = num_tokens
|
112 |
+
|
113 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
114 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
115 |
+
|
116 |
+
def forward(
|
117 |
+
self,
|
118 |
+
attn,
|
119 |
+
hidden_states,
|
120 |
+
encoder_hidden_states=None,
|
121 |
+
attention_mask=None,
|
122 |
+
temb=None,
|
123 |
+
):
|
124 |
+
residual = hidden_states
|
125 |
+
|
126 |
+
if attn.spatial_norm is not None:
|
127 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
128 |
+
|
129 |
+
input_ndim = hidden_states.ndim
|
130 |
+
|
131 |
+
if input_ndim == 4:
|
132 |
+
batch_size, channel, height, width = hidden_states.shape
|
133 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
134 |
+
|
135 |
+
batch_size, sequence_length, _ = (
|
136 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
137 |
+
)
|
138 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
139 |
+
|
140 |
+
if attn.group_norm is not None:
|
141 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
142 |
+
|
143 |
+
query = attn.to_q(hidden_states)
|
144 |
+
|
145 |
+
if encoder_hidden_states is None:
|
146 |
+
encoder_hidden_states = hidden_states
|
147 |
+
else:
|
148 |
+
# get encoder_hidden_states, ip_hidden_states
|
149 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
150 |
+
encoder_hidden_states, ip_hidden_states = encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :]
|
151 |
+
if attn.norm_cross:
|
152 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
153 |
+
|
154 |
+
key = attn.to_k(encoder_hidden_states)
|
155 |
+
value = attn.to_v(encoder_hidden_states)
|
156 |
+
|
157 |
+
query = attn.head_to_batch_dim(query)
|
158 |
+
key = attn.head_to_batch_dim(key)
|
159 |
+
value = attn.head_to_batch_dim(value)
|
160 |
+
|
161 |
+
if xformers_available:
|
162 |
+
hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
|
163 |
+
else:
|
164 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
165 |
+
hidden_states = torch.bmm(attention_probs, value)
|
166 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
167 |
+
|
168 |
+
# for ip-adapter
|
169 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
170 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
171 |
+
|
172 |
+
ip_key = attn.head_to_batch_dim(ip_key)
|
173 |
+
ip_value = attn.head_to_batch_dim(ip_value)
|
174 |
+
|
175 |
+
if xformers_available:
|
176 |
+
ip_hidden_states = self._memory_efficient_attention_xformers(query, ip_key, ip_value, None)
|
177 |
+
else:
|
178 |
+
ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
|
179 |
+
ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
|
180 |
+
ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
|
181 |
+
|
182 |
+
# region control
|
183 |
+
if len(region_control.prompt_image_conditioning) == 1:
|
184 |
+
region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None)
|
185 |
+
if region_mask is not None:
|
186 |
+
h, w = region_mask.shape[:2]
|
187 |
+
ratio = (h * w / query.shape[1]) ** 0.5
|
188 |
+
mask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1])
|
189 |
+
else:
|
190 |
+
mask = torch.ones_like(ip_hidden_states)
|
191 |
+
ip_hidden_states = ip_hidden_states * mask
|
192 |
+
|
193 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
194 |
+
|
195 |
+
# linear proj
|
196 |
+
hidden_states = attn.to_out[0](hidden_states)
|
197 |
+
# dropout
|
198 |
+
hidden_states = attn.to_out[1](hidden_states)
|
199 |
+
|
200 |
+
if input_ndim == 4:
|
201 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
202 |
+
|
203 |
+
if attn.residual_connection:
|
204 |
+
hidden_states = hidden_states + residual
|
205 |
+
|
206 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
207 |
+
|
208 |
+
return hidden_states
|
209 |
+
|
210 |
+
|
211 |
+
def _memory_efficient_attention_xformers(self, query, key, value, attention_mask):
|
212 |
+
# TODO attention_mask
|
213 |
+
query = query.contiguous()
|
214 |
+
key = key.contiguous()
|
215 |
+
value = value.contiguous()
|
216 |
+
hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_bias=attention_mask)
|
217 |
+
# hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
|
218 |
+
return hidden_states
|
219 |
+
|
220 |
+
|
221 |
+
class AttnProcessor2_0(torch.nn.Module):
|
222 |
+
r"""
|
223 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
224 |
+
"""
|
225 |
+
def __init__(
|
226 |
+
self,
|
227 |
+
hidden_size=None,
|
228 |
+
cross_attention_dim=None,
|
229 |
+
):
|
230 |
+
super().__init__()
|
231 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
232 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
233 |
+
|
234 |
+
def forward(
|
235 |
+
self,
|
236 |
+
attn,
|
237 |
+
hidden_states,
|
238 |
+
encoder_hidden_states=None,
|
239 |
+
attention_mask=None,
|
240 |
+
temb=None,
|
241 |
+
):
|
242 |
+
residual = hidden_states
|
243 |
+
|
244 |
+
if attn.spatial_norm is not None:
|
245 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
246 |
+
|
247 |
+
input_ndim = hidden_states.ndim
|
248 |
+
|
249 |
+
if input_ndim == 4:
|
250 |
+
batch_size, channel, height, width = hidden_states.shape
|
251 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
252 |
+
|
253 |
+
batch_size, sequence_length, _ = (
|
254 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
255 |
+
)
|
256 |
+
|
257 |
+
if attention_mask is not None:
|
258 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
259 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
260 |
+
# (batch, heads, source_length, target_length)
|
261 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
262 |
+
|
263 |
+
if attn.group_norm is not None:
|
264 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
265 |
+
|
266 |
+
query = attn.to_q(hidden_states)
|
267 |
+
|
268 |
+
if encoder_hidden_states is None:
|
269 |
+
encoder_hidden_states = hidden_states
|
270 |
+
elif attn.norm_cross:
|
271 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
272 |
+
|
273 |
+
key = attn.to_k(encoder_hidden_states)
|
274 |
+
value = attn.to_v(encoder_hidden_states)
|
275 |
+
|
276 |
+
inner_dim = key.shape[-1]
|
277 |
+
head_dim = inner_dim // attn.heads
|
278 |
+
|
279 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
280 |
+
|
281 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
282 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
283 |
+
|
284 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
285 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
286 |
+
hidden_states = F.scaled_dot_product_attention(
|
287 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
288 |
+
)
|
289 |
+
|
290 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
291 |
+
hidden_states = hidden_states.to(query.dtype)
|
292 |
+
|
293 |
+
# linear proj
|
294 |
+
hidden_states = attn.to_out[0](hidden_states)
|
295 |
+
# dropout
|
296 |
+
hidden_states = attn.to_out[1](hidden_states)
|
297 |
+
|
298 |
+
if input_ndim == 4:
|
299 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
300 |
+
|
301 |
+
if attn.residual_connection:
|
302 |
+
hidden_states = hidden_states + residual
|
303 |
+
|
304 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
305 |
+
|
306 |
+
return hidden_states
|
307 |
+
|
308 |
+
|
309 |
+
class IPAttnProcessor2_0(torch.nn.Module):
|
310 |
+
r"""
|
311 |
+
Attention processor for IP-Adapater for PyTorch 2.0.
|
312 |
+
Args:
|
313 |
+
hidden_size (`int`):
|
314 |
+
The hidden size of the attention layer.
|
315 |
+
cross_attention_dim (`int`):
|
316 |
+
The number of channels in the `encoder_hidden_states`.
|
317 |
+
scale (`float`, defaults to 1.0):
|
318 |
+
the weight scale of image prompt.
|
319 |
+
num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
|
320 |
+
The context length of the image features.
|
321 |
+
"""
|
322 |
+
|
323 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
|
324 |
+
super().__init__()
|
325 |
+
|
326 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
327 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
328 |
+
|
329 |
+
self.hidden_size = hidden_size
|
330 |
+
self.cross_attention_dim = cross_attention_dim
|
331 |
+
self.scale = scale
|
332 |
+
self.num_tokens = num_tokens
|
333 |
+
|
334 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
335 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
336 |
+
|
337 |
+
def __call__(
|
338 |
+
self,
|
339 |
+
attn,
|
340 |
+
hidden_states,
|
341 |
+
encoder_hidden_states=None,
|
342 |
+
attention_mask=None,
|
343 |
+
temb=None,
|
344 |
+
):
|
345 |
+
# 保存输入的 hidden_states,用于最后的残差连接。
|
346 |
+
residual = hidden_states
|
347 |
+
# 检查是否有 空间归一化 (spatial normalization)
|
348 |
+
if attn.spatial_norm is not None:
|
349 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
350 |
+
|
351 |
+
# hidden_states 可能是一个 4D 张量(比如图像数据),也可能是一个 3D 张量(比如文本数据)
|
352 |
+
input_ndim = hidden_states.ndim
|
353 |
+
if input_ndim == 4:
|
354 |
+
batch_size, channel, height, width = hidden_states.shape
|
355 |
+
# 调整其形状为 (batch_size, channel, height * width)
|
356 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
357 |
+
|
358 |
+
# 选择 encoder_hidden_states 如果有的话,否则使用 hidden_states 作为输入。sequence_length 表示序列长度,通常是时间步或图像的像素数量。
|
359 |
+
batch_size, sequence_length, _ = (hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape)
|
360 |
+
|
361 |
+
# 处理并调整注意力掩码 (attention mask),使其符合 scaled_dot_product_attention 函数的要求。
|
362 |
+
if attention_mask is not None:
|
363 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
364 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
365 |
+
# (batch, heads, source_length, target_length)
|
366 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
367 |
+
|
368 |
+
# 对 hidden_states 进行组归一化
|
369 |
+
if attn.group_norm is not None:
|
370 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
371 |
+
|
372 |
+
# 通过线性变换将 hidden_states 映射到query向量
|
373 |
+
query = attn.to_q(hidden_states)
|
374 |
+
|
375 |
+
if encoder_hidden_states is None:
|
376 |
+
encoder_hidden_states = hidden_states
|
377 |
+
else:
|
378 |
+
# 分割 encoder_hidden_states 和 ip_hidden_states
|
379 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
380 |
+
encoder_hidden_states, ip_hidden_states = (
|
381 |
+
encoder_hidden_states[:, :end_pos, :],
|
382 |
+
encoder_hidden_states[:, end_pos:, :],
|
383 |
+
)
|
384 |
+
if attn.norm_cross:
|
385 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
386 |
+
|
387 |
+
# 将 encoder_hidden_states 映射为多头自注意力计算中的键和值
|
388 |
+
key = attn.to_k(encoder_hidden_states)
|
389 |
+
value = attn.to_v(encoder_hidden_states)
|
390 |
+
|
391 |
+
# 获取每个注意力头的维度
|
392 |
+
inner_dim = key.shape[-1]
|
393 |
+
head_dim = inner_dim // attn.heads
|
394 |
+
|
395 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
396 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
397 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
398 |
+
|
399 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
400 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
401 |
+
hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False)
|
402 |
+
# hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_bias=attention_mask)
|
403 |
+
|
404 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
405 |
+
hidden_states = hidden_states.to(query.dtype)
|
406 |
+
|
407 |
+
# for ip-adapter
|
408 |
+
# 投影 ip_hidden_states 得到其键和值
|
409 |
+
|
410 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
411 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
412 |
+
|
413 |
+
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
414 |
+
ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
415 |
+
|
416 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
417 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
418 |
+
# 注意力计算 得到图像提示的隐藏状态
|
419 |
+
ip_hidden_states = F.scaled_dot_product_attention(query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False)
|
420 |
+
# ip_hidden_states = xformers.ops.memory_efficient_attention(query, ip_key, ip_value, attn_bias=None)
|
421 |
+
|
422 |
+
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
423 |
+
ip_hidden_states = ip_hidden_states.to(query.dtype)
|
424 |
+
|
425 |
+
# 通过给图像提示隐藏状态加权缩放后与原始隐藏状态相加,实现跨域信息融合
|
426 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
427 |
+
|
428 |
+
# linear proj
|
429 |
+
hidden_states = attn.to_out[0](hidden_states)
|
430 |
+
# dropout
|
431 |
+
hidden_states = attn.to_out[1](hidden_states)
|
432 |
+
|
433 |
+
if input_ndim == 4:
|
434 |
+
# 如果输入是 4D 张量(图像数据),则将 hidden_states 转换回原始形状。
|
435 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
436 |
+
|
437 |
+
if attn.residual_connection:
|
438 |
+
# 如果启用了残差连接,则将 residual 添加回 hidden_states
|
439 |
+
hidden_states = hidden_states + residual
|
440 |
+
|
441 |
+
# 对输出进行缩放
|
442 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
443 |
+
|
444 |
+
return hidden_states
|
445 |
+
|
446 |
+
|
447 |
+
## for controlnet
|
448 |
+
|
449 |
+
|
450 |
+
|
451 |
+
|
452 |
+
class CNAttnProcessor:
|
453 |
+
r"""
|
454 |
+
Default processor for performing attention-related computations.
|
455 |
+
"""
|
456 |
+
|
457 |
+
def __init__(self, num_tokens=4):
|
458 |
+
self.num_tokens = num_tokens
|
459 |
+
|
460 |
+
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, *args, **kwargs,):
|
461 |
+
residual = hidden_states
|
462 |
+
|
463 |
+
if attn.spatial_norm is not None:
|
464 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
465 |
+
|
466 |
+
input_ndim = hidden_states.ndim
|
467 |
+
|
468 |
+
if input_ndim == 4:
|
469 |
+
batch_size, channel, height, width = hidden_states.shape
|
470 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
471 |
+
|
472 |
+
batch_size, sequence_length, _ = (
|
473 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
474 |
+
)
|
475 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
476 |
+
|
477 |
+
if attn.group_norm is not None:
|
478 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
479 |
+
|
480 |
+
query = attn.to_q(hidden_states)
|
481 |
+
|
482 |
+
if encoder_hidden_states is None:
|
483 |
+
encoder_hidden_states = hidden_states
|
484 |
+
else:
|
485 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
486 |
+
encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text
|
487 |
+
if attn.norm_cross:
|
488 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
489 |
+
|
490 |
+
key = attn.to_k(encoder_hidden_states)
|
491 |
+
value = attn.to_v(encoder_hidden_states)
|
492 |
+
|
493 |
+
query = attn.head_to_batch_dim(query)
|
494 |
+
key = attn.head_to_batch_dim(key)
|
495 |
+
value = attn.head_to_batch_dim(value)
|
496 |
+
|
497 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
498 |
+
hidden_states = torch.bmm(attention_probs, value)
|
499 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
500 |
+
|
501 |
+
# linear proj
|
502 |
+
hidden_states = attn.to_out[0](hidden_states)
|
503 |
+
# dropout
|
504 |
+
hidden_states = attn.to_out[1](hidden_states)
|
505 |
+
|
506 |
+
if input_ndim == 4:
|
507 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
508 |
+
|
509 |
+
if attn.residual_connection:
|
510 |
+
hidden_states = hidden_states + residual
|
511 |
+
|
512 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
513 |
+
|
514 |
+
return hidden_states
|
515 |
+
|
516 |
+
|
517 |
+
class CNAttnProcessor2_0:
|
518 |
+
r"""
|
519 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
520 |
+
"""
|
521 |
+
|
522 |
+
def __init__(self, num_tokens=4):
|
523 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
524 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
525 |
+
self.num_tokens = num_tokens
|
526 |
+
|
527 |
+
def __call__(
|
528 |
+
self,
|
529 |
+
attn,
|
530 |
+
hidden_states,
|
531 |
+
encoder_hidden_states=None,
|
532 |
+
attention_mask=None,
|
533 |
+
temb=None,
|
534 |
+
*args,
|
535 |
+
**kwargs,
|
536 |
+
):
|
537 |
+
residual = hidden_states
|
538 |
+
|
539 |
+
if attn.spatial_norm is not None:
|
540 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
541 |
+
|
542 |
+
input_ndim = hidden_states.ndim
|
543 |
+
|
544 |
+
if input_ndim == 4:
|
545 |
+
batch_size, channel, height, width = hidden_states.shape
|
546 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
547 |
+
|
548 |
+
batch_size, sequence_length, _ = (
|
549 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
550 |
+
)
|
551 |
+
|
552 |
+
if attention_mask is not None:
|
553 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
554 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
555 |
+
# (batch, heads, source_length, target_length)
|
556 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
557 |
+
|
558 |
+
if attn.group_norm is not None:
|
559 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
560 |
+
|
561 |
+
query = attn.to_q(hidden_states)
|
562 |
+
|
563 |
+
if encoder_hidden_states is None:
|
564 |
+
encoder_hidden_states = hidden_states
|
565 |
+
else:
|
566 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
567 |
+
encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text
|
568 |
+
if attn.norm_cross:
|
569 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
570 |
+
|
571 |
+
key = attn.to_k(encoder_hidden_states)
|
572 |
+
value = attn.to_v(encoder_hidden_states)
|
573 |
+
|
574 |
+
inner_dim = key.shape[-1]
|
575 |
+
head_dim = inner_dim // attn.heads
|
576 |
+
|
577 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
578 |
+
|
579 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
580 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
581 |
+
|
582 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
583 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
584 |
+
hidden_states = F.scaled_dot_product_attention(
|
585 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
586 |
+
)
|
587 |
+
|
588 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
589 |
+
hidden_states = hidden_states.to(query.dtype)
|
590 |
+
|
591 |
+
# linear proj
|
592 |
+
hidden_states = attn.to_out[0](hidden_states)
|
593 |
+
# dropout
|
594 |
+
hidden_states = attn.to_out[1](hidden_states)
|
595 |
+
|
596 |
+
if input_ndim == 4:
|
597 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
598 |
+
|
599 |
+
if attn.residual_connection:
|
600 |
+
hidden_states = hidden_states + residual
|
601 |
+
|
602 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
603 |
+
|
604 |
+
return hidden_states
|
605 |
+
|
606 |
+
|
607 |
+
|
608 |
+
class IPAttnProcessor2_02(torch.nn.Module):
|
609 |
+
r"""
|
610 |
+
Attention processor for IP-Adapater for PyTorch 2.0.
|
611 |
+
Args:
|
612 |
+
hidden_size (`int`):
|
613 |
+
The hidden size of the attention layer.
|
614 |
+
cross_attention_dim (`int`):
|
615 |
+
The number of channels in the `encoder_hidden_states`.
|
616 |
+
scale (`float`, defaults to 1.0):
|
617 |
+
the weight scale of image prompt.
|
618 |
+
num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
|
619 |
+
The context length of the image features.
|
620 |
+
"""
|
621 |
+
|
622 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
|
623 |
+
super().__init__()
|
624 |
+
|
625 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
626 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
627 |
+
|
628 |
+
self.hidden_size = hidden_size
|
629 |
+
self.cross_attention_dim = cross_attention_dim
|
630 |
+
self.scale = scale
|
631 |
+
self.num_tokens = num_tokens
|
632 |
+
|
633 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
634 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
635 |
+
|
636 |
+
def forward(
|
637 |
+
self,
|
638 |
+
attn,
|
639 |
+
hidden_states,
|
640 |
+
encoder_hidden_states=None,
|
641 |
+
attention_mask=None,
|
642 |
+
temb=None,
|
643 |
+
):
|
644 |
+
residual = hidden_states
|
645 |
+
|
646 |
+
if attn.spatial_norm is not None:
|
647 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
648 |
+
|
649 |
+
input_ndim = hidden_states.ndim
|
650 |
+
|
651 |
+
if input_ndim == 4:
|
652 |
+
batch_size, channel, height, width = hidden_states.shape
|
653 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
654 |
+
|
655 |
+
batch_size, sequence_length, _ = (
|
656 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
657 |
+
)
|
658 |
+
|
659 |
+
if attention_mask is not None:
|
660 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
661 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
662 |
+
# (batch, heads, source_length, target_length)
|
663 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
664 |
+
|
665 |
+
if attn.group_norm is not None:
|
666 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
667 |
+
|
668 |
+
query = attn.to_q(hidden_states)
|
669 |
+
|
670 |
+
if encoder_hidden_states is None:
|
671 |
+
encoder_hidden_states = hidden_states
|
672 |
+
else:
|
673 |
+
# get encoder_hidden_states, ip_hidden_states
|
674 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
675 |
+
encoder_hidden_states, ip_hidden_states = (
|
676 |
+
encoder_hidden_states[:, :end_pos, :],
|
677 |
+
encoder_hidden_states[:, end_pos:, :],
|
678 |
+
)
|
679 |
+
if attn.norm_cross:
|
680 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
681 |
+
|
682 |
+
key = attn.to_k(encoder_hidden_states)
|
683 |
+
value = attn.to_v(encoder_hidden_states)
|
684 |
+
|
685 |
+
inner_dim = key.shape[-1]
|
686 |
+
head_dim = inner_dim // attn.heads
|
687 |
+
|
688 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
689 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
690 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
691 |
+
|
692 |
+
hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
|
693 |
+
# hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False)
|
694 |
+
|
695 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
696 |
+
hidden_states = hidden_states.to(query.dtype)
|
697 |
+
|
698 |
+
# hidden_states = memory_efficient_attention(query, key, value, attn_mask=attention_mask, dropout_p=0.0)
|
699 |
+
|
700 |
+
# for ip-adapter
|
701 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
702 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
703 |
+
|
704 |
+
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
705 |
+
ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
706 |
+
|
707 |
+
# ip_hidden_states = F.scaled_dot_product_attention(query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False)
|
708 |
+
# ip_hidden_states = xformers.ops.memory_efficient_attention(query, ip_key, ip_value, None)
|
709 |
+
ip_hidden_states = self._memory_efficient_attention_xformers(query, ip_key, ip_value, None)
|
710 |
+
|
711 |
+
with torch.no_grad():
|
712 |
+
self.attn_map = query @ ip_key.transpose(-2, -1).softmax(dim=-1)
|
713 |
+
#print(self.attn_map.shape)
|
714 |
+
|
715 |
+
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
716 |
+
ip_hidden_states = ip_hidden_states.to(query.dtype)
|
717 |
+
|
718 |
+
# region control
|
719 |
+
if len(region_control.prompt_image_conditioning) == 1:
|
720 |
+
region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None)
|
721 |
+
if region_mask is not None:
|
722 |
+
query = query.reshape([-1, query.shape[-2], query.shape[-1]])
|
723 |
+
h, w = region_mask.shape[:2]
|
724 |
+
ratio = (h * w / query.shape[1]) ** 0.5
|
725 |
+
mask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1])
|
726 |
+
else:
|
727 |
+
mask = torch.ones_like(ip_hidden_states)
|
728 |
+
ip_hidden_states = ip_hidden_states * mask
|
729 |
+
# ip_hidden_states = memory_efficient_attention(query, ip_key, ip_value, attn_mask=None, dropout_p=0.0)
|
730 |
+
|
731 |
+
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * (ip_key.shape[-1] // attn.heads))
|
732 |
+
|
733 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
734 |
+
|
735 |
+
# linear proj
|
736 |
+
hidden_states = attn.to_out[0](hidden_states)
|
737 |
+
# dropout
|
738 |
+
hidden_states = attn.to_out[1](hidden_states)
|
739 |
+
|
740 |
+
if input_ndim == 4:
|
741 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
742 |
+
|
743 |
+
if attn.residual_connection:
|
744 |
+
hidden_states = hidden_states + residual
|
745 |
+
|
746 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
747 |
+
|
748 |
+
return hidden_states
|
749 |
+
|
750 |
+
def _memory_efficient_attention_xformers(self, query, key, value, attention_mask):
|
751 |
+
# TODO attention_mask
|
752 |
+
query = query.contiguous()
|
753 |
+
key = key.contiguous()
|
754 |
+
value = value.contiguous()
|
755 |
+
hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_bias=attention_mask)
|
756 |
+
# hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
|
757 |
+
return hidden_states
|
758 |
+
|
759 |
+
|
760 |
+
class IPAttnProcessor2_00(torch.nn.Module):
|
761 |
+
r"""
|
762 |
+
Attention processor for IP-Adapater for PyTorch 2.0.
|
763 |
+
Args:
|
764 |
+
hidden_size (`int`):
|
765 |
+
The hidden size of the attention layer.
|
766 |
+
cross_attention_dim (`int`):
|
767 |
+
The number of channels in the `encoder_hidden_states`.
|
768 |
+
scale (`float`, defaults to 1.0):
|
769 |
+
the weight scale of image prompt.
|
770 |
+
num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
|
771 |
+
The context length of the image features.
|
772 |
+
"""
|
773 |
+
|
774 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
|
775 |
+
super().__init__()
|
776 |
+
|
777 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
778 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
779 |
+
|
780 |
+
self.hidden_size = hidden_size
|
781 |
+
self.cross_attention_dim = cross_attention_dim
|
782 |
+
self.scale = scale
|
783 |
+
self.num_tokens = num_tokens
|
784 |
+
|
785 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
786 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
787 |
+
|
788 |
+
def __call__(
|
789 |
+
self,
|
790 |
+
attn,
|
791 |
+
hidden_states,
|
792 |
+
encoder_hidden_states=None,
|
793 |
+
attention_mask=None,
|
794 |
+
temb=None,
|
795 |
+
):
|
796 |
+
residual = hidden_states
|
797 |
+
|
798 |
+
if attn.spatial_norm is not None:
|
799 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
800 |
+
|
801 |
+
input_ndim = hidden_states.ndim
|
802 |
+
|
803 |
+
if input_ndim == 4:
|
804 |
+
batch_size, channel, height, width = hidden_states.shape
|
805 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
806 |
+
|
807 |
+
batch_size, sequence_length, _ = (
|
808 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
809 |
+
)
|
810 |
+
|
811 |
+
if attention_mask is not None:
|
812 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
813 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
814 |
+
# (batch, heads, source_length, target_length)
|
815 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
816 |
+
|
817 |
+
if attn.group_norm is not None:
|
818 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
819 |
+
|
820 |
+
query = attn.to_q(hidden_states)
|
821 |
+
|
822 |
+
if encoder_hidden_states is None:
|
823 |
+
encoder_hidden_states = hidden_states
|
824 |
+
else:
|
825 |
+
# get encoder_hidden_states, ip_hidden_states
|
826 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
827 |
+
encoder_hidden_states, ip_hidden_states = (
|
828 |
+
encoder_hidden_states[:, :end_pos, :],
|
829 |
+
encoder_hidden_states[:, end_pos:, :],
|
830 |
+
)
|
831 |
+
if attn.norm_cross:
|
832 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
833 |
+
|
834 |
+
key = attn.to_k(encoder_hidden_states)
|
835 |
+
value = attn.to_v(encoder_hidden_states)
|
836 |
+
|
837 |
+
inner_dim = key.shape[-1]
|
838 |
+
head_dim = inner_dim // attn.heads
|
839 |
+
|
840 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
841 |
+
|
842 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
843 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
844 |
+
|
845 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
846 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
847 |
+
hidden_states = F.scaled_dot_product_attention(
|
848 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
849 |
+
)
|
850 |
+
|
851 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
852 |
+
hidden_states = hidden_states.to(query.dtype)
|
853 |
+
|
854 |
+
# for ip-adapter
|
855 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
856 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
857 |
+
|
858 |
+
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
859 |
+
ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
860 |
+
|
861 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
862 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
863 |
+
ip_hidden_states = F.scaled_dot_product_attention(
|
864 |
+
query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
|
865 |
+
)
|
866 |
+
|
867 |
+
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
868 |
+
ip_hidden_states = ip_hidden_states.to(query.dtype)
|
869 |
+
|
870 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
871 |
+
|
872 |
+
# linear proj
|
873 |
+
hidden_states = attn.to_out[0](hidden_states)
|
874 |
+
# dropout
|
875 |
+
hidden_states = attn.to_out[1](hidden_states)
|
876 |
+
|
877 |
+
if input_ndim == 4:
|
878 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
879 |
+
|
880 |
+
if attn.residual_connection:
|
881 |
+
hidden_states = hidden_states + residual
|
882 |
+
|
883 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
884 |
+
|
885 |
+
return hidden_states
|
886 |
+
|
887 |
+
|
888 |
+
## for controlnet
|
utils/callbacks.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict, List
|
2 |
+
|
3 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
4 |
+
from diffusers.utils import CONFIG_NAME
|
5 |
+
|
6 |
+
|
7 |
+
class PipelineCallback(ConfigMixin):
|
8 |
+
"""
|
9 |
+
Base class for all the official callbacks used in a pipeline. This class provides a structure for implementing
|
10 |
+
custom callbacks and ensures that all callbacks have a consistent interface.
|
11 |
+
|
12 |
+
Please implement the following:
|
13 |
+
`tensor_inputs`: This should return a list of tensor inputs specific to your callback. You will only be able to
|
14 |
+
include
|
15 |
+
variables listed in the `._callback_tensor_inputs` attribute of your pipeline class.
|
16 |
+
`callback_fn`: This method defines the core functionality of your callback.
|
17 |
+
"""
|
18 |
+
|
19 |
+
config_name = CONFIG_NAME
|
20 |
+
|
21 |
+
@register_to_config
|
22 |
+
def __init__(self, cutoff_step_ratio=1.0, cutoff_step_index=None):
|
23 |
+
super().__init__()
|
24 |
+
|
25 |
+
if (cutoff_step_ratio is None and cutoff_step_index is None) or (
|
26 |
+
cutoff_step_ratio is not None and cutoff_step_index is not None
|
27 |
+
):
|
28 |
+
raise ValueError("Either cutoff_step_ratio or cutoff_step_index should be provided, not both or none.")
|
29 |
+
|
30 |
+
if cutoff_step_ratio is not None and (
|
31 |
+
not isinstance(cutoff_step_ratio, float) or not (0.0 <= cutoff_step_ratio <= 1.0)
|
32 |
+
):
|
33 |
+
raise ValueError("cutoff_step_ratio must be a float between 0.0 and 1.0.")
|
34 |
+
|
35 |
+
@property
|
36 |
+
def tensor_inputs(self) -> List[str]:
|
37 |
+
raise NotImplementedError(f"You need to set the attribute `tensor_inputs` for {self.__class__}")
|
38 |
+
|
39 |
+
def callback_fn(self, pipeline, step_index, timesteps, callback_kwargs) -> Dict[str, Any]:
|
40 |
+
raise NotImplementedError(f"You need to implement the method `callback_fn` for {self.__class__}")
|
41 |
+
|
42 |
+
def __call__(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]:
|
43 |
+
return self.callback_fn(pipeline, step_index, timestep, callback_kwargs)
|
44 |
+
|
45 |
+
|
46 |
+
class MultiPipelineCallbacks:
|
47 |
+
"""
|
48 |
+
This class is designed to handle multiple pipeline callbacks. It accepts a list of PipelineCallback objects and
|
49 |
+
provides a unified interface for calling all of them.
|
50 |
+
"""
|
51 |
+
|
52 |
+
def __init__(self, callbacks: List[PipelineCallback]):
|
53 |
+
self.callbacks = callbacks
|
54 |
+
|
55 |
+
@property
|
56 |
+
def tensor_inputs(self) -> List[str]:
|
57 |
+
return [input for callback in self.callbacks for input in callback.tensor_inputs]
|
58 |
+
|
59 |
+
def __call__(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]:
|
60 |
+
"""
|
61 |
+
Calls all the callbacks in order with the given arguments and returns the final callback_kwargs.
|
62 |
+
"""
|
63 |
+
for callback in self.callbacks:
|
64 |
+
callback_kwargs = callback(pipeline, step_index, timestep, callback_kwargs)
|
65 |
+
|
66 |
+
return callback_kwargs
|
67 |
+
|
68 |
+
|
69 |
+
class SDCFGCutoffCallback(PipelineCallback):
|
70 |
+
"""
|
71 |
+
Callback function for Stable Diffusion Pipelines. After certain number of steps (set by `cutoff_step_ratio` or
|
72 |
+
`cutoff_step_index`), this callback will disable the CFG.
|
73 |
+
|
74 |
+
Note: This callback mutates the pipeline by changing the `_guidance_scale` attribute to 0.0 after the cutoff step.
|
75 |
+
"""
|
76 |
+
|
77 |
+
tensor_inputs = ["prompt_embeds"]
|
78 |
+
|
79 |
+
def callback_fn(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]:
|
80 |
+
cutoff_step_ratio = self.config.cutoff_step_ratio
|
81 |
+
cutoff_step_index = self.config.cutoff_step_index
|
82 |
+
|
83 |
+
# Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio
|
84 |
+
cutoff_step = (
|
85 |
+
cutoff_step_index if cutoff_step_index is not None else int(pipeline.num_timesteps * cutoff_step_ratio)
|
86 |
+
)
|
87 |
+
|
88 |
+
if step_index == cutoff_step:
|
89 |
+
prompt_embeds = callback_kwargs[self.tensor_inputs[0]]
|
90 |
+
prompt_embeds = prompt_embeds[-1:] # "-1" denotes the embeddings for conditional text tokens.
|
91 |
+
|
92 |
+
pipeline._guidance_scale = 0.0
|
93 |
+
|
94 |
+
callback_kwargs[self.tensor_inputs[0]] = prompt_embeds
|
95 |
+
return callback_kwargs
|
96 |
+
|
97 |
+
|
98 |
+
class SDXLCFGCutoffCallback(PipelineCallback):
|
99 |
+
"""
|
100 |
+
Callback function for Stable Diffusion XL Pipelines. After certain number of steps (set by `cutoff_step_ratio` or
|
101 |
+
`cutoff_step_index`), this callback will disable the CFG.
|
102 |
+
|
103 |
+
Note: This callback mutates the pipeline by changing the `_guidance_scale` attribute to 0.0 after the cutoff step.
|
104 |
+
"""
|
105 |
+
|
106 |
+
tensor_inputs = ["prompt_embeds", "add_text_embeds", "add_time_ids"]
|
107 |
+
|
108 |
+
def callback_fn(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]:
|
109 |
+
cutoff_step_ratio = self.config.cutoff_step_ratio
|
110 |
+
cutoff_step_index = self.config.cutoff_step_index
|
111 |
+
|
112 |
+
# Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio
|
113 |
+
cutoff_step = (
|
114 |
+
cutoff_step_index if cutoff_step_index is not None else int(pipeline.num_timesteps * cutoff_step_ratio)
|
115 |
+
)
|
116 |
+
|
117 |
+
if step_index == cutoff_step:
|
118 |
+
prompt_embeds = callback_kwargs[self.tensor_inputs[0]]
|
119 |
+
prompt_embeds = prompt_embeds[-1:] # "-1" denotes the embeddings for conditional text tokens.
|
120 |
+
|
121 |
+
add_text_embeds = callback_kwargs[self.tensor_inputs[1]]
|
122 |
+
add_text_embeds = add_text_embeds[-1:] # "-1" denotes the embeddings for conditional pooled text tokens
|
123 |
+
|
124 |
+
add_time_ids = callback_kwargs[self.tensor_inputs[2]]
|
125 |
+
add_time_ids = add_time_ids[-1:] # "-1" denotes the embeddings for conditional added time vector
|
126 |
+
|
127 |
+
pipeline._guidance_scale = 0.0
|
128 |
+
|
129 |
+
callback_kwargs[self.tensor_inputs[0]] = prompt_embeds
|
130 |
+
callback_kwargs[self.tensor_inputs[1]] = add_text_embeds
|
131 |
+
callback_kwargs[self.tensor_inputs[2]] = add_time_ids
|
132 |
+
return callback_kwargs
|
133 |
+
|
134 |
+
|
135 |
+
class IPAdapterScaleCutoffCallback(PipelineCallback):
|
136 |
+
"""
|
137 |
+
Callback function for any pipeline that inherits `IPAdapterMixin`. After certain number of steps (set by
|
138 |
+
`cutoff_step_ratio` or `cutoff_step_index`), this callback will set the IP Adapter scale to `0.0`.
|
139 |
+
|
140 |
+
Note: This callback mutates the IP Adapter attention processors by setting the scale to 0.0 after the cutoff step.
|
141 |
+
"""
|
142 |
+
|
143 |
+
tensor_inputs = []
|
144 |
+
|
145 |
+
def callback_fn(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]:
|
146 |
+
cutoff_step_ratio = self.config.cutoff_step_ratio
|
147 |
+
cutoff_step_index = self.config.cutoff_step_index
|
148 |
+
|
149 |
+
# Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio
|
150 |
+
cutoff_step = (
|
151 |
+
cutoff_step_index if cutoff_step_index is not None else int(pipeline.num_timesteps * cutoff_step_ratio)
|
152 |
+
)
|
153 |
+
|
154 |
+
if step_index == cutoff_step:
|
155 |
+
pipeline.set_ip_adapter_scale(0.0)
|
156 |
+
return callback_kwargs
|
utils/controlnet_xs.py
ADDED
@@ -0,0 +1,2066 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
from dataclasses import dataclass
|
15 |
+
from math import gcd
|
16 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
17 |
+
|
18 |
+
import torch
|
19 |
+
import torch.utils.checkpoint
|
20 |
+
from torch import Tensor, nn
|
21 |
+
from torch.nn import functional as F
|
22 |
+
|
23 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
24 |
+
from diffusers.utils import BaseOutput, is_torch_version, logging
|
25 |
+
from diffusers.utils.torch_utils import apply_freeu
|
26 |
+
from diffusers.models.attention_processor import (
|
27 |
+
ADDED_KV_ATTENTION_PROCESSORS,
|
28 |
+
CROSS_ATTENTION_PROCESSORS,
|
29 |
+
Attention,
|
30 |
+
AttentionProcessor,
|
31 |
+
AttnAddedKVProcessor,
|
32 |
+
AttnProcessor,
|
33 |
+
)
|
34 |
+
#from diffusers.models.controlnet import ControlNetConditioningEmbedding
|
35 |
+
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
36 |
+
from diffusers.models.modeling_utils import ModelMixin
|
37 |
+
from diffusers.models.unets.unet_2d_blocks import (
|
38 |
+
CrossAttnDownBlock2D,
|
39 |
+
CrossAttnUpBlock2D,
|
40 |
+
Downsample2D,
|
41 |
+
ResnetBlock2D,
|
42 |
+
Transformer2DModel,
|
43 |
+
Upsample2D,
|
44 |
+
)
|
45 |
+
|
46 |
+
from utils.modules import UNetMidBlock2DCrossAttn
|
47 |
+
|
48 |
+
from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
|
49 |
+
from diffusers.loaders import UNet2DConditionLoadersMixin
|
50 |
+
|
51 |
+
# from modules.unet_2d_condition import UNet2DConditionModel
|
52 |
+
# from modules.unet import UNet2DConditionLoadersMixin
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
55 |
+
|
56 |
+
class ControlNetConditioningEmbedding(nn.Module):
|
57 |
+
"""
|
58 |
+
Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
|
59 |
+
[11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
|
60 |
+
training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
|
61 |
+
convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
|
62 |
+
(activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
|
63 |
+
model) to encode image-space conditions ... into feature maps ..."
|
64 |
+
"""
|
65 |
+
|
66 |
+
def __init__(
|
67 |
+
self,
|
68 |
+
conditioning_embedding_channels: int,
|
69 |
+
conditioning_channels: int = 3,
|
70 |
+
block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
|
71 |
+
):
|
72 |
+
super().__init__()
|
73 |
+
|
74 |
+
self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
|
75 |
+
|
76 |
+
self.blocks = nn.ModuleList([])
|
77 |
+
|
78 |
+
for i in range(len(block_out_channels) - 1):
|
79 |
+
channel_in = block_out_channels[i]
|
80 |
+
channel_out = block_out_channels[i + 1]
|
81 |
+
self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
|
82 |
+
|
83 |
+
stride = 1 if conditioning_channels == 4 else 2
|
84 |
+
self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=stride))
|
85 |
+
|
86 |
+
self.conv_out = zero_module(
|
87 |
+
nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
|
88 |
+
)
|
89 |
+
|
90 |
+
def forward(self, conditioning):
|
91 |
+
embedding = self.conv_in(conditioning)
|
92 |
+
embedding = F.silu(embedding)
|
93 |
+
|
94 |
+
for block in self.blocks:
|
95 |
+
embedding = block(embedding)
|
96 |
+
embedding = F.silu(embedding)
|
97 |
+
|
98 |
+
embedding = self.conv_out(embedding)
|
99 |
+
|
100 |
+
return embedding
|
101 |
+
|
102 |
+
|
103 |
+
@dataclass
|
104 |
+
class ControlNetXSOutput(BaseOutput):
|
105 |
+
"""
|
106 |
+
The output of [`UNetControlNetXSModel`].
|
107 |
+
|
108 |
+
Args:
|
109 |
+
sample (`Tensor` of shape `(batch_size, num_channels, height, width)`):
|
110 |
+
The output of the `UNetControlNetXSModel`. Unlike `ControlNetOutput` this is NOT to be added to the base
|
111 |
+
model output, but is already the final output.
|
112 |
+
"""
|
113 |
+
|
114 |
+
sample: Tensor = None
|
115 |
+
|
116 |
+
|
117 |
+
class DownBlockControlNetXSAdapter(nn.Module):
|
118 |
+
"""Components that together with corresponding components from the base model will form a
|
119 |
+
`ControlNetXSCrossAttnDownBlock2D`"""
|
120 |
+
|
121 |
+
def __init__(
|
122 |
+
self,
|
123 |
+
resnets: nn.ModuleList,
|
124 |
+
base_to_ctrl: nn.ModuleList,
|
125 |
+
ctrl_to_base: nn.ModuleList,
|
126 |
+
attentions: Optional[nn.ModuleList] = None,
|
127 |
+
downsampler: Optional[nn.Conv2d] = None,
|
128 |
+
):
|
129 |
+
super().__init__()
|
130 |
+
self.resnets = resnets
|
131 |
+
self.base_to_ctrl = base_to_ctrl
|
132 |
+
self.ctrl_to_base = ctrl_to_base
|
133 |
+
self.attentions = attentions
|
134 |
+
self.downsamplers = downsampler
|
135 |
+
|
136 |
+
|
137 |
+
class MidBlockControlNetXSAdapter(nn.Module):
|
138 |
+
"""Components that together with corresponding components from the base model will form a
|
139 |
+
`ControlNetXSCrossAttnMidBlock2D`"""
|
140 |
+
|
141 |
+
def __init__(self, midblock: UNetMidBlock2DCrossAttn, base_to_ctrl: nn.ModuleList, ctrl_to_base: nn.ModuleList):
|
142 |
+
super().__init__()
|
143 |
+
self.midblock = midblock
|
144 |
+
self.base_to_ctrl = base_to_ctrl
|
145 |
+
self.ctrl_to_base = ctrl_to_base
|
146 |
+
|
147 |
+
|
148 |
+
class UpBlockControlNetXSAdapter(nn.Module):
|
149 |
+
"""Components that together with corresponding components from the base model will form a `ControlNetXSCrossAttnUpBlock2D`"""
|
150 |
+
|
151 |
+
def __init__(self, ctrl_to_base: nn.ModuleList):
|
152 |
+
super().__init__()
|
153 |
+
self.ctrl_to_base = ctrl_to_base
|
154 |
+
|
155 |
+
|
156 |
+
def get_down_block_adapter(
|
157 |
+
base_in_channels: int,
|
158 |
+
base_out_channels: int,
|
159 |
+
ctrl_in_channels: int,
|
160 |
+
ctrl_out_channels: int,
|
161 |
+
temb_channels: int,
|
162 |
+
max_norm_num_groups: Optional[int] = 32,
|
163 |
+
has_crossattn=True,
|
164 |
+
transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
|
165 |
+
num_attention_heads: Optional[int] = 1,
|
166 |
+
cross_attention_dim: Optional[int] = 1024,
|
167 |
+
add_downsample: bool = True,
|
168 |
+
upcast_attention: Optional[bool] = False,
|
169 |
+
):
|
170 |
+
num_layers = 2 # only support sd + sdxl
|
171 |
+
|
172 |
+
resnets = []
|
173 |
+
attentions = []
|
174 |
+
ctrl_to_base = []
|
175 |
+
base_to_ctrl = []
|
176 |
+
|
177 |
+
if isinstance(transformer_layers_per_block, int):
|
178 |
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
179 |
+
|
180 |
+
for i in range(num_layers):
|
181 |
+
base_in_channels = base_in_channels if i == 0 else base_out_channels
|
182 |
+
ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
|
183 |
+
|
184 |
+
# Before the resnet/attention application, information is concatted from base to control.
|
185 |
+
# Concat doesn't require change in number of channels
|
186 |
+
base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
|
187 |
+
|
188 |
+
resnets.append(
|
189 |
+
ResnetBlock2D(
|
190 |
+
in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
|
191 |
+
out_channels=ctrl_out_channels,
|
192 |
+
temb_channels=temb_channels,
|
193 |
+
groups=find_largest_factor(ctrl_in_channels + base_in_channels, max_factor=max_norm_num_groups),
|
194 |
+
groups_out=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
|
195 |
+
eps=1e-5,
|
196 |
+
)
|
197 |
+
)
|
198 |
+
|
199 |
+
if has_crossattn:
|
200 |
+
attentions.append(
|
201 |
+
Transformer2DModel(
|
202 |
+
num_attention_heads,
|
203 |
+
ctrl_out_channels // num_attention_heads,
|
204 |
+
in_channels=ctrl_out_channels,
|
205 |
+
num_layers=transformer_layers_per_block[i],
|
206 |
+
cross_attention_dim=cross_attention_dim,
|
207 |
+
use_linear_projection=True,
|
208 |
+
upcast_attention=upcast_attention,
|
209 |
+
norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
|
210 |
+
)
|
211 |
+
)
|
212 |
+
|
213 |
+
# After the resnet/attention application, information is added from control to base
|
214 |
+
# Addition requires change in number of channels
|
215 |
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
216 |
+
|
217 |
+
if add_downsample:
|
218 |
+
# Before the downsampler application, information is concatted from base to control
|
219 |
+
# Concat doesn't require change in number of channels
|
220 |
+
base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
|
221 |
+
|
222 |
+
downsamplers = Downsample2D(
|
223 |
+
ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
|
224 |
+
)
|
225 |
+
|
226 |
+
# After the downsampler application, information is added from control to base
|
227 |
+
# Addition requires change in number of channels
|
228 |
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
229 |
+
else:
|
230 |
+
downsamplers = None
|
231 |
+
|
232 |
+
down_block_components = DownBlockControlNetXSAdapter(
|
233 |
+
resnets=nn.ModuleList(resnets),
|
234 |
+
base_to_ctrl=nn.ModuleList(base_to_ctrl),
|
235 |
+
ctrl_to_base=nn.ModuleList(ctrl_to_base),
|
236 |
+
)
|
237 |
+
|
238 |
+
if has_crossattn:
|
239 |
+
down_block_components.attentions = nn.ModuleList(attentions)
|
240 |
+
if downsamplers is not None:
|
241 |
+
down_block_components.downsamplers = downsamplers
|
242 |
+
|
243 |
+
return down_block_components
|
244 |
+
|
245 |
+
|
246 |
+
def get_mid_block_adapter(
|
247 |
+
base_channels: int,
|
248 |
+
ctrl_channels: int,
|
249 |
+
temb_channels: Optional[int] = None,
|
250 |
+
max_norm_num_groups: Optional[int] = 32,
|
251 |
+
transformer_layers_per_block: int = 1,
|
252 |
+
num_attention_heads: Optional[int] = 1,
|
253 |
+
cross_attention_dim: Optional[int] = 1024,
|
254 |
+
upcast_attention: bool = False,
|
255 |
+
):
|
256 |
+
# Before the midblock application, information is concatted from base to control.
|
257 |
+
# Concat doesn't require change in number of channels
|
258 |
+
base_to_ctrl = make_zero_conv(base_channels, base_channels)
|
259 |
+
|
260 |
+
midblock = UNetMidBlock2DCrossAttn(
|
261 |
+
transformer_layers_per_block=transformer_layers_per_block,
|
262 |
+
in_channels=ctrl_channels + base_channels,
|
263 |
+
out_channels=ctrl_channels,
|
264 |
+
temb_channels=temb_channels,
|
265 |
+
# number or norm groups must divide both in_channels and out_channels
|
266 |
+
resnet_groups=find_largest_factor(gcd(ctrl_channels, ctrl_channels + base_channels), max_norm_num_groups),
|
267 |
+
cross_attention_dim=cross_attention_dim,
|
268 |
+
num_attention_heads=num_attention_heads,
|
269 |
+
use_linear_projection=True,
|
270 |
+
upcast_attention=upcast_attention,
|
271 |
+
)
|
272 |
+
|
273 |
+
# After the midblock application, information is added from control to base
|
274 |
+
# Addition requires change in number of channels
|
275 |
+
ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
|
276 |
+
|
277 |
+
return MidBlockControlNetXSAdapter(base_to_ctrl=base_to_ctrl, midblock=midblock, ctrl_to_base=ctrl_to_base)
|
278 |
+
|
279 |
+
|
280 |
+
def get_up_block_adapter(
|
281 |
+
out_channels: int,
|
282 |
+
prev_output_channel: int,
|
283 |
+
ctrl_skip_channels: List[int],
|
284 |
+
):
|
285 |
+
ctrl_to_base = []
|
286 |
+
num_layers = 3 # only support sd + sdxl
|
287 |
+
for i in range(num_layers):
|
288 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
289 |
+
ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
|
290 |
+
|
291 |
+
return UpBlockControlNetXSAdapter(ctrl_to_base=nn.ModuleList(ctrl_to_base))
|
292 |
+
|
293 |
+
|
294 |
+
class ControlNetXSAdapter(ModelMixin, ConfigMixin):
|
295 |
+
r"""
|
296 |
+
A `ControlNetXSAdapter` model. To use it, pass it into a `UNetControlNetXSModel` (together with a
|
297 |
+
`UNet2DConditionModel` base model).
|
298 |
+
|
299 |
+
This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
|
300 |
+
methods implemented for all models (such as downloading or saving).
|
301 |
+
|
302 |
+
Like `UNetControlNetXSModel`, `ControlNetXSAdapter` is compatible with StableDiffusion and StableDiffusion-XL. It's
|
303 |
+
default parameters are compatible with StableDiffusion.
|
304 |
+
|
305 |
+
Parameters:
|
306 |
+
conditioning_channels (`int`, defaults to 3):
|
307 |
+
Number of channels of conditioning input (e.g. an image)
|
308 |
+
conditioning_channel_order (`str`, defaults to `"rgb"`):
|
309 |
+
The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
|
310 |
+
conditioning_embedding_out_channels (`tuple[int]`, defaults to `(16, 32, 96, 256)`):
|
311 |
+
The tuple of output channels for each block in the `controlnet_cond_embedding` layer.
|
312 |
+
time_embedding_mix (`float`, defaults to 1.0):
|
313 |
+
If 0, then only the control adapters's time embedding is used. If 1, then only the base unet's time
|
314 |
+
embedding is used. Otherwise, both are combined.
|
315 |
+
learn_time_embedding (`bool`, defaults to `False`):
|
316 |
+
Whether a time embedding should be learned. If yes, `UNetControlNetXSModel` will combine the time
|
317 |
+
embeddings of the base model and the control adapter. If no, `UNetControlNetXSModel` will use the base
|
318 |
+
model's time embedding.
|
319 |
+
num_attention_heads (`list[int]`, defaults to `[4]`):
|
320 |
+
The number of attention heads.
|
321 |
+
block_out_channels (`list[int]`, defaults to `[4, 8, 16, 16]`):
|
322 |
+
The tuple of output channels for each block.
|
323 |
+
base_block_out_channels (`list[int]`, defaults to `[320, 640, 1280, 1280]`):
|
324 |
+
The tuple of output channels for each block in the base unet.
|
325 |
+
cross_attention_dim (`int`, defaults to 1024):
|
326 |
+
The dimension of the cross attention features.
|
327 |
+
down_block_types (`list[str]`, defaults to `["CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D"]`):
|
328 |
+
The tuple of downsample blocks to use.
|
329 |
+
sample_size (`int`, defaults to 96):
|
330 |
+
Height and width of input/output sample.
|
331 |
+
transformer_layers_per_block (`Union[int, Tuple[int]]`, defaults to 1):
|
332 |
+
The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
|
333 |
+
[`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
|
334 |
+
upcast_attention (`bool`, defaults to `True`):
|
335 |
+
Whether the attention computation should always be upcasted.
|
336 |
+
max_norm_num_groups (`int`, defaults to 32):
|
337 |
+
Maximum number of groups in group normal. The actual number will the the largest divisor of the respective
|
338 |
+
channels, that is <= max_norm_num_groups.
|
339 |
+
"""
|
340 |
+
|
341 |
+
@register_to_config
|
342 |
+
def __init__(
|
343 |
+
self,
|
344 |
+
conditioning_channels: int = 3,
|
345 |
+
conditioning_channel_order: str = "rgb",
|
346 |
+
conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
|
347 |
+
time_embedding_mix: float = 1.0,
|
348 |
+
learn_time_embedding: bool = False,
|
349 |
+
num_attention_heads: Union[int, Tuple[int]] = 4,
|
350 |
+
block_out_channels: Tuple[int] = (4, 8, 16, 16),
|
351 |
+
base_block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
352 |
+
cross_attention_dim: int = 1024,
|
353 |
+
down_block_types: Tuple[str] = (
|
354 |
+
"CrossAttnDownBlock2D",
|
355 |
+
"CrossAttnDownBlock2D",
|
356 |
+
"CrossAttnDownBlock2D",
|
357 |
+
"DownBlock2D",
|
358 |
+
),
|
359 |
+
sample_size: Optional[int] = 96,
|
360 |
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
361 |
+
upcast_attention: bool = True,
|
362 |
+
max_norm_num_groups: int = 32,
|
363 |
+
):
|
364 |
+
super().__init__()
|
365 |
+
|
366 |
+
time_embedding_input_dim = base_block_out_channels[0]
|
367 |
+
time_embedding_dim = base_block_out_channels[0] * 4
|
368 |
+
|
369 |
+
# Check inputs
|
370 |
+
if conditioning_channel_order not in ["rgb", "bgr"]:
|
371 |
+
raise ValueError(f"unknown `conditioning_channel_order`: {conditioning_channel_order}")
|
372 |
+
|
373 |
+
if len(block_out_channels) != len(down_block_types):
|
374 |
+
raise ValueError(
|
375 |
+
f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
|
376 |
+
)
|
377 |
+
|
378 |
+
if not isinstance(transformer_layers_per_block, (list, tuple)):
|
379 |
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
380 |
+
if not isinstance(cross_attention_dim, (list, tuple)):
|
381 |
+
cross_attention_dim = [cross_attention_dim] * len(down_block_types)
|
382 |
+
# see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why `ControlNetXSAdapter` takes `num_attention_heads` instead of `attention_head_dim`
|
383 |
+
if not isinstance(num_attention_heads, (list, tuple)):
|
384 |
+
num_attention_heads = [num_attention_heads] * len(down_block_types)
|
385 |
+
|
386 |
+
if len(num_attention_heads) != len(down_block_types):
|
387 |
+
raise ValueError(
|
388 |
+
f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
|
389 |
+
)
|
390 |
+
|
391 |
+
# 5 - Create conditioning hint embedding
|
392 |
+
self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
|
393 |
+
conditioning_embedding_channels=block_out_channels[0],
|
394 |
+
block_out_channels=conditioning_embedding_out_channels,
|
395 |
+
conditioning_channels=conditioning_channels,
|
396 |
+
)
|
397 |
+
|
398 |
+
# time
|
399 |
+
if learn_time_embedding:
|
400 |
+
self.time_embedding = TimestepEmbedding(time_embedding_input_dim, time_embedding_dim)
|
401 |
+
else:
|
402 |
+
self.time_embedding = None
|
403 |
+
|
404 |
+
self.down_blocks = nn.ModuleList([])
|
405 |
+
self.up_connections = nn.ModuleList([])
|
406 |
+
|
407 |
+
# input
|
408 |
+
self.conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
|
409 |
+
self.control_to_base_for_conv_in = make_zero_conv(block_out_channels[0], base_block_out_channels[0])
|
410 |
+
|
411 |
+
# down
|
412 |
+
base_out_channels = base_block_out_channels[0]
|
413 |
+
ctrl_out_channels = block_out_channels[0]
|
414 |
+
for i, down_block_type in enumerate(down_block_types):
|
415 |
+
base_in_channels = base_out_channels
|
416 |
+
base_out_channels = base_block_out_channels[i]
|
417 |
+
ctrl_in_channels = ctrl_out_channels
|
418 |
+
ctrl_out_channels = block_out_channels[i]
|
419 |
+
has_crossattn = "CrossAttn" in down_block_type
|
420 |
+
is_final_block = i == len(down_block_types) - 1
|
421 |
+
|
422 |
+
self.down_blocks.append(
|
423 |
+
get_down_block_adapter(
|
424 |
+
base_in_channels=base_in_channels,
|
425 |
+
base_out_channels=base_out_channels,
|
426 |
+
ctrl_in_channels=ctrl_in_channels,
|
427 |
+
ctrl_out_channels=ctrl_out_channels,
|
428 |
+
temb_channels=time_embedding_dim,
|
429 |
+
max_norm_num_groups=max_norm_num_groups,
|
430 |
+
has_crossattn=has_crossattn,
|
431 |
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
432 |
+
num_attention_heads=num_attention_heads[i],
|
433 |
+
cross_attention_dim=cross_attention_dim[i],
|
434 |
+
add_downsample=not is_final_block,
|
435 |
+
upcast_attention=upcast_attention,
|
436 |
+
)
|
437 |
+
)
|
438 |
+
|
439 |
+
# mid
|
440 |
+
self.mid_block = get_mid_block_adapter(
|
441 |
+
base_channels=base_block_out_channels[-1],
|
442 |
+
ctrl_channels=block_out_channels[-1],
|
443 |
+
temb_channels=time_embedding_dim,
|
444 |
+
transformer_layers_per_block=transformer_layers_per_block[-1],
|
445 |
+
num_attention_heads=num_attention_heads[-1],
|
446 |
+
cross_attention_dim=cross_attention_dim[-1],
|
447 |
+
upcast_attention=upcast_attention,
|
448 |
+
)
|
449 |
+
|
450 |
+
# up
|
451 |
+
# The skip connection channels are the output of the conv_in and of all the down subblocks
|
452 |
+
ctrl_skip_channels = [block_out_channels[0]]
|
453 |
+
for i, out_channels in enumerate(block_out_channels):
|
454 |
+
number_of_subblocks = (
|
455 |
+
3 if i < len(block_out_channels) - 1 else 2
|
456 |
+
) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
|
457 |
+
ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
|
458 |
+
|
459 |
+
reversed_base_block_out_channels = list(reversed(base_block_out_channels))
|
460 |
+
|
461 |
+
base_out_channels = reversed_base_block_out_channels[0]
|
462 |
+
for i in range(len(down_block_types)):
|
463 |
+
prev_base_output_channel = base_out_channels
|
464 |
+
base_out_channels = reversed_base_block_out_channels[i]
|
465 |
+
ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
|
466 |
+
|
467 |
+
self.up_connections.append(
|
468 |
+
get_up_block_adapter(
|
469 |
+
out_channels=base_out_channels,
|
470 |
+
prev_output_channel=prev_base_output_channel,
|
471 |
+
ctrl_skip_channels=ctrl_skip_channels_,
|
472 |
+
)
|
473 |
+
)
|
474 |
+
|
475 |
+
@classmethod
|
476 |
+
def from_unet(
|
477 |
+
cls,
|
478 |
+
unet: UNet2DConditionModel,
|
479 |
+
size_ratio: Optional[float] = None,
|
480 |
+
block_out_channels: Optional[List[int]] = None,
|
481 |
+
num_attention_heads: Optional[List[int]] = None,
|
482 |
+
learn_time_embedding: bool = False,
|
483 |
+
time_embedding_mix: int = 1.0,
|
484 |
+
conditioning_channels: int = 3,
|
485 |
+
conditioning_channel_order: str = "rgb",
|
486 |
+
conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
|
487 |
+
):
|
488 |
+
r"""
|
489 |
+
Instantiate a [`ControlNetXSAdapter`] from a [`UNet2DConditionModel`].
|
490 |
+
|
491 |
+
Parameters:
|
492 |
+
unet (`UNet2DConditionModel`):
|
493 |
+
The UNet model we want to control. The dimensions of the ControlNetXSAdapter will be adapted to it.
|
494 |
+
size_ratio (float, *optional*, defaults to `None`):
|
495 |
+
When given, block_out_channels is set to a fraction of the base model's block_out_channels. Either this
|
496 |
+
or `block_out_channels` must be given.
|
497 |
+
block_out_channels (`List[int]`, *optional*, defaults to `None`):
|
498 |
+
Down blocks output channels in control model. Either this or `size_ratio` must be given.
|
499 |
+
num_attention_heads (`List[int]`, *optional*, defaults to `None`):
|
500 |
+
The dimension of the attention heads. The naming seems a bit confusing and it is, see
|
501 |
+
https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
|
502 |
+
learn_time_embedding (`bool`, defaults to `False`):
|
503 |
+
Whether the `ControlNetXSAdapter` should learn a time embedding.
|
504 |
+
time_embedding_mix (`float`, defaults to 1.0):
|
505 |
+
If 0, then only the control adapter's time embedding is used. If 1, then only the base unet's time
|
506 |
+
embedding is used. Otherwise, both are combined.
|
507 |
+
conditioning_channels (`int`, defaults to 3):
|
508 |
+
Number of channels of conditioning input (e.g. an image)
|
509 |
+
conditioning_channel_order (`str`, defaults to `"rgb"`):
|
510 |
+
The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
|
511 |
+
conditioning_embedding_out_channels (`Tuple[int]`, defaults to `(16, 32, 96, 256)`):
|
512 |
+
The tuple of output channel for each block in the `controlnet_cond_embedding` layer.
|
513 |
+
"""
|
514 |
+
|
515 |
+
# Check input
|
516 |
+
fixed_size = block_out_channels is not None
|
517 |
+
relative_size = size_ratio is not None
|
518 |
+
if not (fixed_size ^ relative_size):
|
519 |
+
raise ValueError(
|
520 |
+
"Pass exactly one of `block_out_channels` (for absolute sizing) or `size_ratio` (for relative sizing)."
|
521 |
+
)
|
522 |
+
|
523 |
+
# Create model
|
524 |
+
block_out_channels = block_out_channels or [int(b * size_ratio) for b in unet.config.block_out_channels]
|
525 |
+
if num_attention_heads is None:
|
526 |
+
# The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
|
527 |
+
num_attention_heads = unet.config.attention_head_dim
|
528 |
+
|
529 |
+
model = cls(
|
530 |
+
conditioning_channels=conditioning_channels,
|
531 |
+
conditioning_channel_order=conditioning_channel_order,
|
532 |
+
conditioning_embedding_out_channels=conditioning_embedding_out_channels,
|
533 |
+
time_embedding_mix=time_embedding_mix,
|
534 |
+
learn_time_embedding=learn_time_embedding,
|
535 |
+
num_attention_heads=num_attention_heads,
|
536 |
+
block_out_channels=block_out_channels,
|
537 |
+
base_block_out_channels=unet.config.block_out_channels,
|
538 |
+
cross_attention_dim=unet.config.cross_attention_dim,
|
539 |
+
down_block_types=unet.config.down_block_types,
|
540 |
+
sample_size=unet.config.sample_size,
|
541 |
+
transformer_layers_per_block=unet.config.transformer_layers_per_block,
|
542 |
+
upcast_attention=unet.config.upcast_attention,
|
543 |
+
max_norm_num_groups=unet.config.norm_num_groups,
|
544 |
+
)
|
545 |
+
|
546 |
+
# ensure that the ControlNetXSAdapter is the same dtype as the UNet2DConditionModel
|
547 |
+
model.to(unet.dtype)
|
548 |
+
|
549 |
+
return model
|
550 |
+
|
551 |
+
def forward(self, *args, **kwargs):
|
552 |
+
raise ValueError(
|
553 |
+
"A ControlNetXSAdapter cannot be run by itself. Use it together with a UNet2DConditionModel to instantiate a UNetControlNetXSModel."
|
554 |
+
)
|
555 |
+
|
556 |
+
|
557 |
+
class UNetControlNetXSModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
558 |
+
r"""
|
559 |
+
A UNet fused with a ControlNet-XS adapter model
|
560 |
+
|
561 |
+
This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
|
562 |
+
methods implemented for all models (such as downloading or saving).
|
563 |
+
|
564 |
+
`UNetControlNetXSModel` is compatible with StableDiffusion and StableDiffusion-XL. It's default parameters are
|
565 |
+
compatible with StableDiffusion.
|
566 |
+
|
567 |
+
It's parameters are either passed to the underlying `UNet2DConditionModel` or used exactly like in
|
568 |
+
`ControlNetXSAdapter` . See their documentation for details.
|
569 |
+
"""
|
570 |
+
|
571 |
+
_supports_gradient_checkpointing = True
|
572 |
+
|
573 |
+
@register_to_config
|
574 |
+
def __init__(
|
575 |
+
self,
|
576 |
+
# unet configs
|
577 |
+
sample_size: Optional[int] = 96,
|
578 |
+
down_block_types: Tuple[str] = (
|
579 |
+
"CrossAttnDownBlock2D",
|
580 |
+
"CrossAttnDownBlock2D",
|
581 |
+
"CrossAttnDownBlock2D",
|
582 |
+
"DownBlock2D",
|
583 |
+
),
|
584 |
+
up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
|
585 |
+
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
586 |
+
norm_num_groups: Optional[int] = 32,
|
587 |
+
cross_attention_dim: Union[int, Tuple[int]] = 1024,
|
588 |
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
589 |
+
num_attention_heads: Union[int, Tuple[int]] = 8,
|
590 |
+
addition_embed_type: Optional[str] = None,
|
591 |
+
addition_time_embed_dim: Optional[int] = None,
|
592 |
+
upcast_attention: bool = True,
|
593 |
+
time_cond_proj_dim: Optional[int] = None,
|
594 |
+
projection_class_embeddings_input_dim: Optional[int] = None,
|
595 |
+
# additional controlnet configs
|
596 |
+
time_embedding_mix: float = 1.0,
|
597 |
+
ctrl_conditioning_channels: int = 3,
|
598 |
+
ctrl_conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
|
599 |
+
ctrl_conditioning_channel_order: str = "rgb",
|
600 |
+
ctrl_learn_time_embedding: bool = False,
|
601 |
+
ctrl_block_out_channels: Tuple[int] = (4, 8, 16, 16),
|
602 |
+
ctrl_num_attention_heads: Union[int, Tuple[int]] = 4,
|
603 |
+
ctrl_max_norm_num_groups: int = 32,
|
604 |
+
):
|
605 |
+
super().__init__()
|
606 |
+
|
607 |
+
if time_embedding_mix < 0 or time_embedding_mix > 1:
|
608 |
+
raise ValueError("`time_embedding_mix` needs to be between 0 and 1.")
|
609 |
+
if time_embedding_mix < 1 and not ctrl_learn_time_embedding:
|
610 |
+
raise ValueError("To use `time_embedding_mix` < 1, `ctrl_learn_time_embedding` must be `True`")
|
611 |
+
|
612 |
+
if addition_embed_type is not None and addition_embed_type != "text_time":
|
613 |
+
raise ValueError(
|
614 |
+
"As `UNetControlNetXSModel` currently only supports StableDiffusion and StableDiffusion-XL, `addition_embed_type` must be `None` or `'text_time'`."
|
615 |
+
)
|
616 |
+
|
617 |
+
if not isinstance(transformer_layers_per_block, (list, tuple)):
|
618 |
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
619 |
+
if not isinstance(cross_attention_dim, (list, tuple)):
|
620 |
+
cross_attention_dim = [cross_attention_dim] * len(down_block_types)
|
621 |
+
if not isinstance(num_attention_heads, (list, tuple)):
|
622 |
+
num_attention_heads = [num_attention_heads] * len(down_block_types)
|
623 |
+
if not isinstance(ctrl_num_attention_heads, (list, tuple)):
|
624 |
+
ctrl_num_attention_heads = [ctrl_num_attention_heads] * len(down_block_types)
|
625 |
+
|
626 |
+
base_num_attention_heads = num_attention_heads
|
627 |
+
|
628 |
+
self.in_channels = 4
|
629 |
+
|
630 |
+
# # Input
|
631 |
+
self.base_conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
|
632 |
+
self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
|
633 |
+
conditioning_embedding_channels=ctrl_block_out_channels[0],
|
634 |
+
block_out_channels=ctrl_conditioning_embedding_out_channels,
|
635 |
+
conditioning_channels=ctrl_conditioning_channels,
|
636 |
+
)
|
637 |
+
self.ctrl_conv_in = nn.Conv2d(4, ctrl_block_out_channels[0], kernel_size=3, padding=1)
|
638 |
+
self.control_to_base_for_conv_in = make_zero_conv(ctrl_block_out_channels[0], block_out_channels[0])
|
639 |
+
|
640 |
+
# # Time
|
641 |
+
time_embed_input_dim = block_out_channels[0]
|
642 |
+
time_embed_dim = block_out_channels[0] * 4
|
643 |
+
|
644 |
+
self.base_time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos=True, downscale_freq_shift=0)
|
645 |
+
self.base_time_embedding = TimestepEmbedding(
|
646 |
+
time_embed_input_dim,
|
647 |
+
time_embed_dim,
|
648 |
+
cond_proj_dim=time_cond_proj_dim,
|
649 |
+
)
|
650 |
+
self.ctrl_time_embedding = TimestepEmbedding(in_channels=time_embed_input_dim, time_embed_dim=time_embed_dim)
|
651 |
+
|
652 |
+
if addition_embed_type is None:
|
653 |
+
self.base_add_time_proj = None
|
654 |
+
self.base_add_embedding = None
|
655 |
+
else:
|
656 |
+
self.base_add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
|
657 |
+
self.base_add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
|
658 |
+
|
659 |
+
# # Create down blocks
|
660 |
+
down_blocks = []
|
661 |
+
base_out_channels = block_out_channels[0]
|
662 |
+
ctrl_out_channels = ctrl_block_out_channels[0]
|
663 |
+
for i, down_block_type in enumerate(down_block_types):
|
664 |
+
base_in_channels = base_out_channels
|
665 |
+
base_out_channels = block_out_channels[i]
|
666 |
+
ctrl_in_channels = ctrl_out_channels
|
667 |
+
ctrl_out_channels = ctrl_block_out_channels[i]
|
668 |
+
has_crossattn = "CrossAttn" in down_block_type
|
669 |
+
is_final_block = i == len(down_block_types) - 1
|
670 |
+
|
671 |
+
down_blocks.append(
|
672 |
+
ControlNetXSCrossAttnDownBlock2D(
|
673 |
+
base_in_channels=base_in_channels,
|
674 |
+
base_out_channels=base_out_channels,
|
675 |
+
ctrl_in_channels=ctrl_in_channels,
|
676 |
+
ctrl_out_channels=ctrl_out_channels,
|
677 |
+
temb_channels=time_embed_dim,
|
678 |
+
norm_num_groups=norm_num_groups,
|
679 |
+
ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
|
680 |
+
has_crossattn=has_crossattn,
|
681 |
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
682 |
+
base_num_attention_heads=base_num_attention_heads[i],
|
683 |
+
ctrl_num_attention_heads=ctrl_num_attention_heads[i],
|
684 |
+
cross_attention_dim=cross_attention_dim[i],
|
685 |
+
add_downsample=not is_final_block,
|
686 |
+
upcast_attention=upcast_attention,
|
687 |
+
)
|
688 |
+
)
|
689 |
+
|
690 |
+
# # Create mid block
|
691 |
+
self.mid_block = ControlNetXSCrossAttnMidBlock2D(
|
692 |
+
base_channels=block_out_channels[-1],
|
693 |
+
ctrl_channels=ctrl_block_out_channels[-1],
|
694 |
+
temb_channels=time_embed_dim,
|
695 |
+
norm_num_groups=norm_num_groups,
|
696 |
+
ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
|
697 |
+
transformer_layers_per_block=transformer_layers_per_block[-1],
|
698 |
+
base_num_attention_heads=base_num_attention_heads[-1],
|
699 |
+
ctrl_num_attention_heads=ctrl_num_attention_heads[-1],
|
700 |
+
cross_attention_dim=cross_attention_dim[-1],
|
701 |
+
upcast_attention=upcast_attention,
|
702 |
+
)
|
703 |
+
|
704 |
+
# # Create up blocks
|
705 |
+
up_blocks = []
|
706 |
+
rev_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
|
707 |
+
rev_num_attention_heads = list(reversed(base_num_attention_heads))
|
708 |
+
rev_cross_attention_dim = list(reversed(cross_attention_dim))
|
709 |
+
|
710 |
+
# The skip connection channels are the output of the conv_in and of all the down subblocks
|
711 |
+
ctrl_skip_channels = [ctrl_block_out_channels[0]]
|
712 |
+
for i, out_channels in enumerate(ctrl_block_out_channels):
|
713 |
+
number_of_subblocks = (
|
714 |
+
3 if i < len(ctrl_block_out_channels) - 1 else 2
|
715 |
+
) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
|
716 |
+
ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
|
717 |
+
|
718 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
719 |
+
|
720 |
+
out_channels = reversed_block_out_channels[0]
|
721 |
+
for i, up_block_type in enumerate(up_block_types):
|
722 |
+
prev_output_channel = out_channels
|
723 |
+
out_channels = reversed_block_out_channels[i]
|
724 |
+
in_channels = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
725 |
+
ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
|
726 |
+
|
727 |
+
has_crossattn = "CrossAttn" in up_block_type
|
728 |
+
is_final_block = i == len(block_out_channels) - 1
|
729 |
+
|
730 |
+
up_blocks.append(
|
731 |
+
ControlNetXSCrossAttnUpBlock2D(
|
732 |
+
in_channels=in_channels,
|
733 |
+
out_channels=out_channels,
|
734 |
+
prev_output_channel=prev_output_channel,
|
735 |
+
ctrl_skip_channels=ctrl_skip_channels_,
|
736 |
+
temb_channels=time_embed_dim,
|
737 |
+
resolution_idx=i,
|
738 |
+
has_crossattn=has_crossattn,
|
739 |
+
transformer_layers_per_block=rev_transformer_layers_per_block[i],
|
740 |
+
num_attention_heads=rev_num_attention_heads[i],
|
741 |
+
cross_attention_dim=rev_cross_attention_dim[i],
|
742 |
+
add_upsample=not is_final_block,
|
743 |
+
upcast_attention=upcast_attention,
|
744 |
+
norm_num_groups=norm_num_groups,
|
745 |
+
)
|
746 |
+
)
|
747 |
+
|
748 |
+
self.down_blocks = nn.ModuleList(down_blocks)
|
749 |
+
self.up_blocks = nn.ModuleList(up_blocks)
|
750 |
+
|
751 |
+
self.base_conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups)
|
752 |
+
self.base_conv_act = nn.SiLU()
|
753 |
+
self.base_conv_out = nn.Conv2d(block_out_channels[0], 4, kernel_size=3, padding=1)
|
754 |
+
|
755 |
+
@classmethod
|
756 |
+
def from_unet(
|
757 |
+
cls,
|
758 |
+
unet: UNet2DConditionModel,
|
759 |
+
controlnet: Optional[ControlNetXSAdapter] = None,
|
760 |
+
size_ratio: Optional[float] = None,
|
761 |
+
ctrl_block_out_channels: Optional[List[float]] = None,
|
762 |
+
time_embedding_mix: Optional[float] = None,
|
763 |
+
ctrl_optional_kwargs: Optional[Dict] = None,
|
764 |
+
conditioning_channels: int = 3,
|
765 |
+
):
|
766 |
+
r"""
|
767 |
+
Instantiate a [`UNetControlNetXSModel`] from a [`UNet2DConditionModel`] and an optional [`ControlNetXSAdapter`]
|
768 |
+
.
|
769 |
+
|
770 |
+
Parameters:
|
771 |
+
unet (`UNet2DConditionModel`):
|
772 |
+
The UNet model we want to control.
|
773 |
+
controlnet (`ControlNetXSAdapter`):
|
774 |
+
The ConntrolNet-XS adapter with which the UNet will be fused. If none is given, a new ConntrolNet-XS
|
775 |
+
adapter will be created.
|
776 |
+
size_ratio (float, *optional*, defaults to `None`):
|
777 |
+
Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
|
778 |
+
ctrl_block_out_channels (`List[int]`, *optional*, defaults to `None`):
|
779 |
+
Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details,
|
780 |
+
where this parameter is called `block_out_channels`.
|
781 |
+
time_embedding_mix (`float`, *optional*, defaults to None):
|
782 |
+
Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
|
783 |
+
ctrl_optional_kwargs (`Dict`, *optional*, defaults to `None`):
|
784 |
+
Passed to the `init` of the new controlent if no controlent was given.
|
785 |
+
"""
|
786 |
+
if controlnet is None:
|
787 |
+
# controlnet = ControlNetXSAdapter.from_unet(
|
788 |
+
# unet, size_ratio, ctrl_block_out_channels, **ctrl_optional_kwargs
|
789 |
+
# )
|
790 |
+
controlnet = ControlNetXSAdapter.from_unet(
|
791 |
+
unet, size_ratio, ctrl_block_out_channels, conditioning_channels=conditioning_channels
|
792 |
+
)
|
793 |
+
else:
|
794 |
+
if any(
|
795 |
+
o is not None for o in (size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs)
|
796 |
+
):
|
797 |
+
raise ValueError(
|
798 |
+
"When a controlnet is passed, none of these parameters should be passed: size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs."
|
799 |
+
)
|
800 |
+
|
801 |
+
# # get params
|
802 |
+
params_for_unet = [
|
803 |
+
"sample_size",
|
804 |
+
"down_block_types",
|
805 |
+
"up_block_types",
|
806 |
+
"block_out_channels",
|
807 |
+
"norm_num_groups",
|
808 |
+
"cross_attention_dim",
|
809 |
+
"transformer_layers_per_block",
|
810 |
+
"addition_embed_type",
|
811 |
+
"addition_time_embed_dim",
|
812 |
+
"upcast_attention",
|
813 |
+
"time_cond_proj_dim",
|
814 |
+
"projection_class_embeddings_input_dim",
|
815 |
+
]
|
816 |
+
params_for_unet = {k: v for k, v in unet.config.items() if k in params_for_unet}
|
817 |
+
# The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
|
818 |
+
params_for_unet["num_attention_heads"] = unet.config.attention_head_dim
|
819 |
+
|
820 |
+
params_for_controlnet = [
|
821 |
+
"conditioning_channels",
|
822 |
+
"conditioning_embedding_out_channels",
|
823 |
+
"conditioning_channel_order",
|
824 |
+
"learn_time_embedding",
|
825 |
+
"block_out_channels",
|
826 |
+
"num_attention_heads",
|
827 |
+
"max_norm_num_groups",
|
828 |
+
]
|
829 |
+
params_for_controlnet = {"ctrl_" + k: v for k, v in controlnet.config.items() if k in params_for_controlnet}
|
830 |
+
params_for_controlnet["time_embedding_mix"] = controlnet.config.time_embedding_mix
|
831 |
+
|
832 |
+
# # create model
|
833 |
+
model = cls.from_config({**params_for_unet, **params_for_controlnet})
|
834 |
+
|
835 |
+
# # load weights
|
836 |
+
# from unet
|
837 |
+
modules_from_unet = [
|
838 |
+
"time_embedding",
|
839 |
+
"conv_in",
|
840 |
+
"conv_norm_out",
|
841 |
+
"conv_out",
|
842 |
+
]
|
843 |
+
for m in modules_from_unet:
|
844 |
+
getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
|
845 |
+
|
846 |
+
optional_modules_from_unet = [
|
847 |
+
"add_time_proj",
|
848 |
+
"add_embedding",
|
849 |
+
]
|
850 |
+
for m in optional_modules_from_unet:
|
851 |
+
if hasattr(unet, m) and getattr(unet, m) is not None:
|
852 |
+
getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
|
853 |
+
|
854 |
+
# from controlnet
|
855 |
+
model.controlnet_cond_embedding.load_state_dict(controlnet.controlnet_cond_embedding.state_dict())
|
856 |
+
model.ctrl_conv_in.load_state_dict(controlnet.conv_in.state_dict())
|
857 |
+
if controlnet.time_embedding is not None:
|
858 |
+
model.ctrl_time_embedding.load_state_dict(controlnet.time_embedding.state_dict())
|
859 |
+
model.control_to_base_for_conv_in.load_state_dict(controlnet.control_to_base_for_conv_in.state_dict())
|
860 |
+
|
861 |
+
# from both
|
862 |
+
model.down_blocks = nn.ModuleList(
|
863 |
+
ControlNetXSCrossAttnDownBlock2D.from_modules(b, c)
|
864 |
+
for b, c in zip(unet.down_blocks, controlnet.down_blocks)
|
865 |
+
)
|
866 |
+
model.mid_block = ControlNetXSCrossAttnMidBlock2D.from_modules(unet.mid_block, controlnet.mid_block)
|
867 |
+
model.up_blocks = nn.ModuleList(
|
868 |
+
ControlNetXSCrossAttnUpBlock2D.from_modules(b, c)
|
869 |
+
for b, c in zip(unet.up_blocks, controlnet.up_connections)
|
870 |
+
)
|
871 |
+
|
872 |
+
# ensure that the UNetControlNetXSModel is the same dtype as the UNet2DConditionModel
|
873 |
+
model.to(unet.dtype)
|
874 |
+
|
875 |
+
return model
|
876 |
+
|
877 |
+
def freeze_unet_params(self) -> None:
|
878 |
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
879 |
+
tuning."""
|
880 |
+
# Freeze everything
|
881 |
+
for param in self.parameters():
|
882 |
+
param.requires_grad = True
|
883 |
+
|
884 |
+
# Unfreeze ControlNetXSAdapter
|
885 |
+
base_parts = [
|
886 |
+
"base_time_proj",
|
887 |
+
"base_time_embedding",
|
888 |
+
"base_add_time_proj",
|
889 |
+
"base_add_embedding",
|
890 |
+
"base_conv_in",
|
891 |
+
"base_conv_norm_out",
|
892 |
+
"base_conv_act",
|
893 |
+
"base_conv_out",
|
894 |
+
]
|
895 |
+
base_parts = [getattr(self, part) for part in base_parts if getattr(self, part) is not None]
|
896 |
+
for part in base_parts:
|
897 |
+
for param in part.parameters():
|
898 |
+
param.requires_grad = False
|
899 |
+
|
900 |
+
for d in self.down_blocks:
|
901 |
+
d.freeze_base_params()
|
902 |
+
self.mid_block.freeze_base_params()
|
903 |
+
for u in self.up_blocks:
|
904 |
+
u.freeze_base_params()
|
905 |
+
|
906 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
907 |
+
if hasattr(module, "gradient_checkpointing"):
|
908 |
+
module.gradient_checkpointing = value
|
909 |
+
|
910 |
+
# copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel
|
911 |
+
@property
|
912 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
913 |
+
r"""
|
914 |
+
Returns:
|
915 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
916 |
+
indexed by its weight name.
|
917 |
+
"""
|
918 |
+
# set recursively
|
919 |
+
processors = {}
|
920 |
+
|
921 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
922 |
+
if hasattr(module, "get_processor"):
|
923 |
+
processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
|
924 |
+
|
925 |
+
for sub_name, child in module.named_children():
|
926 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
927 |
+
|
928 |
+
return processors
|
929 |
+
|
930 |
+
for name, module in self.named_children():
|
931 |
+
fn_recursive_add_processors(name, module, processors)
|
932 |
+
|
933 |
+
return processors
|
934 |
+
|
935 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
936 |
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
937 |
+
r"""
|
938 |
+
Sets the attention processor to use to compute attention.
|
939 |
+
|
940 |
+
Parameters:
|
941 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
942 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
943 |
+
for **all** `Attention` layers.
|
944 |
+
|
945 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
946 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
947 |
+
|
948 |
+
"""
|
949 |
+
count = len(self.attn_processors.keys())
|
950 |
+
|
951 |
+
if isinstance(processor, dict) and len(processor) != count:
|
952 |
+
raise ValueError(
|
953 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
954 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
955 |
+
)
|
956 |
+
|
957 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
958 |
+
if hasattr(module, "set_processor"):
|
959 |
+
if not isinstance(processor, dict):
|
960 |
+
module.set_processor(processor)
|
961 |
+
else:
|
962 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
963 |
+
|
964 |
+
for sub_name, child in module.named_children():
|
965 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
966 |
+
|
967 |
+
for name, module in self.named_children():
|
968 |
+
fn_recursive_attn_processor(name, module, processor)
|
969 |
+
|
970 |
+
@property
|
971 |
+
def attn_processors_unet(self) -> Dict[str, AttentionProcessor]:
|
972 |
+
r"""
|
973 |
+
Returns:
|
974 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
975 |
+
indexed by its weight name.
|
976 |
+
"""
|
977 |
+
# set recursively
|
978 |
+
processors = {}
|
979 |
+
|
980 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
981 |
+
if 'ctrl_' in name:
|
982 |
+
'''ip-adapter设置交叉注意力,attn_processor时,只获取unet的参数'''
|
983 |
+
return processors
|
984 |
+
|
985 |
+
if hasattr(module, "get_processor"):
|
986 |
+
# processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
|
987 |
+
# 为什么??? module.get_processor(return_deprecated_lora=True)返回值是None
|
988 |
+
processors[f"{name}.processor"] = module.processor
|
989 |
+
|
990 |
+
for sub_name, child in module.named_children():
|
991 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
992 |
+
|
993 |
+
return processors
|
994 |
+
|
995 |
+
for name, module in self.named_children():
|
996 |
+
fn_recursive_add_processors(name, module, processors)
|
997 |
+
|
998 |
+
return processors
|
999 |
+
|
1000 |
+
def set_attn_processor_unet(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
1001 |
+
r"""
|
1002 |
+
Sets the attention processor to use to compute attention.
|
1003 |
+
|
1004 |
+
Parameters:
|
1005 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
1006 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
1007 |
+
for **all** `Attention` layers.
|
1008 |
+
|
1009 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
1010 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
1011 |
+
|
1012 |
+
"""
|
1013 |
+
'''ip-adapter设置交叉注意力,set_attn_processor时,只针对unet设置,不为controlnetxs设置'''
|
1014 |
+
|
1015 |
+
count = len(self.attn_processors_unet.keys())
|
1016 |
+
|
1017 |
+
if isinstance(processor, dict) and len(processor) != count:
|
1018 |
+
raise ValueError(
|
1019 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
1020 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
1021 |
+
)
|
1022 |
+
|
1023 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
1024 |
+
|
1025 |
+
if hasattr(module, "set_processor"):
|
1026 |
+
if 'ctrl_' in name:
|
1027 |
+
return
|
1028 |
+
|
1029 |
+
if not isinstance(processor, dict):
|
1030 |
+
module.set_processor(processor)
|
1031 |
+
else:
|
1032 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
1033 |
+
|
1034 |
+
for sub_name, child in module.named_children():
|
1035 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
1036 |
+
|
1037 |
+
for name, module in self.named_children():
|
1038 |
+
fn_recursive_attn_processor(name, module, processor)
|
1039 |
+
|
1040 |
+
# copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
|
1041 |
+
def set_default_attn_processor(self):
|
1042 |
+
"""
|
1043 |
+
Disables custom attention processors and sets the default attention implementation.
|
1044 |
+
"""
|
1045 |
+
if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
1046 |
+
processor = AttnAddedKVProcessor()
|
1047 |
+
elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
1048 |
+
processor = AttnProcessor()
|
1049 |
+
else:
|
1050 |
+
raise ValueError(
|
1051 |
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
1052 |
+
)
|
1053 |
+
|
1054 |
+
self.set_attn_processor_cnxs(processor)
|
1055 |
+
|
1056 |
+
# copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.enable_freeu
|
1057 |
+
def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
|
1058 |
+
r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
|
1059 |
+
|
1060 |
+
The suffixes after the scaling factors represent the stage blocks where they are being applied.
|
1061 |
+
|
1062 |
+
Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
|
1063 |
+
are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
|
1064 |
+
|
1065 |
+
Args:
|
1066 |
+
s1 (`float`):
|
1067 |
+
Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
|
1068 |
+
mitigate the "oversmoothing effect" in the enhanced denoising process.
|
1069 |
+
s2 (`float`):
|
1070 |
+
Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
|
1071 |
+
mitigate the "oversmoothing effect" in the enhanced denoising process.
|
1072 |
+
b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
|
1073 |
+
b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
|
1074 |
+
"""
|
1075 |
+
for i, upsample_block in enumerate(self.up_blocks):
|
1076 |
+
setattr(upsample_block, "s1", s1)
|
1077 |
+
setattr(upsample_block, "s2", s2)
|
1078 |
+
setattr(upsample_block, "b1", b1)
|
1079 |
+
setattr(upsample_block, "b2", b2)
|
1080 |
+
|
1081 |
+
# copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.disable_freeu
|
1082 |
+
def disable_freeu(self):
|
1083 |
+
"""Disables the FreeU mechanism."""
|
1084 |
+
freeu_keys = {"s1", "s2", "b1", "b2"}
|
1085 |
+
for i, upsample_block in enumerate(self.up_blocks):
|
1086 |
+
for k in freeu_keys:
|
1087 |
+
if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
|
1088 |
+
setattr(upsample_block, k, None)
|
1089 |
+
|
1090 |
+
# copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
|
1091 |
+
def fuse_qkv_projections(self):
|
1092 |
+
"""
|
1093 |
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
|
1094 |
+
are fused. For cross-attention modules, key and value projection matrices are fused.
|
1095 |
+
|
1096 |
+
<Tip warning={true}>
|
1097 |
+
|
1098 |
+
This API is 🧪 experimental.
|
1099 |
+
|
1100 |
+
</Tip>
|
1101 |
+
"""
|
1102 |
+
self.original_attn_processors = None
|
1103 |
+
|
1104 |
+
for _, attn_processor in self.attn_processors.items():
|
1105 |
+
if "Added" in str(attn_processor.__class__.__name__):
|
1106 |
+
raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
|
1107 |
+
|
1108 |
+
self.original_attn_processors = self.attn_processors
|
1109 |
+
|
1110 |
+
for module in self.modules():
|
1111 |
+
if isinstance(module, Attention):
|
1112 |
+
module.fuse_projections(fuse=True)
|
1113 |
+
|
1114 |
+
# copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
|
1115 |
+
def unfuse_qkv_projections(self):
|
1116 |
+
"""Disables the fused QKV projection if enabled.
|
1117 |
+
|
1118 |
+
<Tip warning={true}>
|
1119 |
+
|
1120 |
+
This API is 🧪 experimental.
|
1121 |
+
|
1122 |
+
</Tip>
|
1123 |
+
|
1124 |
+
"""
|
1125 |
+
if self.original_attn_processors is not None:
|
1126 |
+
self.set_attn_processor(self.original_attn_processors)
|
1127 |
+
|
1128 |
+
def forward(
|
1129 |
+
self,
|
1130 |
+
sample: Tensor,
|
1131 |
+
timestep: Union[torch.Tensor, float, int],
|
1132 |
+
unet_encoder_hidden_states: torch.Tensor,
|
1133 |
+
cnxs_encoder_hidden_states: torch.Tensor,
|
1134 |
+
controlnet_cond: Optional[torch.Tensor] = None,
|
1135 |
+
conditioning_scale: Optional[float] = 1.0,
|
1136 |
+
class_labels: Optional[torch.Tensor] = None,
|
1137 |
+
timestep_cond: Optional[torch.Tensor] = None,
|
1138 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1139 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1140 |
+
added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
|
1141 |
+
return_dict: bool = True,
|
1142 |
+
apply_control: bool = True,
|
1143 |
+
) -> Union[ControlNetXSOutput, Tuple]:
|
1144 |
+
"""
|
1145 |
+
The [`ControlNetXSModel`] forward method.
|
1146 |
+
|
1147 |
+
Args:
|
1148 |
+
sample (`Tensor`):
|
1149 |
+
The noisy input tensor.
|
1150 |
+
timestep (`Union[torch.Tensor, float, int]`):
|
1151 |
+
The number of timesteps to denoise an input.
|
1152 |
+
encoder_hidden_states (`torch.Tensor`):
|
1153 |
+
The encoder hidden states.
|
1154 |
+
controlnet_cond (`Tensor`):
|
1155 |
+
The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
|
1156 |
+
conditioning_scale (`float`, defaults to `1.0`):
|
1157 |
+
How much the control model affects the base model outputs.
|
1158 |
+
class_labels (`torch.Tensor`, *optional*, defaults to `None`):
|
1159 |
+
Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
|
1160 |
+
timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
|
1161 |
+
Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
|
1162 |
+
timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
|
1163 |
+
embeddings.
|
1164 |
+
attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
|
1165 |
+
An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
|
1166 |
+
is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
|
1167 |
+
negative values to the attention scores corresponding to "discard" tokens.
|
1168 |
+
cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
|
1169 |
+
A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
|
1170 |
+
added_cond_kwargs (`dict`):
|
1171 |
+
Additional conditions for the Stable Diffusion XL UNet.
|
1172 |
+
return_dict (`bool`, defaults to `True`):
|
1173 |
+
Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
|
1174 |
+
apply_control (`bool`, defaults to `True`):
|
1175 |
+
If `False`, the input is run only through the base model.
|
1176 |
+
|
1177 |
+
Returns:
|
1178 |
+
[`~models.controlnetxs.ControlNetXSOutput`] **or** `tuple`:
|
1179 |
+
If `return_dict` is `True`, a [`~models.controlnetxs.ControlNetXSOutput`] is returned, otherwise a
|
1180 |
+
tuple is returned where the first element is the sample tensor.
|
1181 |
+
"""
|
1182 |
+
|
1183 |
+
# check channel order
|
1184 |
+
if self.config.ctrl_conditioning_channel_order == "bgr":
|
1185 |
+
controlnet_cond = torch.flip(controlnet_cond, dims=[1])
|
1186 |
+
|
1187 |
+
# prepare attention_mask
|
1188 |
+
if attention_mask is not None:
|
1189 |
+
attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
|
1190 |
+
attention_mask = attention_mask.unsqueeze(1)
|
1191 |
+
|
1192 |
+
# 1. time
|
1193 |
+
timesteps = timestep
|
1194 |
+
if not torch.is_tensor(timesteps):
|
1195 |
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
1196 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
1197 |
+
is_mps = sample.device.type == "mps"
|
1198 |
+
if isinstance(timestep, float):
|
1199 |
+
dtype = torch.float32 if is_mps else torch.float64
|
1200 |
+
else:
|
1201 |
+
dtype = torch.int32 if is_mps else torch.int64
|
1202 |
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
1203 |
+
elif len(timesteps.shape) == 0:
|
1204 |
+
timesteps = timesteps[None].to(sample.device)
|
1205 |
+
|
1206 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
1207 |
+
timesteps = timesteps.expand(sample.shape[0])
|
1208 |
+
|
1209 |
+
t_emb = self.base_time_proj(timesteps)
|
1210 |
+
|
1211 |
+
# timesteps does not contain any weights and will always return f32 tensors
|
1212 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
1213 |
+
# there might be better ways to encapsulate this.
|
1214 |
+
t_emb = t_emb.to(dtype=sample.dtype)
|
1215 |
+
|
1216 |
+
if self.config.ctrl_learn_time_embedding and apply_control:
|
1217 |
+
ctrl_temb = self.ctrl_time_embedding(t_emb, timestep_cond)
|
1218 |
+
base_temb = self.base_time_embedding(t_emb, timestep_cond)
|
1219 |
+
interpolation_param = self.config.time_embedding_mix**0.3
|
1220 |
+
|
1221 |
+
temb = ctrl_temb * interpolation_param + base_temb * (1 - interpolation_param)
|
1222 |
+
else:
|
1223 |
+
temb = self.base_time_embedding(t_emb)
|
1224 |
+
|
1225 |
+
# added time & text embeddings
|
1226 |
+
aug_emb = None
|
1227 |
+
|
1228 |
+
if self.config.addition_embed_type is None:
|
1229 |
+
pass
|
1230 |
+
elif self.config.addition_embed_type == "text_time":
|
1231 |
+
# SDXL - style
|
1232 |
+
if "text_embeds" not in added_cond_kwargs:
|
1233 |
+
raise ValueError(
|
1234 |
+
f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
|
1235 |
+
)
|
1236 |
+
text_embeds = added_cond_kwargs.get("text_embeds")
|
1237 |
+
if "time_ids" not in added_cond_kwargs:
|
1238 |
+
raise ValueError(
|
1239 |
+
f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
|
1240 |
+
)
|
1241 |
+
time_ids = added_cond_kwargs.get("time_ids")
|
1242 |
+
time_embeds = self.base_add_time_proj(time_ids.flatten())
|
1243 |
+
time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
|
1244 |
+
add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
|
1245 |
+
add_embeds = add_embeds.to(temb.dtype)
|
1246 |
+
aug_emb = self.base_add_embedding(add_embeds)
|
1247 |
+
else:
|
1248 |
+
raise ValueError(
|
1249 |
+
f"ControlNet-XS currently only supports StableDiffusion and StableDiffusion-XL, so addition_embed_type = {self.config.addition_embed_type} is currently not supported."
|
1250 |
+
)
|
1251 |
+
|
1252 |
+
temb = temb + aug_emb if aug_emb is not None else temb
|
1253 |
+
|
1254 |
+
# text embeddings
|
1255 |
+
# cemb = unet_encoder_hidden_states
|
1256 |
+
|
1257 |
+
# Preparation
|
1258 |
+
h_ctrl = h_base = sample
|
1259 |
+
hs_base, hs_ctrl = [], []
|
1260 |
+
|
1261 |
+
# Cross Control
|
1262 |
+
guided_hint = self.controlnet_cond_embedding(controlnet_cond)
|
1263 |
+
|
1264 |
+
# 1 - conv in & down
|
1265 |
+
|
1266 |
+
h_base = self.base_conv_in(h_base)
|
1267 |
+
h_ctrl = self.ctrl_conv_in(h_ctrl)
|
1268 |
+
if guided_hint is not None:
|
1269 |
+
h_ctrl += guided_hint
|
1270 |
+
if apply_control:
|
1271 |
+
h_base = h_base + self.control_to_base_for_conv_in(h_ctrl) * conditioning_scale # add ctrl -> base
|
1272 |
+
|
1273 |
+
hs_base.append(h_base)
|
1274 |
+
hs_ctrl.append(h_ctrl)
|
1275 |
+
|
1276 |
+
for down in self.down_blocks:
|
1277 |
+
h_base, h_ctrl, residual_hb, residual_hc = down(
|
1278 |
+
hidden_states_base=h_base,
|
1279 |
+
hidden_states_ctrl=h_ctrl,
|
1280 |
+
temb=temb,
|
1281 |
+
# encoder_hidden_states=cemb,
|
1282 |
+
unet_encoder_hidden_states=unet_encoder_hidden_states,
|
1283 |
+
cnxs_encoder_hidden_states=cnxs_encoder_hidden_states,
|
1284 |
+
conditioning_scale=conditioning_scale,
|
1285 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1286 |
+
attention_mask=attention_mask,
|
1287 |
+
apply_control=apply_control,
|
1288 |
+
)
|
1289 |
+
hs_base.extend(residual_hb)
|
1290 |
+
hs_ctrl.extend(residual_hc)
|
1291 |
+
|
1292 |
+
# 2 - mid
|
1293 |
+
h_base, h_ctrl = self.mid_block(
|
1294 |
+
hidden_states_base=h_base,
|
1295 |
+
hidden_states_ctrl=h_ctrl,
|
1296 |
+
temb=temb,
|
1297 |
+
# encoder_hidden_states=cemb,
|
1298 |
+
unet_encoder_hidden_states=unet_encoder_hidden_states,
|
1299 |
+
cnxs_encoder_hidden_states=cnxs_encoder_hidden_states,
|
1300 |
+
conditioning_scale=conditioning_scale,
|
1301 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1302 |
+
attention_mask=attention_mask,
|
1303 |
+
apply_control=apply_control,
|
1304 |
+
)
|
1305 |
+
|
1306 |
+
# 3 - up
|
1307 |
+
for up in self.up_blocks:
|
1308 |
+
n_resnets = len(up.resnets)
|
1309 |
+
skips_hb = hs_base[-n_resnets:]
|
1310 |
+
skips_hc = hs_ctrl[-n_resnets:]
|
1311 |
+
hs_base = hs_base[:-n_resnets]
|
1312 |
+
hs_ctrl = hs_ctrl[:-n_resnets]
|
1313 |
+
h_base = up(
|
1314 |
+
hidden_states=h_base,
|
1315 |
+
res_hidden_states_tuple_base=skips_hb,
|
1316 |
+
res_hidden_states_tuple_ctrl=skips_hc,
|
1317 |
+
temb=temb,
|
1318 |
+
encoder_hidden_states=unet_encoder_hidden_states,
|
1319 |
+
conditioning_scale=conditioning_scale,
|
1320 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1321 |
+
attention_mask=attention_mask,
|
1322 |
+
apply_control=apply_control,
|
1323 |
+
)
|
1324 |
+
|
1325 |
+
# 4 - conv out
|
1326 |
+
h_base = self.base_conv_norm_out(h_base)
|
1327 |
+
h_base = self.base_conv_act(h_base)
|
1328 |
+
h_base = self.base_conv_out(h_base)
|
1329 |
+
|
1330 |
+
if not return_dict:
|
1331 |
+
return (h_base,)
|
1332 |
+
|
1333 |
+
return ControlNetXSOutput(sample=h_base)
|
1334 |
+
|
1335 |
+
|
1336 |
+
class ControlNetXSCrossAttnDownBlock2D(nn.Module):
|
1337 |
+
def __init__(
|
1338 |
+
self,
|
1339 |
+
base_in_channels: int,
|
1340 |
+
base_out_channels: int,
|
1341 |
+
ctrl_in_channels: int,
|
1342 |
+
ctrl_out_channels: int,
|
1343 |
+
temb_channels: int,
|
1344 |
+
norm_num_groups: int = 32,
|
1345 |
+
ctrl_max_norm_num_groups: int = 32,
|
1346 |
+
has_crossattn=True,
|
1347 |
+
transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
|
1348 |
+
base_num_attention_heads: Optional[int] = 1,
|
1349 |
+
ctrl_num_attention_heads: Optional[int] = 1,
|
1350 |
+
cross_attention_dim: Optional[int] = 1024,
|
1351 |
+
add_downsample: bool = True,
|
1352 |
+
upcast_attention: Optional[bool] = False,
|
1353 |
+
):
|
1354 |
+
super().__init__()
|
1355 |
+
base_resnets = []
|
1356 |
+
base_attentions = []
|
1357 |
+
ctrl_resnets = []
|
1358 |
+
ctrl_attentions = []
|
1359 |
+
ctrl_to_base = []
|
1360 |
+
base_to_ctrl = []
|
1361 |
+
|
1362 |
+
num_layers = 2 # only support sd + sdxl
|
1363 |
+
|
1364 |
+
if isinstance(transformer_layers_per_block, int):
|
1365 |
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
1366 |
+
|
1367 |
+
for i in range(num_layers):
|
1368 |
+
base_in_channels = base_in_channels if i == 0 else base_out_channels
|
1369 |
+
ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
|
1370 |
+
|
1371 |
+
# Before the resnet/attention application, information is concatted from base to control.
|
1372 |
+
# Concat doesn't require change in number of channels
|
1373 |
+
base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
|
1374 |
+
|
1375 |
+
base_resnets.append(
|
1376 |
+
ResnetBlock2D(
|
1377 |
+
in_channels=base_in_channels,
|
1378 |
+
out_channels=base_out_channels,
|
1379 |
+
temb_channels=temb_channels,
|
1380 |
+
groups=norm_num_groups,
|
1381 |
+
)
|
1382 |
+
)
|
1383 |
+
ctrl_resnets.append(
|
1384 |
+
ResnetBlock2D(
|
1385 |
+
in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
|
1386 |
+
out_channels=ctrl_out_channels,
|
1387 |
+
temb_channels=temb_channels,
|
1388 |
+
groups=find_largest_factor(
|
1389 |
+
ctrl_in_channels + base_in_channels, max_factor=ctrl_max_norm_num_groups
|
1390 |
+
),
|
1391 |
+
groups_out=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
|
1392 |
+
eps=1e-5,
|
1393 |
+
)
|
1394 |
+
)
|
1395 |
+
|
1396 |
+
if has_crossattn:
|
1397 |
+
base_attentions.append(
|
1398 |
+
Transformer2DModel(
|
1399 |
+
base_num_attention_heads,
|
1400 |
+
base_out_channels // base_num_attention_heads,
|
1401 |
+
in_channels=base_out_channels,
|
1402 |
+
num_layers=transformer_layers_per_block[i],
|
1403 |
+
cross_attention_dim=cross_attention_dim,
|
1404 |
+
use_linear_projection=True,
|
1405 |
+
upcast_attention=upcast_attention,
|
1406 |
+
norm_num_groups=norm_num_groups,
|
1407 |
+
)
|
1408 |
+
)
|
1409 |
+
ctrl_attentions.append(
|
1410 |
+
Transformer2DModel(
|
1411 |
+
ctrl_num_attention_heads,
|
1412 |
+
ctrl_out_channels // ctrl_num_attention_heads,
|
1413 |
+
in_channels=ctrl_out_channels,
|
1414 |
+
num_layers=transformer_layers_per_block[i],
|
1415 |
+
cross_attention_dim=cross_attention_dim,
|
1416 |
+
use_linear_projection=True,
|
1417 |
+
upcast_attention=upcast_attention,
|
1418 |
+
norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
|
1419 |
+
)
|
1420 |
+
)
|
1421 |
+
|
1422 |
+
# After the resnet/attention application, information is added from control to base
|
1423 |
+
# Addition requires change in number of channels
|
1424 |
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
1425 |
+
|
1426 |
+
if add_downsample:
|
1427 |
+
# Before the downsampler application, information is concatted from base to control
|
1428 |
+
# Concat doesn't require change in number of channels
|
1429 |
+
base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
|
1430 |
+
|
1431 |
+
self.base_downsamplers = Downsample2D(
|
1432 |
+
base_out_channels, use_conv=True, out_channels=base_out_channels, name="op"
|
1433 |
+
)
|
1434 |
+
self.ctrl_downsamplers = Downsample2D(
|
1435 |
+
ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
|
1436 |
+
)
|
1437 |
+
|
1438 |
+
# After the downsampler application, information is added from control to base
|
1439 |
+
# Addition requires change in number of channels
|
1440 |
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
1441 |
+
else:
|
1442 |
+
self.base_downsamplers = None
|
1443 |
+
self.ctrl_downsamplers = None
|
1444 |
+
|
1445 |
+
self.base_resnets = nn.ModuleList(base_resnets)
|
1446 |
+
self.ctrl_resnets = nn.ModuleList(ctrl_resnets)
|
1447 |
+
self.base_attentions = nn.ModuleList(base_attentions) if has_crossattn else [None] * num_layers
|
1448 |
+
self.ctrl_attentions = nn.ModuleList(ctrl_attentions) if has_crossattn else [None] * num_layers
|
1449 |
+
self.base_to_ctrl = nn.ModuleList(base_to_ctrl)
|
1450 |
+
self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
|
1451 |
+
|
1452 |
+
self.gradient_checkpointing = False
|
1453 |
+
|
1454 |
+
@classmethod
|
1455 |
+
def from_modules(cls, base_downblock: CrossAttnDownBlock2D, ctrl_downblock: DownBlockControlNetXSAdapter):
|
1456 |
+
# get params
|
1457 |
+
def get_first_cross_attention(block):
|
1458 |
+
return block.attentions[0].transformer_blocks[0].attn2
|
1459 |
+
|
1460 |
+
base_in_channels = base_downblock.resnets[0].in_channels
|
1461 |
+
base_out_channels = base_downblock.resnets[0].out_channels
|
1462 |
+
ctrl_in_channels = (
|
1463 |
+
ctrl_downblock.resnets[0].in_channels - base_in_channels
|
1464 |
+
) # base channels are concatted to ctrl channels in init
|
1465 |
+
ctrl_out_channels = ctrl_downblock.resnets[0].out_channels
|
1466 |
+
temb_channels = base_downblock.resnets[0].time_emb_proj.in_features
|
1467 |
+
num_groups = base_downblock.resnets[0].norm1.num_groups
|
1468 |
+
ctrl_num_groups = ctrl_downblock.resnets[0].norm1.num_groups
|
1469 |
+
if hasattr(base_downblock, "attentions"):
|
1470 |
+
has_crossattn = True
|
1471 |
+
transformer_layers_per_block = len(base_downblock.attentions[0].transformer_blocks)
|
1472 |
+
base_num_attention_heads = get_first_cross_attention(base_downblock).heads
|
1473 |
+
ctrl_num_attention_heads = get_first_cross_attention(ctrl_downblock).heads
|
1474 |
+
cross_attention_dim = get_first_cross_attention(base_downblock).cross_attention_dim
|
1475 |
+
upcast_attention = get_first_cross_attention(base_downblock).upcast_attention
|
1476 |
+
else:
|
1477 |
+
has_crossattn = False
|
1478 |
+
transformer_layers_per_block = None
|
1479 |
+
base_num_attention_heads = None
|
1480 |
+
ctrl_num_attention_heads = None
|
1481 |
+
cross_attention_dim = None
|
1482 |
+
upcast_attention = None
|
1483 |
+
add_downsample = base_downblock.downsamplers is not None
|
1484 |
+
|
1485 |
+
# create model
|
1486 |
+
model = cls(
|
1487 |
+
base_in_channels=base_in_channels,
|
1488 |
+
base_out_channels=base_out_channels,
|
1489 |
+
ctrl_in_channels=ctrl_in_channels,
|
1490 |
+
ctrl_out_channels=ctrl_out_channels,
|
1491 |
+
temb_channels=temb_channels,
|
1492 |
+
norm_num_groups=num_groups,
|
1493 |
+
ctrl_max_norm_num_groups=ctrl_num_groups,
|
1494 |
+
has_crossattn=has_crossattn,
|
1495 |
+
transformer_layers_per_block=transformer_layers_per_block,
|
1496 |
+
base_num_attention_heads=base_num_attention_heads,
|
1497 |
+
ctrl_num_attention_heads=ctrl_num_attention_heads,
|
1498 |
+
cross_attention_dim=cross_attention_dim,
|
1499 |
+
add_downsample=add_downsample,
|
1500 |
+
upcast_attention=upcast_attention,
|
1501 |
+
)
|
1502 |
+
|
1503 |
+
# # load weights
|
1504 |
+
model.base_resnets.load_state_dict(base_downblock.resnets.state_dict())
|
1505 |
+
model.ctrl_resnets.load_state_dict(ctrl_downblock.resnets.state_dict())
|
1506 |
+
if has_crossattn:
|
1507 |
+
model.base_attentions.load_state_dict(base_downblock.attentions.state_dict())
|
1508 |
+
model.ctrl_attentions.load_state_dict(ctrl_downblock.attentions.state_dict())
|
1509 |
+
if add_downsample:
|
1510 |
+
model.base_downsamplers.load_state_dict(base_downblock.downsamplers[0].state_dict())
|
1511 |
+
model.ctrl_downsamplers.load_state_dict(ctrl_downblock.downsamplers.state_dict())
|
1512 |
+
model.base_to_ctrl.load_state_dict(ctrl_downblock.base_to_ctrl.state_dict())
|
1513 |
+
model.ctrl_to_base.load_state_dict(ctrl_downblock.ctrl_to_base.state_dict())
|
1514 |
+
|
1515 |
+
return model
|
1516 |
+
|
1517 |
+
def freeze_base_params(self) -> None:
|
1518 |
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
1519 |
+
tuning."""
|
1520 |
+
# Unfreeze everything
|
1521 |
+
for param in self.parameters():
|
1522 |
+
param.requires_grad = True
|
1523 |
+
|
1524 |
+
# Freeze base part
|
1525 |
+
base_parts = [self.base_resnets]
|
1526 |
+
if isinstance(self.base_attentions, nn.ModuleList): # attentions can be a list of Nones
|
1527 |
+
base_parts.append(self.base_attentions)
|
1528 |
+
if self.base_downsamplers is not None:
|
1529 |
+
base_parts.append(self.base_downsamplers)
|
1530 |
+
for part in base_parts:
|
1531 |
+
for param in part.parameters():
|
1532 |
+
param.requires_grad = False
|
1533 |
+
|
1534 |
+
def forward(
|
1535 |
+
self,
|
1536 |
+
hidden_states_base: Tensor,
|
1537 |
+
temb: Tensor,
|
1538 |
+
unet_encoder_hidden_states: Optional[Tensor] = None,
|
1539 |
+
cnxs_encoder_hidden_states: Optional[Tensor] = None,
|
1540 |
+
hidden_states_ctrl: Optional[Tensor] = None,
|
1541 |
+
conditioning_scale: Optional[float] = 1.0,
|
1542 |
+
attention_mask: Optional[Tensor] = None,
|
1543 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1544 |
+
encoder_attention_mask: Optional[Tensor] = None,
|
1545 |
+
apply_control: bool = True,
|
1546 |
+
) -> Tuple[Tensor, Tensor, Tuple[Tensor, ...], Tuple[Tensor, ...]]:
|
1547 |
+
if cross_attention_kwargs is not None:
|
1548 |
+
if cross_attention_kwargs.get("scale", None) is not None:
|
1549 |
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
1550 |
+
|
1551 |
+
h_base = hidden_states_base
|
1552 |
+
h_ctrl = hidden_states_ctrl
|
1553 |
+
|
1554 |
+
base_output_states = ()
|
1555 |
+
ctrl_output_states = ()
|
1556 |
+
|
1557 |
+
base_blocks = list(zip(self.base_resnets, self.base_attentions))
|
1558 |
+
ctrl_blocks = list(zip(self.ctrl_resnets, self.ctrl_attentions))
|
1559 |
+
|
1560 |
+
def create_custom_forward(module, return_dict=None):
|
1561 |
+
def custom_forward(*inputs):
|
1562 |
+
if return_dict is not None:
|
1563 |
+
return module(*inputs, return_dict=return_dict)
|
1564 |
+
else:
|
1565 |
+
return module(*inputs)
|
1566 |
+
|
1567 |
+
return custom_forward
|
1568 |
+
|
1569 |
+
for (b_res, b_attn), (c_res, c_attn), b2c, c2b in zip(
|
1570 |
+
base_blocks, ctrl_blocks, self.base_to_ctrl, self.ctrl_to_base
|
1571 |
+
):
|
1572 |
+
# concat base -> ctrl
|
1573 |
+
if apply_control:
|
1574 |
+
h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
|
1575 |
+
|
1576 |
+
# apply base subblock
|
1577 |
+
if self.training and self.gradient_checkpointing:
|
1578 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
1579 |
+
h_base = torch.utils.checkpoint.checkpoint(
|
1580 |
+
create_custom_forward(b_res),
|
1581 |
+
h_base,
|
1582 |
+
temb,
|
1583 |
+
**ckpt_kwargs,
|
1584 |
+
)
|
1585 |
+
else:
|
1586 |
+
h_base = b_res(h_base, temb)
|
1587 |
+
|
1588 |
+
if b_attn is not None:
|
1589 |
+
h_base = b_attn(
|
1590 |
+
h_base,
|
1591 |
+
# 11-07
|
1592 |
+
encoder_hidden_states=unet_encoder_hidden_states,
|
1593 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1594 |
+
attention_mask=attention_mask,
|
1595 |
+
encoder_attention_mask=encoder_attention_mask,
|
1596 |
+
return_dict=False,
|
1597 |
+
)[0]
|
1598 |
+
|
1599 |
+
# apply ctrl subblock
|
1600 |
+
if apply_control:
|
1601 |
+
if self.training and self.gradient_checkpointing:
|
1602 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
1603 |
+
h_ctrl = torch.utils.checkpoint.checkpoint(
|
1604 |
+
create_custom_forward(c_res),
|
1605 |
+
h_ctrl,
|
1606 |
+
temb,
|
1607 |
+
**ckpt_kwargs,
|
1608 |
+
)
|
1609 |
+
else:
|
1610 |
+
h_ctrl = c_res(h_ctrl, temb)
|
1611 |
+
if c_attn is not None:
|
1612 |
+
h_ctrl = c_attn(
|
1613 |
+
h_ctrl,
|
1614 |
+
# 11-07
|
1615 |
+
encoder_hidden_states=cnxs_encoder_hidden_states,
|
1616 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1617 |
+
attention_mask=attention_mask,
|
1618 |
+
encoder_attention_mask=encoder_attention_mask,
|
1619 |
+
return_dict=False,
|
1620 |
+
)[0]
|
1621 |
+
|
1622 |
+
# add ctrl -> base
|
1623 |
+
if apply_control:
|
1624 |
+
h_base = h_base + c2b(h_ctrl) * conditioning_scale
|
1625 |
+
|
1626 |
+
base_output_states = base_output_states + (h_base,)
|
1627 |
+
ctrl_output_states = ctrl_output_states + (h_ctrl,)
|
1628 |
+
|
1629 |
+
if self.base_downsamplers is not None: # if we have a base_downsampler, then also a ctrl_downsampler
|
1630 |
+
b2c = self.base_to_ctrl[-1]
|
1631 |
+
c2b = self.ctrl_to_base[-1]
|
1632 |
+
|
1633 |
+
# concat base -> ctrl
|
1634 |
+
if apply_control:
|
1635 |
+
h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
|
1636 |
+
# apply base subblock
|
1637 |
+
h_base = self.base_downsamplers(h_base)
|
1638 |
+
# apply ctrl subblock
|
1639 |
+
if apply_control:
|
1640 |
+
h_ctrl = self.ctrl_downsamplers(h_ctrl)
|
1641 |
+
# add ctrl -> base
|
1642 |
+
if apply_control:
|
1643 |
+
h_base = h_base + c2b(h_ctrl) * conditioning_scale
|
1644 |
+
|
1645 |
+
base_output_states = base_output_states + (h_base,)
|
1646 |
+
ctrl_output_states = ctrl_output_states + (h_ctrl,)
|
1647 |
+
|
1648 |
+
return h_base, h_ctrl, base_output_states, ctrl_output_states
|
1649 |
+
|
1650 |
+
|
1651 |
+
class ControlNetXSCrossAttnMidBlock2D(nn.Module):
|
1652 |
+
def __init__(
|
1653 |
+
self,
|
1654 |
+
base_channels: int,
|
1655 |
+
ctrl_channels: int,
|
1656 |
+
temb_channels: Optional[int] = None,
|
1657 |
+
norm_num_groups: int = 32,
|
1658 |
+
ctrl_max_norm_num_groups: int = 32,
|
1659 |
+
transformer_layers_per_block: int = 1,
|
1660 |
+
base_num_attention_heads: Optional[int] = 1,
|
1661 |
+
ctrl_num_attention_heads: Optional[int] = 1,
|
1662 |
+
cross_attention_dim: Optional[int] = 1024,
|
1663 |
+
upcast_attention: bool = False,
|
1664 |
+
):
|
1665 |
+
super().__init__()
|
1666 |
+
|
1667 |
+
# Before the midblock application, information is concatted from base to control.
|
1668 |
+
# Concat doesn't require change in number of channels
|
1669 |
+
self.base_to_ctrl = make_zero_conv(base_channels, base_channels)
|
1670 |
+
|
1671 |
+
self.base_midblock = UNetMidBlock2DCrossAttn(
|
1672 |
+
transformer_layers_per_block=transformer_layers_per_block,
|
1673 |
+
in_channels=base_channels,
|
1674 |
+
temb_channels=temb_channels,
|
1675 |
+
resnet_groups=norm_num_groups,
|
1676 |
+
cross_attention_dim=cross_attention_dim,
|
1677 |
+
num_attention_heads=base_num_attention_heads,
|
1678 |
+
use_linear_projection=True,
|
1679 |
+
upcast_attention=upcast_attention,
|
1680 |
+
)
|
1681 |
+
|
1682 |
+
self.ctrl_midblock = UNetMidBlock2DCrossAttn(
|
1683 |
+
transformer_layers_per_block=transformer_layers_per_block,
|
1684 |
+
in_channels=ctrl_channels + base_channels,
|
1685 |
+
out_channels=ctrl_channels,
|
1686 |
+
temb_channels=temb_channels,
|
1687 |
+
# number or norm groups must divide both in_channels and out_channels
|
1688 |
+
resnet_groups=find_largest_factor(
|
1689 |
+
gcd(ctrl_channels, ctrl_channels + base_channels), ctrl_max_norm_num_groups
|
1690 |
+
),
|
1691 |
+
cross_attention_dim=cross_attention_dim,
|
1692 |
+
num_attention_heads=ctrl_num_attention_heads,
|
1693 |
+
use_linear_projection=True,
|
1694 |
+
upcast_attention=upcast_attention,
|
1695 |
+
)
|
1696 |
+
|
1697 |
+
# After the midblock application, information is added from control to base
|
1698 |
+
# Addition requires change in number of channels
|
1699 |
+
self.ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
|
1700 |
+
|
1701 |
+
self.gradient_checkpointing = False
|
1702 |
+
|
1703 |
+
@classmethod
|
1704 |
+
def from_modules(
|
1705 |
+
cls,
|
1706 |
+
base_midblock: UNetMidBlock2DCrossAttn,
|
1707 |
+
ctrl_midblock: MidBlockControlNetXSAdapter,
|
1708 |
+
):
|
1709 |
+
base_to_ctrl = ctrl_midblock.base_to_ctrl
|
1710 |
+
ctrl_to_base = ctrl_midblock.ctrl_to_base
|
1711 |
+
ctrl_midblock = ctrl_midblock.midblock
|
1712 |
+
|
1713 |
+
# get params
|
1714 |
+
def get_first_cross_attention(midblock):
|
1715 |
+
return midblock.attentions[0].transformer_blocks[0].attn2
|
1716 |
+
|
1717 |
+
base_channels = ctrl_to_base.out_channels
|
1718 |
+
ctrl_channels = ctrl_to_base.in_channels
|
1719 |
+
transformer_layers_per_block = len(base_midblock.attentions[0].transformer_blocks)
|
1720 |
+
temb_channels = base_midblock.resnets[0].time_emb_proj.in_features
|
1721 |
+
num_groups = base_midblock.resnets[0].norm1.num_groups
|
1722 |
+
ctrl_num_groups = ctrl_midblock.resnets[0].norm1.num_groups
|
1723 |
+
base_num_attention_heads = get_first_cross_attention(base_midblock).heads
|
1724 |
+
ctrl_num_attention_heads = get_first_cross_attention(ctrl_midblock).heads
|
1725 |
+
cross_attention_dim = get_first_cross_attention(base_midblock).cross_attention_dim
|
1726 |
+
upcast_attention = get_first_cross_attention(base_midblock).upcast_attention
|
1727 |
+
|
1728 |
+
# create model
|
1729 |
+
model = cls(
|
1730 |
+
base_channels=base_channels,
|
1731 |
+
ctrl_channels=ctrl_channels,
|
1732 |
+
temb_channels=temb_channels,
|
1733 |
+
norm_num_groups=num_groups,
|
1734 |
+
ctrl_max_norm_num_groups=ctrl_num_groups,
|
1735 |
+
transformer_layers_per_block=transformer_layers_per_block,
|
1736 |
+
base_num_attention_heads=base_num_attention_heads,
|
1737 |
+
ctrl_num_attention_heads=ctrl_num_attention_heads,
|
1738 |
+
cross_attention_dim=cross_attention_dim,
|
1739 |
+
upcast_attention=upcast_attention,
|
1740 |
+
)
|
1741 |
+
|
1742 |
+
# load weights
|
1743 |
+
model.base_to_ctrl.load_state_dict(base_to_ctrl.state_dict())
|
1744 |
+
model.base_midblock.load_state_dict(base_midblock.state_dict())
|
1745 |
+
model.ctrl_midblock.load_state_dict(ctrl_midblock.state_dict())
|
1746 |
+
model.ctrl_to_base.load_state_dict(ctrl_to_base.state_dict())
|
1747 |
+
|
1748 |
+
return model
|
1749 |
+
|
1750 |
+
def freeze_base_params(self) -> None:
|
1751 |
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
1752 |
+
tuning."""
|
1753 |
+
# Unfreeze everything
|
1754 |
+
for param in self.parameters():
|
1755 |
+
param.requires_grad = True
|
1756 |
+
|
1757 |
+
# Freeze base part
|
1758 |
+
for param in self.base_midblock.parameters():
|
1759 |
+
param.requires_grad = False
|
1760 |
+
|
1761 |
+
def forward(
|
1762 |
+
self,
|
1763 |
+
hidden_states_base: Tensor,
|
1764 |
+
temb: Tensor,
|
1765 |
+
unet_encoder_hidden_states: Optional[Tensor] = None,
|
1766 |
+
cnxs_encoder_hidden_states: Optional[Tensor] = None,
|
1767 |
+
hidden_states_ctrl: Optional[Tensor] = None,
|
1768 |
+
conditioning_scale: Optional[float] = 1.0,
|
1769 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1770 |
+
attention_mask: Optional[Tensor] = None,
|
1771 |
+
encoder_attention_mask: Optional[Tensor] = None,
|
1772 |
+
apply_control: bool = True,
|
1773 |
+
) -> Tuple[Tensor, Tensor]:
|
1774 |
+
if cross_attention_kwargs is not None:
|
1775 |
+
if cross_attention_kwargs.get("scale", None) is not None:
|
1776 |
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
1777 |
+
|
1778 |
+
h_base = hidden_states_base
|
1779 |
+
h_ctrl = hidden_states_ctrl
|
1780 |
+
|
1781 |
+
# joint_args = {
|
1782 |
+
# "temb": temb,
|
1783 |
+
# "encoder_hidden_states": encoder_hidden_states,
|
1784 |
+
# "attention_mask": attention_mask,
|
1785 |
+
# "cross_attention_kwargs": cross_attention_kwargs,
|
1786 |
+
# "encoder_attention_mask": encoder_attention_mask,
|
1787 |
+
# }
|
1788 |
+
unet_joint_args = {
|
1789 |
+
"temb": temb,
|
1790 |
+
"encoder_hidden_states": unet_encoder_hidden_states,
|
1791 |
+
"attention_mask": attention_mask,
|
1792 |
+
"cross_attention_kwargs": cross_attention_kwargs,
|
1793 |
+
"encoder_attention_mask": encoder_attention_mask,
|
1794 |
+
}
|
1795 |
+
|
1796 |
+
cnxs_joint_args = {
|
1797 |
+
"temb": temb,
|
1798 |
+
"encoder_hidden_states": cnxs_encoder_hidden_states,
|
1799 |
+
"attention_mask": attention_mask,
|
1800 |
+
"cross_attention_kwargs": cross_attention_kwargs,
|
1801 |
+
"encoder_attention_mask": encoder_attention_mask,
|
1802 |
+
}
|
1803 |
+
|
1804 |
+
if apply_control:
|
1805 |
+
h_ctrl = torch.cat([h_ctrl, self.base_to_ctrl(h_base)], dim=1) # concat base -> ctrl
|
1806 |
+
h_base = self.base_midblock(h_base, **unet_joint_args) # apply base mid block
|
1807 |
+
if apply_control:
|
1808 |
+
h_ctrl = self.ctrl_midblock(h_ctrl, **cnxs_joint_args) # apply ctrl mid block
|
1809 |
+
h_base = h_base + self.ctrl_to_base(h_ctrl) * conditioning_scale # add ctrl -> base
|
1810 |
+
|
1811 |
+
return h_base, h_ctrl
|
1812 |
+
|
1813 |
+
|
1814 |
+
class ControlNetXSCrossAttnUpBlock2D(nn.Module):
|
1815 |
+
def __init__(
|
1816 |
+
self,
|
1817 |
+
in_channels: int,
|
1818 |
+
out_channels: int,
|
1819 |
+
prev_output_channel: int,
|
1820 |
+
ctrl_skip_channels: List[int],
|
1821 |
+
temb_channels: int,
|
1822 |
+
norm_num_groups: int = 32,
|
1823 |
+
resolution_idx: Optional[int] = None,
|
1824 |
+
has_crossattn=True,
|
1825 |
+
transformer_layers_per_block: int = 1,
|
1826 |
+
num_attention_heads: int = 1,
|
1827 |
+
cross_attention_dim: int = 1024,
|
1828 |
+
add_upsample: bool = True,
|
1829 |
+
upcast_attention: bool = False,
|
1830 |
+
):
|
1831 |
+
super().__init__()
|
1832 |
+
resnets = []
|
1833 |
+
attentions = []
|
1834 |
+
ctrl_to_base = []
|
1835 |
+
|
1836 |
+
num_layers = 3 # only support sd + sdxl
|
1837 |
+
|
1838 |
+
self.has_cross_attention = has_crossattn
|
1839 |
+
self.num_attention_heads = num_attention_heads
|
1840 |
+
|
1841 |
+
if isinstance(transformer_layers_per_block, int):
|
1842 |
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
1843 |
+
|
1844 |
+
for i in range(num_layers):
|
1845 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
1846 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
1847 |
+
|
1848 |
+
ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
|
1849 |
+
|
1850 |
+
resnets.append(
|
1851 |
+
ResnetBlock2D(
|
1852 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
1853 |
+
out_channels=out_channels,
|
1854 |
+
temb_channels=temb_channels,
|
1855 |
+
groups=norm_num_groups,
|
1856 |
+
)
|
1857 |
+
)
|
1858 |
+
|
1859 |
+
if has_crossattn:
|
1860 |
+
attentions.append(
|
1861 |
+
Transformer2DModel(
|
1862 |
+
num_attention_heads,
|
1863 |
+
out_channels // num_attention_heads,
|
1864 |
+
in_channels=out_channels,
|
1865 |
+
num_layers=transformer_layers_per_block[i],
|
1866 |
+
cross_attention_dim=cross_attention_dim,
|
1867 |
+
use_linear_projection=True,
|
1868 |
+
upcast_attention=upcast_attention,
|
1869 |
+
norm_num_groups=norm_num_groups,
|
1870 |
+
)
|
1871 |
+
)
|
1872 |
+
|
1873 |
+
self.resnets = nn.ModuleList(resnets)
|
1874 |
+
self.attentions = nn.ModuleList(attentions) if has_crossattn else [None] * num_layers
|
1875 |
+
self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
|
1876 |
+
|
1877 |
+
if add_upsample:
|
1878 |
+
self.upsamplers = Upsample2D(out_channels, use_conv=True, out_channels=out_channels)
|
1879 |
+
else:
|
1880 |
+
self.upsamplers = None
|
1881 |
+
|
1882 |
+
self.gradient_checkpointing = False
|
1883 |
+
self.resolution_idx = resolution_idx
|
1884 |
+
|
1885 |
+
@classmethod
|
1886 |
+
def from_modules(cls, base_upblock: CrossAttnUpBlock2D, ctrl_upblock: UpBlockControlNetXSAdapter):
|
1887 |
+
ctrl_to_base_skip_connections = ctrl_upblock.ctrl_to_base
|
1888 |
+
|
1889 |
+
# get params
|
1890 |
+
def get_first_cross_attention(block):
|
1891 |
+
return block.attentions[0].transformer_blocks[0].attn2
|
1892 |
+
|
1893 |
+
out_channels = base_upblock.resnets[0].out_channels
|
1894 |
+
in_channels = base_upblock.resnets[-1].in_channels - out_channels
|
1895 |
+
prev_output_channels = base_upblock.resnets[0].in_channels - out_channels
|
1896 |
+
ctrl_skip_channelss = [c.in_channels for c in ctrl_to_base_skip_connections]
|
1897 |
+
temb_channels = base_upblock.resnets[0].time_emb_proj.in_features
|
1898 |
+
num_groups = base_upblock.resnets[0].norm1.num_groups
|
1899 |
+
resolution_idx = base_upblock.resolution_idx
|
1900 |
+
if hasattr(base_upblock, "attentions"):
|
1901 |
+
has_crossattn = True
|
1902 |
+
transformer_layers_per_block = len(base_upblock.attentions[0].transformer_blocks)
|
1903 |
+
num_attention_heads = get_first_cross_attention(base_upblock).heads
|
1904 |
+
cross_attention_dim = get_first_cross_attention(base_upblock).cross_attention_dim
|
1905 |
+
upcast_attention = get_first_cross_attention(base_upblock).upcast_attention
|
1906 |
+
else:
|
1907 |
+
has_crossattn = False
|
1908 |
+
transformer_layers_per_block = None
|
1909 |
+
num_attention_heads = None
|
1910 |
+
cross_attention_dim = None
|
1911 |
+
upcast_attention = None
|
1912 |
+
add_upsample = base_upblock.upsamplers is not None
|
1913 |
+
|
1914 |
+
# create model
|
1915 |
+
model = cls(
|
1916 |
+
in_channels=in_channels,
|
1917 |
+
out_channels=out_channels,
|
1918 |
+
prev_output_channel=prev_output_channels,
|
1919 |
+
ctrl_skip_channels=ctrl_skip_channelss,
|
1920 |
+
temb_channels=temb_channels,
|
1921 |
+
norm_num_groups=num_groups,
|
1922 |
+
resolution_idx=resolution_idx,
|
1923 |
+
has_crossattn=has_crossattn,
|
1924 |
+
transformer_layers_per_block=transformer_layers_per_block,
|
1925 |
+
num_attention_heads=num_attention_heads,
|
1926 |
+
cross_attention_dim=cross_attention_dim,
|
1927 |
+
add_upsample=add_upsample,
|
1928 |
+
upcast_attention=upcast_attention,
|
1929 |
+
)
|
1930 |
+
|
1931 |
+
# load weights
|
1932 |
+
model.resnets.load_state_dict(base_upblock.resnets.state_dict())
|
1933 |
+
if has_crossattn:
|
1934 |
+
model.attentions.load_state_dict(base_upblock.attentions.state_dict())
|
1935 |
+
if add_upsample:
|
1936 |
+
model.upsamplers.load_state_dict(base_upblock.upsamplers[0].state_dict())
|
1937 |
+
model.ctrl_to_base.load_state_dict(ctrl_to_base_skip_connections.state_dict())
|
1938 |
+
|
1939 |
+
return model
|
1940 |
+
|
1941 |
+
def freeze_base_params(self) -> None:
|
1942 |
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
1943 |
+
tuning."""
|
1944 |
+
# Unfreeze everything
|
1945 |
+
for param in self.parameters():
|
1946 |
+
param.requires_grad = True
|
1947 |
+
|
1948 |
+
# Freeze base part
|
1949 |
+
base_parts = [self.resnets]
|
1950 |
+
if isinstance(self.attentions, nn.ModuleList): # attentions can be a list of Nones
|
1951 |
+
base_parts.append(self.attentions)
|
1952 |
+
if self.upsamplers is not None:
|
1953 |
+
base_parts.append(self.upsamplers)
|
1954 |
+
for part in base_parts:
|
1955 |
+
for param in part.parameters():
|
1956 |
+
param.requires_grad = False
|
1957 |
+
|
1958 |
+
def forward(
|
1959 |
+
self,
|
1960 |
+
hidden_states: Tensor,
|
1961 |
+
res_hidden_states_tuple_base: Tuple[Tensor, ...],
|
1962 |
+
res_hidden_states_tuple_ctrl: Tuple[Tensor, ...],
|
1963 |
+
temb: Tensor,
|
1964 |
+
encoder_hidden_states: Optional[Tensor] = None,
|
1965 |
+
conditioning_scale: Optional[float] = 1.0,
|
1966 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1967 |
+
attention_mask: Optional[Tensor] = None,
|
1968 |
+
upsample_size: Optional[int] = None,
|
1969 |
+
encoder_attention_mask: Optional[Tensor] = None,
|
1970 |
+
apply_control: bool = True,
|
1971 |
+
) -> Tensor:
|
1972 |
+
if cross_attention_kwargs is not None:
|
1973 |
+
if cross_attention_kwargs.get("scale", None) is not None:
|
1974 |
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
1975 |
+
|
1976 |
+
is_freeu_enabled = (
|
1977 |
+
getattr(self, "s1", None)
|
1978 |
+
and getattr(self, "s2", None)
|
1979 |
+
and getattr(self, "b1", None)
|
1980 |
+
and getattr(self, "b2", None)
|
1981 |
+
)
|
1982 |
+
|
1983 |
+
def create_custom_forward(module, return_dict=None):
|
1984 |
+
def custom_forward(*inputs):
|
1985 |
+
if return_dict is not None:
|
1986 |
+
return module(*inputs, return_dict=return_dict)
|
1987 |
+
else:
|
1988 |
+
return module(*inputs)
|
1989 |
+
|
1990 |
+
return custom_forward
|
1991 |
+
|
1992 |
+
def maybe_apply_freeu_to_subblock(hidden_states, res_h_base):
|
1993 |
+
# FreeU: Only operate on the first two stages
|
1994 |
+
if is_freeu_enabled:
|
1995 |
+
return apply_freeu(
|
1996 |
+
self.resolution_idx,
|
1997 |
+
hidden_states,
|
1998 |
+
res_h_base,
|
1999 |
+
s1=self.s1,
|
2000 |
+
s2=self.s2,
|
2001 |
+
b1=self.b1,
|
2002 |
+
b2=self.b2,
|
2003 |
+
)
|
2004 |
+
else:
|
2005 |
+
return hidden_states, res_h_base
|
2006 |
+
|
2007 |
+
for resnet, attn, c2b, res_h_base, res_h_ctrl in zip(
|
2008 |
+
self.resnets,
|
2009 |
+
self.attentions,
|
2010 |
+
self.ctrl_to_base,
|
2011 |
+
reversed(res_hidden_states_tuple_base),
|
2012 |
+
reversed(res_hidden_states_tuple_ctrl),
|
2013 |
+
):
|
2014 |
+
if apply_control:
|
2015 |
+
# print('up:', hidden_states.shape, res_h_ctrl.shape)
|
2016 |
+
hidden_states += c2b(res_h_ctrl) * conditioning_scale
|
2017 |
+
|
2018 |
+
hidden_states, res_h_base = maybe_apply_freeu_to_subblock(hidden_states, res_h_base)
|
2019 |
+
hidden_states = torch.cat([hidden_states, res_h_base], dim=1)
|
2020 |
+
|
2021 |
+
if self.training and self.gradient_checkpointing:
|
2022 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
2023 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
2024 |
+
create_custom_forward(resnet),
|
2025 |
+
hidden_states,
|
2026 |
+
temb,
|
2027 |
+
**ckpt_kwargs,
|
2028 |
+
)
|
2029 |
+
else:
|
2030 |
+
hidden_states = resnet(hidden_states, temb)
|
2031 |
+
|
2032 |
+
if attn is not None:
|
2033 |
+
hidden_states = attn(
|
2034 |
+
hidden_states,
|
2035 |
+
encoder_hidden_states=encoder_hidden_states,
|
2036 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
2037 |
+
attention_mask=attention_mask,
|
2038 |
+
encoder_attention_mask=encoder_attention_mask,
|
2039 |
+
return_dict=False,
|
2040 |
+
)[0]
|
2041 |
+
|
2042 |
+
if self.upsamplers is not None:
|
2043 |
+
hidden_states = self.upsamplers(hidden_states, upsample_size)
|
2044 |
+
|
2045 |
+
return hidden_states
|
2046 |
+
|
2047 |
+
|
2048 |
+
def make_zero_conv(in_channels, out_channels=None):
|
2049 |
+
return zero_module(nn.Conv2d(in_channels, out_channels, 1, padding=0))
|
2050 |
+
|
2051 |
+
|
2052 |
+
def zero_module(module):
|
2053 |
+
for p in module.parameters():
|
2054 |
+
nn.init.zeros_(p)
|
2055 |
+
return module
|
2056 |
+
|
2057 |
+
|
2058 |
+
def find_largest_factor(number, max_factor):
|
2059 |
+
factor = max_factor
|
2060 |
+
if factor >= number:
|
2061 |
+
return number
|
2062 |
+
while factor != 0:
|
2063 |
+
residual = number % factor
|
2064 |
+
if residual == 0:
|
2065 |
+
return factor
|
2066 |
+
factor -= 1
|
utils/modules.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from diffusers.models.unets.unet_2d_blocks import *
|
3 |
+
|
4 |
+
class UNetMidBlock2DCrossAttn(nn.Module):
|
5 |
+
def __init__(
|
6 |
+
self,
|
7 |
+
in_channels: int,
|
8 |
+
temb_channels: int,
|
9 |
+
out_channels: Optional[int] = None,
|
10 |
+
dropout: float = 0.0,
|
11 |
+
num_layers: int = 1,
|
12 |
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
13 |
+
resnet_eps: float = 1e-6,
|
14 |
+
resnet_time_scale_shift: str = "default",
|
15 |
+
resnet_act_fn: str = "swish",
|
16 |
+
resnet_groups: int = 32,
|
17 |
+
resnet_groups_out: Optional[int] = None,
|
18 |
+
resnet_pre_norm: bool = True,
|
19 |
+
num_attention_heads: int = 1,
|
20 |
+
output_scale_factor: float = 1.0,
|
21 |
+
cross_attention_dim: int = 1280,
|
22 |
+
dual_cross_attention: bool = False,
|
23 |
+
use_linear_projection: bool = False,
|
24 |
+
upcast_attention: bool = False,
|
25 |
+
attention_type: str = "default",
|
26 |
+
):
|
27 |
+
super().__init__()
|
28 |
+
|
29 |
+
out_channels = out_channels or in_channels
|
30 |
+
self.in_channels = in_channels
|
31 |
+
self.out_channels = out_channels
|
32 |
+
|
33 |
+
self.has_cross_attention = True
|
34 |
+
self.num_attention_heads = num_attention_heads
|
35 |
+
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
|
36 |
+
|
37 |
+
# support for variable transformer layers per block
|
38 |
+
if isinstance(transformer_layers_per_block, int):
|
39 |
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
40 |
+
|
41 |
+
resnet_groups_out = resnet_groups_out or resnet_groups
|
42 |
+
|
43 |
+
# there is always at least one resnet
|
44 |
+
resnets = [
|
45 |
+
ResnetBlock2D(
|
46 |
+
in_channels=in_channels,
|
47 |
+
out_channels=out_channels,
|
48 |
+
temb_channels=temb_channels,
|
49 |
+
eps=resnet_eps,
|
50 |
+
groups=resnet_groups,
|
51 |
+
groups_out=resnet_groups_out,
|
52 |
+
dropout=dropout,
|
53 |
+
time_embedding_norm=resnet_time_scale_shift,
|
54 |
+
non_linearity=resnet_act_fn,
|
55 |
+
output_scale_factor=output_scale_factor,
|
56 |
+
pre_norm=resnet_pre_norm,
|
57 |
+
)
|
58 |
+
]
|
59 |
+
attentions = []
|
60 |
+
|
61 |
+
for i in range(num_layers):
|
62 |
+
if not dual_cross_attention:
|
63 |
+
attentions.append(
|
64 |
+
Transformer2DModel(
|
65 |
+
num_attention_heads,
|
66 |
+
out_channels // num_attention_heads,
|
67 |
+
in_channels=out_channels,
|
68 |
+
num_layers=transformer_layers_per_block[i],
|
69 |
+
cross_attention_dim=cross_attention_dim,
|
70 |
+
norm_num_groups=resnet_groups_out,
|
71 |
+
use_linear_projection=use_linear_projection,
|
72 |
+
upcast_attention=upcast_attention,
|
73 |
+
attention_type=attention_type,
|
74 |
+
)
|
75 |
+
)
|
76 |
+
else:
|
77 |
+
attentions.append(
|
78 |
+
DualTransformer2DModel(
|
79 |
+
num_attention_heads,
|
80 |
+
out_channels // num_attention_heads,
|
81 |
+
in_channels=out_channels,
|
82 |
+
num_layers=1,
|
83 |
+
cross_attention_dim=cross_attention_dim,
|
84 |
+
norm_num_groups=resnet_groups,
|
85 |
+
)
|
86 |
+
)
|
87 |
+
resnets.append(
|
88 |
+
ResnetBlock2D(
|
89 |
+
in_channels=out_channels,
|
90 |
+
out_channels=out_channels,
|
91 |
+
temb_channels=temb_channels,
|
92 |
+
eps=resnet_eps,
|
93 |
+
groups=resnet_groups_out,
|
94 |
+
dropout=dropout,
|
95 |
+
time_embedding_norm=resnet_time_scale_shift,
|
96 |
+
non_linearity=resnet_act_fn,
|
97 |
+
output_scale_factor=output_scale_factor,
|
98 |
+
pre_norm=resnet_pre_norm,
|
99 |
+
)
|
100 |
+
)
|
101 |
+
|
102 |
+
self.attentions = nn.ModuleList(attentions)
|
103 |
+
self.resnets = nn.ModuleList(resnets)
|
104 |
+
|
105 |
+
self.gradient_checkpointing = False
|
106 |
+
|
107 |
+
def forward(
|
108 |
+
self,
|
109 |
+
hidden_states: torch.Tensor,
|
110 |
+
temb: Optional[torch.Tensor] = None,
|
111 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
112 |
+
attention_mask: Optional[torch.Tensor] = None,
|
113 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
114 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
115 |
+
) -> torch.Tensor:
|
116 |
+
if cross_attention_kwargs is not None:
|
117 |
+
if cross_attention_kwargs.get("scale", None) is not None:
|
118 |
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
119 |
+
|
120 |
+
hidden_states = self.resnets[0](hidden_states, temb)
|
121 |
+
for attn, resnet in zip(self.attentions, self.resnets[1:]):
|
122 |
+
if self.training and self.gradient_checkpointing:
|
123 |
+
|
124 |
+
def create_custom_forward(module, return_dict=None):
|
125 |
+
def custom_forward(*inputs):
|
126 |
+
if return_dict is not None:
|
127 |
+
return module(*inputs, return_dict=return_dict)
|
128 |
+
else:
|
129 |
+
return module(*inputs)
|
130 |
+
|
131 |
+
return custom_forward
|
132 |
+
|
133 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
134 |
+
hidden_states = attn(
|
135 |
+
hidden_states,
|
136 |
+
encoder_hidden_states=encoder_hidden_states,
|
137 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
138 |
+
attention_mask=attention_mask,
|
139 |
+
encoder_attention_mask=encoder_attention_mask,
|
140 |
+
return_dict=False,
|
141 |
+
)[0]
|
142 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
143 |
+
create_custom_forward(resnet),
|
144 |
+
hidden_states,
|
145 |
+
temb,
|
146 |
+
**ckpt_kwargs,
|
147 |
+
)
|
148 |
+
else:
|
149 |
+
hidden_states = attn(
|
150 |
+
hidden_states,
|
151 |
+
encoder_hidden_states=encoder_hidden_states,
|
152 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
153 |
+
attention_mask=attention_mask,
|
154 |
+
encoder_attention_mask=encoder_attention_mask,
|
155 |
+
return_dict=False,
|
156 |
+
)[0]
|
157 |
+
hidden_states = resnet(hidden_states, temb)
|
158 |
+
|
159 |
+
return hidden_states
|
utils/resampler.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
|
2 |
+
# and https://github.com/lucidrains/imagen-pytorch/blob/main/imagen_pytorch/imagen_pytorch.py
|
3 |
+
|
4 |
+
import math
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn as nn
|
8 |
+
from einops import rearrange
|
9 |
+
from einops.layers.torch import Rearrange
|
10 |
+
|
11 |
+
|
12 |
+
# FFN
|
13 |
+
def FeedForward(dim, mult=4):
|
14 |
+
inner_dim = int(dim * mult)
|
15 |
+
return nn.Sequential(
|
16 |
+
nn.LayerNorm(dim),
|
17 |
+
nn.Linear(dim, inner_dim, bias=False),
|
18 |
+
nn.GELU(),
|
19 |
+
nn.Linear(inner_dim, dim, bias=False),
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
def reshape_tensor(x, heads):
|
24 |
+
bs, length, width = x.shape
|
25 |
+
# (bs, length, width) --> (bs, length, n_heads, dim_per_head)
|
26 |
+
x = x.view(bs, length, heads, -1)
|
27 |
+
# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
|
28 |
+
x = x.transpose(1, 2)
|
29 |
+
# (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
|
30 |
+
x = x.reshape(bs, heads, length, -1)
|
31 |
+
return x
|
32 |
+
|
33 |
+
|
34 |
+
class PerceiverAttention(nn.Module):
|
35 |
+
def __init__(self, *, dim, dim_head=64, heads=8):
|
36 |
+
super().__init__()
|
37 |
+
self.scale = dim_head**-0.5
|
38 |
+
self.dim_head = dim_head
|
39 |
+
self.heads = heads
|
40 |
+
inner_dim = dim_head * heads
|
41 |
+
|
42 |
+
self.norm1 = nn.LayerNorm(dim)
|
43 |
+
self.norm2 = nn.LayerNorm(dim)
|
44 |
+
|
45 |
+
self.to_q = nn.Linear(dim, inner_dim, bias=False)
|
46 |
+
self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
|
47 |
+
self.to_out = nn.Linear(inner_dim, dim, bias=False)
|
48 |
+
|
49 |
+
def forward(self, x, latents):
|
50 |
+
"""
|
51 |
+
Args:
|
52 |
+
x (torch.Tensor): image features
|
53 |
+
shape (b, n1, D)
|
54 |
+
latent (torch.Tensor): latent features
|
55 |
+
shape (b, n2, D)
|
56 |
+
"""
|
57 |
+
x = self.norm1(x)
|
58 |
+
latents = self.norm2(latents)
|
59 |
+
|
60 |
+
b, l, _ = latents.shape
|
61 |
+
|
62 |
+
q = self.to_q(latents)
|
63 |
+
kv_input = torch.cat((x, latents), dim=-2)
|
64 |
+
k, v = self.to_kv(kv_input).chunk(2, dim=-1)
|
65 |
+
|
66 |
+
q = reshape_tensor(q, self.heads)
|
67 |
+
k = reshape_tensor(k, self.heads)
|
68 |
+
v = reshape_tensor(v, self.heads)
|
69 |
+
|
70 |
+
# attention
|
71 |
+
scale = 1 / math.sqrt(math.sqrt(self.dim_head))
|
72 |
+
weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
|
73 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
74 |
+
out = weight @ v
|
75 |
+
|
76 |
+
out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
|
77 |
+
|
78 |
+
return self.to_out(out)
|
79 |
+
|
80 |
+
|
81 |
+
class Resampler(nn.Module):
|
82 |
+
def __init__(
|
83 |
+
self,
|
84 |
+
dim=1280,
|
85 |
+
depth=4,
|
86 |
+
dim_head=64,
|
87 |
+
heads=20,
|
88 |
+
num_queries=16,
|
89 |
+
embedding_dim=512,
|
90 |
+
output_dim=2048,
|
91 |
+
ff_mult=4,
|
92 |
+
max_seq_len: int = 257, # CLIP tokens + CLS token
|
93 |
+
apply_pos_emb: bool = False,
|
94 |
+
num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence
|
95 |
+
):
|
96 |
+
super().__init__()
|
97 |
+
# self.pos_emb = nn.Embedding(max_seq_len, embedding_dim) if apply_pos_emb else None
|
98 |
+
|
99 |
+
self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
|
100 |
+
|
101 |
+
self.proj_in = nn.Linear(embedding_dim, dim)
|
102 |
+
self.proj_out = nn.Linear(dim, output_dim)
|
103 |
+
self.norm_out = nn.LayerNorm(output_dim)
|
104 |
+
|
105 |
+
# self.to_latents_from_mean_pooled_seq = (
|
106 |
+
# nn.Sequential(
|
107 |
+
# nn.LayerNorm(dim),
|
108 |
+
# nn.Linear(dim, dim * num_latents_mean_pooled),
|
109 |
+
# Rearrange("b (n d) -> b n d", n=num_latents_mean_pooled),
|
110 |
+
# )
|
111 |
+
# if num_latents_mean_pooled > 0
|
112 |
+
# else None
|
113 |
+
# )
|
114 |
+
|
115 |
+
self.layers = nn.ModuleList([])
|
116 |
+
for _ in range(depth):
|
117 |
+
self.layers.append(
|
118 |
+
nn.ModuleList(
|
119 |
+
[
|
120 |
+
PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
|
121 |
+
FeedForward(dim=dim, mult=ff_mult),
|
122 |
+
]
|
123 |
+
)
|
124 |
+
)
|
125 |
+
|
126 |
+
def forward(self, x):
|
127 |
+
# if self.pos_emb is not None:
|
128 |
+
# n, device = x.shape[1], x.device
|
129 |
+
# pos_emb = self.pos_emb(torch.arange(n, device=device))
|
130 |
+
# x = x + pos_emb
|
131 |
+
|
132 |
+
latents = self.latents.repeat(x.size(0), 1, 1)
|
133 |
+
|
134 |
+
# print(self.latents.size(), x.size(), latents.size())
|
135 |
+
|
136 |
+
x = self.proj_in(x)
|
137 |
+
|
138 |
+
# if self.to_latents_from_mean_pooled_seq:
|
139 |
+
# meanpooled_seq = masked_mean(x, dim=1, mask=torch.ones(x.shape[:2], device=x.device, dtype=torch.bool))
|
140 |
+
# meanpooled_latents = self.to_latents_from_mean_pooled_seq(meanpooled_seq)
|
141 |
+
# latents = torch.cat((meanpooled_latents, latents), dim=-2)
|
142 |
+
|
143 |
+
for attn, ff in self.layers:
|
144 |
+
latents = attn(x, latents) + latents
|
145 |
+
latents = ff(latents) + latents
|
146 |
+
|
147 |
+
latents = self.proj_out(latents)
|
148 |
+
return self.norm_out(latents)
|
149 |
+
|
150 |
+
|
151 |
+
def masked_mean(t, *, dim, mask=None):
|
152 |
+
if mask is None:
|
153 |
+
return t.mean(dim=dim)
|
154 |
+
|
155 |
+
denom = mask.sum(dim=dim, keepdim=True)
|
156 |
+
mask = rearrange(mask, "b n -> b n 1")
|
157 |
+
masked_t = t.masked_fill(~mask, 0.0)
|
158 |
+
|
159 |
+
return masked_t.sum(dim=dim) / denom.clamp(min=1e-5)
|
utils/resize.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
import PIL
|
3 |
+
import cv2, math,os
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
# 最短边为1024,并进行中心裁剪
|
7 |
+
def resize_image_pil(input_image, min_side=1024):
|
8 |
+
|
9 |
+
# 获取图像的宽度和高度
|
10 |
+
width, height = input_image.size
|
11 |
+
|
12 |
+
# 计算缩放比例
|
13 |
+
scale = min_side / min(height, width)
|
14 |
+
|
15 |
+
# 计算新的尺寸
|
16 |
+
new_width = int(width * scale)
|
17 |
+
new_height = int(height * scale)
|
18 |
+
|
19 |
+
# 调整图像大小
|
20 |
+
resized_image = input_image.resize((new_width, new_height), Image.ANTIALIAS)
|
21 |
+
|
22 |
+
# 计算中心裁剪的位置
|
23 |
+
crop_top = (new_height - min_side) // 2
|
24 |
+
crop_left = (new_width - min_side) // 2
|
25 |
+
|
26 |
+
# 进行中心裁剪
|
27 |
+
cropped_image = resized_image.crop((crop_left, crop_top, crop_left + min_side, crop_top + min_side))
|
28 |
+
|
29 |
+
return cropped_image
|
30 |
+
|
31 |
+
def resize_image_cv2(input_image, min_side=1024, ):
|
32 |
+
# cv2读取的image
|
33 |
+
(height, width, _ )= input_image.shape
|
34 |
+
# print(height, width)
|
35 |
+
scale = min_side / min(height, width)
|
36 |
+
|
37 |
+
# 计算新的尺寸
|
38 |
+
new_width = int(width * scale)
|
39 |
+
new_height = int(height * scale)
|
40 |
+
input_image =cv2.resize(input_image, (new_width, new_height))
|
41 |
+
|
42 |
+
# 计算中心裁剪的位置
|
43 |
+
crop_top = (new_height - min_side) // 2
|
44 |
+
crop_left = (new_width - min_side) // 2
|
45 |
+
|
46 |
+
# 进行中心裁剪
|
47 |
+
image = input_image[crop_top:crop_top + min_side, crop_left:crop_left + min_side]
|
48 |
+
|
49 |
+
return image
|
50 |
+
|
51 |
+
|
52 |
+
def resize_img0(input_image, max_side=1280, min_side=1024,
|
53 |
+
mode=Image.BILINEAR, base_pixel_number=64):
|
54 |
+
|
55 |
+
w, h = input_image.size
|
56 |
+
|
57 |
+
ratio = min_side / min(h, w)
|
58 |
+
w, h = round(ratio*w), round(ratio*h)
|
59 |
+
ratio = max_side / max(h, w)
|
60 |
+
input_image = input_image.resize([round(ratio*w), round(ratio*h)], mode)
|
61 |
+
w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number
|
62 |
+
h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number
|
63 |
+
|
64 |
+
input_image = input_image.resize([w_resize_new, h_resize_new], mode)
|
65 |
+
|
66 |
+
|
67 |
+
return input_image
|
68 |
+
|
69 |
+
def resize_img1(input_image, max_side=1280, min_side=1024,
|
70 |
+
mode=Image.BILINEAR, base_pixel_number=64):
|
71 |
+
|
72 |
+
w, h = input_image.size
|
73 |
+
|
74 |
+
ratio = min_side / w
|
75 |
+
w, h = round(ratio*w), round(ratio*h)
|
76 |
+
input_image = input_image.resize([w, h], mode)
|
77 |
+
|
78 |
+
w_resize_new = (w // base_pixel_number) * base_pixel_number
|
79 |
+
h_resize_new = (h // base_pixel_number) * base_pixel_number
|
80 |
+
|
81 |
+
input_image = input_image.resize([w_resize_new, h_resize_new], mode)
|
82 |
+
|
83 |
+
|
84 |
+
return input_image
|
85 |
+
|
86 |
+
|
87 |
+
def resize_img(input_image, max_side=1024, min_side=1024, size=None,
|
88 |
+
pad_to_max_side=False, mode=Image.BILINEAR, base_pixel_number=64):
|
89 |
+
w, h = input_image.size
|
90 |
+
if size is not None:
|
91 |
+
w_resize_new, h_resize_new = size
|
92 |
+
else:
|
93 |
+
ratio = min_side / min(h, w)
|
94 |
+
w, h = round(ratio * w), round(ratio * h)
|
95 |
+
ratio = max_side / max(h, w)
|
96 |
+
input_image = input_image.resize([round(ratio * w), round(ratio * h)], mode)
|
97 |
+
w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number
|
98 |
+
h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number
|
99 |
+
input_image = input_image.resize([w_resize_new, h_resize_new], mode)
|
100 |
+
|
101 |
+
if pad_to_max_side:
|
102 |
+
res = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255
|
103 |
+
offset_x = (max_side - w_resize_new) // 2
|
104 |
+
offset_y = (max_side - h_resize_new) // 2
|
105 |
+
res[offset_y:offset_y + h_resize_new, offset_x:offset_x + w_resize_new] = np.array(input_image)[:, :, :3]
|
106 |
+
input_image = Image.fromarray(res)
|
107 |
+
return input_image
|
utils/tools.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, json
|
2 |
+
import cv2
|
3 |
+
import glob
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
import torch
|
7 |
+
|
8 |
+
def im_resize(original_image, short_len=1024):
|
9 |
+
h, w = original_image.shape[:-1]
|
10 |
+
if min(h, w) != short_len:
|
11 |
+
if h > w:
|
12 |
+
out_size = (short_len, int(h/w*short_len))
|
13 |
+
else:
|
14 |
+
out_size = (int(w/h*short_len), short_len)
|
15 |
+
else:
|
16 |
+
out_size = w, h
|
17 |
+
|
18 |
+
return cv2.resize(original_image, out_size)
|
19 |
+
|
20 |
+
def pixelize(image, block_size=64):
|
21 |
+
# 获取图像的宽度和高度
|
22 |
+
height, width, _ = image.shape
|
23 |
+
|
24 |
+
# 计算新图像的宽度和高度,使得每个块为 block_size x block_size 的大小
|
25 |
+
new_width = (width // block_size) * block_size
|
26 |
+
new_height = (height // block_size) * block_size
|
27 |
+
|
28 |
+
# 缩放图像以匹配新的宽度和高度
|
29 |
+
resized_image = cv2.resize(image, (new_width, new_height))
|
30 |
+
|
31 |
+
# 将图像分割成块并用块的平均值替代
|
32 |
+
for i in range(0, new_height, block_size):
|
33 |
+
for j in range(0, new_width, block_size):
|
34 |
+
block = resized_image[i:i+block_size, j:j+block_size, :]
|
35 |
+
average_color = np.mean(block, axis=(0, 1), dtype=int)
|
36 |
+
resized_image[i:i+block_size, j:j+block_size, :] = average_color
|
37 |
+
|
38 |
+
# 将图像缩小回原始大小,以增加像素风格的效果
|
39 |
+
final_image = cv2.resize(resized_image, (width, height))
|
40 |
+
|
41 |
+
return final_image
|
42 |
+
|
43 |
+
def get_kps_bbox_faceid(w, h, json_path):
|
44 |
+
def get_new_kps_and_bbox(w, h, kps, bbox):
|
45 |
+
scale = 512/max(w, h)
|
46 |
+
pad = abs(w - h) * scale / 2
|
47 |
+
if w < h:
|
48 |
+
kps[:, 0] -= pad
|
49 |
+
bbox[0] -= pad
|
50 |
+
bbox[2] -= pad
|
51 |
+
elif h < w:
|
52 |
+
kps[:, 1] -= pad
|
53 |
+
bbox[1] -= pad
|
54 |
+
bbox[3] -= pad
|
55 |
+
kps /= scale
|
56 |
+
bbox /= scale
|
57 |
+
return kps, bbox
|
58 |
+
|
59 |
+
with open(json_path, 'r') as file:
|
60 |
+
data = json.load(file)
|
61 |
+
kps = np.array(data.get("kps"))
|
62 |
+
bbox = np.array(data.get("bbox"))
|
63 |
+
kps, bbox = get_new_kps_and_bbox(w, h, kps, bbox)
|
64 |
+
embedding = data.get("embedding")
|
65 |
+
face_id_embed = embedding / np.linalg.norm(embedding)
|
66 |
+
face_id_embed = torch.from_numpy(face_id_embed)
|
67 |
+
return kps, bbox, face_id_embed
|
68 |
+
|
69 |
+
def get_kps_and_face_id_embed(w, h, json_path):
|
70 |
+
def get_new_kps(w, h, kps):
|
71 |
+
scale = 512/max(w, h)
|
72 |
+
pad = abs(w - h) * scale / 2
|
73 |
+
if w < h:
|
74 |
+
kps[:, 0] -= pad
|
75 |
+
elif h < w:
|
76 |
+
kps[:, 1] -= pad
|
77 |
+
kps = kps / scale
|
78 |
+
return kps
|
79 |
+
|
80 |
+
with open(json_path, 'r') as file:
|
81 |
+
data = json.load(file)
|
82 |
+
kps = np.array(data.get("kps"))
|
83 |
+
kps = get_new_kps(w, h, kps)
|
84 |
+
embedding = data.get("embedding")
|
85 |
+
face_id_embed = embedding / np.linalg.norm(embedding)
|
86 |
+
face_id_embed = torch.from_numpy(face_id_embed)
|
87 |
+
return kps, face_id_embed
|
88 |
+
|
89 |
+
def get_face_id_embed(json_path):
|
90 |
+
|
91 |
+
with open(json_path, 'r') as file:
|
92 |
+
data = json.load(file)
|
93 |
+
embedding = data.get("embedding")
|
94 |
+
face_id_embed = embedding / np.linalg.norm(embedding)
|
95 |
+
face_id_embed = torch.from_numpy(face_id_embed)
|
96 |
+
return face_id_embed
|
97 |
+
|
98 |
+
def get_module_kohya_state_dict(module, prefix: str, dtype: torch.dtype, adapter_name: str = "default"):
|
99 |
+
kohya_ss_state_dict = {}
|
100 |
+
for peft_key, weight in module.items():
|
101 |
+
kohya_key = peft_key.replace("unet.base_model.model", prefix)
|
102 |
+
kohya_key = kohya_key.replace("lora_A", "lora_down")
|
103 |
+
kohya_key = kohya_key.replace("lora_B", "lora_up")
|
104 |
+
kohya_key = kohya_key.replace(".", "_", kohya_key.count(".") - 2)
|
105 |
+
kohya_ss_state_dict[kohya_key] = weight.to(dtype)
|
106 |
+
# Set alpha parameter
|
107 |
+
if "lora_down" in kohya_key:
|
108 |
+
alpha_key = f'{kohya_key.split(".")[0]}.alpha'
|
109 |
+
kohya_ss_state_dict[alpha_key] = torch.tensor(8).to(dtype)
|
110 |
+
|
111 |
+
return kohya_ss_state_dict
|
112 |
+
|
113 |
+
def get_module_kohya_state_dict_xs(module, dtype):
|
114 |
+
kohya_ss_state_dict = {}
|
115 |
+
for peft_key, weight in module.items():
|
116 |
+
if "mid_block" in peft_key:
|
117 |
+
peft_key = peft_key.replace('attentions', 'base_midblock.attentions')
|
118 |
+
elif "down_block" in peft_key:
|
119 |
+
peft_key = peft_key.replace('attentions', 'base_attentions')
|
120 |
+
if dtype == None:
|
121 |
+
kohya_ss_state_dict[peft_key] = weight
|
122 |
+
else:
|
123 |
+
kohya_ss_state_dict[peft_key] = weight.to(dtype)
|
124 |
+
return kohya_ss_state_dict
|
utils/utils.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
attn_maps = {}
|
7 |
+
def hook_fn(name):
|
8 |
+
def forward_hook(module, input, output):
|
9 |
+
if hasattr(module.processor, "attn_map"):
|
10 |
+
attn_maps[name] = module.processor.attn_map
|
11 |
+
del module.processor.attn_map
|
12 |
+
|
13 |
+
return forward_hook
|
14 |
+
|
15 |
+
def register_cross_attention_hook(unet):
|
16 |
+
for name, module in unet.named_modules():
|
17 |
+
if name.split('.')[-1].startswith('attn2'):
|
18 |
+
module.register_forward_hook(hook_fn(name))
|
19 |
+
|
20 |
+
return unet
|
21 |
+
|
22 |
+
def upscale(attn_map, target_size):
|
23 |
+
attn_map = torch.mean(attn_map, dim=0)
|
24 |
+
attn_map = attn_map.permute(1,0)
|
25 |
+
temp_size = None
|
26 |
+
|
27 |
+
for i in range(0,5):
|
28 |
+
scale = 2 ** i
|
29 |
+
if ( target_size[0] // scale ) * ( target_size[1] // scale) == attn_map.shape[1]*64:
|
30 |
+
temp_size = (target_size[0]//(scale*8), target_size[1]//(scale*8))
|
31 |
+
break
|
32 |
+
|
33 |
+
assert temp_size is not None, "temp_size cannot is None"
|
34 |
+
|
35 |
+
attn_map = attn_map.view(attn_map.shape[0], *temp_size)
|
36 |
+
|
37 |
+
attn_map = F.interpolate(
|
38 |
+
attn_map.unsqueeze(0).to(dtype=torch.float32),
|
39 |
+
size=target_size,
|
40 |
+
mode='bilinear',
|
41 |
+
align_corners=False
|
42 |
+
)[0]
|
43 |
+
|
44 |
+
attn_map = torch.softmax(attn_map, dim=0)
|
45 |
+
return attn_map
|
46 |
+
def get_net_attn_map(image_size, batch_size=2, instance_or_negative=False, detach=True):
|
47 |
+
|
48 |
+
idx = 0 if instance_or_negative else 1
|
49 |
+
net_attn_maps = []
|
50 |
+
|
51 |
+
for name, attn_map in attn_maps.items():
|
52 |
+
attn_map = attn_map.cpu() if detach else attn_map
|
53 |
+
attn_map = torch.chunk(attn_map, batch_size)[idx].squeeze()
|
54 |
+
attn_map = upscale(attn_map, image_size)
|
55 |
+
net_attn_maps.append(attn_map)
|
56 |
+
|
57 |
+
net_attn_maps = torch.mean(torch.stack(net_attn_maps,dim=0),dim=0)
|
58 |
+
|
59 |
+
return net_attn_maps
|
60 |
+
|
61 |
+
def attnmaps2images(net_attn_maps):
|
62 |
+
|
63 |
+
#total_attn_scores = 0
|
64 |
+
images = []
|
65 |
+
|
66 |
+
for attn_map in net_attn_maps:
|
67 |
+
attn_map = attn_map.cpu().numpy()
|
68 |
+
#total_attn_scores += attn_map.mean().item()
|
69 |
+
|
70 |
+
normalized_attn_map = (attn_map - np.min(attn_map)) / (np.max(attn_map) - np.min(attn_map)) * 255
|
71 |
+
normalized_attn_map = normalized_attn_map.astype(np.uint8)
|
72 |
+
#print("norm: ", normalized_attn_map.shape)
|
73 |
+
image = Image.fromarray(normalized_attn_map)
|
74 |
+
|
75 |
+
#image = fix_save_attn_map(attn_map)
|
76 |
+
images.append(image)
|
77 |
+
|
78 |
+
#print(total_attn_scores)
|
79 |
+
return images
|
80 |
+
|
81 |
+
def is_torch2_available():
|
82 |
+
return hasattr(F, "scaled_dot_product_attention")
|
83 |
+
|
84 |
+
def get_generator(seed, device):
|
85 |
+
|
86 |
+
if seed is not None:
|
87 |
+
if isinstance(seed, list):
|
88 |
+
generator = [torch.Generator(device).manual_seed(seed_item) for seed_item in seed]
|
89 |
+
else:
|
90 |
+
generator = torch.Generator(device).manual_seed(seed)
|
91 |
+
else:
|
92 |
+
generator = None
|
93 |
+
|
94 |
+
return generator
|