diffusers 0.28.0__py3-none-any.whl → 0.28.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. diffusers/__init__.py +9 -1
  2. diffusers/configuration_utils.py +17 -0
  3. diffusers/loaders/single_file_utils.py +1 -1
  4. diffusers/models/__init__.py +6 -0
  5. diffusers/models/activations.py +12 -0
  6. diffusers/models/attention_processor.py +108 -0
  7. diffusers/models/embeddings.py +216 -8
  8. diffusers/models/model_loading_utils.py +28 -0
  9. diffusers/models/modeling_outputs.py +14 -0
  10. diffusers/models/modeling_utils.py +57 -1
  11. diffusers/models/normalization.py +2 -1
  12. diffusers/models/transformers/__init__.py +3 -0
  13. diffusers/models/transformers/dit_transformer_2d.py +240 -0
  14. diffusers/models/transformers/hunyuan_transformer_2d.py +427 -0
  15. diffusers/models/transformers/pixart_transformer_2d.py +336 -0
  16. diffusers/models/transformers/transformer_2d.py +37 -45
  17. diffusers/pipelines/__init__.py +2 -0
  18. diffusers/pipelines/dit/pipeline_dit.py +4 -4
  19. diffusers/pipelines/hunyuandit/__init__.py +48 -0
  20. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +881 -0
  21. diffusers/pipelines/pipeline_loading_utils.py +1 -0
  22. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +4 -4
  23. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +2 -2
  24. diffusers/utils/dummy_pt_objects.py +45 -0
  25. diffusers/utils/dummy_torch_and_transformers_objects.py +15 -0
  26. {diffusers-0.28.0.dist-info → diffusers-0.28.2.dist-info}/METADATA +44 -44
  27. {diffusers-0.28.0.dist-info → diffusers-0.28.2.dist-info}/RECORD +31 -26
  28. {diffusers-0.28.0.dist-info → diffusers-0.28.2.dist-info}/WHEEL +1 -1
  29. {diffusers-0.28.0.dist-info → diffusers-0.28.2.dist-info}/LICENSE +0 -0
  30. {diffusers-0.28.0.dist-info → diffusers-0.28.2.dist-info}/entry_points.txt +0 -0
  31. {diffusers-0.28.0.dist-info → diffusers-0.28.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,881 @@
1
+ # Copyright 2024 HunyuanDiT Authors and 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 Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import BertModel, BertTokenizer, CLIPImageProcessor, MT5Tokenizer, T5EncoderModel
21
+
22
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
23
+
24
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
25
+ from ...image_processor import VaeImageProcessor
26
+ from ...models import AutoencoderKL, HunyuanDiT2DModel
27
+ from ...models.embeddings import get_2d_rotary_pos_embed
28
+ from ...pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
29
+ from ...schedulers import DDPMScheduler
30
+ from ...utils import (
31
+ is_torch_xla_available,
32
+ logging,
33
+ replace_example_docstring,
34
+ )
35
+ from ...utils.torch_utils import randn_tensor
36
+ from ..pipeline_utils import DiffusionPipeline
37
+
38
+
39
+ if is_torch_xla_available():
40
+ import torch_xla.core.xla_model as xm
41
+
42
+ XLA_AVAILABLE = True
43
+ else:
44
+ XLA_AVAILABLE = False
45
+
46
+
47
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
48
+
49
+ EXAMPLE_DOC_STRING = """
50
+ Examples:
51
+ ```py
52
+ >>> import torch
53
+ >>> from diffusers import HunyuanDiTPipeline
54
+
55
+ >>> pipe = HunyuanDiTPipeline.from_pretrained("Tencent-Hunyuan/HunyuanDiT", torch_dtype=torch.float16)
56
+ >>> pipe.to("cuda")
57
+
58
+ >>> # You may also use English prompt as HunyuanDiT supports both English and Chinese
59
+ >>> # prompt = "An astronaut riding a horse"
60
+ >>> prompt = "一个宇航员在骑马"
61
+ >>> image = pipe(prompt).images[0]
62
+ ```
63
+ """
64
+
65
+ STANDARD_RATIO = np.array(
66
+ [
67
+ 1.0, # 1:1
68
+ 4.0 / 3.0, # 4:3
69
+ 3.0 / 4.0, # 3:4
70
+ 16.0 / 9.0, # 16:9
71
+ 9.0 / 16.0, # 9:16
72
+ ]
73
+ )
74
+ STANDARD_SHAPE = [
75
+ [(1024, 1024), (1280, 1280)], # 1:1
76
+ [(1024, 768), (1152, 864), (1280, 960)], # 4:3
77
+ [(768, 1024), (864, 1152), (960, 1280)], # 3:4
78
+ [(1280, 768)], # 16:9
79
+ [(768, 1280)], # 9:16
80
+ ]
81
+ STANDARD_AREA = [np.array([w * h for w, h in shapes]) for shapes in STANDARD_SHAPE]
82
+ SUPPORTED_SHAPE = [
83
+ (1024, 1024),
84
+ (1280, 1280), # 1:1
85
+ (1024, 768),
86
+ (1152, 864),
87
+ (1280, 960), # 4:3
88
+ (768, 1024),
89
+ (864, 1152),
90
+ (960, 1280), # 3:4
91
+ (1280, 768), # 16:9
92
+ (768, 1280), # 9:16
93
+ ]
94
+
95
+
96
+ def map_to_standard_shapes(target_width, target_height):
97
+ target_ratio = target_width / target_height
98
+ closest_ratio_idx = np.argmin(np.abs(STANDARD_RATIO - target_ratio))
99
+ closest_area_idx = np.argmin(np.abs(STANDARD_AREA[closest_ratio_idx] - target_width * target_height))
100
+ width, height = STANDARD_SHAPE[closest_ratio_idx][closest_area_idx]
101
+ return width, height
102
+
103
+
104
+ def get_resize_crop_region_for_grid(src, tgt_size):
105
+ th = tw = tgt_size
106
+ h, w = src
107
+
108
+ r = h / w
109
+
110
+ # resize
111
+ if r > 1:
112
+ resize_height = th
113
+ resize_width = int(round(th / h * w))
114
+ else:
115
+ resize_width = tw
116
+ resize_height = int(round(tw / w * h))
117
+
118
+ crop_top = int(round((th - resize_height) / 2.0))
119
+ crop_left = int(round((tw - resize_width) / 2.0))
120
+
121
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
122
+
123
+
124
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
125
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
126
+ """
127
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
128
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
129
+ """
130
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
131
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
132
+ # rescale the results from guidance (fixes overexposure)
133
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
134
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
135
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
136
+ return noise_cfg
137
+
138
+
139
+ class HunyuanDiTPipeline(DiffusionPipeline):
140
+ r"""
141
+ Pipeline for English/Chinese-to-image generation using HunyuanDiT.
142
+
143
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
144
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
145
+
146
+ HunyuanDiT uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned by
147
+ ourselves)
148
+
149
+ Args:
150
+ vae ([`AutoencoderKL`]):
151
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. We use
152
+ `sdxl-vae-fp16-fix`.
153
+ text_encoder (Optional[`~transformers.BertModel`, `~transformers.CLIPTextModel`]):
154
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
155
+ HunyuanDiT uses a fine-tuned [bilingual CLIP].
156
+ tokenizer (Optional[`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer`]):
157
+ A `BertTokenizer` or `CLIPTokenizer` to tokenize text.
158
+ transformer ([`HunyuanDiT2DModel`]):
159
+ The HunyuanDiT model designed by Tencent Hunyuan.
160
+ text_encoder_2 (`T5EncoderModel`):
161
+ The mT5 embedder. Specifically, it is 't5-v1_1-xxl'.
162
+ tokenizer_2 (`MT5Tokenizer`):
163
+ The tokenizer for the mT5 embedder.
164
+ scheduler ([`DDPMScheduler`]):
165
+ A scheduler to be used in combination with HunyuanDiT to denoise the encoded image latents.
166
+ """
167
+
168
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
169
+ _optional_components = [
170
+ "safety_checker",
171
+ "feature_extractor",
172
+ "text_encoder_2",
173
+ "tokenizer_2",
174
+ "text_encoder",
175
+ "tokenizer",
176
+ ]
177
+ _exclude_from_cpu_offload = ["safety_checker"]
178
+ _callback_tensor_inputs = [
179
+ "latents",
180
+ "prompt_embeds",
181
+ "negative_prompt_embeds",
182
+ "prompt_embeds_2",
183
+ "negative_prompt_embeds_2",
184
+ ]
185
+
186
+ def __init__(
187
+ self,
188
+ vae: AutoencoderKL,
189
+ text_encoder: BertModel,
190
+ tokenizer: BertTokenizer,
191
+ transformer: HunyuanDiT2DModel,
192
+ scheduler: DDPMScheduler,
193
+ safety_checker: StableDiffusionSafetyChecker,
194
+ feature_extractor: CLIPImageProcessor,
195
+ requires_safety_checker: bool = True,
196
+ text_encoder_2=T5EncoderModel,
197
+ tokenizer_2=MT5Tokenizer,
198
+ ):
199
+ super().__init__()
200
+
201
+ self.register_modules(
202
+ vae=vae,
203
+ text_encoder=text_encoder,
204
+ tokenizer=tokenizer,
205
+ tokenizer_2=tokenizer_2,
206
+ transformer=transformer,
207
+ scheduler=scheduler,
208
+ safety_checker=safety_checker,
209
+ feature_extractor=feature_extractor,
210
+ text_encoder_2=text_encoder_2,
211
+ )
212
+
213
+ if safety_checker is None and requires_safety_checker:
214
+ logger.warning(
215
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
216
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
217
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
218
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
219
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
220
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
221
+ )
222
+
223
+ if safety_checker is not None and feature_extractor is None:
224
+ raise ValueError(
225
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
226
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
227
+ )
228
+
229
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
230
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
231
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
232
+ self.default_sample_size = self.transformer.config.sample_size
233
+
234
+ def encode_prompt(
235
+ self,
236
+ prompt: str,
237
+ device: torch.device,
238
+ dtype: torch.dtype,
239
+ num_images_per_prompt: int = 1,
240
+ do_classifier_free_guidance: bool = True,
241
+ negative_prompt: Optional[str] = None,
242
+ prompt_embeds: Optional[torch.Tensor] = None,
243
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
244
+ prompt_attention_mask: Optional[torch.Tensor] = None,
245
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
246
+ max_sequence_length: Optional[int] = None,
247
+ text_encoder_index: int = 0,
248
+ ):
249
+ r"""
250
+ Encodes the prompt into text encoder hidden states.
251
+
252
+ Args:
253
+ prompt (`str` or `List[str]`, *optional*):
254
+ prompt to be encoded
255
+ device: (`torch.device`):
256
+ torch device
257
+ dtype (`torch.dtype`):
258
+ torch dtype
259
+ num_images_per_prompt (`int`):
260
+ number of images that should be generated per prompt
261
+ do_classifier_free_guidance (`bool`):
262
+ whether to use classifier free guidance or not
263
+ negative_prompt (`str` or `List[str]`, *optional*):
264
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
265
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
266
+ less than `1`).
267
+ prompt_embeds (`torch.Tensor`, *optional*):
268
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
269
+ provided, text embeddings will be generated from `prompt` input argument.
270
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
271
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
272
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
273
+ argument.
274
+ prompt_attention_mask (`torch.Tensor`, *optional*):
275
+ Attention mask for the prompt. Required when `prompt_embeds` is passed directly.
276
+ negative_prompt_attention_mask (`torch.Tensor`, *optional*):
277
+ Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.
278
+ max_sequence_length (`int`, *optional*): maximum sequence length to use for the prompt.
279
+ text_encoder_index (`int`, *optional*):
280
+ Index of the text encoder to use. `0` for clip and `1` for T5.
281
+ """
282
+ tokenizers = [self.tokenizer, self.tokenizer_2]
283
+ text_encoders = [self.text_encoder, self.text_encoder_2]
284
+
285
+ tokenizer = tokenizers[text_encoder_index]
286
+ text_encoder = text_encoders[text_encoder_index]
287
+
288
+ if max_sequence_length is None:
289
+ if text_encoder_index == 0:
290
+ max_length = 77
291
+ if text_encoder_index == 1:
292
+ max_length = 256
293
+ else:
294
+ max_length = max_sequence_length
295
+
296
+ if prompt is not None and isinstance(prompt, str):
297
+ batch_size = 1
298
+ elif prompt is not None and isinstance(prompt, list):
299
+ batch_size = len(prompt)
300
+ else:
301
+ batch_size = prompt_embeds.shape[0]
302
+
303
+ if prompt_embeds is None:
304
+ text_inputs = tokenizer(
305
+ prompt,
306
+ padding="max_length",
307
+ max_length=max_length,
308
+ truncation=True,
309
+ return_attention_mask=True,
310
+ return_tensors="pt",
311
+ )
312
+ text_input_ids = text_inputs.input_ids
313
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
314
+
315
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
316
+ text_input_ids, untruncated_ids
317
+ ):
318
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
319
+ logger.warning(
320
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
321
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
322
+ )
323
+
324
+ prompt_attention_mask = text_inputs.attention_mask.to(device)
325
+ prompt_embeds = text_encoder(
326
+ text_input_ids.to(device),
327
+ attention_mask=prompt_attention_mask,
328
+ )
329
+ prompt_embeds = prompt_embeds[0]
330
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
331
+
332
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
333
+
334
+ bs_embed, seq_len, _ = prompt_embeds.shape
335
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
336
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
337
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
338
+
339
+ # get unconditional embeddings for classifier free guidance
340
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
341
+ uncond_tokens: List[str]
342
+ if negative_prompt is None:
343
+ uncond_tokens = [""] * batch_size
344
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
345
+ raise TypeError(
346
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
347
+ f" {type(prompt)}."
348
+ )
349
+ elif isinstance(negative_prompt, str):
350
+ uncond_tokens = [negative_prompt]
351
+ elif batch_size != len(negative_prompt):
352
+ raise ValueError(
353
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
354
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
355
+ " the batch size of `prompt`."
356
+ )
357
+ else:
358
+ uncond_tokens = negative_prompt
359
+
360
+ max_length = prompt_embeds.shape[1]
361
+ uncond_input = tokenizer(
362
+ uncond_tokens,
363
+ padding="max_length",
364
+ max_length=max_length,
365
+ truncation=True,
366
+ return_tensors="pt",
367
+ )
368
+
369
+ negative_prompt_attention_mask = uncond_input.attention_mask.to(device)
370
+ negative_prompt_embeds = text_encoder(
371
+ uncond_input.input_ids.to(device),
372
+ attention_mask=negative_prompt_attention_mask,
373
+ )
374
+ negative_prompt_embeds = negative_prompt_embeds[0]
375
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
376
+
377
+ if do_classifier_free_guidance:
378
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
379
+ seq_len = negative_prompt_embeds.shape[1]
380
+
381
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
382
+
383
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
384
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
385
+
386
+ return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask
387
+
388
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
389
+ def run_safety_checker(self, image, device, dtype):
390
+ if self.safety_checker is None:
391
+ has_nsfw_concept = None
392
+ else:
393
+ if torch.is_tensor(image):
394
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
395
+ else:
396
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
397
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
398
+ image, has_nsfw_concept = self.safety_checker(
399
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
400
+ )
401
+ return image, has_nsfw_concept
402
+
403
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
404
+ def prepare_extra_step_kwargs(self, generator, eta):
405
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
406
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
407
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
408
+ # and should be between [0, 1]
409
+
410
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
411
+ extra_step_kwargs = {}
412
+ if accepts_eta:
413
+ extra_step_kwargs["eta"] = eta
414
+
415
+ # check if the scheduler accepts generator
416
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
417
+ if accepts_generator:
418
+ extra_step_kwargs["generator"] = generator
419
+ return extra_step_kwargs
420
+
421
+ def check_inputs(
422
+ self,
423
+ prompt,
424
+ height,
425
+ width,
426
+ negative_prompt=None,
427
+ prompt_embeds=None,
428
+ negative_prompt_embeds=None,
429
+ prompt_attention_mask=None,
430
+ negative_prompt_attention_mask=None,
431
+ prompt_embeds_2=None,
432
+ negative_prompt_embeds_2=None,
433
+ prompt_attention_mask_2=None,
434
+ negative_prompt_attention_mask_2=None,
435
+ callback_on_step_end_tensor_inputs=None,
436
+ ):
437
+ if height % 8 != 0 or width % 8 != 0:
438
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
439
+
440
+ if callback_on_step_end_tensor_inputs is not None and not all(
441
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
442
+ ):
443
+ raise ValueError(
444
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
445
+ )
446
+
447
+ if prompt is not None and prompt_embeds is not None:
448
+ raise ValueError(
449
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
450
+ " only forward one of the two."
451
+ )
452
+ elif prompt is None and prompt_embeds is None:
453
+ raise ValueError(
454
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
455
+ )
456
+ elif prompt is None and prompt_embeds_2 is None:
457
+ raise ValueError(
458
+ "Provide either `prompt` or `prompt_embeds_2`. Cannot leave both `prompt` and `prompt_embeds_2` undefined."
459
+ )
460
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
461
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
462
+
463
+ if prompt_embeds is not None and prompt_attention_mask is None:
464
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
465
+
466
+ if prompt_embeds_2 is not None and prompt_attention_mask_2 is None:
467
+ raise ValueError("Must provide `prompt_attention_mask_2` when specifying `prompt_embeds_2`.")
468
+
469
+ if negative_prompt is not None and negative_prompt_embeds is not None:
470
+ raise ValueError(
471
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
472
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
473
+ )
474
+
475
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
476
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
477
+
478
+ if negative_prompt_embeds_2 is not None and negative_prompt_attention_mask_2 is None:
479
+ raise ValueError(
480
+ "Must provide `negative_prompt_attention_mask_2` when specifying `negative_prompt_embeds_2`."
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
+ if prompt_embeds_2 is not None and negative_prompt_embeds_2 is not None:
490
+ if prompt_embeds_2.shape != negative_prompt_embeds_2.shape:
491
+ raise ValueError(
492
+ "`prompt_embeds_2` and `negative_prompt_embeds_2` must have the same shape when passed directly, but"
493
+ f" got: `prompt_embeds_2` {prompt_embeds_2.shape} != `negative_prompt_embeds_2`"
494
+ f" {negative_prompt_embeds_2.shape}."
495
+ )
496
+
497
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
498
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
499
+ shape = (
500
+ batch_size,
501
+ num_channels_latents,
502
+ int(height) // self.vae_scale_factor,
503
+ int(width) // self.vae_scale_factor,
504
+ )
505
+ if isinstance(generator, list) and len(generator) != batch_size:
506
+ raise ValueError(
507
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
508
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
509
+ )
510
+
511
+ if latents is None:
512
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
513
+ else:
514
+ latents = latents.to(device)
515
+
516
+ # scale the initial noise by the standard deviation required by the scheduler
517
+ latents = latents * self.scheduler.init_noise_sigma
518
+ return latents
519
+
520
+ @property
521
+ def guidance_scale(self):
522
+ return self._guidance_scale
523
+
524
+ @property
525
+ def guidance_rescale(self):
526
+ return self._guidance_rescale
527
+
528
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
529
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
530
+ # corresponds to doing no classifier free guidance.
531
+ @property
532
+ def do_classifier_free_guidance(self):
533
+ return self._guidance_scale > 1
534
+
535
+ @property
536
+ def num_timesteps(self):
537
+ return self._num_timesteps
538
+
539
+ @property
540
+ def interrupt(self):
541
+ return self._interrupt
542
+
543
+ @torch.no_grad()
544
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
545
+ def __call__(
546
+ self,
547
+ prompt: Union[str, List[str]] = None,
548
+ height: Optional[int] = None,
549
+ width: Optional[int] = None,
550
+ num_inference_steps: Optional[int] = 50,
551
+ guidance_scale: Optional[float] = 5.0,
552
+ negative_prompt: Optional[Union[str, List[str]]] = None,
553
+ num_images_per_prompt: Optional[int] = 1,
554
+ eta: Optional[float] = 0.0,
555
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
556
+ latents: Optional[torch.Tensor] = None,
557
+ prompt_embeds: Optional[torch.Tensor] = None,
558
+ prompt_embeds_2: Optional[torch.Tensor] = None,
559
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
560
+ negative_prompt_embeds_2: Optional[torch.Tensor] = None,
561
+ prompt_attention_mask: Optional[torch.Tensor] = None,
562
+ prompt_attention_mask_2: Optional[torch.Tensor] = None,
563
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
564
+ negative_prompt_attention_mask_2: Optional[torch.Tensor] = None,
565
+ output_type: Optional[str] = "pil",
566
+ return_dict: bool = True,
567
+ callback_on_step_end: Optional[
568
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
569
+ ] = None,
570
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
571
+ guidance_rescale: float = 0.0,
572
+ original_size: Optional[Tuple[int, int]] = (1024, 1024),
573
+ target_size: Optional[Tuple[int, int]] = None,
574
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
575
+ use_resolution_binning: bool = True,
576
+ ):
577
+ r"""
578
+ The call function to the pipeline for generation with HunyuanDiT.
579
+
580
+ Args:
581
+ prompt (`str` or `List[str]`, *optional*):
582
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
583
+ height (`int`):
584
+ The height in pixels of the generated image.
585
+ width (`int`):
586
+ The width in pixels of the generated image.
587
+ num_inference_steps (`int`, *optional*, defaults to 50):
588
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
589
+ expense of slower inference. This parameter is modulated by `strength`.
590
+ guidance_scale (`float`, *optional*, defaults to 7.5):
591
+ A higher guidance scale value encourages the model to generate images closely linked to the text
592
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
593
+ negative_prompt (`str` or `List[str]`, *optional*):
594
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
595
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
596
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
597
+ The number of images to generate per prompt.
598
+ eta (`float`, *optional*, defaults to 0.0):
599
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
600
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
601
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
602
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
603
+ generation deterministic.
604
+ prompt_embeds (`torch.Tensor`, *optional*):
605
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
606
+ provided, text embeddings are generated from the `prompt` input argument.
607
+ prompt_embeds_2 (`torch.Tensor`, *optional*):
608
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
609
+ provided, text embeddings are generated from the `prompt` input argument.
610
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
611
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
612
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
613
+ negative_prompt_embeds_2 (`torch.Tensor`, *optional*):
614
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
615
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
616
+ prompt_attention_mask (`torch.Tensor`, *optional*):
617
+ Attention mask for the prompt. Required when `prompt_embeds` is passed directly.
618
+ prompt_attention_mask_2 (`torch.Tensor`, *optional*):
619
+ Attention mask for the prompt. Required when `prompt_embeds_2` is passed directly.
620
+ negative_prompt_attention_mask (`torch.Tensor`, *optional*):
621
+ Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.
622
+ negative_prompt_attention_mask_2 (`torch.Tensor`, *optional*):
623
+ Attention mask for the negative prompt. Required when `negative_prompt_embeds_2` is passed directly.
624
+ output_type (`str`, *optional*, defaults to `"pil"`):
625
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
626
+ return_dict (`bool`, *optional*, defaults to `True`):
627
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
628
+ plain tuple.
629
+ callback_on_step_end (`Callable[[int, int, Dict], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
630
+ A callback function or a list of callback functions to be called at the end of each denoising step.
631
+ callback_on_step_end_tensor_inputs (`List[str]`, *optional*):
632
+ A list of tensor inputs that should be passed to the callback function. If not defined, all tensor
633
+ inputs will be passed.
634
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
635
+ Rescale the noise_cfg according to `guidance_rescale`. Based on findings of [Common Diffusion Noise
636
+ Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
637
+ original_size (`Tuple[int, int]`, *optional*, defaults to `(1024, 1024)`):
638
+ The original size of the image. Used to calculate the time ids.
639
+ target_size (`Tuple[int, int]`, *optional*):
640
+ The target size of the image. Used to calculate the time ids.
641
+ crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to `(0, 0)`):
642
+ The top left coordinates of the crop. Used to calculate the time ids.
643
+ use_resolution_binning (`bool`, *optional*, defaults to `True`):
644
+ Whether to use resolution binning or not. If `True`, the input resolution will be mapped to the closest
645
+ standard resolution. Supported resolutions are 1024x1024, 1280x1280, 1024x768, 1152x864, 1280x960,
646
+ 768x1024, 864x1152, 960x1280, 1280x768, and 768x1280. It is recommended to set this to `True`.
647
+
648
+ Examples:
649
+
650
+ Returns:
651
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
652
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
653
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
654
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
655
+ "not-safe-for-work" (nsfw) content.
656
+ """
657
+
658
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
659
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
660
+
661
+ # 0. default height and width
662
+ height = height or self.default_sample_size * self.vae_scale_factor
663
+ width = width or self.default_sample_size * self.vae_scale_factor
664
+ height = int((height // 16) * 16)
665
+ width = int((width // 16) * 16)
666
+
667
+ if use_resolution_binning and (height, width) not in SUPPORTED_SHAPE:
668
+ width, height = map_to_standard_shapes(width, height)
669
+ height = int(height)
670
+ width = int(width)
671
+ logger.warning(f"Reshaped to (height, width)=({height}, {width}), Supported shapes are {SUPPORTED_SHAPE}")
672
+
673
+ # 1. Check inputs. Raise error if not correct
674
+ self.check_inputs(
675
+ prompt,
676
+ height,
677
+ width,
678
+ negative_prompt,
679
+ prompt_embeds,
680
+ negative_prompt_embeds,
681
+ prompt_attention_mask,
682
+ negative_prompt_attention_mask,
683
+ prompt_embeds_2,
684
+ negative_prompt_embeds_2,
685
+ prompt_attention_mask_2,
686
+ negative_prompt_attention_mask_2,
687
+ callback_on_step_end_tensor_inputs,
688
+ )
689
+ self._guidance_scale = guidance_scale
690
+ self._guidance_rescale = guidance_rescale
691
+ self._interrupt = False
692
+
693
+ # 2. Define call parameters
694
+ if prompt is not None and isinstance(prompt, str):
695
+ batch_size = 1
696
+ elif prompt is not None and isinstance(prompt, list):
697
+ batch_size = len(prompt)
698
+ else:
699
+ batch_size = prompt_embeds.shape[0]
700
+
701
+ device = self._execution_device
702
+
703
+ # 3. Encode input prompt
704
+
705
+ (
706
+ prompt_embeds,
707
+ negative_prompt_embeds,
708
+ prompt_attention_mask,
709
+ negative_prompt_attention_mask,
710
+ ) = self.encode_prompt(
711
+ prompt=prompt,
712
+ device=device,
713
+ dtype=self.transformer.dtype,
714
+ num_images_per_prompt=num_images_per_prompt,
715
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
716
+ negative_prompt=negative_prompt,
717
+ prompt_embeds=prompt_embeds,
718
+ negative_prompt_embeds=negative_prompt_embeds,
719
+ prompt_attention_mask=prompt_attention_mask,
720
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
721
+ max_sequence_length=77,
722
+ text_encoder_index=0,
723
+ )
724
+ (
725
+ prompt_embeds_2,
726
+ negative_prompt_embeds_2,
727
+ prompt_attention_mask_2,
728
+ negative_prompt_attention_mask_2,
729
+ ) = self.encode_prompt(
730
+ prompt=prompt,
731
+ device=device,
732
+ dtype=self.transformer.dtype,
733
+ num_images_per_prompt=num_images_per_prompt,
734
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
735
+ negative_prompt=negative_prompt,
736
+ prompt_embeds=prompt_embeds_2,
737
+ negative_prompt_embeds=negative_prompt_embeds_2,
738
+ prompt_attention_mask=prompt_attention_mask_2,
739
+ negative_prompt_attention_mask=negative_prompt_attention_mask_2,
740
+ max_sequence_length=256,
741
+ text_encoder_index=1,
742
+ )
743
+
744
+ # 4. Prepare timesteps
745
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
746
+ timesteps = self.scheduler.timesteps
747
+
748
+ # 5. Prepare latent variables
749
+ num_channels_latents = self.transformer.config.in_channels
750
+ latents = self.prepare_latents(
751
+ batch_size * num_images_per_prompt,
752
+ num_channels_latents,
753
+ height,
754
+ width,
755
+ prompt_embeds.dtype,
756
+ device,
757
+ generator,
758
+ latents,
759
+ )
760
+
761
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
762
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
763
+
764
+ # 7 create image_rotary_emb, style embedding & time ids
765
+ grid_height = height // 8 // self.transformer.config.patch_size
766
+ grid_width = width // 8 // self.transformer.config.patch_size
767
+ base_size = 512 // 8 // self.transformer.config.patch_size
768
+ grid_crops_coords = get_resize_crop_region_for_grid((grid_height, grid_width), base_size)
769
+ image_rotary_emb = get_2d_rotary_pos_embed(
770
+ self.transformer.inner_dim // self.transformer.num_heads, grid_crops_coords, (grid_height, grid_width)
771
+ )
772
+
773
+ style = torch.tensor([0], device=device)
774
+
775
+ target_size = target_size or (height, width)
776
+ add_time_ids = list(original_size + target_size + crops_coords_top_left)
777
+ add_time_ids = torch.tensor([add_time_ids], dtype=prompt_embeds.dtype)
778
+
779
+ if self.do_classifier_free_guidance:
780
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
781
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])
782
+ prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])
783
+ prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2])
784
+ add_time_ids = torch.cat([add_time_ids] * 2, dim=0)
785
+ style = torch.cat([style] * 2, dim=0)
786
+
787
+ prompt_embeds = prompt_embeds.to(device=device)
788
+ prompt_attention_mask = prompt_attention_mask.to(device=device)
789
+ prompt_embeds_2 = prompt_embeds_2.to(device=device)
790
+ prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device)
791
+ add_time_ids = add_time_ids.to(dtype=prompt_embeds.dtype, device=device).repeat(
792
+ batch_size * num_images_per_prompt, 1
793
+ )
794
+ style = style.to(device=device).repeat(batch_size * num_images_per_prompt)
795
+
796
+ # 8. Denoising loop
797
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
798
+ self._num_timesteps = len(timesteps)
799
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
800
+ for i, t in enumerate(timesteps):
801
+ if self.interrupt:
802
+ continue
803
+
804
+ # expand the latents if we are doing classifier free guidance
805
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
806
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
807
+
808
+ # expand scalar t to 1-D tensor to match the 1st dim of latent_model_input
809
+ t_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to(
810
+ dtype=latent_model_input.dtype
811
+ )
812
+
813
+ # predict the noise residual
814
+ noise_pred = self.transformer(
815
+ latent_model_input,
816
+ t_expand,
817
+ encoder_hidden_states=prompt_embeds,
818
+ text_embedding_mask=prompt_attention_mask,
819
+ encoder_hidden_states_t5=prompt_embeds_2,
820
+ text_embedding_mask_t5=prompt_attention_mask_2,
821
+ image_meta_size=add_time_ids,
822
+ style=style,
823
+ image_rotary_emb=image_rotary_emb,
824
+ return_dict=False,
825
+ )[0]
826
+
827
+ noise_pred, _ = noise_pred.chunk(2, dim=1)
828
+
829
+ # perform guidance
830
+ if self.do_classifier_free_guidance:
831
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
832
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
833
+
834
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
835
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
836
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
837
+
838
+ # compute the previous noisy sample x_t -> x_t-1
839
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
840
+
841
+ if callback_on_step_end is not None:
842
+ callback_kwargs = {}
843
+ for k in callback_on_step_end_tensor_inputs:
844
+ callback_kwargs[k] = locals()[k]
845
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
846
+
847
+ latents = callback_outputs.pop("latents", latents)
848
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
849
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
850
+ prompt_embeds_2 = callback_outputs.pop("prompt_embeds_2", prompt_embeds_2)
851
+ negative_prompt_embeds_2 = callback_outputs.pop(
852
+ "negative_prompt_embeds_2", negative_prompt_embeds_2
853
+ )
854
+
855
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
856
+ progress_bar.update()
857
+
858
+ if XLA_AVAILABLE:
859
+ xm.mark_step()
860
+
861
+ if not output_type == "latent":
862
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
863
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
864
+ else:
865
+ image = latents
866
+ has_nsfw_concept = None
867
+
868
+ if has_nsfw_concept is None:
869
+ do_denormalize = [True] * image.shape[0]
870
+ else:
871
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
872
+
873
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
874
+
875
+ # Offload all models
876
+ self.maybe_free_model_hooks()
877
+
878
+ if not return_dict:
879
+ return (image, has_nsfw_concept)
880
+
881
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)