XCLiu commited on
Commit
92500b2
1 Parent(s): 5ea557e

Upload pipeline_rf.py

Browse files
Files changed (1) hide show
  1. pipeline_rf.py +703 -0
pipeline_rf.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import torch
19
+ from packaging import version
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers.configuration_utils import FrozenDict
23
+ from diffusers.image_processor import VaeImageProcessor
24
+ from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
25
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
26
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
27
+ from diffusers.schedulers import KarrasDiffusionSchedulers
28
+ from diffusers.utils import (
29
+ deprecate,
30
+ logging,
31
+ replace_example_docstring,
32
+ )
33
+ from diffusers.utils.torch_utils import randn_tensor
34
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
35
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
36
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
43
+ """
44
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
45
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
46
+ """
47
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
48
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
49
+ # rescale the results from guidance (fixes overexposure)
50
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
51
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
52
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
53
+ return noise_cfg
54
+
55
+
56
+ class RectifiedFlowPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin):
57
+ r"""
58
+ Pipeline for text-to-image generation using Rectified Flow and Euler discretization.
59
+ This customized pipeline is based on StableDiffusionPipeline from the official Diffusers library (0.21.4)
60
+
61
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
62
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
63
+
64
+ The pipeline also inherits the following loading methods:
65
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
66
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
67
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
68
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
69
+
70
+ Args:
71
+ vae ([`AutoencoderKL`]):
72
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
73
+ text_encoder ([`~transformers.CLIPTextModel`]):
74
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
75
+ tokenizer ([`~transformers.CLIPTokenizer`]):
76
+ A `CLIPTokenizer` to tokenize text.
77
+ unet ([`UNet2DConditionModel`]):
78
+ A `UNet2DConditionModel` to denoise the encoded image latents.
79
+ scheduler ([`SchedulerMixin`]):
80
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
81
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
82
+ safety_checker ([`StableDiffusionSafetyChecker`]):
83
+ Classification module that estimates whether generated images could be considered offensive or harmful.
84
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
85
+ about a model's potential harms.
86
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
87
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
88
+ """
89
+ model_cpu_offload_seq = "text_encoder->unet->vae"
90
+ _optional_components = ["safety_checker", "feature_extractor"]
91
+ _exclude_from_cpu_offload = ["safety_checker"]
92
+
93
+ def __init__(
94
+ self,
95
+ vae: AutoencoderKL,
96
+ text_encoder: CLIPTextModel,
97
+ tokenizer: CLIPTokenizer,
98
+ unet: UNet2DConditionModel,
99
+ scheduler: KarrasDiffusionSchedulers,
100
+ safety_checker: StableDiffusionSafetyChecker,
101
+ feature_extractor: CLIPImageProcessor,
102
+ requires_safety_checker: bool = True,
103
+ ):
104
+ super().__init__()
105
+
106
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
107
+ deprecation_message = (
108
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
109
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
110
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
111
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
112
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
113
+ " file"
114
+ )
115
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
116
+ new_config = dict(scheduler.config)
117
+ new_config["steps_offset"] = 1
118
+ scheduler._internal_dict = FrozenDict(new_config)
119
+
120
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
121
+ deprecation_message = (
122
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
123
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
124
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
125
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
126
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
127
+ )
128
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
129
+ new_config = dict(scheduler.config)
130
+ new_config["clip_sample"] = False
131
+ scheduler._internal_dict = FrozenDict(new_config)
132
+
133
+ if safety_checker is None and requires_safety_checker:
134
+ logger.warning(
135
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
136
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
137
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
138
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
139
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
140
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
141
+ )
142
+
143
+ if safety_checker is not None and feature_extractor is None:
144
+ raise ValueError(
145
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
146
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
147
+ )
148
+
149
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
150
+ version.parse(unet.config._diffusers_version).base_version
151
+ ) < version.parse("0.9.0.dev0")
152
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
153
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
154
+ deprecation_message = (
155
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
156
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
157
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
158
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
159
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
160
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
161
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
162
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
163
+ " the `unet/config.json` file"
164
+ )
165
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
166
+ new_config = dict(unet.config)
167
+ new_config["sample_size"] = 64
168
+ unet._internal_dict = FrozenDict(new_config)
169
+
170
+ self.register_modules(
171
+ vae=vae,
172
+ text_encoder=text_encoder,
173
+ tokenizer=tokenizer,
174
+ unet=unet,
175
+ scheduler=scheduler,
176
+ safety_checker=safety_checker,
177
+ feature_extractor=feature_extractor,
178
+ )
179
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
180
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
181
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
182
+
183
+ def enable_vae_slicing(self):
184
+ r"""
185
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
186
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
187
+ """
188
+ self.vae.enable_slicing()
189
+
190
+ def disable_vae_slicing(self):
191
+ r"""
192
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
193
+ computing decoding in one step.
194
+ """
195
+ self.vae.disable_slicing()
196
+
197
+ def enable_vae_tiling(self):
198
+ r"""
199
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
200
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
201
+ processing larger images.
202
+ """
203
+ self.vae.enable_tiling()
204
+
205
+ def disable_vae_tiling(self):
206
+ r"""
207
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
208
+ computing decoding in one step.
209
+ """
210
+ self.vae.disable_tiling()
211
+
212
+ def _encode_prompt(
213
+ self,
214
+ prompt,
215
+ device,
216
+ num_images_per_prompt,
217
+ do_classifier_free_guidance,
218
+ negative_prompt=None,
219
+ prompt_embeds: Optional[torch.FloatTensor] = None,
220
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
221
+ lora_scale: Optional[float] = None,
222
+ ):
223
+ 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."
224
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
225
+
226
+ prompt_embeds_tuple = self.encode_prompt(
227
+ prompt=prompt,
228
+ device=device,
229
+ num_images_per_prompt=num_images_per_prompt,
230
+ do_classifier_free_guidance=do_classifier_free_guidance,
231
+ negative_prompt=negative_prompt,
232
+ prompt_embeds=prompt_embeds,
233
+ negative_prompt_embeds=negative_prompt_embeds,
234
+ lora_scale=lora_scale,
235
+ )
236
+
237
+ # concatenate for backwards comp
238
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
239
+
240
+ return prompt_embeds
241
+
242
+ def encode_prompt(
243
+ self,
244
+ prompt,
245
+ device,
246
+ num_images_per_prompt,
247
+ do_classifier_free_guidance,
248
+ negative_prompt=None,
249
+ prompt_embeds: Optional[torch.FloatTensor] = None,
250
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
251
+ lora_scale: Optional[float] = None,
252
+ ):
253
+ r"""
254
+ Encodes the prompt into text encoder hidden states.
255
+
256
+ Args:
257
+ prompt (`str` or `List[str]`, *optional*):
258
+ prompt to be encoded
259
+ device: (`torch.device`):
260
+ torch device
261
+ num_images_per_prompt (`int`):
262
+ number of images that should be generated per prompt
263
+ do_classifier_free_guidance (`bool`):
264
+ whether to use classifier free guidance or not
265
+ negative_prompt (`str` or `List[str]`, *optional*):
266
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
267
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
268
+ less than `1`).
269
+ prompt_embeds (`torch.FloatTensor`, *optional*):
270
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
271
+ provided, text embeddings will be generated from `prompt` input argument.
272
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
273
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
274
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
275
+ argument.
276
+ lora_scale (`float`, *optional*):
277
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
278
+ """
279
+ # set lora scale so that monkey patched LoRA
280
+ # function of text encoder can correctly access it
281
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
282
+ self._lora_scale = lora_scale
283
+
284
+ # dynamically adjust the LoRA scale
285
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
286
+
287
+ if prompt is not None and isinstance(prompt, str):
288
+ batch_size = 1
289
+ elif prompt is not None and isinstance(prompt, list):
290
+ batch_size = len(prompt)
291
+ else:
292
+ batch_size = prompt_embeds.shape[0]
293
+
294
+ if prompt_embeds is None:
295
+ # textual inversion: procecss multi-vector tokens if necessary
296
+ if isinstance(self, TextualInversionLoaderMixin):
297
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
298
+
299
+ text_inputs = self.tokenizer(
300
+ prompt,
301
+ padding="max_length",
302
+ max_length=self.tokenizer.model_max_length,
303
+ truncation=True,
304
+ return_tensors="pt",
305
+ )
306
+ text_input_ids = text_inputs.input_ids
307
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
308
+
309
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
310
+ text_input_ids, untruncated_ids
311
+ ):
312
+ removed_text = self.tokenizer.batch_decode(
313
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
314
+ )
315
+ logger.warning(
316
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
317
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
318
+ )
319
+
320
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
321
+ attention_mask = text_inputs.attention_mask.to(device)
322
+ else:
323
+ attention_mask = None
324
+
325
+ prompt_embeds = self.text_encoder(
326
+ text_input_ids.to(device),
327
+ attention_mask=attention_mask,
328
+ )
329
+ prompt_embeds = prompt_embeds[0]
330
+
331
+ if self.text_encoder is not None:
332
+ prompt_embeds_dtype = self.text_encoder.dtype
333
+ elif self.unet is not None:
334
+ prompt_embeds_dtype = self.unet.dtype
335
+ else:
336
+ prompt_embeds_dtype = prompt_embeds.dtype
337
+
338
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
339
+
340
+ bs_embed, seq_len, _ = prompt_embeds.shape
341
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
342
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
343
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
344
+
345
+ # get unconditional embeddings for classifier free guidance
346
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
347
+ uncond_tokens: List[str]
348
+ if negative_prompt is None:
349
+ uncond_tokens = [""] * batch_size
350
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
351
+ raise TypeError(
352
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
353
+ f" {type(prompt)}."
354
+ )
355
+ elif isinstance(negative_prompt, str):
356
+ uncond_tokens = [negative_prompt]
357
+ elif batch_size != len(negative_prompt):
358
+ raise ValueError(
359
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
360
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
361
+ " the batch size of `prompt`."
362
+ )
363
+ else:
364
+ uncond_tokens = negative_prompt
365
+
366
+ # textual inversion: procecss multi-vector tokens if necessary
367
+ if isinstance(self, TextualInversionLoaderMixin):
368
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
369
+
370
+ max_length = prompt_embeds.shape[1]
371
+ uncond_input = self.tokenizer(
372
+ uncond_tokens,
373
+ padding="max_length",
374
+ max_length=max_length,
375
+ truncation=True,
376
+ return_tensors="pt",
377
+ )
378
+
379
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
380
+ attention_mask = uncond_input.attention_mask.to(device)
381
+ else:
382
+ attention_mask = None
383
+
384
+ negative_prompt_embeds = self.text_encoder(
385
+ uncond_input.input_ids.to(device),
386
+ attention_mask=attention_mask,
387
+ )
388
+ negative_prompt_embeds = negative_prompt_embeds[0]
389
+
390
+ if do_classifier_free_guidance:
391
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
392
+ seq_len = negative_prompt_embeds.shape[1]
393
+
394
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
395
+
396
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
397
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
398
+
399
+ return prompt_embeds, negative_prompt_embeds
400
+
401
+ def run_safety_checker(self, image, device, dtype):
402
+ if self.safety_checker is None:
403
+ has_nsfw_concept = None
404
+ else:
405
+ if torch.is_tensor(image):
406
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
407
+ else:
408
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
409
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
410
+ image, has_nsfw_concept = self.safety_checker(
411
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
412
+ )
413
+ return image, has_nsfw_concept
414
+
415
+ def decode_latents(self, latents):
416
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
417
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
418
+
419
+ latents = 1 / self.vae.config.scaling_factor * latents
420
+ image = self.vae.decode(latents, return_dict=False)[0]
421
+ image = (image / 2 + 0.5).clamp(0, 1)
422
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
423
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
424
+ return image
425
+
426
+ def prepare_extra_step_kwargs(self, generator, eta):
427
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
428
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
429
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
430
+ # and should be between [0, 1]
431
+
432
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
433
+ extra_step_kwargs = {}
434
+ if accepts_eta:
435
+ extra_step_kwargs["eta"] = eta
436
+
437
+ # check if the scheduler accepts generator
438
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
439
+ if accepts_generator:
440
+ extra_step_kwargs["generator"] = generator
441
+ return extra_step_kwargs
442
+
443
+ def check_inputs(
444
+ self,
445
+ prompt,
446
+ height,
447
+ width,
448
+ callback_steps,
449
+ negative_prompt=None,
450
+ prompt_embeds=None,
451
+ negative_prompt_embeds=None,
452
+ ):
453
+ if height % 8 != 0 or width % 8 != 0:
454
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
455
+
456
+ if (callback_steps is None) or (
457
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
458
+ ):
459
+ raise ValueError(
460
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
461
+ f" {type(callback_steps)}."
462
+ )
463
+
464
+ if prompt is not None and prompt_embeds is not None:
465
+ raise ValueError(
466
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
467
+ " only forward one of the two."
468
+ )
469
+ elif prompt is None and prompt_embeds is None:
470
+ raise ValueError(
471
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
472
+ )
473
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
474
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
475
+
476
+ if negative_prompt is not None and negative_prompt_embeds is not None:
477
+ raise ValueError(
478
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
479
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
480
+ )
481
+
482
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
483
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
484
+ raise ValueError(
485
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
486
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
487
+ f" {negative_prompt_embeds.shape}."
488
+ )
489
+
490
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
491
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
492
+ if isinstance(generator, list) and len(generator) != batch_size:
493
+ raise ValueError(
494
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
495
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
496
+ )
497
+
498
+ if latents is None:
499
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
500
+ else:
501
+ latents = latents.to(device)
502
+
503
+ # scale the initial noise by the standard deviation required by the scheduler
504
+ latents = latents * self.scheduler.init_noise_sigma
505
+ return latents
506
+
507
+ @torch.no_grad()
508
+ def __call__(
509
+ self,
510
+ prompt: Union[str, List[str]] = None,
511
+ height: Optional[int] = None,
512
+ width: Optional[int] = None,
513
+ num_inference_steps: int = 50,
514
+ guidance_scale: float = 7.5,
515
+ negative_prompt: Optional[Union[str, List[str]]] = None,
516
+ num_images_per_prompt: Optional[int] = 1,
517
+ eta: float = 0.0,
518
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
519
+ latents: Optional[torch.FloatTensor] = None,
520
+ prompt_embeds: Optional[torch.FloatTensor] = None,
521
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
522
+ output_type: Optional[str] = "pil",
523
+ return_dict: bool = True,
524
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
525
+ callback_steps: int = 1,
526
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
527
+ guidance_rescale: float = 0.0,
528
+ ):
529
+ r"""
530
+ The call function to the pipeline for generation.
531
+
532
+ Args:
533
+ prompt (`str` or `List[str]`, *optional*):
534
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
535
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
536
+ The height in pixels of the generated image.
537
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
538
+ The width in pixels of the generated image.
539
+ num_inference_steps (`int`, *optional*, defaults to 50):
540
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
541
+ expense of slower inference.
542
+ guidance_scale (`float`, *optional*, defaults to 7.5):
543
+ A higher guidance scale value encourages the model to generate images closely linked to the text
544
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
545
+ negative_prompt (`str` or `List[str]`, *optional*):
546
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
547
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
548
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
549
+ The number of images to generate per prompt.
550
+ eta (`float`, *optional*, defaults to 0.0):
551
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
552
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
553
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
554
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
555
+ generation deterministic.
556
+ latents (`torch.FloatTensor`, *optional*):
557
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
558
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
559
+ tensor is generated by sampling using the supplied random `generator`.
560
+ prompt_embeds (`torch.FloatTensor`, *optional*):
561
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
562
+ provided, text embeddings are generated from the `prompt` input argument.
563
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
564
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
565
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
566
+ output_type (`str`, *optional*, defaults to `"pil"`):
567
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
568
+ return_dict (`bool`, *optional*, defaults to `True`):
569
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
570
+ plain tuple.
571
+ callback (`Callable`, *optional*):
572
+ A function that calls every `callback_steps` steps during inference. The function is called with the
573
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
574
+ callback_steps (`int`, *optional*, defaults to 1):
575
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
576
+ every step.
577
+ cross_attention_kwargs (`dict`, *optional*):
578
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
579
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
580
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
581
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
582
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
583
+ using zero terminal SNR.
584
+
585
+ Examples:
586
+
587
+ Returns:
588
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
589
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
590
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
591
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
592
+ "not-safe-for-work" (nsfw) content.
593
+ """
594
+ # 0. Default height and width to unet
595
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
596
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
597
+
598
+ # 1. Check inputs. Raise error if not correct
599
+ self.check_inputs(
600
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, 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
+ text_encoder_lora_scale = (
619
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
620
+ )
621
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
622
+ prompt,
623
+ device,
624
+ num_images_per_prompt,
625
+ do_classifier_free_guidance,
626
+ negative_prompt,
627
+ prompt_embeds=prompt_embeds,
628
+ negative_prompt_embeds=negative_prompt_embeds,
629
+ lora_scale=text_encoder_lora_scale,
630
+ )
631
+ # For classifier free guidance, we need to do two forward passes.
632
+ # Here we concatenate the unconditional and text embeddings into a single batch
633
+ # to avoid doing two forward passes
634
+ if do_classifier_free_guidance:
635
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
636
+
637
+ # 4. Prepare timesteps
638
+ timesteps = [(1. - i/num_inference_steps) * 1000. for i in range(num_inference_steps)]
639
+
640
+ # 5. Prepare latent variables
641
+ num_channels_latents = self.unet.config.in_channels
642
+ latents = self.prepare_latents(
643
+ batch_size * num_images_per_prompt,
644
+ num_channels_latents,
645
+ height,
646
+ width,
647
+ prompt_embeds.dtype,
648
+ device,
649
+ generator,
650
+ latents,
651
+ )
652
+
653
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
654
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
655
+ dt = 1.0 / num_inference_steps
656
+
657
+ # 7. Denoising loop of Euler discretization from t = 0 to t = 1
658
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
659
+ for i, t in enumerate(timesteps):
660
+ # expand the latents if we are doing classifier free guidance
661
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
662
+
663
+ vec_t = torch.ones((latent_model_input.shape[0],), device=latents.device) * t
664
+
665
+ v_pred = self.unet(latent_model_input, vec_t, encoder_hidden_states=prompt_embeds).sample
666
+
667
+ # perform guidance
668
+ if do_classifier_free_guidance:
669
+ v_pred_neg, v_pred_text = v_pred.chunk(2)
670
+ v_pred = v_pred_neg + guidance_scale * (v_pred_text - v_pred_neg)
671
+
672
+ latents = latents + dt * v_pred
673
+
674
+ # call the callback, if provided
675
+ if i == len(timesteps) - 1 or ((i + 1) % self.scheduler.order == 0):
676
+ progress_bar.update()
677
+ if callback is not None and i % callback_steps == 0:
678
+ step_idx = i // getattr(self.scheduler, "order", 1)
679
+ callback(step_idx, t, latents)
680
+
681
+
682
+
683
+ if not output_type == "latent":
684
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
685
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
686
+ else:
687
+ image = latents
688
+ has_nsfw_concept = None
689
+
690
+ if has_nsfw_concept is None:
691
+ do_denormalize = [True] * image.shape[0]
692
+ else:
693
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
694
+
695
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
696
+
697
+ # Offload all models
698
+ self.maybe_free_model_hooks()
699
+
700
+ if not return_dict:
701
+ return (image, has_nsfw_concept)
702
+
703
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)