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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
|
2 |
+
# Copyright 2023 The 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 |
+
|
17 |
+
import inspect
|
18 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
19 |
+
|
20 |
+
import numpy as np
|
21 |
+
import paddle
|
22 |
+
import PIL.Image
|
23 |
+
|
24 |
+
from paddlenlp.transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
25 |
+
from ppdiffusers.image_processor import VaeImageProcessor
|
26 |
+
from ppdiffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin
|
27 |
+
from ppdiffusers.models import AutoencoderKL, ControlNetModel, UNet2DConditionModel
|
28 |
+
from ppdiffusers.pipeline_utils import DiffusionPipeline
|
29 |
+
from ppdiffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
|
30 |
+
from ppdiffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import (
|
31 |
+
MultiControlNetModel,
|
32 |
+
)
|
33 |
+
from ppdiffusers.pipelines.stable_diffusion.safety_checker import (
|
34 |
+
StableDiffusionSafetyChecker,
|
35 |
+
)
|
36 |
+
from ppdiffusers.schedulers import KarrasDiffusionSchedulers
|
37 |
+
from ppdiffusers.utils import (
|
38 |
+
deprecate,
|
39 |
+
logging,
|
40 |
+
randn_tensor,
|
41 |
+
replace_example_docstring,
|
42 |
+
)
|
43 |
+
|
44 |
+
|
45 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
46 |
+
|
47 |
+
|
48 |
+
EXAMPLE_DOC_STRING = """
|
49 |
+
Examples:
|
50 |
+
```py
|
51 |
+
>>> # !pip install opencv-python paddlenlp
|
52 |
+
>>> from ppdiffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, UniPCMultistepScheduler
|
53 |
+
>>> from ppdiffusers.utils import load_image
|
54 |
+
>>> import numpy as np
|
55 |
+
>>> import paddle
|
56 |
+
|
57 |
+
>>> import cv2
|
58 |
+
>>> from PIL import Image
|
59 |
+
|
60 |
+
>>> # download an image
|
61 |
+
>>> image = load_image(
|
62 |
+
... "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
|
63 |
+
... )
|
64 |
+
>>> np_image = np.array(image)
|
65 |
+
|
66 |
+
>>> # get canny image
|
67 |
+
>>> np_image = cv2.Canny(np_image, 100, 200)
|
68 |
+
>>> np_image = np_image[:, :, None]
|
69 |
+
>>> np_image = np.concatenate([np_image, np_image, np_image], axis=2)
|
70 |
+
>>> canny_image = Image.fromarray(np_image)
|
71 |
+
|
72 |
+
>>> # load control net and stable diffusion v1-5
|
73 |
+
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", paddle_dtype=paddle.float16)
|
74 |
+
>>> pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
|
75 |
+
... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, paddle_dtype=paddle.float16
|
76 |
+
... )
|
77 |
+
|
78 |
+
>>> # speed up diffusion process with faster scheduler and memory optimization
|
79 |
+
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
80 |
+
|
81 |
+
>>> # generate image
|
82 |
+
>>> generator = paddle.Generaotr().manual_seed(0)
|
83 |
+
>>> image = pipe(
|
84 |
+
... "futuristic-looking woman",
|
85 |
+
... num_inference_steps=20,
|
86 |
+
... generator=generator,
|
87 |
+
... image=image,
|
88 |
+
... control_image=canny_image,
|
89 |
+
... ).images[0]
|
90 |
+
>>> image.save("demo.png")
|
91 |
+
```
|
92 |
+
"""
|
93 |
+
|
94 |
+
|
95 |
+
class StableDiffusionControlNetImg2ImgPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin):
|
96 |
+
r"""
|
97 |
+
Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.
|
98 |
+
|
99 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
100 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
101 |
+
|
102 |
+
In addition the pipeline inherits the following loading methods:
|
103 |
+
- *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]
|
104 |
+
|
105 |
+
Args:
|
106 |
+
vae ([`AutoencoderKL`]):
|
107 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
108 |
+
text_encoder ([`CLIPTextModel`]):
|
109 |
+
Frozen text-encoder. Stable Diffusion uses the text portion of
|
110 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
111 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
112 |
+
tokenizer (`CLIPTokenizer`):
|
113 |
+
Tokenizer of class
|
114 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
115 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
116 |
+
controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
|
117 |
+
Provides additional conditioning to the unet during the denoising process. If you set multiple ControlNets
|
118 |
+
as a list, the outputs from each ControlNet are added together to create one combined additional
|
119 |
+
conditioning.
|
120 |
+
scheduler ([`SchedulerMixin`]):
|
121 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
122 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
123 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
124 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
125 |
+
Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
|
126 |
+
feature_extractor ([`CLIPImageProcessor`]):
|
127 |
+
Model that extracts features from generated images to be used as inputs for the `safety_checker`.
|
128 |
+
"""
|
129 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
130 |
+
|
131 |
+
def __init__(
|
132 |
+
self,
|
133 |
+
vae: AutoencoderKL,
|
134 |
+
text_encoder: CLIPTextModel,
|
135 |
+
tokenizer: CLIPTokenizer,
|
136 |
+
unet: UNet2DConditionModel,
|
137 |
+
controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
|
138 |
+
scheduler: KarrasDiffusionSchedulers,
|
139 |
+
safety_checker: StableDiffusionSafetyChecker,
|
140 |
+
feature_extractor: CLIPImageProcessor,
|
141 |
+
requires_safety_checker: bool = True,
|
142 |
+
):
|
143 |
+
super().__init__()
|
144 |
+
|
145 |
+
if safety_checker is None and requires_safety_checker:
|
146 |
+
logger.warning(
|
147 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
148 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
149 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
150 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
151 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
152 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
153 |
+
)
|
154 |
+
|
155 |
+
if safety_checker is not None and feature_extractor is None:
|
156 |
+
raise ValueError(
|
157 |
+
f"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
158 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
159 |
+
)
|
160 |
+
|
161 |
+
if isinstance(controlnet, (list, tuple)):
|
162 |
+
controlnet = MultiControlNetModel(controlnet)
|
163 |
+
|
164 |
+
self.register_modules(
|
165 |
+
vae=vae,
|
166 |
+
text_encoder=text_encoder,
|
167 |
+
tokenizer=tokenizer,
|
168 |
+
unet=unet,
|
169 |
+
controlnet=controlnet,
|
170 |
+
scheduler=scheduler,
|
171 |
+
safety_checker=safety_checker,
|
172 |
+
feature_extractor=feature_extractor,
|
173 |
+
)
|
174 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
175 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
176 |
+
self.control_image_processor = VaeImageProcessor(
|
177 |
+
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
|
178 |
+
)
|
179 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
180 |
+
|
181 |
+
def _encode_prompt(
|
182 |
+
self,
|
183 |
+
prompt,
|
184 |
+
num_images_per_prompt,
|
185 |
+
do_classifier_free_guidance,
|
186 |
+
negative_prompt=None,
|
187 |
+
prompt_embeds: Optional[paddle.Tensor] = None,
|
188 |
+
negative_prompt_embeds: Optional[paddle.Tensor] = None,
|
189 |
+
lora_scale: Optional[float] = None,
|
190 |
+
):
|
191 |
+
r"""
|
192 |
+
Encodes the prompt into text encoder hidden states.
|
193 |
+
|
194 |
+
Args:
|
195 |
+
prompt (`str` or `List[str]`, *optional*):
|
196 |
+
prompt to be encoded
|
197 |
+
num_images_per_prompt (`int`):
|
198 |
+
number of images that should be generated per prompt
|
199 |
+
do_classifier_free_guidance (`bool`):
|
200 |
+
whether to use classifier free guidance or not
|
201 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
202 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
203 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
204 |
+
less than `1`).
|
205 |
+
prompt_embeds (`paddle.Tensor`, *optional*):
|
206 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
207 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
208 |
+
negative_prompt_embeds (`paddle.Tensor`, *optional*):
|
209 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
210 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
211 |
+
argument.
|
212 |
+
lora_scale (`float`, *optional*):
|
213 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
214 |
+
"""
|
215 |
+
# set lora scale so that monkey patched LoRA
|
216 |
+
# function of text encoder can correctly access it
|
217 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
218 |
+
self._lora_scale = lora_scale
|
219 |
+
|
220 |
+
if prompt is not None and isinstance(prompt, str):
|
221 |
+
batch_size = 1
|
222 |
+
elif prompt is not None and isinstance(prompt, list):
|
223 |
+
batch_size = len(prompt)
|
224 |
+
else:
|
225 |
+
batch_size = prompt_embeds.shape[0]
|
226 |
+
|
227 |
+
if prompt_embeds is None:
|
228 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
229 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
230 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
231 |
+
|
232 |
+
text_inputs = self.tokenizer(
|
233 |
+
prompt,
|
234 |
+
padding="max_length",
|
235 |
+
max_length=self.tokenizer.model_max_length,
|
236 |
+
truncation=True,
|
237 |
+
return_tensors="pd",
|
238 |
+
)
|
239 |
+
text_input_ids = text_inputs.input_ids
|
240 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pd").input_ids
|
241 |
+
|
242 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not paddle.equal_all(
|
243 |
+
text_input_ids, untruncated_ids
|
244 |
+
):
|
245 |
+
removed_text = self.tokenizer.batch_decode(
|
246 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
247 |
+
)
|
248 |
+
logger.warning(
|
249 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
250 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
251 |
+
)
|
252 |
+
|
253 |
+
config = (
|
254 |
+
self.text_encoder.config
|
255 |
+
if isinstance(self.text_encoder.config, dict)
|
256 |
+
else self.text_encoder.config.to_dict()
|
257 |
+
)
|
258 |
+
if config.get("use_attention_mask", None) is not None and config["use_attention_mask"]:
|
259 |
+
attention_mask = text_inputs.attention_mask
|
260 |
+
else:
|
261 |
+
attention_mask = None
|
262 |
+
|
263 |
+
prompt_embeds = self.text_encoder(
|
264 |
+
text_input_ids,
|
265 |
+
attention_mask=attention_mask,
|
266 |
+
)
|
267 |
+
prompt_embeds = prompt_embeds[0]
|
268 |
+
|
269 |
+
prompt_embeds = prompt_embeds.cast(dtype=self.text_encoder.dtype)
|
270 |
+
|
271 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
272 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
273 |
+
prompt_embeds = prompt_embeds.tile([1, num_images_per_prompt, 1])
|
274 |
+
prompt_embeds = prompt_embeds.reshape([bs_embed * num_images_per_prompt, seq_len, -1])
|
275 |
+
|
276 |
+
# get unconditional embeddings for classifier free guidance
|
277 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
278 |
+
uncond_tokens: List[str]
|
279 |
+
if negative_prompt is None:
|
280 |
+
uncond_tokens = [""] * batch_size
|
281 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
282 |
+
raise TypeError(
|
283 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
284 |
+
f" {type(prompt)}."
|
285 |
+
)
|
286 |
+
elif isinstance(negative_prompt, str):
|
287 |
+
uncond_tokens = [negative_prompt]
|
288 |
+
elif batch_size != len(negative_prompt):
|
289 |
+
raise ValueError(
|
290 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
291 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
292 |
+
" the batch size of `prompt`."
|
293 |
+
)
|
294 |
+
else:
|
295 |
+
uncond_tokens = negative_prompt
|
296 |
+
|
297 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
298 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
299 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
300 |
+
|
301 |
+
max_length = prompt_embeds.shape[1]
|
302 |
+
uncond_input = self.tokenizer(
|
303 |
+
uncond_tokens,
|
304 |
+
padding="max_length",
|
305 |
+
max_length=max_length,
|
306 |
+
truncation=True,
|
307 |
+
return_tensors="pd",
|
308 |
+
)
|
309 |
+
|
310 |
+
config = (
|
311 |
+
self.text_encoder.config
|
312 |
+
if isinstance(self.text_encoder.config, dict)
|
313 |
+
else self.text_encoder.config.to_dict()
|
314 |
+
)
|
315 |
+
if config.get("use_attention_mask", None) is not None and config["use_attention_mask"]:
|
316 |
+
attention_mask = uncond_input.attention_mask
|
317 |
+
else:
|
318 |
+
attention_mask = None
|
319 |
+
|
320 |
+
negative_prompt_embeds = self.text_encoder(
|
321 |
+
uncond_input.input_ids,
|
322 |
+
attention_mask=attention_mask,
|
323 |
+
)
|
324 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
325 |
+
|
326 |
+
if do_classifier_free_guidance:
|
327 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
328 |
+
seq_len = negative_prompt_embeds.shape[1]
|
329 |
+
|
330 |
+
negative_prompt_embeds = negative_prompt_embeds.cast(dtype=self.text_encoder.dtype)
|
331 |
+
|
332 |
+
negative_prompt_embeds = negative_prompt_embeds.tile([1, num_images_per_prompt, 1])
|
333 |
+
negative_prompt_embeds = negative_prompt_embeds.reshape([batch_size * num_images_per_prompt, seq_len, -1])
|
334 |
+
|
335 |
+
# For classifier free guidance, we need to do two forward passes.
|
336 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
337 |
+
# to avoid doing two forward passes
|
338 |
+
prompt_embeds = paddle.concat([negative_prompt_embeds, prompt_embeds])
|
339 |
+
|
340 |
+
return prompt_embeds
|
341 |
+
|
342 |
+
def run_safety_checker(self, image, dtype):
|
343 |
+
if self.safety_checker is None:
|
344 |
+
has_nsfw_concept = None
|
345 |
+
else:
|
346 |
+
if paddle.is_tensor(image):
|
347 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
348 |
+
else:
|
349 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
350 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pd")
|
351 |
+
image, has_nsfw_concept = self.safety_checker(
|
352 |
+
images=image, clip_input=safety_checker_input.pixel_values.cast(dtype)
|
353 |
+
)
|
354 |
+
return image, has_nsfw_concept
|
355 |
+
|
356 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
357 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
358 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
359 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
360 |
+
# and should be between [0, 1]
|
361 |
+
|
362 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
363 |
+
extra_step_kwargs = {}
|
364 |
+
if accepts_eta:
|
365 |
+
extra_step_kwargs["eta"] = eta
|
366 |
+
|
367 |
+
# check if the scheduler accepts generator
|
368 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
369 |
+
if accepts_generator:
|
370 |
+
extra_step_kwargs["generator"] = generator
|
371 |
+
return extra_step_kwargs
|
372 |
+
|
373 |
+
def check_inputs(
|
374 |
+
self,
|
375 |
+
prompt,
|
376 |
+
image,
|
377 |
+
callback_steps,
|
378 |
+
negative_prompt=None,
|
379 |
+
prompt_embeds=None,
|
380 |
+
negative_prompt_embeds=None,
|
381 |
+
controlnet_conditioning_scale=1.0,
|
382 |
+
):
|
383 |
+
if (callback_steps is None) or (
|
384 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
385 |
+
):
|
386 |
+
raise ValueError(
|
387 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
388 |
+
f" {type(callback_steps)}."
|
389 |
+
)
|
390 |
+
|
391 |
+
if prompt is not None and prompt_embeds is not None:
|
392 |
+
raise ValueError(
|
393 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
394 |
+
" only forward one of the two."
|
395 |
+
)
|
396 |
+
elif prompt is None and prompt_embeds is None:
|
397 |
+
raise ValueError(
|
398 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
399 |
+
)
|
400 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
401 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
402 |
+
|
403 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
404 |
+
raise ValueError(
|
405 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
406 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
407 |
+
)
|
408 |
+
|
409 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
410 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
411 |
+
raise ValueError(
|
412 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
413 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
414 |
+
f" {negative_prompt_embeds.shape}."
|
415 |
+
)
|
416 |
+
|
417 |
+
# `prompt` needs more sophisticated handling when there are multiple
|
418 |
+
# conditionings.
|
419 |
+
if isinstance(self.controlnet, MultiControlNetModel):
|
420 |
+
if isinstance(prompt, list):
|
421 |
+
logger.warning(
|
422 |
+
f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
|
423 |
+
" prompts. The conditionings will be fixed across the prompts."
|
424 |
+
)
|
425 |
+
|
426 |
+
if isinstance(self.controlnet, ControlNetModel):
|
427 |
+
self.check_image(image, prompt, prompt_embeds)
|
428 |
+
elif isinstance(self.controlnet, MultiControlNetModel):
|
429 |
+
if not isinstance(image, list):
|
430 |
+
raise TypeError("For multiple controlnets: `image` must be type `list`")
|
431 |
+
|
432 |
+
# When `image` is a nested list:
|
433 |
+
# (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
|
434 |
+
elif any(isinstance(i, list) for i in image):
|
435 |
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
436 |
+
elif len(image) != len(self.controlnet.nets):
|
437 |
+
raise ValueError(
|
438 |
+
f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
|
439 |
+
)
|
440 |
+
|
441 |
+
for image_ in image:
|
442 |
+
self.check_image(image_, prompt, prompt_embeds)
|
443 |
+
else:
|
444 |
+
assert False
|
445 |
+
|
446 |
+
# Check `controlnet_conditioning_scale`
|
447 |
+
if isinstance(self.controlnet, ControlNetModel):
|
448 |
+
if not isinstance(controlnet_conditioning_scale, float):
|
449 |
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
450 |
+
elif isinstance(self.controlnet, MultiControlNetModel):
|
451 |
+
if isinstance(controlnet_conditioning_scale, list):
|
452 |
+
if any(isinstance(i, list) for i in controlnet_conditioning_scale):
|
453 |
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
454 |
+
elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
|
455 |
+
self.controlnet.nets
|
456 |
+
):
|
457 |
+
raise ValueError(
|
458 |
+
"For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
|
459 |
+
" the same length as the number of controlnets"
|
460 |
+
)
|
461 |
+
else:
|
462 |
+
assert False
|
463 |
+
|
464 |
+
def check_image(self, image, prompt, prompt_embeds):
|
465 |
+
image_is_pil = isinstance(image, PIL.Image.Image)
|
466 |
+
image_is_tensor = isinstance(image, paddle.Tensor)
|
467 |
+
image_is_np = isinstance(image, np.ndarray)
|
468 |
+
image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
|
469 |
+
image_is_tensor_list = isinstance(image, list) and isinstance(image[0], paddle.Tensor)
|
470 |
+
image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
|
471 |
+
|
472 |
+
if (
|
473 |
+
not image_is_pil
|
474 |
+
and not image_is_tensor
|
475 |
+
and not image_is_np
|
476 |
+
and not image_is_pil_list
|
477 |
+
and not image_is_tensor_list
|
478 |
+
and not image_is_np_list
|
479 |
+
):
|
480 |
+
raise TypeError(
|
481 |
+
f"image must be passed and be one of PIL image, numpy array, paddle tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
|
482 |
+
)
|
483 |
+
|
484 |
+
if image_is_pil:
|
485 |
+
image_batch_size = 1
|
486 |
+
else:
|
487 |
+
image_batch_size = len(image)
|
488 |
+
|
489 |
+
if prompt is not None and isinstance(prompt, str):
|
490 |
+
prompt_batch_size = 1
|
491 |
+
elif prompt is not None and isinstance(prompt, list):
|
492 |
+
prompt_batch_size = len(prompt)
|
493 |
+
elif prompt_embeds is not None:
|
494 |
+
prompt_batch_size = prompt_embeds.shape[0]
|
495 |
+
|
496 |
+
if image_batch_size != 1 and image_batch_size != prompt_batch_size:
|
497 |
+
raise ValueError(
|
498 |
+
f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
|
499 |
+
)
|
500 |
+
|
501 |
+
def prepare_control_image(
|
502 |
+
self,
|
503 |
+
image,
|
504 |
+
width,
|
505 |
+
height,
|
506 |
+
batch_size,
|
507 |
+
num_images_per_prompt,
|
508 |
+
dtype,
|
509 |
+
do_classifier_free_guidance=False,
|
510 |
+
guess_mode=False,
|
511 |
+
):
|
512 |
+
image = self.control_image_processor.preprocess(image, height=height, width=width).cast(dtype=paddle.float32)
|
513 |
+
image_batch_size = image.shape[0]
|
514 |
+
|
515 |
+
if image_batch_size == 1:
|
516 |
+
repeat_by = batch_size
|
517 |
+
else:
|
518 |
+
# image batch size is the same as prompt batch size
|
519 |
+
repeat_by = num_images_per_prompt
|
520 |
+
|
521 |
+
image = image.repeat_interleave(repeat_by, axis=0)
|
522 |
+
|
523 |
+
image = image.cast(dtype)
|
524 |
+
|
525 |
+
if do_classifier_free_guidance and not guess_mode:
|
526 |
+
image = paddle.concat([image] * 2)
|
527 |
+
|
528 |
+
return image
|
529 |
+
|
530 |
+
def get_timesteps(self, num_inference_steps, strength):
|
531 |
+
# get the original timestep using init_timestep
|
532 |
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
533 |
+
|
534 |
+
t_start = max(num_inference_steps - init_timestep, 0)
|
535 |
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
536 |
+
|
537 |
+
return timesteps, num_inference_steps - t_start
|
538 |
+
|
539 |
+
def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, generator=None):
|
540 |
+
if not isinstance(image, (paddle.Tensor, PIL.Image.Image, list)):
|
541 |
+
raise ValueError(
|
542 |
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
543 |
+
)
|
544 |
+
|
545 |
+
image = image.cast(dtype=dtype)
|
546 |
+
|
547 |
+
batch_size = batch_size * num_images_per_prompt
|
548 |
+
|
549 |
+
if image.shape[1] == 4:
|
550 |
+
init_latents = image
|
551 |
+
|
552 |
+
else:
|
553 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
554 |
+
raise ValueError(
|
555 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
556 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
557 |
+
)
|
558 |
+
|
559 |
+
elif isinstance(generator, list):
|
560 |
+
init_latents = [
|
561 |
+
self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
|
562 |
+
]
|
563 |
+
init_latents = paddle.concat(init_latents, axis=0)
|
564 |
+
else:
|
565 |
+
init_latents = self.vae.encode(image).latent_dist.sample(generator)
|
566 |
+
|
567 |
+
init_latents = self.vae.config.scaling_factor * init_latents
|
568 |
+
|
569 |
+
if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
|
570 |
+
# expand init_latents for batch_size
|
571 |
+
deprecation_message = (
|
572 |
+
f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
|
573 |
+
" images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
|
574 |
+
" that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
|
575 |
+
" your script to pass as many initial images as text prompts to suppress this warning."
|
576 |
+
)
|
577 |
+
deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
|
578 |
+
additional_image_per_prompt = batch_size // init_latents.shape[0]
|
579 |
+
init_latents = paddle.concat([init_latents] * additional_image_per_prompt, axis=0)
|
580 |
+
elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
|
581 |
+
raise ValueError(
|
582 |
+
f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
|
583 |
+
)
|
584 |
+
else:
|
585 |
+
init_latents = paddle.concat([init_latents], axis=0)
|
586 |
+
|
587 |
+
shape = init_latents.shape
|
588 |
+
noise = randn_tensor(shape, generator=generator, dtype=dtype)
|
589 |
+
|
590 |
+
# get latents
|
591 |
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
592 |
+
latents = init_latents
|
593 |
+
|
594 |
+
return latents
|
595 |
+
|
596 |
+
@paddle.no_grad()
|
597 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
598 |
+
def __call__(
|
599 |
+
self,
|
600 |
+
prompt: Union[str, List[str]] = None,
|
601 |
+
image: Union[
|
602 |
+
paddle.Tensor,
|
603 |
+
PIL.Image.Image,
|
604 |
+
np.ndarray,
|
605 |
+
List[paddle.Tensor],
|
606 |
+
List[PIL.Image.Image],
|
607 |
+
List[np.ndarray],
|
608 |
+
] = None,
|
609 |
+
control_image: Union[
|
610 |
+
paddle.Tensor,
|
611 |
+
PIL.Image.Image,
|
612 |
+
np.ndarray,
|
613 |
+
List[paddle.Tensor],
|
614 |
+
List[PIL.Image.Image],
|
615 |
+
List[np.ndarray],
|
616 |
+
] = None,
|
617 |
+
height: Optional[int] = None,
|
618 |
+
width: Optional[int] = None,
|
619 |
+
strength: float = 0.8,
|
620 |
+
num_inference_steps: int = 50,
|
621 |
+
guidance_scale: float = 7.5,
|
622 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
623 |
+
num_images_per_prompt: Optional[int] = 1,
|
624 |
+
eta: float = 0.0,
|
625 |
+
generator: Optional[Union[paddle.Generator, List[paddle.Generator]]] = None,
|
626 |
+
latents: Optional[paddle.Tensor] = None,
|
627 |
+
prompt_embeds: Optional[paddle.Tensor] = None,
|
628 |
+
negative_prompt_embeds: Optional[paddle.Tensor] = None,
|
629 |
+
output_type: Optional[str] = "pil",
|
630 |
+
return_dict: bool = True,
|
631 |
+
callback: Optional[Callable[[int, int, paddle.Tensor], None]] = None,
|
632 |
+
callback_steps: int = 1,
|
633 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
634 |
+
controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
|
635 |
+
guess_mode: bool = False,
|
636 |
+
):
|
637 |
+
r"""
|
638 |
+
Function invoked when calling the pipeline for generation.
|
639 |
+
|
640 |
+
Args:
|
641 |
+
prompt (`str` or `List[str]`, *optional*):
|
642 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
643 |
+
instead.
|
644 |
+
image (`paddle.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[paddle.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
645 |
+
`List[List[paddle.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
646 |
+
The initial image will be used as the starting point for the image generation process. Can also accpet
|
647 |
+
image latents as `image`, if passing latents directly, it will not be encoded again.
|
648 |
+
control_image (`paddle.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[paddle.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
649 |
+
`List[List[paddle.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
650 |
+
The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
|
651 |
+
the type is specified as `paddle.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can
|
652 |
+
also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If
|
653 |
+
height and/or width are passed, `image` is resized according to them. If multiple ControlNets are
|
654 |
+
specified in init, images must be passed as a list such that each element of the list can be correctly
|
655 |
+
batched for input to a single controlnet.
|
656 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
657 |
+
The height in pixels of the generated image.
|
658 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
659 |
+
The width in pixels of the generated image.
|
660 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
661 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
662 |
+
expense of slower inference.
|
663 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
664 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
665 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
666 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
667 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
668 |
+
usually at the expense of lower image quality.
|
669 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
670 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
671 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
672 |
+
less than `1`).
|
673 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
674 |
+
The number of images to generate per prompt.
|
675 |
+
eta (`float`, *optional*, defaults to 0.0):
|
676 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
677 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
678 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
679 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
680 |
+
to make generation deterministic.
|
681 |
+
latents (`paddle.Tensor`, *optional*):
|
682 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
683 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
684 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
685 |
+
prompt_embeds (`paddle.Tensor`, *optional*):
|
686 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
687 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
688 |
+
negative_prompt_embeds (`paddle.Tensor`, *optional*):
|
689 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
690 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
691 |
+
argument.
|
692 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
693 |
+
The output format of the generate image. Choose between
|
694 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
695 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
696 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
697 |
+
plain tuple.
|
698 |
+
callback (`Callable`, *optional*):
|
699 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
700 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: paddle.Tensor)`.
|
701 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
702 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
703 |
+
called at every step.
|
704 |
+
cross_attention_kwargs (`dict`, *optional*):
|
705 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
706 |
+
`self.processor` in
|
707 |
+
[diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
|
708 |
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
709 |
+
The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
|
710 |
+
to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
|
711 |
+
corresponding scale as a list. Note that by default, we use a smaller conditioning scale for inpainting
|
712 |
+
than for [`~StableDiffusionControlNetPipeline.__call__`].
|
713 |
+
guess_mode (`bool`, *optional*, defaults to `False`):
|
714 |
+
In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
|
715 |
+
you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
|
716 |
+
|
717 |
+
Examples:
|
718 |
+
|
719 |
+
Returns:
|
720 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
721 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
|
722 |
+
When returning a tuple, the first element is a list with the generated images, and the second element is a
|
723 |
+
list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
|
724 |
+
(nsfw) content, according to the `safety_checker`.
|
725 |
+
"""
|
726 |
+
# 1. Check inputs. Raise error if not correct
|
727 |
+
self.check_inputs(
|
728 |
+
prompt,
|
729 |
+
control_image,
|
730 |
+
callback_steps,
|
731 |
+
negative_prompt,
|
732 |
+
prompt_embeds,
|
733 |
+
negative_prompt_embeds,
|
734 |
+
controlnet_conditioning_scale,
|
735 |
+
)
|
736 |
+
|
737 |
+
# 2. Define call parameters
|
738 |
+
if prompt is not None and isinstance(prompt, str):
|
739 |
+
batch_size = 1
|
740 |
+
elif prompt is not None and isinstance(prompt, list):
|
741 |
+
batch_size = len(prompt)
|
742 |
+
else:
|
743 |
+
batch_size = prompt_embeds.shape[0]
|
744 |
+
|
745 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
746 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
747 |
+
# corresponds to doing no classifier free guidance.
|
748 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
749 |
+
|
750 |
+
controlnet = self.controlnet
|
751 |
+
|
752 |
+
if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
|
753 |
+
controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
|
754 |
+
|
755 |
+
global_pool_conditions = (
|
756 |
+
controlnet.config.global_pool_conditions
|
757 |
+
if isinstance(controlnet, ControlNetModel)
|
758 |
+
else controlnet.nets[0].config.global_pool_conditions
|
759 |
+
)
|
760 |
+
guess_mode = guess_mode or global_pool_conditions
|
761 |
+
|
762 |
+
# 3. Encode input prompt
|
763 |
+
text_encoder_lora_scale = (
|
764 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
765 |
+
)
|
766 |
+
prompt_embeds = self._encode_prompt(
|
767 |
+
prompt,
|
768 |
+
num_images_per_prompt,
|
769 |
+
do_classifier_free_guidance,
|
770 |
+
negative_prompt,
|
771 |
+
prompt_embeds=prompt_embeds,
|
772 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
773 |
+
lora_scale=text_encoder_lora_scale,
|
774 |
+
)
|
775 |
+
# 4. Prepare image
|
776 |
+
image = self.image_processor.preprocess(image).cast(dtype=paddle.float32)
|
777 |
+
|
778 |
+
# 5. Prepare controlnet_conditioning_image
|
779 |
+
if isinstance(controlnet, ControlNetModel):
|
780 |
+
control_image = self.prepare_control_image(
|
781 |
+
image=control_image,
|
782 |
+
width=width,
|
783 |
+
height=height,
|
784 |
+
batch_size=batch_size * num_images_per_prompt,
|
785 |
+
num_images_per_prompt=num_images_per_prompt,
|
786 |
+
dtype=controlnet.dtype,
|
787 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
788 |
+
guess_mode=guess_mode,
|
789 |
+
)
|
790 |
+
elif isinstance(controlnet, MultiControlNetModel):
|
791 |
+
control_images = []
|
792 |
+
|
793 |
+
for control_image_ in control_image:
|
794 |
+
control_image_ = self.prepare_control_image(
|
795 |
+
image=control_image_,
|
796 |
+
width=width,
|
797 |
+
height=height,
|
798 |
+
batch_size=batch_size * num_images_per_prompt,
|
799 |
+
num_images_per_prompt=num_images_per_prompt,
|
800 |
+
dtype=controlnet.dtype,
|
801 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
802 |
+
guess_mode=guess_mode,
|
803 |
+
)
|
804 |
+
|
805 |
+
control_images.append(control_image_)
|
806 |
+
|
807 |
+
control_image = control_images
|
808 |
+
else:
|
809 |
+
assert False
|
810 |
+
|
811 |
+
# 5. Prepare timesteps
|
812 |
+
self.scheduler.set_timesteps(
|
813 |
+
num_inference_steps,
|
814 |
+
)
|
815 |
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength)
|
816 |
+
latent_timestep = timesteps[:1].tile([batch_size * num_images_per_prompt])
|
817 |
+
|
818 |
+
# 6. Prepare latent variables
|
819 |
+
latents = self.prepare_latents(
|
820 |
+
image,
|
821 |
+
latent_timestep,
|
822 |
+
batch_size,
|
823 |
+
num_images_per_prompt,
|
824 |
+
prompt_embeds.dtype,
|
825 |
+
generator,
|
826 |
+
)
|
827 |
+
|
828 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
829 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
830 |
+
|
831 |
+
# 8. Denoising loop
|
832 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
833 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
834 |
+
for i, t in enumerate(timesteps):
|
835 |
+
# expand the latents if we are doing classifier free guidance
|
836 |
+
latent_model_input = paddle.concat([latents] * 2) if do_classifier_free_guidance else latents
|
837 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
838 |
+
|
839 |
+
# controlnet(s) inference
|
840 |
+
if guess_mode and do_classifier_free_guidance:
|
841 |
+
# Infer ControlNet only for the conditional batch.
|
842 |
+
control_model_input = latents
|
843 |
+
control_model_input = self.scheduler.scale_model_input(control_model_input, t)
|
844 |
+
controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
|
845 |
+
else:
|
846 |
+
control_model_input = latent_model_input
|
847 |
+
controlnet_prompt_embeds = prompt_embeds
|
848 |
+
|
849 |
+
down_block_res_samples, mid_block_res_sample = self.controlnet(
|
850 |
+
control_model_input,
|
851 |
+
t,
|
852 |
+
encoder_hidden_states=controlnet_prompt_embeds,
|
853 |
+
controlnet_cond=control_image,
|
854 |
+
conditioning_scale=controlnet_conditioning_scale,
|
855 |
+
guess_mode=guess_mode,
|
856 |
+
return_dict=False,
|
857 |
+
)
|
858 |
+
|
859 |
+
if guess_mode and do_classifier_free_guidance:
|
860 |
+
# Infered ControlNet only for the conditional batch.
|
861 |
+
# To apply the output of ControlNet to both the unconditional and conditional batches,
|
862 |
+
# add 0 to the unconditional batch to keep it unchanged.
|
863 |
+
down_block_res_samples = [paddle.concat([paddle.zeros_like(d), d]) for d in down_block_res_samples]
|
864 |
+
mid_block_res_sample = paddle.concat(
|
865 |
+
[paddle.zeros_like(mid_block_res_sample), mid_block_res_sample]
|
866 |
+
)
|
867 |
+
|
868 |
+
# predict the noise residual
|
869 |
+
noise_pred = self.unet(
|
870 |
+
latent_model_input,
|
871 |
+
t,
|
872 |
+
encoder_hidden_states=prompt_embeds,
|
873 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
874 |
+
down_block_additional_residuals=down_block_res_samples,
|
875 |
+
mid_block_additional_residual=mid_block_res_sample,
|
876 |
+
return_dict=False,
|
877 |
+
)[0]
|
878 |
+
|
879 |
+
# perform guidance
|
880 |
+
if do_classifier_free_guidance:
|
881 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
882 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
883 |
+
|
884 |
+
# compute the previous noisy sample x_t -> x_t-1
|
885 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
886 |
+
|
887 |
+
# call the callback, if provided
|
888 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
889 |
+
progress_bar.update()
|
890 |
+
if callback is not None and i % callback_steps == 0:
|
891 |
+
callback(i, t, latents)
|
892 |
+
|
893 |
+
if not output_type == "latent":
|
894 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
895 |
+
image, has_nsfw_concept = self.run_safety_checker(image, prompt_embeds.dtype)
|
896 |
+
else:
|
897 |
+
image = latents
|
898 |
+
has_nsfw_concept = None
|
899 |
+
|
900 |
+
if has_nsfw_concept is None:
|
901 |
+
do_denormalize = [True] * image.shape[0]
|
902 |
+
else:
|
903 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
904 |
+
|
905 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
906 |
+
|
907 |
+
if not return_dict:
|
908 |
+
return (image, has_nsfw_concept)
|
909 |
+
|
910 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|