add pipeline
Browse files- .gitignore +2 -0
- model_index.json +4 -4
- pipeline_stable_diffusion_interactdiffusion.py +779 -0
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.ipynb_checkpoints/
|
| 2 |
+
.idea/
|
model_index.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
{
|
| 2 |
-
"_class_name": "StableDiffusionInteractDiffusionPipeline",
|
| 3 |
"_diffusers_version": "0.27.0.dev0",
|
| 4 |
"feature_extractor": [
|
| 5 |
null,
|
| 6 |
null
|
| 7 |
],
|
| 8 |
-
"requires_safety_checker":
|
| 9 |
"safety_checker": [
|
| 10 |
null,
|
| 11 |
null
|
|
@@ -23,8 +23,8 @@
|
|
| 23 |
"CLIPTokenizer"
|
| 24 |
],
|
| 25 |
"unet": [
|
| 26 |
-
"
|
| 27 |
-
"
|
| 28 |
],
|
| 29 |
"vae": [
|
| 30 |
"diffusers",
|
|
|
|
| 1 |
{
|
| 2 |
+
"_class_name": ["pipeline_stable_diffusion_interactdiffusion", "StableDiffusionInteractDiffusionPipeline"],
|
| 3 |
"_diffusers_version": "0.27.0.dev0",
|
| 4 |
"feature_extractor": [
|
| 5 |
null,
|
| 6 |
null
|
| 7 |
],
|
| 8 |
+
"requires_safety_checker": false,
|
| 9 |
"safety_checker": [
|
| 10 |
null,
|
| 11 |
null
|
|
|
|
| 23 |
"CLIPTokenizer"
|
| 24 |
],
|
| 25 |
"unet": [
|
| 26 |
+
"interactdiffusion_unet_2d_condition",
|
| 27 |
+
"InteractDiffusionUNet2DConditionModel"
|
| 28 |
],
|
| 29 |
"vae": [
|
| 30 |
"diffusers",
|
pipeline_stable_diffusion_interactdiffusion.py
ADDED
|
@@ -0,0 +1,779 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The InteractDiffusion Authors, The GLIGEN Authors and
|
| 2 |
+
# HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import inspect
|
| 17 |
+
import warnings
|
| 18 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 19 |
+
|
| 20 |
+
import PIL.Image
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
|
| 24 |
+
|
| 25 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 26 |
+
from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin
|
| 27 |
+
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
| 28 |
+
from diffusers.models.attention import GatedSelfAttentionDense
|
| 29 |
+
from diffusers.models.embeddings import get_fourier_embeds_from_boundingbox
|
| 30 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
| 31 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
| 32 |
+
from diffusers.utils import (
|
| 33 |
+
USE_PEFT_BACKEND,
|
| 34 |
+
deprecate,
|
| 35 |
+
logging,
|
| 36 |
+
replace_example_docstring,
|
| 37 |
+
scale_lora_layers,
|
| 38 |
+
unscale_lora_layers,
|
| 39 |
+
)
|
| 40 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 41 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
| 42 |
+
from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
|
| 43 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class StableDiffusionInteractDiffusionPipeline(DiffusionPipeline, StableDiffusionMixin):
|
| 50 |
+
r"""
|
| 51 |
+
Pipeline for text-to-image generation using Stable Diffusion with Interaction-to-Image Generation (InteractDiffusion).
|
| 52 |
+
|
| 53 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
| 54 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.).
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
vae ([`AutoencoderKL`]):
|
| 58 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 59 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
| 60 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 61 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
| 62 |
+
A `CLIPTokenizer` to tokenize text.
|
| 63 |
+
unet ([`UNet2DConditionModel`]):
|
| 64 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 65 |
+
scheduler ([`SchedulerMixin`]):
|
| 66 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 67 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 68 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 69 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 70 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
| 71 |
+
about a model's potential harms.
|
| 72 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 73 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
| 77 |
+
model_cpu_offload_seq = "text_encoder->unet->vae"
|
| 78 |
+
_exclude_from_cpu_offload = ["safety_checker"]
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
vae: AutoencoderKL,
|
| 83 |
+
text_encoder: CLIPTextModel,
|
| 84 |
+
tokenizer: CLIPTokenizer,
|
| 85 |
+
unet: UNet2DConditionModel,
|
| 86 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 87 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 88 |
+
feature_extractor: CLIPFeatureExtractor,
|
| 89 |
+
requires_safety_checker: bool = True,
|
| 90 |
+
):
|
| 91 |
+
super().__init__()
|
| 92 |
+
|
| 93 |
+
if safety_checker is None and requires_safety_checker:
|
| 94 |
+
logger.warning(
|
| 95 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
| 96 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
| 97 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
| 98 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
| 99 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
| 100 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if safety_checker is not None and feature_extractor is None:
|
| 104 |
+
raise ValueError(
|
| 105 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
| 106 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# # load position_net
|
| 110 |
+
# positive_len = 768
|
| 111 |
+
# if isinstance(unet.config.cross_attention_dim, int):
|
| 112 |
+
# positive_len = unet.config.cross_attention_dim
|
| 113 |
+
# elif isinstance(unet.config.cross_attention_dim, tuple) or isinstance(unet.config.cross_attention_dim, list):
|
| 114 |
+
# positive_len = unet.config.cross_attention_dim[0]
|
| 115 |
+
|
| 116 |
+
# self.position_net = InteractDiffusionInteractionProjection(
|
| 117 |
+
# in_dim=positive_len, out_dim=unet.config.cross_attention_dim
|
| 118 |
+
# )
|
| 119 |
+
|
| 120 |
+
self.register_modules(
|
| 121 |
+
vae=vae,
|
| 122 |
+
text_encoder=text_encoder,
|
| 123 |
+
tokenizer=tokenizer,
|
| 124 |
+
unet=unet,
|
| 125 |
+
scheduler=scheduler,
|
| 126 |
+
safety_checker=safety_checker,
|
| 127 |
+
feature_extractor=feature_extractor,
|
| 128 |
+
)
|
| 129 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 130 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
| 131 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 132 |
+
|
| 133 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
|
| 134 |
+
def _encode_prompt(
|
| 135 |
+
self,
|
| 136 |
+
prompt,
|
| 137 |
+
device,
|
| 138 |
+
num_images_per_prompt,
|
| 139 |
+
do_classifier_free_guidance,
|
| 140 |
+
negative_prompt=None,
|
| 141 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 142 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 143 |
+
lora_scale: Optional[float] = None,
|
| 144 |
+
**kwargs,
|
| 145 |
+
):
|
| 146 |
+
deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
|
| 147 |
+
deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
|
| 148 |
+
|
| 149 |
+
prompt_embeds_tuple = self.encode_prompt(
|
| 150 |
+
prompt=prompt,
|
| 151 |
+
device=device,
|
| 152 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 153 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 154 |
+
negative_prompt=negative_prompt,
|
| 155 |
+
prompt_embeds=prompt_embeds,
|
| 156 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 157 |
+
lora_scale=lora_scale,
|
| 158 |
+
**kwargs,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# concatenate for backwards comp
|
| 162 |
+
prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
|
| 163 |
+
|
| 164 |
+
return prompt_embeds
|
| 165 |
+
|
| 166 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
|
| 167 |
+
def encode_prompt(
|
| 168 |
+
self,
|
| 169 |
+
prompt,
|
| 170 |
+
device,
|
| 171 |
+
num_images_per_prompt,
|
| 172 |
+
do_classifier_free_guidance,
|
| 173 |
+
negative_prompt=None,
|
| 174 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 175 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 176 |
+
lora_scale: Optional[float] = None,
|
| 177 |
+
clip_skip: Optional[int] = None,
|
| 178 |
+
):
|
| 179 |
+
r"""
|
| 180 |
+
Encodes the prompt into text encoder hidden states.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 184 |
+
prompt to be encoded
|
| 185 |
+
device: (`torch.device`):
|
| 186 |
+
torch device
|
| 187 |
+
num_images_per_prompt (`int`):
|
| 188 |
+
number of images that should be generated per prompt
|
| 189 |
+
do_classifier_free_guidance (`bool`):
|
| 190 |
+
whether to use classifier free guidance or not
|
| 191 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 192 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 193 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 194 |
+
less than `1`).
|
| 195 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 196 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 197 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 198 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 199 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 200 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 201 |
+
argument.
|
| 202 |
+
lora_scale (`float`, *optional*):
|
| 203 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 204 |
+
clip_skip (`int`, *optional*):
|
| 205 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 206 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 207 |
+
"""
|
| 208 |
+
# set lora scale so that monkey patched LoRA
|
| 209 |
+
# function of text encoder can correctly access it
|
| 210 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 211 |
+
self._lora_scale = lora_scale
|
| 212 |
+
|
| 213 |
+
# dynamically adjust the LoRA scale
|
| 214 |
+
if not USE_PEFT_BACKEND:
|
| 215 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 216 |
+
else:
|
| 217 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 218 |
+
|
| 219 |
+
if prompt is not None and isinstance(prompt, str):
|
| 220 |
+
batch_size = 1
|
| 221 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 222 |
+
batch_size = len(prompt)
|
| 223 |
+
else:
|
| 224 |
+
batch_size = prompt_embeds.shape[0]
|
| 225 |
+
|
| 226 |
+
if prompt_embeds is None:
|
| 227 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 228 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 229 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 230 |
+
|
| 231 |
+
text_inputs = self.tokenizer(
|
| 232 |
+
prompt,
|
| 233 |
+
padding="max_length",
|
| 234 |
+
max_length=self.tokenizer.model_max_length,
|
| 235 |
+
truncation=True,
|
| 236 |
+
return_tensors="pt",
|
| 237 |
+
)
|
| 238 |
+
text_input_ids = text_inputs.input_ids
|
| 239 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 240 |
+
|
| 241 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 242 |
+
text_input_ids, untruncated_ids
|
| 243 |
+
):
|
| 244 |
+
removed_text = self.tokenizer.batch_decode(
|
| 245 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 246 |
+
)
|
| 247 |
+
logger.warning(
|
| 248 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 249 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 253 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 254 |
+
else:
|
| 255 |
+
attention_mask = None
|
| 256 |
+
|
| 257 |
+
if clip_skip is None:
|
| 258 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 259 |
+
prompt_embeds = prompt_embeds[0]
|
| 260 |
+
else:
|
| 261 |
+
prompt_embeds = self.text_encoder(
|
| 262 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 263 |
+
)
|
| 264 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 265 |
+
# all the hidden states from the encoder layers. Then index into
|
| 266 |
+
# the tuple to access the hidden states from the desired layer.
|
| 267 |
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
| 268 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 269 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 270 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 271 |
+
# layer.
|
| 272 |
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
| 273 |
+
|
| 274 |
+
if self.text_encoder is not None:
|
| 275 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 276 |
+
elif self.unet is not None:
|
| 277 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 278 |
+
else:
|
| 279 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 280 |
+
|
| 281 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 282 |
+
|
| 283 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 284 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 285 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 286 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 287 |
+
|
| 288 |
+
# get unconditional embeddings for classifier free guidance
|
| 289 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 290 |
+
uncond_tokens: List[str]
|
| 291 |
+
if negative_prompt is None:
|
| 292 |
+
uncond_tokens = [""] * batch_size
|
| 293 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 294 |
+
raise TypeError(
|
| 295 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 296 |
+
f" {type(prompt)}."
|
| 297 |
+
)
|
| 298 |
+
elif isinstance(negative_prompt, str):
|
| 299 |
+
uncond_tokens = [negative_prompt]
|
| 300 |
+
elif batch_size != len(negative_prompt):
|
| 301 |
+
raise ValueError(
|
| 302 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 303 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 304 |
+
" the batch size of `prompt`."
|
| 305 |
+
)
|
| 306 |
+
else:
|
| 307 |
+
uncond_tokens = negative_prompt
|
| 308 |
+
|
| 309 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 310 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 311 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 312 |
+
|
| 313 |
+
max_length = prompt_embeds.shape[1]
|
| 314 |
+
uncond_input = self.tokenizer(
|
| 315 |
+
uncond_tokens,
|
| 316 |
+
padding="max_length",
|
| 317 |
+
max_length=max_length,
|
| 318 |
+
truncation=True,
|
| 319 |
+
return_tensors="pt",
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 323 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 324 |
+
else:
|
| 325 |
+
attention_mask = None
|
| 326 |
+
|
| 327 |
+
negative_prompt_embeds = self.text_encoder(
|
| 328 |
+
uncond_input.input_ids.to(device),
|
| 329 |
+
attention_mask=attention_mask,
|
| 330 |
+
)
|
| 331 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 332 |
+
|
| 333 |
+
if do_classifier_free_guidance:
|
| 334 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 335 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 336 |
+
|
| 337 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 338 |
+
|
| 339 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 340 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 341 |
+
|
| 342 |
+
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 343 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 344 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 345 |
+
|
| 346 |
+
return prompt_embeds, negative_prompt_embeds
|
| 347 |
+
|
| 348 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
| 349 |
+
def run_safety_checker(self, image, device, dtype):
|
| 350 |
+
if self.safety_checker is None:
|
| 351 |
+
has_nsfw_concept = None
|
| 352 |
+
else:
|
| 353 |
+
if torch.is_tensor(image):
|
| 354 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
| 355 |
+
else:
|
| 356 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
| 357 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
| 358 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 359 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 360 |
+
)
|
| 361 |
+
return image, has_nsfw_concept
|
| 362 |
+
|
| 363 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 364 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 365 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 366 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 367 |
+
# and should be between [0, 1]
|
| 368 |
+
|
| 369 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 370 |
+
extra_step_kwargs = {}
|
| 371 |
+
if accepts_eta:
|
| 372 |
+
extra_step_kwargs["eta"] = eta
|
| 373 |
+
|
| 374 |
+
# check if the scheduler accepts generator
|
| 375 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 376 |
+
if accepts_generator:
|
| 377 |
+
extra_step_kwargs["generator"] = generator
|
| 378 |
+
return extra_step_kwargs
|
| 379 |
+
|
| 380 |
+
def check_inputs(
|
| 381 |
+
self,
|
| 382 |
+
prompt,
|
| 383 |
+
height,
|
| 384 |
+
width,
|
| 385 |
+
callback_steps,
|
| 386 |
+
interactdiffusion_subject_phrases,
|
| 387 |
+
interactdiffusion_subject_boxes,
|
| 388 |
+
interactdiffusion_object_phrases,
|
| 389 |
+
interactdiffusion_object_boxes,
|
| 390 |
+
interactdiffusion_action_phrases,
|
| 391 |
+
negative_prompt=None,
|
| 392 |
+
prompt_embeds=None,
|
| 393 |
+
negative_prompt_embeds=None,
|
| 394 |
+
):
|
| 395 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 396 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 397 |
+
|
| 398 |
+
if (callback_steps is None) or (
|
| 399 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 400 |
+
):
|
| 401 |
+
raise ValueError(
|
| 402 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 403 |
+
f" {type(callback_steps)}."
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
if prompt is not None and prompt_embeds is not None:
|
| 407 |
+
raise ValueError(
|
| 408 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 409 |
+
" only forward one of the two."
|
| 410 |
+
)
|
| 411 |
+
elif prompt is None and prompt_embeds is None:
|
| 412 |
+
raise ValueError(
|
| 413 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 414 |
+
)
|
| 415 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 416 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 417 |
+
|
| 418 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 419 |
+
raise ValueError(
|
| 420 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 421 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 425 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 426 |
+
raise ValueError(
|
| 427 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 428 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 429 |
+
f" {negative_prompt_embeds.shape}."
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
if len(interactdiffusion_subject_phrases) == len(interactdiffusion_subject_boxes) == len(interactdiffusion_object_phrases) == len(interactdiffusion_object_boxes) == len(interactdiffusion_action_phrases):
|
| 433 |
+
ValueError(
|
| 434 |
+
"length of `interactdiffusion_subject_phrases`, `interactdiffusion_subject_boxes`, `interactdiffusion_object_phrases`, "
|
| 435 |
+
"`interactdiffusion_object_boxes`, and `interactdiffusion_action_phrases` has to be same, but"
|
| 436 |
+
f" got: `interactdiffusion_subject_phrases` {len(interactdiffusion_subject_phrases)},"
|
| 437 |
+
f"`interactdiffusion_subject_boxes` {len(interactdiffusion_subject_boxes)}"
|
| 438 |
+
f"`interactdiffusion_object_phrases` {len(interactdiffusion_object_phrases)}"
|
| 439 |
+
f"`interactdiffusion_object_boxes` {len(interactdiffusion_object_boxes)}"
|
| 440 |
+
f"`interactdiffusion_action_phrases` {len(interactdiffusion_action_phrases)}"
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 444 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 445 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 446 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 447 |
+
raise ValueError(
|
| 448 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 449 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
if latents is None:
|
| 453 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 454 |
+
else:
|
| 455 |
+
latents = latents.to(device)
|
| 456 |
+
|
| 457 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 458 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 459 |
+
return latents
|
| 460 |
+
|
| 461 |
+
def enable_fuser(self, enabled=True):
|
| 462 |
+
for module in self.unet.modules():
|
| 463 |
+
if type(module) is GatedSelfAttentionDense:
|
| 464 |
+
module.enabled = enabled
|
| 465 |
+
|
| 466 |
+
@torch.no_grad()
|
| 467 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 468 |
+
def __call__(
|
| 469 |
+
self,
|
| 470 |
+
prompt: Union[str, List[str]] = None,
|
| 471 |
+
height: Optional[int] = None,
|
| 472 |
+
width: Optional[int] = None,
|
| 473 |
+
num_inference_steps: int = 50,
|
| 474 |
+
guidance_scale: float = 7.5,
|
| 475 |
+
interactdiffusion_scheduled_sampling_beta: float = 1.0,
|
| 476 |
+
interactdiffusion_subject_phrases: List[str] = None,
|
| 477 |
+
interactdiffusion_subject_boxes: List[List[float]] = None,
|
| 478 |
+
interactdiffusion_object_phrases: List[str] = None,
|
| 479 |
+
interactdiffusion_object_boxes: List[List[float]] = None,
|
| 480 |
+
interactdiffusion_action_phrases: List[str] = None,
|
| 481 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 482 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 483 |
+
eta: float = 0.0,
|
| 484 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 485 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 486 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 487 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 488 |
+
output_type: Optional[str] = "pil",
|
| 489 |
+
return_dict: bool = True,
|
| 490 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 491 |
+
callback_steps: int = 1,
|
| 492 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 493 |
+
clip_skip: Optional[int] = None,
|
| 494 |
+
):
|
| 495 |
+
r"""
|
| 496 |
+
The call function to the pipeline for generation.
|
| 497 |
+
|
| 498 |
+
Args:
|
| 499 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 500 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 501 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 502 |
+
The height in pixels of the generated image.
|
| 503 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 504 |
+
The width in pixels of the generated image.
|
| 505 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 506 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 507 |
+
expense of slower inference.
|
| 508 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 509 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 510 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 511 |
+
interactdiffusion_subject_phrases (`List[str]`):
|
| 512 |
+
The phrases to guide what to include in each of the subject defined by the corresponding
|
| 513 |
+
`interactdiffusion_subject_boxes`. There should only be one phrase per subject bounding box.
|
| 514 |
+
interactdiffusion_subject_boxes (`List[List[float]]`):
|
| 515 |
+
The bounding boxes that identify rectangular regions of the image that are going to be filled with the
|
| 516 |
+
subject described by the corresponding `interactdiffusion_subject_phrases`. Each rectangular box is
|
| 517 |
+
defined as a `List[float]` of 4 elements `[xmin, ymin, xmax, ymax]` where each value is between [0,1].
|
| 518 |
+
interactdiffusion_object_phrases (`List[str]`):
|
| 519 |
+
The phrases to guide what to include in each of the object defined by the corresponding
|
| 520 |
+
`interactdiffusion_object_boxes`. There should only be one phrase per object bounding box.
|
| 521 |
+
interactdiffusion_object_boxes (`List[List[float]]`):
|
| 522 |
+
The bounding boxes that identify rectangular regions of the image that are going to be filled with the
|
| 523 |
+
object described by the corresponding `interactdiffusion_object_phrases`. Each rectangular box is
|
| 524 |
+
defined as a `List[float]` of 4 elements `[xmin, ymin, xmax, ymax]` where each value is between [0,1].
|
| 525 |
+
interactdiffusion_action_phrases (`List[str]`):
|
| 526 |
+
The phrases to guide what to include in each of the interaction defined between subject and object bounding boxes.
|
| 527 |
+
There should only be one phrase per subject-object pair.
|
| 528 |
+
interactdiffusion_scheduled_sampling_beta (`float`, defaults to 1.0):
|
| 529 |
+
Scheduled Sampling factor from [GLIGEN: Open-Set Grounded Text-to-Image
|
| 530 |
+
Generation](https://arxiv.org/pdf/2301.07093.pdf). Scheduled Sampling factor is only varied for
|
| 531 |
+
scheduled sampling during inference for improved quality and controllability.
|
| 532 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 533 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 534 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 535 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 536 |
+
The number of images to generate per prompt.
|
| 537 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 538 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 539 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 540 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 541 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 542 |
+
generation deterministic.
|
| 543 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 544 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 545 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 546 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 547 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 548 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 549 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 550 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 551 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 552 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 553 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 554 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 555 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 556 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 557 |
+
plain tuple.
|
| 558 |
+
callback (`Callable`, *optional*):
|
| 559 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 560 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 561 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 562 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 563 |
+
every step.
|
| 564 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 565 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 566 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 567 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
| 568 |
+
Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
|
| 569 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
|
| 570 |
+
using zero terminal SNR.
|
| 571 |
+
clip_skip (`int`, *optional*):
|
| 572 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 573 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 574 |
+
Examples:
|
| 575 |
+
|
| 576 |
+
Returns:
|
| 577 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 578 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
| 579 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
| 580 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
| 581 |
+
"not-safe-for-work" (nsfw) content.
|
| 582 |
+
"""
|
| 583 |
+
# 0. Default height and width to unet
|
| 584 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 585 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 586 |
+
|
| 587 |
+
# 1. Check inputs. Raise error if not correct
|
| 588 |
+
self.check_inputs(
|
| 589 |
+
prompt,
|
| 590 |
+
height,
|
| 591 |
+
width,
|
| 592 |
+
callback_steps,
|
| 593 |
+
interactdiffusion_subject_phrases,
|
| 594 |
+
interactdiffusion_subject_boxes,
|
| 595 |
+
interactdiffusion_object_phrases,
|
| 596 |
+
interactdiffusion_object_boxes,
|
| 597 |
+
interactdiffusion_action_phrases,
|
| 598 |
+
negative_prompt,
|
| 599 |
+
prompt_embeds,
|
| 600 |
+
negative_prompt_embeds,
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
# 2. Define call parameters
|
| 604 |
+
if prompt is not None and isinstance(prompt, str):
|
| 605 |
+
batch_size = 1
|
| 606 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 607 |
+
batch_size = len(prompt)
|
| 608 |
+
else:
|
| 609 |
+
batch_size = prompt_embeds.shape[0]
|
| 610 |
+
|
| 611 |
+
device = self._execution_device
|
| 612 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 613 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 614 |
+
# corresponds to doing no classifier free guidance.
|
| 615 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 616 |
+
|
| 617 |
+
# 3. Encode input prompt
|
| 618 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 619 |
+
prompt,
|
| 620 |
+
device,
|
| 621 |
+
num_images_per_prompt,
|
| 622 |
+
do_classifier_free_guidance,
|
| 623 |
+
negative_prompt,
|
| 624 |
+
prompt_embeds=prompt_embeds,
|
| 625 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 626 |
+
clip_skip=clip_skip,
|
| 627 |
+
)
|
| 628 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 629 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 630 |
+
# to avoid doing two forward passes
|
| 631 |
+
if do_classifier_free_guidance:
|
| 632 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 633 |
+
|
| 634 |
+
# 4. Prepare timesteps
|
| 635 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 636 |
+
timesteps = self.scheduler.timesteps
|
| 637 |
+
|
| 638 |
+
# 5. Prepare latent variables
|
| 639 |
+
num_channels_latents = self.unet.config.in_channels
|
| 640 |
+
latents = self.prepare_latents(
|
| 641 |
+
batch_size * num_images_per_prompt,
|
| 642 |
+
num_channels_latents,
|
| 643 |
+
height,
|
| 644 |
+
width,
|
| 645 |
+
prompt_embeds.dtype,
|
| 646 |
+
device,
|
| 647 |
+
generator,
|
| 648 |
+
latents,
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
# 5.1 Prepare InteractDiffusion variables
|
| 652 |
+
max_objs = 30
|
| 653 |
+
if len(interactdiffusion_action_phrases) > max_objs:
|
| 654 |
+
warnings.warn(
|
| 655 |
+
f"More that {max_objs} objects found. Only first {max_objs} objects will be processed.",
|
| 656 |
+
FutureWarning,
|
| 657 |
+
)
|
| 658 |
+
interactdiffusion_subject_phrases = interactdiffusion_subject_phrases[:max_objs]
|
| 659 |
+
interactdiffusion_subject_boxes = interactdiffusion_subject_boxes[:max_objs]
|
| 660 |
+
interactdiffusion_object_phrases = interactdiffusion_object_phrases[:max_objs]
|
| 661 |
+
interactdiffusion_object_boxes = interactdiffusion_object_boxes[:max_objs]
|
| 662 |
+
interactdiffusion_action_phrases = interactdiffusion_action_phrases[:max_objs]
|
| 663 |
+
# prepare batched input to the InteractDiffusionInteractionProjection (boxes, phrases, mask)
|
| 664 |
+
# Get tokens for phrases from pre-trained CLIPTokenizer
|
| 665 |
+
tokenizer_inputs = self.tokenizer(interactdiffusion_subject_phrases+interactdiffusion_object_phrases+interactdiffusion_action_phrases,
|
| 666 |
+
padding=True, return_tensors="pt").to(device)
|
| 667 |
+
# For the token, we use the same pre-trained text encoder
|
| 668 |
+
# to obtain its text feature
|
| 669 |
+
_text_embeddings = self.text_encoder(**tokenizer_inputs).pooler_output
|
| 670 |
+
n_objs = min(len(interactdiffusion_subject_boxes), max_objs)
|
| 671 |
+
# For each entity, described in phrases, is denoted with a bounding box,
|
| 672 |
+
# we represent the location information as (xmin,ymin,xmax,ymax)
|
| 673 |
+
subject_boxes = torch.zeros(max_objs, 4, device=device, dtype=self.text_encoder.dtype)
|
| 674 |
+
object_boxes = torch.zeros(max_objs, 4, device=device, dtype=self.text_encoder.dtype)
|
| 675 |
+
subject_boxes[:n_objs] = torch.tensor(interactdiffusion_subject_boxes[:n_objs])
|
| 676 |
+
object_boxes[:n_objs] = torch.tensor(interactdiffusion_object_boxes[:n_objs])
|
| 677 |
+
subject_text_embeddings = torch.zeros(max_objs, 768, device=device, dtype=self.text_encoder.dtype)
|
| 678 |
+
subject_text_embeddings[:n_objs] = _text_embeddings[:n_objs*1]
|
| 679 |
+
object_text_embeddings = torch.zeros(max_objs, 768, device=device, dtype=self.text_encoder.dtype)
|
| 680 |
+
object_text_embeddings[:n_objs] = _text_embeddings[n_objs*1:n_objs*2]
|
| 681 |
+
action_text_embeddings = torch.zeros(max_objs, 768, device=device, dtype=self.text_encoder.dtype)
|
| 682 |
+
action_text_embeddings[:n_objs] = _text_embeddings[n_objs*2:n_objs*3]
|
| 683 |
+
# Generate a mask for each object that is entity described by phrases
|
| 684 |
+
masks = torch.zeros(max_objs, device=device, dtype=self.text_encoder.dtype)
|
| 685 |
+
masks[:n_objs] = 1
|
| 686 |
+
|
| 687 |
+
repeat_batch = batch_size * num_images_per_prompt
|
| 688 |
+
subject_boxes = subject_boxes.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
|
| 689 |
+
object_boxes = object_boxes.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
|
| 690 |
+
subject_text_embeddings = subject_text_embeddings.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
|
| 691 |
+
object_text_embeddings = object_text_embeddings.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
|
| 692 |
+
action_text_embeddings = action_text_embeddings.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
|
| 693 |
+
masks = masks.unsqueeze(0).expand(repeat_batch, -1).clone()
|
| 694 |
+
|
| 695 |
+
if do_classifier_free_guidance:
|
| 696 |
+
repeat_batch = repeat_batch * 2
|
| 697 |
+
subject_boxes = torch.cat([subject_boxes] * 2)
|
| 698 |
+
object_boxes = torch.cat([object_boxes] * 2)
|
| 699 |
+
subject_text_embeddings = torch.cat([subject_text_embeddings] * 2)
|
| 700 |
+
object_text_embeddings = torch.cat([object_text_embeddings] * 2)
|
| 701 |
+
action_text_embeddings = torch.cat([action_text_embeddings] * 2)
|
| 702 |
+
masks = torch.cat([masks] * 2)
|
| 703 |
+
masks[: repeat_batch // 2] = 0
|
| 704 |
+
if cross_attention_kwargs is None:
|
| 705 |
+
cross_attention_kwargs = {}
|
| 706 |
+
cross_attention_kwargs['gligen'] = {
|
| 707 |
+
'subject_boxes': subject_boxes,
|
| 708 |
+
'object_boxes': object_boxes,
|
| 709 |
+
'subject_positive_embeddings': subject_text_embeddings,
|
| 710 |
+
'object_positive_embeddings': object_text_embeddings,
|
| 711 |
+
'action_positive_embeddings': action_text_embeddings,
|
| 712 |
+
'masks': masks
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
num_grounding_steps = int(interactdiffusion_scheduled_sampling_beta * len(timesteps))
|
| 716 |
+
self.enable_fuser(True)
|
| 717 |
+
|
| 718 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 719 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 720 |
+
|
| 721 |
+
# 7. Denoising loop
|
| 722 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 723 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 724 |
+
for i, t in enumerate(timesteps):
|
| 725 |
+
# Scheduled sampling
|
| 726 |
+
if i == num_grounding_steps:
|
| 727 |
+
self.enable_fuser(False)
|
| 728 |
+
|
| 729 |
+
if latents.shape[1] != 4:
|
| 730 |
+
latents = torch.randn_like(latents[:, :4])
|
| 731 |
+
|
| 732 |
+
# expand the latents if we are doing classifier free guidance
|
| 733 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 734 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 735 |
+
|
| 736 |
+
# predict the noise residual
|
| 737 |
+
noise_pred = self.unet(
|
| 738 |
+
latent_model_input,
|
| 739 |
+
t,
|
| 740 |
+
encoder_hidden_states=prompt_embeds,
|
| 741 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 742 |
+
).sample
|
| 743 |
+
|
| 744 |
+
# perform guidance
|
| 745 |
+
if do_classifier_free_guidance:
|
| 746 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 747 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 748 |
+
|
| 749 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 750 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
| 751 |
+
|
| 752 |
+
# call the callback, if provided
|
| 753 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 754 |
+
progress_bar.update()
|
| 755 |
+
if callback is not None and i % callback_steps == 0:
|
| 756 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 757 |
+
callback(step_idx, t, latents)
|
| 758 |
+
|
| 759 |
+
if not output_type == "latent":
|
| 760 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 761 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
| 762 |
+
else:
|
| 763 |
+
image = latents
|
| 764 |
+
has_nsfw_concept = None
|
| 765 |
+
|
| 766 |
+
if has_nsfw_concept is None:
|
| 767 |
+
do_denormalize = [True] * image.shape[0]
|
| 768 |
+
else:
|
| 769 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 770 |
+
|
| 771 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 772 |
+
|
| 773 |
+
# Offload all models
|
| 774 |
+
self.maybe_free_model_hooks()
|
| 775 |
+
|
| 776 |
+
if not return_dict:
|
| 777 |
+
return (image, has_nsfw_concept)
|
| 778 |
+
|
| 779 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|