diffusers 0.26.2__py3-none-any.whl → 0.27.0__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diffusers/__init__.py +20 -1
- diffusers/commands/__init__.py +1 -1
- diffusers/commands/diffusers_cli.py +1 -1
- diffusers/commands/env.py +1 -1
- diffusers/commands/fp16_safetensors.py +1 -1
- diffusers/configuration_utils.py +7 -3
- diffusers/dependency_versions_check.py +1 -1
- diffusers/dependency_versions_table.py +2 -2
- diffusers/experimental/rl/value_guided_sampling.py +1 -1
- diffusers/image_processor.py +110 -4
- diffusers/loaders/autoencoder.py +28 -8
- diffusers/loaders/controlnet.py +17 -8
- diffusers/loaders/ip_adapter.py +86 -23
- diffusers/loaders/lora.py +105 -310
- diffusers/loaders/lora_conversion_utils.py +1 -1
- diffusers/loaders/peft.py +1 -1
- diffusers/loaders/single_file.py +51 -12
- diffusers/loaders/single_file_utils.py +278 -49
- diffusers/loaders/textual_inversion.py +23 -4
- diffusers/loaders/unet.py +195 -41
- diffusers/loaders/utils.py +1 -1
- diffusers/models/__init__.py +3 -1
- diffusers/models/activations.py +9 -9
- diffusers/models/attention.py +26 -36
- diffusers/models/attention_flax.py +1 -1
- diffusers/models/attention_processor.py +171 -114
- diffusers/models/autoencoders/autoencoder_asym_kl.py +1 -1
- diffusers/models/autoencoders/autoencoder_kl.py +3 -1
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
- diffusers/models/autoencoders/autoencoder_tiny.py +4 -2
- diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
- diffusers/models/autoencoders/vae.py +1 -1
- diffusers/models/controlnet.py +1 -1
- diffusers/models/controlnet_flax.py +1 -1
- diffusers/models/downsampling.py +8 -12
- diffusers/models/dual_transformer_2d.py +1 -1
- diffusers/models/embeddings.py +3 -4
- diffusers/models/embeddings_flax.py +1 -1
- diffusers/models/lora.py +33 -10
- diffusers/models/modeling_flax_pytorch_utils.py +1 -1
- diffusers/models/modeling_flax_utils.py +1 -1
- diffusers/models/modeling_pytorch_flax_utils.py +1 -1
- diffusers/models/modeling_utils.py +4 -6
- diffusers/models/normalization.py +1 -1
- diffusers/models/resnet.py +31 -58
- diffusers/models/resnet_flax.py +1 -1
- diffusers/models/t5_film_transformer.py +1 -1
- diffusers/models/transformer_2d.py +1 -1
- diffusers/models/transformer_temporal.py +1 -1
- diffusers/models/transformers/dual_transformer_2d.py +1 -1
- diffusers/models/transformers/t5_film_transformer.py +1 -1
- diffusers/models/transformers/transformer_2d.py +29 -31
- diffusers/models/transformers/transformer_temporal.py +1 -1
- diffusers/models/unet_1d.py +1 -1
- diffusers/models/unet_1d_blocks.py +1 -1
- diffusers/models/unet_2d.py +1 -1
- diffusers/models/unet_2d_blocks.py +1 -1
- diffusers/models/unet_2d_condition.py +1 -1
- diffusers/models/unets/__init__.py +1 -0
- diffusers/models/unets/unet_1d.py +1 -1
- diffusers/models/unets/unet_1d_blocks.py +1 -1
- diffusers/models/unets/unet_2d.py +4 -4
- diffusers/models/unets/unet_2d_blocks.py +238 -98
- diffusers/models/unets/unet_2d_blocks_flax.py +1 -1
- diffusers/models/unets/unet_2d_condition.py +420 -323
- diffusers/models/unets/unet_2d_condition_flax.py +21 -12
- diffusers/models/unets/unet_3d_blocks.py +50 -40
- diffusers/models/unets/unet_3d_condition.py +47 -8
- diffusers/models/unets/unet_i2vgen_xl.py +75 -30
- diffusers/models/unets/unet_kandinsky3.py +1 -1
- diffusers/models/unets/unet_motion_model.py +48 -8
- diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
- diffusers/models/unets/unet_stable_cascade.py +610 -0
- diffusers/models/unets/uvit_2d.py +1 -1
- diffusers/models/upsampling.py +10 -16
- diffusers/models/vae_flax.py +1 -1
- diffusers/models/vq_model.py +1 -1
- diffusers/optimization.py +1 -1
- diffusers/pipelines/__init__.py +26 -0
- diffusers/pipelines/amused/pipeline_amused.py +1 -1
- diffusers/pipelines/amused/pipeline_amused_img2img.py +1 -1
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +1 -1
- diffusers/pipelines/animatediff/pipeline_animatediff.py +162 -417
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +165 -137
- diffusers/pipelines/animatediff/pipeline_output.py +7 -6
- diffusers/pipelines/audioldm/pipeline_audioldm.py +3 -19
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +3 -3
- diffusers/pipelines/auto_pipeline.py +7 -16
- diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +2 -2
- diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
- diffusers/pipelines/controlnet/pipeline_controlnet.py +90 -90
- diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +98 -90
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +92 -90
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +145 -70
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +126 -89
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +108 -96
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -1
- diffusers/pipelines/ddim/pipeline_ddim.py +1 -1
- diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +4 -4
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +4 -4
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +5 -5
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +4 -4
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +5 -5
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +5 -5
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +10 -120
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +10 -91
- diffusers/pipelines/deprecated/audio_diffusion/mel.py +1 -1
- diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py +1 -1
- diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +1 -1
- diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +1 -1
- diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +1 -1
- diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +5 -4
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +5 -4
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +7 -22
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +5 -39
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +5 -5
- diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +31 -22
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -2
- diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +1 -1
- diffusers/pipelines/dit/pipeline_dit.py +1 -1
- diffusers/pipelines/free_init_utils.py +184 -0
- diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +22 -104
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +1 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +1 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +1 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +2 -2
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +2 -2
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +104 -93
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +112 -74
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
- diffusers/pipelines/ledits_pp/__init__.py +55 -0
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +1505 -0
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +1797 -0
- diffusers/pipelines/ledits_pp/pipeline_output.py +43 -0
- diffusers/pipelines/musicldm/pipeline_musicldm.py +3 -19
- diffusers/pipelines/onnx_utils.py +1 -1
- diffusers/pipelines/paint_by_example/image_encoder.py +1 -1
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +3 -3
- diffusers/pipelines/pia/pipeline_pia.py +168 -327
- diffusers/pipelines/pipeline_flax_utils.py +1 -1
- diffusers/pipelines/pipeline_loading_utils.py +508 -0
- diffusers/pipelines/pipeline_utils.py +188 -534
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +56 -10
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +3 -3
- diffusers/pipelines/shap_e/camera.py +1 -1
- diffusers/pipelines/shap_e/pipeline_shap_e.py +1 -1
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +1 -1
- diffusers/pipelines/shap_e/renderer.py +1 -1
- diffusers/pipelines/stable_cascade/__init__.py +50 -0
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +482 -0
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +311 -0
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +638 -0
- diffusers/pipelines/stable_diffusion/clip_image_project_model.py +1 -1
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +4 -1
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +90 -146
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -4
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +4 -32
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -119
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -119
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +13 -59
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +3 -31
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +5 -33
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -21
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +7 -21
- diffusers/pipelines/stable_diffusion/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion/safety_checker_flax.py +1 -1
- diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py +1 -1
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +5 -21
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +9 -38
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -34
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +6 -35
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +7 -6
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +4 -124
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +282 -80
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +94 -46
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +3 -3
- diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +6 -22
- diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +96 -148
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +98 -154
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +98 -153
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +25 -87
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +89 -80
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +5 -49
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +80 -88
- diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +8 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +15 -86
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +20 -93
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +5 -5
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +3 -19
- diffusers/pipelines/unclip/pipeline_unclip.py +1 -1
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -1
- diffusers/pipelines/unclip/text_proj.py +1 -1
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +35 -35
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +4 -21
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +2 -2
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +4 -5
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +8 -8
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +2 -2
- diffusers/schedulers/__init__.py +7 -1
- diffusers/schedulers/deprecated/scheduling_karras_ve.py +1 -1
- diffusers/schedulers/deprecated/scheduling_sde_vp.py +1 -1
- diffusers/schedulers/scheduling_consistency_models.py +42 -19
- diffusers/schedulers/scheduling_ddim.py +2 -4
- diffusers/schedulers/scheduling_ddim_flax.py +13 -5
- diffusers/schedulers/scheduling_ddim_inverse.py +2 -4
- diffusers/schedulers/scheduling_ddim_parallel.py +2 -4
- diffusers/schedulers/scheduling_ddpm.py +2 -4
- diffusers/schedulers/scheduling_ddpm_flax.py +1 -1
- diffusers/schedulers/scheduling_ddpm_parallel.py +2 -4
- diffusers/schedulers/scheduling_ddpm_wuerstchen.py +1 -1
- diffusers/schedulers/scheduling_deis_multistep.py +46 -19
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +107 -21
- diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +1 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +9 -7
- diffusers/schedulers/scheduling_dpmsolver_sde.py +35 -35
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +52 -21
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +683 -0
- diffusers/schedulers/scheduling_edm_euler.py +381 -0
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +43 -15
- diffusers/schedulers/scheduling_euler_discrete.py +42 -17
- diffusers/schedulers/scheduling_euler_discrete_flax.py +1 -1
- diffusers/schedulers/scheduling_heun_discrete.py +35 -35
- diffusers/schedulers/scheduling_ipndm.py +37 -11
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +44 -44
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +44 -44
- diffusers/schedulers/scheduling_karras_ve_flax.py +1 -1
- diffusers/schedulers/scheduling_lcm.py +38 -14
- diffusers/schedulers/scheduling_lms_discrete.py +43 -15
- diffusers/schedulers/scheduling_lms_discrete_flax.py +1 -1
- diffusers/schedulers/scheduling_pndm.py +2 -4
- diffusers/schedulers/scheduling_pndm_flax.py +2 -4
- diffusers/schedulers/scheduling_repaint.py +1 -1
- diffusers/schedulers/scheduling_sasolver.py +41 -9
- diffusers/schedulers/scheduling_sde_ve.py +1 -1
- diffusers/schedulers/scheduling_sde_ve_flax.py +1 -1
- diffusers/schedulers/scheduling_tcd.py +686 -0
- diffusers/schedulers/scheduling_unclip.py +1 -1
- diffusers/schedulers/scheduling_unipc_multistep.py +46 -19
- diffusers/schedulers/scheduling_utils.py +2 -1
- diffusers/schedulers/scheduling_utils_flax.py +1 -1
- diffusers/schedulers/scheduling_vq_diffusion.py +1 -1
- diffusers/training_utils.py +9 -2
- diffusers/utils/__init__.py +2 -1
- diffusers/utils/accelerate_utils.py +1 -1
- diffusers/utils/constants.py +1 -1
- diffusers/utils/doc_utils.py +1 -1
- diffusers/utils/dummy_pt_objects.py +60 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +75 -0
- diffusers/utils/dynamic_modules_utils.py +1 -1
- diffusers/utils/export_utils.py +3 -3
- diffusers/utils/hub_utils.py +60 -16
- diffusers/utils/import_utils.py +15 -1
- diffusers/utils/loading_utils.py +2 -0
- diffusers/utils/logging.py +1 -1
- diffusers/utils/model_card_template.md +24 -0
- diffusers/utils/outputs.py +14 -7
- diffusers/utils/peft_utils.py +1 -1
- diffusers/utils/state_dict_utils.py +1 -1
- diffusers/utils/testing_utils.py +2 -0
- diffusers/utils/torch_utils.py +1 -1
- {diffusers-0.26.2.dist-info → diffusers-0.27.0.dist-info}/METADATA +5 -5
- diffusers-0.27.0.dist-info/RECORD +399 -0
- diffusers-0.26.2.dist-info/RECORD +0 -384
- {diffusers-0.26.2.dist-info → diffusers-0.27.0.dist-info}/LICENSE +0 -0
- {diffusers-0.26.2.dist-info → diffusers-0.27.0.dist-info}/WHEEL +0 -0
- {diffusers-0.26.2.dist-info → diffusers-0.27.0.dist-info}/entry_points.txt +0 -0
- {diffusers-0.26.2.dist-info → diffusers-0.27.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,482 @@
|
|
1
|
+
# Copyright 2024 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
|
+
from typing import Callable, Dict, List, Optional, Union
|
16
|
+
|
17
|
+
import torch
|
18
|
+
from transformers import CLIPTextModel, CLIPTokenizer
|
19
|
+
|
20
|
+
from ...models import StableCascadeUNet
|
21
|
+
from ...schedulers import DDPMWuerstchenScheduler
|
22
|
+
from ...utils import is_torch_version, logging, replace_example_docstring
|
23
|
+
from ...utils.torch_utils import randn_tensor
|
24
|
+
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
25
|
+
from ..wuerstchen.modeling_paella_vq_model import PaellaVQModel
|
26
|
+
|
27
|
+
|
28
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
29
|
+
|
30
|
+
EXAMPLE_DOC_STRING = """
|
31
|
+
Examples:
|
32
|
+
```py
|
33
|
+
>>> import torch
|
34
|
+
>>> from diffusers import StableCascadePriorPipeline, StableCascadeDecoderPipeline
|
35
|
+
|
36
|
+
>>> prior_pipe = StableCascadePriorPipeline.from_pretrained(
|
37
|
+
... "stabilityai/stable-cascade-prior", torch_dtype=torch.bfloat16
|
38
|
+
... ).to("cuda")
|
39
|
+
>>> gen_pipe = StableCascadeDecoderPipeline.from_pretrain(
|
40
|
+
... "stabilityai/stable-cascade", torch_dtype=torch.float16
|
41
|
+
... ).to("cuda")
|
42
|
+
|
43
|
+
>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
|
44
|
+
>>> prior_output = pipe(prompt)
|
45
|
+
>>> images = gen_pipe(prior_output.image_embeddings, prompt=prompt)
|
46
|
+
```
|
47
|
+
"""
|
48
|
+
|
49
|
+
|
50
|
+
class StableCascadeDecoderPipeline(DiffusionPipeline):
|
51
|
+
"""
|
52
|
+
Pipeline for generating images from the Stable Cascade model.
|
53
|
+
|
54
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
55
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
56
|
+
|
57
|
+
Args:
|
58
|
+
tokenizer (`CLIPTokenizer`):
|
59
|
+
The CLIP tokenizer.
|
60
|
+
text_encoder (`CLIPTextModel`):
|
61
|
+
The CLIP text encoder.
|
62
|
+
decoder ([`StableCascadeUNet`]):
|
63
|
+
The Stable Cascade decoder unet.
|
64
|
+
vqgan ([`PaellaVQModel`]):
|
65
|
+
The VQGAN model.
|
66
|
+
scheduler ([`DDPMWuerstchenScheduler`]):
|
67
|
+
A scheduler to be used in combination with `prior` to generate image embedding.
|
68
|
+
latent_dim_scale (float, `optional`, defaults to 10.67):
|
69
|
+
Multiplier to determine the VQ latent space size from the image embeddings. If the image embeddings are
|
70
|
+
height=24 and width=24, the VQ latent shape needs to be height=int(24*10.67)=256 and
|
71
|
+
width=int(24*10.67)=256 in order to match the training conditions.
|
72
|
+
"""
|
73
|
+
|
74
|
+
unet_name = "decoder"
|
75
|
+
text_encoder_name = "text_encoder"
|
76
|
+
model_cpu_offload_seq = "text_encoder->decoder->vqgan"
|
77
|
+
_callback_tensor_inputs = [
|
78
|
+
"latents",
|
79
|
+
"prompt_embeds_pooled",
|
80
|
+
"negative_prompt_embeds",
|
81
|
+
"image_embeddings",
|
82
|
+
]
|
83
|
+
|
84
|
+
def __init__(
|
85
|
+
self,
|
86
|
+
decoder: StableCascadeUNet,
|
87
|
+
tokenizer: CLIPTokenizer,
|
88
|
+
text_encoder: CLIPTextModel,
|
89
|
+
scheduler: DDPMWuerstchenScheduler,
|
90
|
+
vqgan: PaellaVQModel,
|
91
|
+
latent_dim_scale: float = 10.67,
|
92
|
+
) -> None:
|
93
|
+
super().__init__()
|
94
|
+
self.register_modules(
|
95
|
+
decoder=decoder,
|
96
|
+
tokenizer=tokenizer,
|
97
|
+
text_encoder=text_encoder,
|
98
|
+
scheduler=scheduler,
|
99
|
+
vqgan=vqgan,
|
100
|
+
)
|
101
|
+
self.register_to_config(latent_dim_scale=latent_dim_scale)
|
102
|
+
|
103
|
+
def prepare_latents(self, image_embeddings, num_images_per_prompt, dtype, device, generator, latents, scheduler):
|
104
|
+
batch_size, channels, height, width = image_embeddings.shape
|
105
|
+
latents_shape = (
|
106
|
+
batch_size * num_images_per_prompt,
|
107
|
+
4,
|
108
|
+
int(height * self.config.latent_dim_scale),
|
109
|
+
int(width * self.config.latent_dim_scale),
|
110
|
+
)
|
111
|
+
|
112
|
+
if latents is None:
|
113
|
+
latents = randn_tensor(latents_shape, generator=generator, device=device, dtype=dtype)
|
114
|
+
else:
|
115
|
+
if latents.shape != latents_shape:
|
116
|
+
raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
|
117
|
+
latents = latents.to(device)
|
118
|
+
|
119
|
+
latents = latents * scheduler.init_noise_sigma
|
120
|
+
return latents
|
121
|
+
|
122
|
+
def encode_prompt(
|
123
|
+
self,
|
124
|
+
device,
|
125
|
+
batch_size,
|
126
|
+
num_images_per_prompt,
|
127
|
+
do_classifier_free_guidance,
|
128
|
+
prompt=None,
|
129
|
+
negative_prompt=None,
|
130
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
131
|
+
prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
132
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
133
|
+
negative_prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
134
|
+
):
|
135
|
+
if prompt_embeds is None:
|
136
|
+
# get prompt text embeddings
|
137
|
+
text_inputs = self.tokenizer(
|
138
|
+
prompt,
|
139
|
+
padding="max_length",
|
140
|
+
max_length=self.tokenizer.model_max_length,
|
141
|
+
truncation=True,
|
142
|
+
return_tensors="pt",
|
143
|
+
)
|
144
|
+
text_input_ids = text_inputs.input_ids
|
145
|
+
attention_mask = text_inputs.attention_mask
|
146
|
+
|
147
|
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
148
|
+
|
149
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
150
|
+
text_input_ids, untruncated_ids
|
151
|
+
):
|
152
|
+
removed_text = self.tokenizer.batch_decode(
|
153
|
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
154
|
+
)
|
155
|
+
logger.warning(
|
156
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
157
|
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
158
|
+
)
|
159
|
+
text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
|
160
|
+
attention_mask = attention_mask[:, : self.tokenizer.model_max_length]
|
161
|
+
|
162
|
+
text_encoder_output = self.text_encoder(
|
163
|
+
text_input_ids.to(device), attention_mask=attention_mask.to(device), output_hidden_states=True
|
164
|
+
)
|
165
|
+
prompt_embeds = text_encoder_output.hidden_states[-1]
|
166
|
+
if prompt_embeds_pooled is None:
|
167
|
+
prompt_embeds_pooled = text_encoder_output.text_embeds.unsqueeze(1)
|
168
|
+
|
169
|
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
170
|
+
prompt_embeds_pooled = prompt_embeds_pooled.to(dtype=self.text_encoder.dtype, device=device)
|
171
|
+
prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
172
|
+
prompt_embeds_pooled = prompt_embeds_pooled.repeat_interleave(num_images_per_prompt, dim=0)
|
173
|
+
|
174
|
+
if negative_prompt_embeds is None and do_classifier_free_guidance:
|
175
|
+
uncond_tokens: List[str]
|
176
|
+
if negative_prompt is None:
|
177
|
+
uncond_tokens = [""] * batch_size
|
178
|
+
elif type(prompt) is not type(negative_prompt):
|
179
|
+
raise TypeError(
|
180
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
181
|
+
f" {type(prompt)}."
|
182
|
+
)
|
183
|
+
elif isinstance(negative_prompt, str):
|
184
|
+
uncond_tokens = [negative_prompt]
|
185
|
+
elif batch_size != len(negative_prompt):
|
186
|
+
raise ValueError(
|
187
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
188
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
189
|
+
" the batch size of `prompt`."
|
190
|
+
)
|
191
|
+
else:
|
192
|
+
uncond_tokens = negative_prompt
|
193
|
+
|
194
|
+
uncond_input = self.tokenizer(
|
195
|
+
uncond_tokens,
|
196
|
+
padding="max_length",
|
197
|
+
max_length=self.tokenizer.model_max_length,
|
198
|
+
truncation=True,
|
199
|
+
return_tensors="pt",
|
200
|
+
)
|
201
|
+
negative_prompt_embeds_text_encoder_output = self.text_encoder(
|
202
|
+
uncond_input.input_ids.to(device),
|
203
|
+
attention_mask=uncond_input.attention_mask.to(device),
|
204
|
+
output_hidden_states=True,
|
205
|
+
)
|
206
|
+
|
207
|
+
negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.hidden_states[-1]
|
208
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_text_encoder_output.text_embeds.unsqueeze(1)
|
209
|
+
|
210
|
+
if do_classifier_free_guidance:
|
211
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
212
|
+
seq_len = negative_prompt_embeds.shape[1]
|
213
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
214
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
215
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
216
|
+
|
217
|
+
seq_len = negative_prompt_embeds_pooled.shape[1]
|
218
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_pooled.to(
|
219
|
+
dtype=self.text_encoder.dtype, device=device
|
220
|
+
)
|
221
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_pooled.repeat(1, num_images_per_prompt, 1)
|
222
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_pooled.view(
|
223
|
+
batch_size * num_images_per_prompt, seq_len, -1
|
224
|
+
)
|
225
|
+
# done duplicates
|
226
|
+
|
227
|
+
return prompt_embeds, prompt_embeds_pooled, negative_prompt_embeds, negative_prompt_embeds_pooled
|
228
|
+
|
229
|
+
def check_inputs(
|
230
|
+
self,
|
231
|
+
prompt,
|
232
|
+
negative_prompt=None,
|
233
|
+
prompt_embeds=None,
|
234
|
+
negative_prompt_embeds=None,
|
235
|
+
callback_on_step_end_tensor_inputs=None,
|
236
|
+
):
|
237
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
238
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
239
|
+
):
|
240
|
+
raise ValueError(
|
241
|
+
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]}"
|
242
|
+
)
|
243
|
+
|
244
|
+
if prompt is not None and prompt_embeds is not None:
|
245
|
+
raise ValueError(
|
246
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
247
|
+
" only forward one of the two."
|
248
|
+
)
|
249
|
+
elif prompt is None and prompt_embeds is None:
|
250
|
+
raise ValueError(
|
251
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
252
|
+
)
|
253
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
254
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
255
|
+
|
256
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
257
|
+
raise ValueError(
|
258
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
259
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
260
|
+
)
|
261
|
+
|
262
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
263
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
264
|
+
raise ValueError(
|
265
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
266
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
267
|
+
f" {negative_prompt_embeds.shape}."
|
268
|
+
)
|
269
|
+
|
270
|
+
@property
|
271
|
+
def guidance_scale(self):
|
272
|
+
return self._guidance_scale
|
273
|
+
|
274
|
+
@property
|
275
|
+
def do_classifier_free_guidance(self):
|
276
|
+
return self._guidance_scale > 1
|
277
|
+
|
278
|
+
@property
|
279
|
+
def num_timesteps(self):
|
280
|
+
return self._num_timesteps
|
281
|
+
|
282
|
+
@torch.no_grad()
|
283
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
284
|
+
def __call__(
|
285
|
+
self,
|
286
|
+
image_embeddings: Union[torch.FloatTensor, List[torch.FloatTensor]],
|
287
|
+
prompt: Union[str, List[str]] = None,
|
288
|
+
num_inference_steps: int = 10,
|
289
|
+
guidance_scale: float = 0.0,
|
290
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
291
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
292
|
+
prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
293
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
294
|
+
negative_prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
295
|
+
num_images_per_prompt: int = 1,
|
296
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
297
|
+
latents: Optional[torch.FloatTensor] = None,
|
298
|
+
output_type: Optional[str] = "pil",
|
299
|
+
return_dict: bool = True,
|
300
|
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
301
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
302
|
+
):
|
303
|
+
"""
|
304
|
+
Function invoked when calling the pipeline for generation.
|
305
|
+
|
306
|
+
Args:
|
307
|
+
image_embedding (`torch.FloatTensor` or `List[torch.FloatTensor]`):
|
308
|
+
Image Embeddings either extracted from an image or generated by a Prior Model.
|
309
|
+
prompt (`str` or `List[str]`):
|
310
|
+
The prompt or prompts to guide the image generation.
|
311
|
+
num_inference_steps (`int`, *optional*, defaults to 12):
|
312
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
313
|
+
expense of slower inference.
|
314
|
+
guidance_scale (`float`, *optional*, defaults to 0.0):
|
315
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
316
|
+
`decoder_guidance_scale` is defined as `w` of equation 2. of [Imagen
|
317
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting
|
318
|
+
`decoder_guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely
|
319
|
+
linked to the text `prompt`, usually at the expense of lower image quality.
|
320
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
321
|
+
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
|
322
|
+
if `decoder_guidance_scale` is less than `1`).
|
323
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
324
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
325
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
326
|
+
prompt_embeds_pooled (`torch.FloatTensor`, *optional*):
|
327
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
328
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
329
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
330
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
331
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
332
|
+
argument.
|
333
|
+
negative_prompt_embeds_pooled (`torch.FloatTensor`, *optional*):
|
334
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
335
|
+
weighting. If not provided, negative_prompt_embeds_pooled will be generated from `negative_prompt` input
|
336
|
+
argument.
|
337
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
338
|
+
The number of images to generate per prompt.
|
339
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
340
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
341
|
+
to make generation deterministic.
|
342
|
+
latents (`torch.FloatTensor`, *optional*):
|
343
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
344
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
345
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
346
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
347
|
+
The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"`
|
348
|
+
(`np.array`) or `"pt"` (`torch.Tensor`).
|
349
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
350
|
+
Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
|
351
|
+
callback_on_step_end (`Callable`, *optional*):
|
352
|
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
353
|
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
354
|
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
355
|
+
`callback_on_step_end_tensor_inputs`.
|
356
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
357
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
358
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
359
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
360
|
+
|
361
|
+
Examples:
|
362
|
+
|
363
|
+
Returns:
|
364
|
+
[`~pipelines.ImagePipelineOutput`] or `tuple` [`~pipelines.ImagePipelineOutput`] if `return_dict` is True,
|
365
|
+
otherwise a `tuple`. When returning a tuple, the first element is a list with the generated image
|
366
|
+
embeddings.
|
367
|
+
"""
|
368
|
+
|
369
|
+
# 0. Define commonly used variables
|
370
|
+
device = self._execution_device
|
371
|
+
dtype = self.decoder.dtype
|
372
|
+
self._guidance_scale = guidance_scale
|
373
|
+
if is_torch_version("<", "2.2.0") and dtype == torch.bfloat16:
|
374
|
+
raise ValueError("`StableCascadeDecoderPipeline` requires torch>=2.2.0 when using `torch.bfloat16` dtype.")
|
375
|
+
|
376
|
+
# 1. Check inputs. Raise error if not correct
|
377
|
+
self.check_inputs(
|
378
|
+
prompt,
|
379
|
+
negative_prompt=negative_prompt,
|
380
|
+
prompt_embeds=prompt_embeds,
|
381
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
382
|
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
383
|
+
)
|
384
|
+
if isinstance(image_embeddings, list):
|
385
|
+
image_embeddings = torch.cat(image_embeddings, dim=0)
|
386
|
+
batch_size = image_embeddings.shape[0]
|
387
|
+
|
388
|
+
# 2. Encode caption
|
389
|
+
if prompt_embeds is None and negative_prompt_embeds is None:
|
390
|
+
_, prompt_embeds_pooled, _, negative_prompt_embeds_pooled = self.encode_prompt(
|
391
|
+
prompt=prompt,
|
392
|
+
device=device,
|
393
|
+
batch_size=batch_size,
|
394
|
+
num_images_per_prompt=num_images_per_prompt,
|
395
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
396
|
+
negative_prompt=negative_prompt,
|
397
|
+
prompt_embeds=prompt_embeds,
|
398
|
+
prompt_embeds_pooled=prompt_embeds_pooled,
|
399
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
400
|
+
negative_prompt_embeds_pooled=negative_prompt_embeds_pooled,
|
401
|
+
)
|
402
|
+
|
403
|
+
# The pooled embeds from the prior are pooled again before being passed to the decoder
|
404
|
+
prompt_embeds_pooled = (
|
405
|
+
torch.cat([prompt_embeds_pooled, negative_prompt_embeds_pooled])
|
406
|
+
if self.do_classifier_free_guidance
|
407
|
+
else prompt_embeds_pooled
|
408
|
+
)
|
409
|
+
effnet = (
|
410
|
+
torch.cat([image_embeddings, torch.zeros_like(image_embeddings)])
|
411
|
+
if self.do_classifier_free_guidance
|
412
|
+
else image_embeddings
|
413
|
+
)
|
414
|
+
|
415
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
416
|
+
timesteps = self.scheduler.timesteps
|
417
|
+
|
418
|
+
# 5. Prepare latents
|
419
|
+
latents = self.prepare_latents(
|
420
|
+
image_embeddings, num_images_per_prompt, dtype, device, generator, latents, self.scheduler
|
421
|
+
)
|
422
|
+
|
423
|
+
# 6. Run denoising loop
|
424
|
+
self._num_timesteps = len(timesteps[:-1])
|
425
|
+
for i, t in enumerate(self.progress_bar(timesteps[:-1])):
|
426
|
+
timestep_ratio = t.expand(latents.size(0)).to(dtype)
|
427
|
+
|
428
|
+
# 7. Denoise latents
|
429
|
+
predicted_latents = self.decoder(
|
430
|
+
sample=torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents,
|
431
|
+
timestep_ratio=torch.cat([timestep_ratio] * 2) if self.do_classifier_free_guidance else timestep_ratio,
|
432
|
+
clip_text_pooled=prompt_embeds_pooled,
|
433
|
+
effnet=effnet,
|
434
|
+
return_dict=False,
|
435
|
+
)[0]
|
436
|
+
|
437
|
+
# 8. Check for classifier free guidance and apply it
|
438
|
+
if self.do_classifier_free_guidance:
|
439
|
+
predicted_latents_text, predicted_latents_uncond = predicted_latents.chunk(2)
|
440
|
+
predicted_latents = torch.lerp(predicted_latents_uncond, predicted_latents_text, self.guidance_scale)
|
441
|
+
|
442
|
+
# 9. Renoise latents to next timestep
|
443
|
+
latents = self.scheduler.step(
|
444
|
+
model_output=predicted_latents,
|
445
|
+
timestep=timestep_ratio,
|
446
|
+
sample=latents,
|
447
|
+
generator=generator,
|
448
|
+
).prev_sample
|
449
|
+
|
450
|
+
if callback_on_step_end is not None:
|
451
|
+
callback_kwargs = {}
|
452
|
+
for k in callback_on_step_end_tensor_inputs:
|
453
|
+
callback_kwargs[k] = locals()[k]
|
454
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
455
|
+
|
456
|
+
latents = callback_outputs.pop("latents", latents)
|
457
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
458
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
459
|
+
|
460
|
+
if output_type not in ["pt", "np", "pil", "latent"]:
|
461
|
+
raise ValueError(
|
462
|
+
f"Only the output types `pt`, `np`, `pil` and `latent` are supported not output_type={output_type}"
|
463
|
+
)
|
464
|
+
|
465
|
+
if not output_type == "latent":
|
466
|
+
# 10. Scale and decode the image latents with vq-vae
|
467
|
+
latents = self.vqgan.config.scale_factor * latents
|
468
|
+
images = self.vqgan.decode(latents).sample.clamp(0, 1)
|
469
|
+
if output_type == "np":
|
470
|
+
images = images.permute(0, 2, 3, 1).cpu().float().numpy() # float() as bfloat16-> numpy doesnt work
|
471
|
+
elif output_type == "pil":
|
472
|
+
images = images.permute(0, 2, 3, 1).cpu().float().numpy() # float() as bfloat16-> numpy doesnt work
|
473
|
+
images = self.numpy_to_pil(images)
|
474
|
+
else:
|
475
|
+
images = latents
|
476
|
+
|
477
|
+
# Offload all models
|
478
|
+
self.maybe_free_model_hooks()
|
479
|
+
|
480
|
+
if not return_dict:
|
481
|
+
return images
|
482
|
+
return ImagePipelineOutput(images)
|