JerryL0 commited on
Commit
0d69315
·
1 Parent(s): 41f236c

Upload customPipe.py

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