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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Long Lian, the GLIGEN Authors, and 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 |
+
|
15 |
+
# This is a single file implementation of LMD+. See README.md for examples.
|
16 |
+
|
17 |
+
import ast
|
18 |
+
import gc
|
19 |
+
import math
|
20 |
+
import warnings
|
21 |
+
from collections.abc import Iterable
|
22 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
23 |
+
|
24 |
+
import torch
|
25 |
+
import torch.nn.functional as F
|
26 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
27 |
+
|
28 |
+
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
29 |
+
from diffusers.models.attention import Attention, GatedSelfAttentionDense
|
30 |
+
from diffusers.models.attention_processor import AttnProcessor2_0
|
31 |
+
from diffusers.pipelines.stable_diffusion import StableDiffusionPipeline
|
32 |
+
from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
|
33 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
34 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
35 |
+
from diffusers.utils import logging, replace_example_docstring, USE_PEFT_BACKEND
|
36 |
+
|
37 |
+
|
38 |
+
EXAMPLE_DOC_STRING = """
|
39 |
+
Examples:
|
40 |
+
```py
|
41 |
+
>>> import torch
|
42 |
+
>>> from diffusers import DiffusionPipeline
|
43 |
+
|
44 |
+
>>> pipe = DiffusionPipeline.from_pretrained(
|
45 |
+
... "longlian/lmd_plus",
|
46 |
+
... custom_pipeline="llm_grounded_diffusion",
|
47 |
+
... variant="fp16", torch_dtype=torch.float16
|
48 |
+
... )
|
49 |
+
>>> pipe.enable_model_cpu_offload()
|
50 |
+
|
51 |
+
>>> # Generate an image described by the prompt and
|
52 |
+
>>> # insert objects described by text at the region defined by bounding boxes
|
53 |
+
>>> prompt = "a waterfall and a modern high speed train in a beautiful forest with fall foliage"
|
54 |
+
>>> boxes = [[0.1387, 0.2051, 0.4277, 0.7090], [0.4980, 0.4355, 0.8516, 0.7266]]
|
55 |
+
>>> phrases = ["a waterfall", "a modern high speed train"]
|
56 |
+
|
57 |
+
>>> images = pipe(
|
58 |
+
... prompt=prompt,
|
59 |
+
... phrases=phrases,
|
60 |
+
... boxes=boxes,
|
61 |
+
... gligen_scheduled_sampling_beta=0.4,
|
62 |
+
... output_type="pil",
|
63 |
+
... num_inference_steps=50,
|
64 |
+
... lmd_guidance_kwargs={}
|
65 |
+
... ).images
|
66 |
+
|
67 |
+
>>> images[0].save("./lmd_plus_generation.jpg")
|
68 |
+
|
69 |
+
>>> # Generate directly from a text prompt and an LLM response
|
70 |
+
>>> prompt = "a waterfall and a modern high speed train in a beautiful forest with fall foliage"
|
71 |
+
>>> phrases, boxes, bg_prompt, neg_prompt = pipe.parse_llm_response(\"""
|
72 |
+
[('a waterfall', [71, 105, 148, 258]), ('a modern high speed train', [255, 223, 181, 149])]
|
73 |
+
Background prompt: A beautiful forest with fall foliage
|
74 |
+
Negative prompt:
|
75 |
+
\""")
|
76 |
+
|
77 |
+
>> images = pipe(
|
78 |
+
... prompt=prompt,
|
79 |
+
... negative_prompt=neg_prompt,
|
80 |
+
... phrases=phrases,
|
81 |
+
... boxes=boxes,
|
82 |
+
... gligen_scheduled_sampling_beta=0.4,
|
83 |
+
... output_type="pil",
|
84 |
+
... num_inference_steps=50,
|
85 |
+
... lmd_guidance_kwargs={}
|
86 |
+
... ).images
|
87 |
+
|
88 |
+
>>> images[0].save("./lmd_plus_generation.jpg")
|
89 |
+
|
90 |
+
images[0]
|
91 |
+
|
92 |
+
```
|
93 |
+
"""
|
94 |
+
|
95 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
96 |
+
|
97 |
+
# All keys in Stable Diffusion models: [('down', 0, 0, 0), ('down', 0, 1, 0), ('down', 1, 0, 0), ('down', 1, 1, 0), ('down', 2, 0, 0), ('down', 2, 1, 0), ('mid', 0, 0, 0), ('up', 1, 0, 0), ('up', 1, 1, 0), ('up', 1, 2, 0), ('up', 2, 0, 0), ('up', 2, 1, 0), ('up', 2, 2, 0), ('up', 3, 0, 0), ('up', 3, 1, 0), ('up', 3, 2, 0)]
|
98 |
+
# Note that the first up block is `UpBlock2D` rather than `CrossAttnUpBlock2D` and does not have attention. The last index is always 0 in our case since we have one `BasicTransformerBlock` in each `Transformer2DModel`.
|
99 |
+
DEFAULT_GUIDANCE_ATTN_KEYS = [("mid", 0, 0, 0), ("up", 1, 0, 0), ("up", 1, 1, 0), ("up", 1, 2, 0)]
|
100 |
+
|
101 |
+
|
102 |
+
def convert_attn_keys(key):
|
103 |
+
"""Convert the attention key from tuple format to the torch state format"""
|
104 |
+
|
105 |
+
if key[0] == "mid":
|
106 |
+
assert key[1] == 0, f"mid block only has one block but the index is {key[1]}"
|
107 |
+
return f"{key[0]}_block.attentions.{key[2]}.transformer_blocks.{key[3]}.attn2.processor"
|
108 |
+
|
109 |
+
return f"{key[0]}_blocks.{key[1]}.attentions.{key[2]}.transformer_blocks.{key[3]}.attn2.processor"
|
110 |
+
|
111 |
+
|
112 |
+
DEFAULT_GUIDANCE_ATTN_KEYS = [convert_attn_keys(key) for key in DEFAULT_GUIDANCE_ATTN_KEYS]
|
113 |
+
|
114 |
+
|
115 |
+
def scale_proportion(obj_box, H, W):
|
116 |
+
# Separately rounding box_w and box_h to allow shift invariant box sizes. Otherwise box sizes may change when both coordinates being rounded end with ".5".
|
117 |
+
x_min, y_min = round(obj_box[0] * W), round(obj_box[1] * H)
|
118 |
+
box_w, box_h = round((obj_box[2] - obj_box[0]) * W), round((obj_box[3] - obj_box[1]) * H)
|
119 |
+
x_max, y_max = x_min + box_w, y_min + box_h
|
120 |
+
|
121 |
+
x_min, y_min = max(x_min, 0), max(y_min, 0)
|
122 |
+
x_max, y_max = min(x_max, W), min(y_max, H)
|
123 |
+
|
124 |
+
return x_min, y_min, x_max, y_max
|
125 |
+
|
126 |
+
|
127 |
+
# Adapted from the parent class `AttnProcessor2_0`
|
128 |
+
class AttnProcessorWithHook(AttnProcessor2_0):
|
129 |
+
def __init__(self, attn_processor_key, hidden_size, cross_attention_dim, hook=None, fast_attn=True, enabled=True):
|
130 |
+
super().__init__()
|
131 |
+
self.attn_processor_key = attn_processor_key
|
132 |
+
self.hidden_size = hidden_size
|
133 |
+
self.cross_attention_dim = cross_attention_dim
|
134 |
+
self.hook = hook
|
135 |
+
self.fast_attn = fast_attn
|
136 |
+
self.enabled = enabled
|
137 |
+
|
138 |
+
def __call__(
|
139 |
+
self,
|
140 |
+
attn: Attention,
|
141 |
+
hidden_states,
|
142 |
+
encoder_hidden_states=None,
|
143 |
+
attention_mask=None,
|
144 |
+
temb=None,
|
145 |
+
scale: float = 1.0,
|
146 |
+
):
|
147 |
+
residual = hidden_states
|
148 |
+
|
149 |
+
if attn.spatial_norm is not None:
|
150 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
151 |
+
|
152 |
+
input_ndim = hidden_states.ndim
|
153 |
+
|
154 |
+
if input_ndim == 4:
|
155 |
+
batch_size, channel, height, width = hidden_states.shape
|
156 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
157 |
+
|
158 |
+
batch_size, sequence_length, _ = (
|
159 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
160 |
+
)
|
161 |
+
|
162 |
+
if attention_mask is not None:
|
163 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
164 |
+
|
165 |
+
if attn.group_norm is not None:
|
166 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
167 |
+
|
168 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
169 |
+
query = attn.to_q(hidden_states, *args)
|
170 |
+
|
171 |
+
if encoder_hidden_states is None:
|
172 |
+
encoder_hidden_states = hidden_states
|
173 |
+
elif attn.norm_cross:
|
174 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
175 |
+
|
176 |
+
key = attn.to_k(encoder_hidden_states, *args)
|
177 |
+
value = attn.to_v(encoder_hidden_states, *args)
|
178 |
+
|
179 |
+
inner_dim = key.shape[-1]
|
180 |
+
head_dim = inner_dim // attn.heads
|
181 |
+
|
182 |
+
if (self.hook is not None and self.enabled) or not self.fast_attn:
|
183 |
+
query_batch_dim = attn.head_to_batch_dim(query)
|
184 |
+
key_batch_dim = attn.head_to_batch_dim(key)
|
185 |
+
value_batch_dim = attn.head_to_batch_dim(value)
|
186 |
+
attention_probs = attn.get_attention_scores(query_batch_dim, key_batch_dim, attention_mask)
|
187 |
+
|
188 |
+
if self.hook is not None and self.enabled:
|
189 |
+
# Call the hook with query, key, value, and attention maps
|
190 |
+
self.hook(self.attn_processor_key, query_batch_dim, key_batch_dim, value_batch_dim, attention_probs)
|
191 |
+
|
192 |
+
if self.fast_attn:
|
193 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
194 |
+
|
195 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
196 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
197 |
+
|
198 |
+
if attention_mask is not None:
|
199 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
200 |
+
# (batch, heads, source_length, target_length)
|
201 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
202 |
+
|
203 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
204 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
205 |
+
hidden_states = F.scaled_dot_product_attention(
|
206 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
207 |
+
)
|
208 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
209 |
+
hidden_states = hidden_states.to(query.dtype)
|
210 |
+
else:
|
211 |
+
hidden_states = torch.bmm(attention_probs, value)
|
212 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
213 |
+
|
214 |
+
# linear proj
|
215 |
+
hidden_states = attn.to_out[0](hidden_states, *args)
|
216 |
+
# dropout
|
217 |
+
hidden_states = attn.to_out[1](hidden_states)
|
218 |
+
|
219 |
+
if input_ndim == 4:
|
220 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
221 |
+
|
222 |
+
if attn.residual_connection:
|
223 |
+
hidden_states = hidden_states + residual
|
224 |
+
|
225 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
226 |
+
|
227 |
+
return hidden_states
|
228 |
+
|
229 |
+
|
230 |
+
class LLMGroundedDiffusionPipeline(StableDiffusionPipeline):
|
231 |
+
r"""
|
232 |
+
Pipeline for layout-grounded text-to-image generation using LLM-grounded Diffusion (LMD+): https://arxiv.org/pdf/2305.13655.pdf.
|
233 |
+
|
234 |
+
This model inherits from [`StableDiffusionPipeline`] and aims at implementing the pipeline with minimal modifications. Check the superclass documentation for the generic methods
|
235 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
236 |
+
|
237 |
+
This is a simplified implementation that does not perform latent or attention transfer from single object generation to overall generation. The final image is generated directly with attention and adapters control.
|
238 |
+
|
239 |
+
Args:
|
240 |
+
vae ([`AutoencoderKL`]):
|
241 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
242 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
243 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
244 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
245 |
+
A `CLIPTokenizer` to tokenize text.
|
246 |
+
unet ([`UNet2DConditionModel`]):
|
247 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
248 |
+
scheduler ([`SchedulerMixin`]):
|
249 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
250 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
251 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
252 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
253 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
254 |
+
about a model's potential harms.
|
255 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
256 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
257 |
+
requires_safety_checker (bool):
|
258 |
+
Whether a safety checker is needed for this pipeline.
|
259 |
+
"""
|
260 |
+
|
261 |
+
objects_text = "Objects: "
|
262 |
+
bg_prompt_text = "Background prompt: "
|
263 |
+
bg_prompt_text_no_trailing_space = bg_prompt_text.rstrip()
|
264 |
+
neg_prompt_text = "Negative prompt: "
|
265 |
+
neg_prompt_text_no_trailing_space = neg_prompt_text.rstrip()
|
266 |
+
|
267 |
+
def __init__(
|
268 |
+
self,
|
269 |
+
vae: AutoencoderKL,
|
270 |
+
text_encoder: CLIPTextModel,
|
271 |
+
tokenizer: CLIPTokenizer,
|
272 |
+
unet: UNet2DConditionModel,
|
273 |
+
scheduler: KarrasDiffusionSchedulers,
|
274 |
+
safety_checker: StableDiffusionSafetyChecker,
|
275 |
+
feature_extractor: CLIPImageProcessor,
|
276 |
+
requires_safety_checker: bool = True,
|
277 |
+
):
|
278 |
+
super().__init__(
|
279 |
+
vae, text_encoder, tokenizer, unet, scheduler, safety_checker, feature_extractor, requires_safety_checker
|
280 |
+
)
|
281 |
+
|
282 |
+
self.register_attn_hooks(unet)
|
283 |
+
self._saved_attn = None
|
284 |
+
|
285 |
+
def attn_hook(self, name, query, key, value, attention_probs):
|
286 |
+
if name in DEFAULT_GUIDANCE_ATTN_KEYS:
|
287 |
+
self._saved_attn[name] = attention_probs
|
288 |
+
|
289 |
+
@classmethod
|
290 |
+
def convert_box(cls, box, height, width):
|
291 |
+
# box: x, y, w, h (in 512 format) -> x_min, y_min, x_max, y_max
|
292 |
+
x_min, y_min = box[0] / width, box[1] / height
|
293 |
+
w_box, h_box = box[2] / width, box[3] / height
|
294 |
+
|
295 |
+
x_max, y_max = x_min + w_box, y_min + h_box
|
296 |
+
|
297 |
+
return x_min, y_min, x_max, y_max
|
298 |
+
|
299 |
+
@classmethod
|
300 |
+
def _parse_response_with_negative(cls, text):
|
301 |
+
if not text:
|
302 |
+
raise ValueError("LLM response is empty")
|
303 |
+
|
304 |
+
if cls.objects_text in text:
|
305 |
+
text = text.split(cls.objects_text)[1]
|
306 |
+
|
307 |
+
text_split = text.split(cls.bg_prompt_text_no_trailing_space)
|
308 |
+
if len(text_split) == 2:
|
309 |
+
gen_boxes, text_rem = text_split
|
310 |
+
else:
|
311 |
+
raise ValueError(f"LLM response is incomplete: {text}")
|
312 |
+
|
313 |
+
text_split = text_rem.split(cls.neg_prompt_text_no_trailing_space)
|
314 |
+
|
315 |
+
if len(text_split) == 2:
|
316 |
+
bg_prompt, neg_prompt = text_split
|
317 |
+
else:
|
318 |
+
raise ValueError(f"LLM response is incomplete: {text}")
|
319 |
+
|
320 |
+
try:
|
321 |
+
gen_boxes = ast.literal_eval(gen_boxes)
|
322 |
+
except SyntaxError as e:
|
323 |
+
# Sometimes the response is in plain text
|
324 |
+
if "No objects" in gen_boxes or gen_boxes.strip() == "":
|
325 |
+
gen_boxes = []
|
326 |
+
else:
|
327 |
+
raise e
|
328 |
+
bg_prompt = bg_prompt.strip()
|
329 |
+
neg_prompt = neg_prompt.strip()
|
330 |
+
|
331 |
+
# LLM may return "None" to mean no negative prompt provided.
|
332 |
+
if neg_prompt == "None":
|
333 |
+
neg_prompt = ""
|
334 |
+
|
335 |
+
return gen_boxes, bg_prompt, neg_prompt
|
336 |
+
|
337 |
+
@classmethod
|
338 |
+
def parse_llm_response(cls, response, canvas_height=512, canvas_width=512):
|
339 |
+
# Infer from spec
|
340 |
+
gen_boxes, bg_prompt, neg_prompt = cls._parse_response_with_negative(text=response)
|
341 |
+
|
342 |
+
gen_boxes = sorted(gen_boxes, key=lambda gen_box: gen_box[0])
|
343 |
+
|
344 |
+
phrases = [name for name, _ in gen_boxes]
|
345 |
+
boxes = [cls.convert_box(box, height=canvas_height, width=canvas_width) for _, box in gen_boxes]
|
346 |
+
|
347 |
+
return phrases, boxes, bg_prompt, neg_prompt
|
348 |
+
|
349 |
+
def check_inputs(
|
350 |
+
self,
|
351 |
+
prompt,
|
352 |
+
height,
|
353 |
+
width,
|
354 |
+
callback_steps,
|
355 |
+
phrases,
|
356 |
+
boxes,
|
357 |
+
negative_prompt=None,
|
358 |
+
prompt_embeds=None,
|
359 |
+
negative_prompt_embeds=None,
|
360 |
+
phrase_indices=None,
|
361 |
+
):
|
362 |
+
if height % 8 != 0 or width % 8 != 0:
|
363 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
364 |
+
|
365 |
+
if (callback_steps is None) or (
|
366 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
367 |
+
):
|
368 |
+
raise ValueError(
|
369 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
370 |
+
f" {type(callback_steps)}."
|
371 |
+
)
|
372 |
+
|
373 |
+
if prompt is not None and prompt_embeds is not None:
|
374 |
+
raise ValueError(
|
375 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
376 |
+
" only forward one of the two."
|
377 |
+
)
|
378 |
+
elif prompt is None and prompt_embeds is None:
|
379 |
+
raise ValueError(
|
380 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
381 |
+
)
|
382 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
383 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
384 |
+
elif prompt is None and phrase_indices is None:
|
385 |
+
raise ValueError("If the prompt is None, the phrase_indices cannot be None")
|
386 |
+
|
387 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
388 |
+
raise ValueError(
|
389 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
390 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
391 |
+
)
|
392 |
+
|
393 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
394 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
395 |
+
raise ValueError(
|
396 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
397 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
398 |
+
f" {negative_prompt_embeds.shape}."
|
399 |
+
)
|
400 |
+
|
401 |
+
if len(phrases) != len(boxes):
|
402 |
+
ValueError(
|
403 |
+
"length of `phrases` and `boxes` has to be same, but"
|
404 |
+
f" got: `phrases` {len(phrases)} != `boxes` {len(boxes)}"
|
405 |
+
)
|
406 |
+
|
407 |
+
def register_attn_hooks(self, unet):
|
408 |
+
"""Registering hooks to obtain the attention maps for guidance"""
|
409 |
+
|
410 |
+
attn_procs = {}
|
411 |
+
|
412 |
+
for name in unet.attn_processors.keys():
|
413 |
+
# Only obtain the queries and keys from cross-attention
|
414 |
+
if name.endswith("attn1.processor") or name.endswith("fuser.attn.processor"):
|
415 |
+
# Keep the same attn_processors for self-attention (no hooks for self-attention)
|
416 |
+
attn_procs[name] = unet.attn_processors[name]
|
417 |
+
continue
|
418 |
+
|
419 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
420 |
+
|
421 |
+
if name.startswith("mid_block"):
|
422 |
+
hidden_size = unet.config.block_out_channels[-1]
|
423 |
+
elif name.startswith("up_blocks"):
|
424 |
+
block_id = int(name[len("up_blocks.")])
|
425 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
426 |
+
elif name.startswith("down_blocks"):
|
427 |
+
block_id = int(name[len("down_blocks.")])
|
428 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
429 |
+
|
430 |
+
attn_procs[name] = AttnProcessorWithHook(
|
431 |
+
attn_processor_key=name,
|
432 |
+
hidden_size=hidden_size,
|
433 |
+
cross_attention_dim=cross_attention_dim,
|
434 |
+
hook=self.attn_hook,
|
435 |
+
fast_attn=True,
|
436 |
+
# Not enabled by default
|
437 |
+
enabled=False,
|
438 |
+
)
|
439 |
+
|
440 |
+
unet.set_attn_processor(attn_procs)
|
441 |
+
|
442 |
+
def enable_fuser(self, enabled=True):
|
443 |
+
for module in self.unet.modules():
|
444 |
+
if isinstance(module, GatedSelfAttentionDense):
|
445 |
+
module.enabled = enabled
|
446 |
+
|
447 |
+
def enable_attn_hook(self, enabled=True):
|
448 |
+
for module in self.unet.attn_processors.values():
|
449 |
+
if isinstance(module, AttnProcessorWithHook):
|
450 |
+
module.enabled = enabled
|
451 |
+
|
452 |
+
def get_token_map(self, prompt, padding="do_not_pad", verbose=False):
|
453 |
+
"""Get a list of mapping: prompt index to str (prompt in a list of token str)"""
|
454 |
+
fg_prompt_tokens = self.tokenizer([prompt], padding=padding, max_length=77, return_tensors="np")
|
455 |
+
input_ids = fg_prompt_tokens["input_ids"][0]
|
456 |
+
|
457 |
+
token_map = []
|
458 |
+
for ind, item in enumerate(input_ids.tolist()):
|
459 |
+
token = self.tokenizer._convert_id_to_token(item)
|
460 |
+
|
461 |
+
if verbose:
|
462 |
+
logger.info(f"{ind}, {token} ({item})")
|
463 |
+
|
464 |
+
token_map.append(token)
|
465 |
+
|
466 |
+
return token_map
|
467 |
+
|
468 |
+
def get_phrase_indices(self, prompt, phrases, token_map=None, add_suffix_if_not_found=False, verbose=False):
|
469 |
+
for obj in phrases:
|
470 |
+
# Suffix the prompt with object name for attention guidance if object is not in the prompt, using "|" to separate the prompt and the suffix
|
471 |
+
if obj not in prompt:
|
472 |
+
prompt += "| " + obj
|
473 |
+
|
474 |
+
if token_map is None:
|
475 |
+
# We allow using a pre-computed token map.
|
476 |
+
token_map = self.get_token_map(prompt=prompt, padding="do_not_pad", verbose=verbose)
|
477 |
+
token_map_str = " ".join(token_map)
|
478 |
+
|
479 |
+
phrase_indices = []
|
480 |
+
|
481 |
+
for obj in phrases:
|
482 |
+
phrase_token_map = self.get_token_map(prompt=obj, padding="do_not_pad", verbose=verbose)
|
483 |
+
# Remove <bos> and <eos> in substr
|
484 |
+
phrase_token_map = phrase_token_map[1:-1]
|
485 |
+
phrase_token_map_len = len(phrase_token_map)
|
486 |
+
phrase_token_map_str = " ".join(phrase_token_map)
|
487 |
+
|
488 |
+
if verbose:
|
489 |
+
logger.info("Full str:", token_map_str, "Substr:", phrase_token_map_str, "Phrase:", phrases)
|
490 |
+
|
491 |
+
# Count the number of token before substr
|
492 |
+
# The substring comes with a trailing space that needs to be removed by minus one in the index.
|
493 |
+
obj_first_index = len(token_map_str[: token_map_str.index(phrase_token_map_str) - 1].split(" "))
|
494 |
+
|
495 |
+
obj_position = list(range(obj_first_index, obj_first_index + phrase_token_map_len))
|
496 |
+
phrase_indices.append(obj_position)
|
497 |
+
|
498 |
+
if add_suffix_if_not_found:
|
499 |
+
return phrase_indices, prompt
|
500 |
+
|
501 |
+
return phrase_indices
|
502 |
+
|
503 |
+
def add_ca_loss_per_attn_map_to_loss(
|
504 |
+
self,
|
505 |
+
loss,
|
506 |
+
attn_map,
|
507 |
+
object_number,
|
508 |
+
bboxes,
|
509 |
+
phrase_indices,
|
510 |
+
fg_top_p=0.2,
|
511 |
+
bg_top_p=0.2,
|
512 |
+
fg_weight=1.0,
|
513 |
+
bg_weight=1.0,
|
514 |
+
):
|
515 |
+
# b is the number of heads, not batch
|
516 |
+
b, i, j = attn_map.shape
|
517 |
+
H = W = int(math.sqrt(i))
|
518 |
+
for obj_idx in range(object_number):
|
519 |
+
obj_loss = 0
|
520 |
+
mask = torch.zeros(size=(H, W), device="cuda")
|
521 |
+
obj_boxes = bboxes[obj_idx]
|
522 |
+
|
523 |
+
# We support two level (one box per phrase) and three level (multiple boxes per phrase)
|
524 |
+
if not isinstance(obj_boxes[0], Iterable):
|
525 |
+
obj_boxes = [obj_boxes]
|
526 |
+
|
527 |
+
for obj_box in obj_boxes:
|
528 |
+
# x_min, y_min, x_max, y_max = int(obj_box[0] * W), int(obj_box[1] * H), int(obj_box[2] * W), int(obj_box[3] * H)
|
529 |
+
x_min, y_min, x_max, y_max = scale_proportion(obj_box, H=H, W=W)
|
530 |
+
mask[y_min:y_max, x_min:x_max] = 1
|
531 |
+
|
532 |
+
for obj_position in phrase_indices[obj_idx]:
|
533 |
+
# Could potentially optimize to compute this for loop in batch.
|
534 |
+
# Could crop the ref cross attention before saving to save memory.
|
535 |
+
|
536 |
+
ca_map_obj = attn_map[:, :, obj_position].reshape(b, H, W)
|
537 |
+
|
538 |
+
# shape: (b, H * W)
|
539 |
+
ca_map_obj = attn_map[:, :, obj_position] # .reshape(b, H, W)
|
540 |
+
k_fg = (mask.sum() * fg_top_p).long().clamp_(min=1)
|
541 |
+
k_bg = ((1 - mask).sum() * bg_top_p).long().clamp_(min=1)
|
542 |
+
|
543 |
+
mask_1d = mask.view(1, -1)
|
544 |
+
|
545 |
+
# Max-based loss function
|
546 |
+
|
547 |
+
# Take the topk over spatial dimension, and then take the sum over heads dim
|
548 |
+
# The mean is over k_fg and k_bg dimension, so we don't need to sum and divide on our own.
|
549 |
+
obj_loss += (1 - (ca_map_obj * mask_1d).topk(k=k_fg).values.mean(dim=1)).sum(dim=0) * fg_weight
|
550 |
+
obj_loss += ((ca_map_obj * (1 - mask_1d)).topk(k=k_bg).values.mean(dim=1)).sum(dim=0) * bg_weight
|
551 |
+
|
552 |
+
loss += obj_loss / len(phrase_indices[obj_idx])
|
553 |
+
|
554 |
+
return loss
|
555 |
+
|
556 |
+
def compute_ca_loss(self, saved_attn, bboxes, phrase_indices, guidance_attn_keys, verbose=False, **kwargs):
|
557 |
+
"""
|
558 |
+
The `saved_attn` is supposed to be passed to `save_attn_to_dict` in `cross_attention_kwargs` prior to computing ths loss.
|
559 |
+
`AttnProcessor` will put attention maps into the `save_attn_to_dict`.
|
560 |
+
|
561 |
+
`index` is the timestep.
|
562 |
+
`ref_ca_word_token_only`: This has precedence over `ref_ca_last_token_only` (i.e., if both are enabled, we take the token from word rather than the last token).
|
563 |
+
`ref_ca_last_token_only`: `ref_ca_saved_attn` comes from the attention map of the last token of the phrase in single object generation, so we apply it only to the last token of the phrase in overall generation if this is set to True. If set to False, `ref_ca_saved_attn` will be applied to all the text tokens.
|
564 |
+
"""
|
565 |
+
loss = torch.tensor(0).float().cuda()
|
566 |
+
object_number = len(bboxes)
|
567 |
+
if object_number == 0:
|
568 |
+
return loss
|
569 |
+
|
570 |
+
for attn_key in guidance_attn_keys:
|
571 |
+
# We only have 1 cross attention for mid.
|
572 |
+
|
573 |
+
attn_map_integrated = saved_attn[attn_key]
|
574 |
+
if not attn_map_integrated.is_cuda:
|
575 |
+
attn_map_integrated = attn_map_integrated.cuda()
|
576 |
+
# Example dimension: [20, 64, 77]
|
577 |
+
attn_map = attn_map_integrated.squeeze(dim=0)
|
578 |
+
|
579 |
+
loss = self.add_ca_loss_per_attn_map_to_loss(
|
580 |
+
loss, attn_map, object_number, bboxes, phrase_indices, **kwargs
|
581 |
+
)
|
582 |
+
|
583 |
+
num_attn = len(guidance_attn_keys)
|
584 |
+
|
585 |
+
if num_attn > 0:
|
586 |
+
loss = loss / (object_number * num_attn)
|
587 |
+
|
588 |
+
return loss
|
589 |
+
|
590 |
+
@torch.no_grad()
|
591 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
592 |
+
def __call__(
|
593 |
+
self,
|
594 |
+
prompt: Union[str, List[str]] = None,
|
595 |
+
height: Optional[int] = None,
|
596 |
+
width: Optional[int] = None,
|
597 |
+
num_inference_steps: int = 50,
|
598 |
+
guidance_scale: float = 7.5,
|
599 |
+
gligen_scheduled_sampling_beta: float = 0.3,
|
600 |
+
phrases: List[str] = None,
|
601 |
+
boxes: List[List[float]] = None,
|
602 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
603 |
+
num_images_per_prompt: Optional[int] = 1,
|
604 |
+
eta: float = 0.0,
|
605 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
606 |
+
latents: Optional[torch.FloatTensor] = None,
|
607 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
608 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
609 |
+
output_type: Optional[str] = "pil",
|
610 |
+
return_dict: bool = True,
|
611 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
612 |
+
callback_steps: int = 1,
|
613 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
614 |
+
clip_skip: Optional[int] = None,
|
615 |
+
lmd_guidance_kwargs: Optional[Dict[str, Any]] = {},
|
616 |
+
phrase_indices: Optional[List[int]] = None,
|
617 |
+
):
|
618 |
+
r"""
|
619 |
+
The call function to the pipeline for generation.
|
620 |
+
|
621 |
+
Args:
|
622 |
+
prompt (`str` or `List[str]`, *optional*):
|
623 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
624 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
625 |
+
The height in pixels of the generated image.
|
626 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
627 |
+
The width in pixels of the generated image.
|
628 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
629 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
630 |
+
expense of slower inference.
|
631 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
632 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
633 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
634 |
+
phrases (`List[str]`):
|
635 |
+
The phrases to guide what to include in each of the regions defined by the corresponding
|
636 |
+
`boxes`. There should only be one phrase per bounding box.
|
637 |
+
boxes (`List[List[float]]`):
|
638 |
+
The bounding boxes that identify rectangular regions of the image that are going to be filled with the
|
639 |
+
content described by the corresponding `phrases`. Each rectangular box is defined as a
|
640 |
+
`List[float]` of 4 elements `[xmin, ymin, xmax, ymax]` where each value is between [0,1].
|
641 |
+
gligen_scheduled_sampling_beta (`float`, defaults to 0.3):
|
642 |
+
Scheduled Sampling factor from [GLIGEN: Open-Set Grounded Text-to-Image
|
643 |
+
Generation](https://arxiv.org/pdf/2301.07093.pdf). Scheduled Sampling factor is only varied for
|
644 |
+
scheduled sampling during inference for improved quality and controllability.
|
645 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
646 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
647 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
648 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
649 |
+
The number of images to generate per prompt.
|
650 |
+
eta (`float`, *optional*, defaults to 0.0):
|
651 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
652 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
653 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
654 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
655 |
+
generation deterministic.
|
656 |
+
latents (`torch.FloatTensor`, *optional*):
|
657 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
658 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
659 |
+
tensor is generated by sampling using the supplied random `generator`.
|
660 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
661 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
662 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
663 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
664 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
665 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
666 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
667 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
668 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
669 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
670 |
+
plain tuple.
|
671 |
+
callback (`Callable`, *optional*):
|
672 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
673 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
674 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
675 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
676 |
+
every step.
|
677 |
+
cross_attention_kwargs (`dict`, *optional*):
|
678 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
679 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
680 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
681 |
+
Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
|
682 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
|
683 |
+
using zero terminal SNR.
|
684 |
+
clip_skip (`int`, *optional*):
|
685 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
686 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
687 |
+
lmd_guidance_kwargs (`dict`, *optional*):
|
688 |
+
A kwargs dictionary that if specified is passed along to `latent_lmd_guidance` function. Useful keys include `loss_scale` (the guidance strength), `loss_threshold` (when loss is lower than this value, the guidance is not applied anymore), `max_iter` (the number of iterations of guidance for each step), and `guidance_timesteps` (the number of diffusion timesteps to apply guidance on). See `latent_lmd_guidance` for implementation details.
|
689 |
+
phrase_indices (`list` of `list`, *optional*): The indices of the tokens of each phrase in the overall prompt. If omitted, the pipeline will match the first token subsequence. The pipeline will append the missing phrases to the end of the prompt by default.
|
690 |
+
Examples:
|
691 |
+
|
692 |
+
Returns:
|
693 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
694 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
695 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
696 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
697 |
+
"not-safe-for-work" (nsfw) content.
|
698 |
+
"""
|
699 |
+
# 0. Default height and width to unet
|
700 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
701 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
702 |
+
|
703 |
+
# 1. Check inputs. Raise error if not correct
|
704 |
+
self.check_inputs(
|
705 |
+
prompt,
|
706 |
+
height,
|
707 |
+
width,
|
708 |
+
callback_steps,
|
709 |
+
phrases,
|
710 |
+
boxes,
|
711 |
+
negative_prompt,
|
712 |
+
prompt_embeds,
|
713 |
+
negative_prompt_embeds,
|
714 |
+
phrase_indices,
|
715 |
+
)
|
716 |
+
|
717 |
+
# 2. Define call parameters
|
718 |
+
if prompt is not None and isinstance(prompt, str):
|
719 |
+
batch_size = 1
|
720 |
+
if phrase_indices is None:
|
721 |
+
phrase_indices, prompt = self.get_phrase_indices(prompt, phrases, add_suffix_if_not_found=True)
|
722 |
+
elif prompt is not None and isinstance(prompt, list):
|
723 |
+
batch_size = len(prompt)
|
724 |
+
if phrase_indices is None:
|
725 |
+
phrase_indices = []
|
726 |
+
prompt_parsed = []
|
727 |
+
for prompt_item in prompt:
|
728 |
+
phrase_indices_parsed_item, prompt_parsed_item = self.get_phrase_indices(
|
729 |
+
prompt_item, add_suffix_if_not_found=True
|
730 |
+
)
|
731 |
+
phrase_indices.append(phrase_indices_parsed_item)
|
732 |
+
prompt_parsed.append(prompt_parsed_item)
|
733 |
+
prompt = prompt_parsed
|
734 |
+
else:
|
735 |
+
batch_size = prompt_embeds.shape[0]
|
736 |
+
|
737 |
+
device = self._execution_device
|
738 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
739 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
740 |
+
# corresponds to doing no classifier free guidance.
|
741 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
742 |
+
|
743 |
+
# 3. Encode input prompt
|
744 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
745 |
+
prompt,
|
746 |
+
device,
|
747 |
+
num_images_per_prompt,
|
748 |
+
do_classifier_free_guidance,
|
749 |
+
negative_prompt,
|
750 |
+
prompt_embeds=prompt_embeds,
|
751 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
752 |
+
clip_skip=clip_skip,
|
753 |
+
)
|
754 |
+
|
755 |
+
cond_prompt_embeds = prompt_embeds
|
756 |
+
|
757 |
+
# For classifier free guidance, we need to do two forward passes.
|
758 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
759 |
+
# to avoid doing two forward passes
|
760 |
+
if do_classifier_free_guidance:
|
761 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
762 |
+
|
763 |
+
# 4. Prepare timesteps
|
764 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
765 |
+
timesteps = self.scheduler.timesteps
|
766 |
+
|
767 |
+
# 5. Prepare latent variables
|
768 |
+
num_channels_latents = self.unet.config.in_channels
|
769 |
+
latents = self.prepare_latents(
|
770 |
+
batch_size * num_images_per_prompt,
|
771 |
+
num_channels_latents,
|
772 |
+
height,
|
773 |
+
width,
|
774 |
+
prompt_embeds.dtype,
|
775 |
+
device,
|
776 |
+
generator,
|
777 |
+
latents,
|
778 |
+
)
|
779 |
+
|
780 |
+
# 5.1 Prepare GLIGEN variables
|
781 |
+
max_objs = 30
|
782 |
+
if len(boxes) > max_objs:
|
783 |
+
warnings.warn(
|
784 |
+
f"More that {max_objs} objects found. Only first {max_objs} objects will be processed.",
|
785 |
+
FutureWarning,
|
786 |
+
)
|
787 |
+
phrases = phrases[:max_objs]
|
788 |
+
boxes = boxes[:max_objs]
|
789 |
+
|
790 |
+
n_objs = len(boxes)
|
791 |
+
if n_objs:
|
792 |
+
# prepare batched input to the PositionNet (boxes, phrases, mask)
|
793 |
+
# Get tokens for phrases from pre-trained CLIPTokenizer
|
794 |
+
tokenizer_inputs = self.tokenizer(phrases, padding=True, return_tensors="pt").to(device)
|
795 |
+
# For the token, we use the same pre-trained text encoder
|
796 |
+
# to obtain its text feature
|
797 |
+
_text_embeddings = self.text_encoder(**tokenizer_inputs).pooler_output
|
798 |
+
|
799 |
+
# For each entity, described in phrases, is denoted with a bounding box,
|
800 |
+
# we represent the location information as (xmin,ymin,xmax,ymax)
|
801 |
+
cond_boxes = torch.zeros(max_objs, 4, device=device, dtype=self.text_encoder.dtype)
|
802 |
+
if n_objs:
|
803 |
+
cond_boxes[:n_objs] = torch.tensor(boxes)
|
804 |
+
text_embeddings = torch.zeros(
|
805 |
+
max_objs, self.unet.config.cross_attention_dim, device=device, dtype=self.text_encoder.dtype
|
806 |
+
)
|
807 |
+
if n_objs:
|
808 |
+
text_embeddings[:n_objs] = _text_embeddings
|
809 |
+
# Generate a mask for each object that is entity described by phrases
|
810 |
+
masks = torch.zeros(max_objs, device=device, dtype=self.text_encoder.dtype)
|
811 |
+
masks[:n_objs] = 1
|
812 |
+
|
813 |
+
repeat_batch = batch_size * num_images_per_prompt
|
814 |
+
cond_boxes = cond_boxes.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
|
815 |
+
text_embeddings = text_embeddings.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
|
816 |
+
masks = masks.unsqueeze(0).expand(repeat_batch, -1).clone()
|
817 |
+
if do_classifier_free_guidance:
|
818 |
+
repeat_batch = repeat_batch * 2
|
819 |
+
cond_boxes = torch.cat([cond_boxes] * 2)
|
820 |
+
text_embeddings = torch.cat([text_embeddings] * 2)
|
821 |
+
masks = torch.cat([masks] * 2)
|
822 |
+
masks[: repeat_batch // 2] = 0
|
823 |
+
if cross_attention_kwargs is None:
|
824 |
+
cross_attention_kwargs = {}
|
825 |
+
cross_attention_kwargs["gligen"] = {
|
826 |
+
"boxes": cond_boxes,
|
827 |
+
"positive_embeddings": text_embeddings,
|
828 |
+
"masks": masks,
|
829 |
+
}
|
830 |
+
|
831 |
+
num_grounding_steps = int(gligen_scheduled_sampling_beta * len(timesteps))
|
832 |
+
self.enable_fuser(True)
|
833 |
+
|
834 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
835 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
836 |
+
|
837 |
+
loss_attn = torch.tensor(10000.0)
|
838 |
+
|
839 |
+
# 7. Denoising loop
|
840 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
841 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
842 |
+
for i, t in enumerate(timesteps):
|
843 |
+
# Scheduled sampling
|
844 |
+
if i == num_grounding_steps:
|
845 |
+
self.enable_fuser(False)
|
846 |
+
|
847 |
+
if latents.shape[1] != 4:
|
848 |
+
latents = torch.randn_like(latents[:, :4])
|
849 |
+
|
850 |
+
# 7.1 Perform LMD guidance
|
851 |
+
if boxes:
|
852 |
+
latents, loss_attn = self.latent_lmd_guidance(
|
853 |
+
cond_prompt_embeds,
|
854 |
+
index=i,
|
855 |
+
boxes=boxes,
|
856 |
+
phrase_indices=phrase_indices,
|
857 |
+
t=t,
|
858 |
+
latents=latents,
|
859 |
+
loss=loss_attn,
|
860 |
+
**lmd_guidance_kwargs,
|
861 |
+
)
|
862 |
+
|
863 |
+
# expand the latents if we are doing classifier free guidance
|
864 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
865 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
866 |
+
|
867 |
+
# predict the noise residual
|
868 |
+
noise_pred = self.unet(
|
869 |
+
latent_model_input,
|
870 |
+
t,
|
871 |
+
encoder_hidden_states=prompt_embeds,
|
872 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
873 |
+
).sample
|
874 |
+
|
875 |
+
# perform guidance
|
876 |
+
if do_classifier_free_guidance:
|
877 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
878 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
879 |
+
|
880 |
+
# compute the previous noisy sample x_t -> x_t-1
|
881 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
882 |
+
|
883 |
+
# call the callback, if provided
|
884 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
885 |
+
progress_bar.update()
|
886 |
+
if callback is not None and i % callback_steps == 0:
|
887 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
888 |
+
callback(step_idx, t, latents)
|
889 |
+
|
890 |
+
if not output_type == "latent":
|
891 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
892 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
893 |
+
else:
|
894 |
+
image = latents
|
895 |
+
has_nsfw_concept = None
|
896 |
+
|
897 |
+
if has_nsfw_concept is None:
|
898 |
+
do_denormalize = [True] * image.shape[0]
|
899 |
+
else:
|
900 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
901 |
+
|
902 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
903 |
+
|
904 |
+
# Offload last model to CPU
|
905 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
906 |
+
self.final_offload_hook.offload()
|
907 |
+
|
908 |
+
if not return_dict:
|
909 |
+
return (image, has_nsfw_concept)
|
910 |
+
|
911 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
912 |
+
|
913 |
+
@torch.set_grad_enabled(True)
|
914 |
+
def latent_lmd_guidance(
|
915 |
+
self,
|
916 |
+
cond_embeddings,
|
917 |
+
index,
|
918 |
+
boxes,
|
919 |
+
phrase_indices,
|
920 |
+
t,
|
921 |
+
latents,
|
922 |
+
loss,
|
923 |
+
*,
|
924 |
+
loss_scale=20,
|
925 |
+
loss_threshold=5.0,
|
926 |
+
max_iter=[3] * 5 + [2] * 5 + [1] * 5,
|
927 |
+
guidance_timesteps=15,
|
928 |
+
cross_attention_kwargs=None,
|
929 |
+
guidance_attn_keys=DEFAULT_GUIDANCE_ATTN_KEYS,
|
930 |
+
verbose=False,
|
931 |
+
clear_cache=False,
|
932 |
+
unet_additional_kwargs={},
|
933 |
+
guidance_callback=None,
|
934 |
+
**kwargs,
|
935 |
+
):
|
936 |
+
scheduler, unet = self.scheduler, self.unet
|
937 |
+
|
938 |
+
iteration = 0
|
939 |
+
|
940 |
+
if index < guidance_timesteps:
|
941 |
+
if isinstance(max_iter, list):
|
942 |
+
max_iter = max_iter[index]
|
943 |
+
|
944 |
+
if verbose:
|
945 |
+
logger.info(
|
946 |
+
f"time index {index}, loss: {loss.item()/loss_scale:.3f} (de-scaled with scale {loss_scale:.1f}), loss threshold: {loss_threshold:.3f}"
|
947 |
+
)
|
948 |
+
|
949 |
+
try:
|
950 |
+
self.enable_attn_hook(enabled=True)
|
951 |
+
|
952 |
+
while (
|
953 |
+
loss.item() / loss_scale > loss_threshold and iteration < max_iter and index < guidance_timesteps
|
954 |
+
):
|
955 |
+
self._saved_attn = {}
|
956 |
+
|
957 |
+
latents.requires_grad_(True)
|
958 |
+
latent_model_input = latents
|
959 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
960 |
+
|
961 |
+
unet(
|
962 |
+
latent_model_input,
|
963 |
+
t,
|
964 |
+
encoder_hidden_states=cond_embeddings,
|
965 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
966 |
+
**unet_additional_kwargs,
|
967 |
+
)
|
968 |
+
|
969 |
+
# update latents with guidance
|
970 |
+
loss = (
|
971 |
+
self.compute_ca_loss(
|
972 |
+
saved_attn=self._saved_attn,
|
973 |
+
bboxes=boxes,
|
974 |
+
phrase_indices=phrase_indices,
|
975 |
+
guidance_attn_keys=guidance_attn_keys,
|
976 |
+
verbose=verbose,
|
977 |
+
**kwargs,
|
978 |
+
)
|
979 |
+
* loss_scale
|
980 |
+
)
|
981 |
+
|
982 |
+
if torch.isnan(loss):
|
983 |
+
raise RuntimeError("**Loss is NaN**")
|
984 |
+
|
985 |
+
# This callback allows visualizations.
|
986 |
+
if guidance_callback is not None:
|
987 |
+
guidance_callback(self, latents, loss, iteration, index)
|
988 |
+
|
989 |
+
self._saved_attn = None
|
990 |
+
|
991 |
+
grad_cond = torch.autograd.grad(loss.requires_grad_(True), [latents])[0]
|
992 |
+
|
993 |
+
latents.requires_grad_(False)
|
994 |
+
|
995 |
+
# Scaling with classifier guidance
|
996 |
+
alpha_prod_t = scheduler.alphas_cumprod[t]
|
997 |
+
# Classifier guidance: https://arxiv.org/pdf/2105.05233.pdf
|
998 |
+
# DDIM: https://arxiv.org/pdf/2010.02502.pdf
|
999 |
+
scale = (1 - alpha_prod_t) ** (0.5)
|
1000 |
+
latents = latents - scale * grad_cond
|
1001 |
+
|
1002 |
+
iteration += 1
|
1003 |
+
|
1004 |
+
if clear_cache:
|
1005 |
+
gc.collect()
|
1006 |
+
torch.cuda.empty_cache()
|
1007 |
+
|
1008 |
+
if verbose:
|
1009 |
+
logger.info(
|
1010 |
+
f"time index {index}, loss: {loss.item()/loss_scale:.3f}, loss threshold: {loss_threshold:.3f}, iteration: {iteration}"
|
1011 |
+
)
|
1012 |
+
|
1013 |
+
finally:
|
1014 |
+
self.enable_attn_hook(enabled=False)
|
1015 |
+
|
1016 |
+
return latents, loss
|