Ahmed Faiyaz commited on
Commit
19f4240
1 Parent(s): 0608938

Create pipeline.py

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