diffusers 0.26.3__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 +7 -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 +274 -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 +49 -18
- 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.3.dist-info → diffusers-0.27.0.dist-info}/METADATA +46 -46
- diffusers-0.27.0.dist-info/RECORD +399 -0
- {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/WHEEL +1 -1
- diffusers-0.26.3.dist-info/RECORD +0 -384
- {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/LICENSE +0 -0
- {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/entry_points.txt +0 -0
- {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,638 @@
|
|
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 dataclasses import dataclass
|
16
|
+
from math import ceil
|
17
|
+
from typing import Callable, Dict, List, Optional, Union
|
18
|
+
|
19
|
+
import numpy as np
|
20
|
+
import PIL
|
21
|
+
import torch
|
22
|
+
from transformers import CLIPImageProcessor, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionModelWithProjection
|
23
|
+
|
24
|
+
from ...models import StableCascadeUNet
|
25
|
+
from ...schedulers import DDPMWuerstchenScheduler
|
26
|
+
from ...utils import BaseOutput, logging, replace_example_docstring
|
27
|
+
from ...utils.torch_utils import randn_tensor
|
28
|
+
from ..pipeline_utils import DiffusionPipeline
|
29
|
+
|
30
|
+
|
31
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
32
|
+
|
33
|
+
DEFAULT_STAGE_C_TIMESTEPS = list(np.linspace(1.0, 2 / 3, 20)) + list(np.linspace(2 / 3, 0.0, 11))[1:]
|
34
|
+
|
35
|
+
EXAMPLE_DOC_STRING = """
|
36
|
+
Examples:
|
37
|
+
```py
|
38
|
+
>>> import torch
|
39
|
+
>>> from diffusers import StableCascadePriorPipeline
|
40
|
+
|
41
|
+
>>> prior_pipe = StableCascadePriorPipeline.from_pretrained(
|
42
|
+
... "stabilityai/stable-cascade-prior", torch_dtype=torch.bfloat16
|
43
|
+
... ).to("cuda")
|
44
|
+
|
45
|
+
>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
|
46
|
+
>>> prior_output = pipe(prompt)
|
47
|
+
```
|
48
|
+
"""
|
49
|
+
|
50
|
+
|
51
|
+
@dataclass
|
52
|
+
class StableCascadePriorPipelineOutput(BaseOutput):
|
53
|
+
"""
|
54
|
+
Output class for WuerstchenPriorPipeline.
|
55
|
+
|
56
|
+
Args:
|
57
|
+
image_embeddings (`torch.FloatTensor` or `np.ndarray`)
|
58
|
+
Prior image embeddings for text prompt
|
59
|
+
prompt_embeds (`torch.FloatTensor`):
|
60
|
+
Text embeddings for the prompt.
|
61
|
+
negative_prompt_embeds (`torch.FloatTensor`):
|
62
|
+
Text embeddings for the negative prompt.
|
63
|
+
"""
|
64
|
+
|
65
|
+
image_embeddings: Union[torch.FloatTensor, np.ndarray]
|
66
|
+
prompt_embeds: Union[torch.FloatTensor, np.ndarray]
|
67
|
+
prompt_embeds_pooled: Union[torch.FloatTensor, np.ndarray]
|
68
|
+
negative_prompt_embeds: Union[torch.FloatTensor, np.ndarray]
|
69
|
+
negative_prompt_embeds_pooled: Union[torch.FloatTensor, np.ndarray]
|
70
|
+
|
71
|
+
|
72
|
+
class StableCascadePriorPipeline(DiffusionPipeline):
|
73
|
+
"""
|
74
|
+
Pipeline for generating image prior for Stable Cascade.
|
75
|
+
|
76
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
77
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
78
|
+
|
79
|
+
Args:
|
80
|
+
prior ([`StableCascadeUNet`]):
|
81
|
+
The Stable Cascade prior to approximate the image embedding from the text and/or image embedding.
|
82
|
+
text_encoder ([`CLIPTextModelWithProjection`]):
|
83
|
+
Frozen text-encoder ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
|
84
|
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
85
|
+
Model that extracts features from generated images to be used as inputs for the `image_encoder`.
|
86
|
+
image_encoder ([`CLIPVisionModelWithProjection`]):
|
87
|
+
Frozen CLIP image-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
88
|
+
tokenizer (`CLIPTokenizer`):
|
89
|
+
Tokenizer of class
|
90
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
91
|
+
scheduler ([`DDPMWuerstchenScheduler`]):
|
92
|
+
A scheduler to be used in combination with `prior` to generate image embedding.
|
93
|
+
resolution_multiple ('float', *optional*, defaults to 42.67):
|
94
|
+
Default resolution for multiple images generated.
|
95
|
+
"""
|
96
|
+
|
97
|
+
unet_name = "prior"
|
98
|
+
text_encoder_name = "text_encoder"
|
99
|
+
model_cpu_offload_seq = "image_encoder->text_encoder->prior"
|
100
|
+
_optional_components = ["image_encoder", "feature_extractor"]
|
101
|
+
_callback_tensor_inputs = ["latents", "text_encoder_hidden_states", "negative_prompt_embeds"]
|
102
|
+
|
103
|
+
def __init__(
|
104
|
+
self,
|
105
|
+
tokenizer: CLIPTokenizer,
|
106
|
+
text_encoder: CLIPTextModelWithProjection,
|
107
|
+
prior: StableCascadeUNet,
|
108
|
+
scheduler: DDPMWuerstchenScheduler,
|
109
|
+
resolution_multiple: float = 42.67,
|
110
|
+
feature_extractor: Optional[CLIPImageProcessor] = None,
|
111
|
+
image_encoder: Optional[CLIPVisionModelWithProjection] = None,
|
112
|
+
) -> None:
|
113
|
+
super().__init__()
|
114
|
+
self.register_modules(
|
115
|
+
tokenizer=tokenizer,
|
116
|
+
text_encoder=text_encoder,
|
117
|
+
image_encoder=image_encoder,
|
118
|
+
feature_extractor=feature_extractor,
|
119
|
+
prior=prior,
|
120
|
+
scheduler=scheduler,
|
121
|
+
)
|
122
|
+
self.register_to_config(resolution_multiple=resolution_multiple)
|
123
|
+
|
124
|
+
def prepare_latents(
|
125
|
+
self, batch_size, height, width, num_images_per_prompt, dtype, device, generator, latents, scheduler
|
126
|
+
):
|
127
|
+
latent_shape = (
|
128
|
+
num_images_per_prompt * batch_size,
|
129
|
+
self.prior.config.in_channels,
|
130
|
+
ceil(height / self.config.resolution_multiple),
|
131
|
+
ceil(width / self.config.resolution_multiple),
|
132
|
+
)
|
133
|
+
|
134
|
+
if latents is None:
|
135
|
+
latents = randn_tensor(latent_shape, generator=generator, device=device, dtype=dtype)
|
136
|
+
else:
|
137
|
+
if latents.shape != latent_shape:
|
138
|
+
raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latent_shape}")
|
139
|
+
latents = latents.to(device)
|
140
|
+
|
141
|
+
latents = latents * scheduler.init_noise_sigma
|
142
|
+
return latents
|
143
|
+
|
144
|
+
def encode_prompt(
|
145
|
+
self,
|
146
|
+
device,
|
147
|
+
batch_size,
|
148
|
+
num_images_per_prompt,
|
149
|
+
do_classifier_free_guidance,
|
150
|
+
prompt=None,
|
151
|
+
negative_prompt=None,
|
152
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
153
|
+
prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
154
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
155
|
+
negative_prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
156
|
+
):
|
157
|
+
if prompt_embeds is None:
|
158
|
+
# get prompt text embeddings
|
159
|
+
text_inputs = self.tokenizer(
|
160
|
+
prompt,
|
161
|
+
padding="max_length",
|
162
|
+
max_length=self.tokenizer.model_max_length,
|
163
|
+
truncation=True,
|
164
|
+
return_tensors="pt",
|
165
|
+
)
|
166
|
+
text_input_ids = text_inputs.input_ids
|
167
|
+
attention_mask = text_inputs.attention_mask
|
168
|
+
|
169
|
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
170
|
+
|
171
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
172
|
+
text_input_ids, untruncated_ids
|
173
|
+
):
|
174
|
+
removed_text = self.tokenizer.batch_decode(
|
175
|
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
176
|
+
)
|
177
|
+
logger.warning(
|
178
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
179
|
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
180
|
+
)
|
181
|
+
text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
|
182
|
+
attention_mask = attention_mask[:, : self.tokenizer.model_max_length]
|
183
|
+
|
184
|
+
text_encoder_output = self.text_encoder(
|
185
|
+
text_input_ids.to(device), attention_mask=attention_mask.to(device), output_hidden_states=True
|
186
|
+
)
|
187
|
+
prompt_embeds = text_encoder_output.hidden_states[-1]
|
188
|
+
if prompt_embeds_pooled is None:
|
189
|
+
prompt_embeds_pooled = text_encoder_output.text_embeds.unsqueeze(1)
|
190
|
+
|
191
|
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
192
|
+
prompt_embeds_pooled = prompt_embeds_pooled.to(dtype=self.text_encoder.dtype, device=device)
|
193
|
+
prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
194
|
+
prompt_embeds_pooled = prompt_embeds_pooled.repeat_interleave(num_images_per_prompt, dim=0)
|
195
|
+
|
196
|
+
if negative_prompt_embeds is None and do_classifier_free_guidance:
|
197
|
+
uncond_tokens: List[str]
|
198
|
+
if negative_prompt is None:
|
199
|
+
uncond_tokens = [""] * batch_size
|
200
|
+
elif type(prompt) is not type(negative_prompt):
|
201
|
+
raise TypeError(
|
202
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
203
|
+
f" {type(prompt)}."
|
204
|
+
)
|
205
|
+
elif isinstance(negative_prompt, str):
|
206
|
+
uncond_tokens = [negative_prompt]
|
207
|
+
elif batch_size != len(negative_prompt):
|
208
|
+
raise ValueError(
|
209
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
210
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
211
|
+
" the batch size of `prompt`."
|
212
|
+
)
|
213
|
+
else:
|
214
|
+
uncond_tokens = negative_prompt
|
215
|
+
|
216
|
+
uncond_input = self.tokenizer(
|
217
|
+
uncond_tokens,
|
218
|
+
padding="max_length",
|
219
|
+
max_length=self.tokenizer.model_max_length,
|
220
|
+
truncation=True,
|
221
|
+
return_tensors="pt",
|
222
|
+
)
|
223
|
+
negative_prompt_embeds_text_encoder_output = self.text_encoder(
|
224
|
+
uncond_input.input_ids.to(device),
|
225
|
+
attention_mask=uncond_input.attention_mask.to(device),
|
226
|
+
output_hidden_states=True,
|
227
|
+
)
|
228
|
+
|
229
|
+
negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.hidden_states[-1]
|
230
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_text_encoder_output.text_embeds.unsqueeze(1)
|
231
|
+
|
232
|
+
if do_classifier_free_guidance:
|
233
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
234
|
+
seq_len = negative_prompt_embeds.shape[1]
|
235
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
236
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
237
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
238
|
+
|
239
|
+
seq_len = negative_prompt_embeds_pooled.shape[1]
|
240
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_pooled.to(
|
241
|
+
dtype=self.text_encoder.dtype, device=device
|
242
|
+
)
|
243
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_pooled.repeat(1, num_images_per_prompt, 1)
|
244
|
+
negative_prompt_embeds_pooled = negative_prompt_embeds_pooled.view(
|
245
|
+
batch_size * num_images_per_prompt, seq_len, -1
|
246
|
+
)
|
247
|
+
# done duplicates
|
248
|
+
|
249
|
+
return prompt_embeds, prompt_embeds_pooled, negative_prompt_embeds, negative_prompt_embeds_pooled
|
250
|
+
|
251
|
+
def encode_image(self, images, device, dtype, batch_size, num_images_per_prompt):
|
252
|
+
image_embeds = []
|
253
|
+
for image in images:
|
254
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
255
|
+
image = image.to(device=device, dtype=dtype)
|
256
|
+
image_embed = self.image_encoder(image).image_embeds.unsqueeze(1)
|
257
|
+
image_embeds.append(image_embed)
|
258
|
+
image_embeds = torch.cat(image_embeds, dim=1)
|
259
|
+
|
260
|
+
image_embeds = image_embeds.repeat(batch_size * num_images_per_prompt, 1, 1)
|
261
|
+
negative_image_embeds = torch.zeros_like(image_embeds)
|
262
|
+
|
263
|
+
return image_embeds, negative_image_embeds
|
264
|
+
|
265
|
+
def check_inputs(
|
266
|
+
self,
|
267
|
+
prompt,
|
268
|
+
images=None,
|
269
|
+
image_embeds=None,
|
270
|
+
negative_prompt=None,
|
271
|
+
prompt_embeds=None,
|
272
|
+
prompt_embeds_pooled=None,
|
273
|
+
negative_prompt_embeds=None,
|
274
|
+
negative_prompt_embeds_pooled=None,
|
275
|
+
callback_on_step_end_tensor_inputs=None,
|
276
|
+
):
|
277
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
278
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
279
|
+
):
|
280
|
+
raise ValueError(
|
281
|
+
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]}"
|
282
|
+
)
|
283
|
+
|
284
|
+
if prompt is not None and prompt_embeds is not None:
|
285
|
+
raise ValueError(
|
286
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
287
|
+
" only forward one of the two."
|
288
|
+
)
|
289
|
+
elif prompt is None and prompt_embeds is None:
|
290
|
+
raise ValueError(
|
291
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
292
|
+
)
|
293
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
294
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
295
|
+
|
296
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
297
|
+
raise ValueError(
|
298
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
299
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
300
|
+
)
|
301
|
+
|
302
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
303
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
304
|
+
raise ValueError(
|
305
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
306
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
307
|
+
f" {negative_prompt_embeds.shape}."
|
308
|
+
)
|
309
|
+
|
310
|
+
if prompt_embeds is not None and prompt_embeds_pooled is None:
|
311
|
+
raise ValueError(
|
312
|
+
"If `prompt_embeds` are provided, `prompt_embeds_pooled` must also be provided. Make sure to generate `prompt_embeds_pooled` from the same text encoder that was used to generate `prompt_embeds`"
|
313
|
+
)
|
314
|
+
|
315
|
+
if negative_prompt_embeds is not None and negative_prompt_embeds_pooled is None:
|
316
|
+
raise ValueError(
|
317
|
+
"If `negative_prompt_embeds` are provided, `negative_prompt_embeds_pooled` must also be provided. Make sure to generate `prompt_embeds_pooled` from the same text encoder that was used to generate `prompt_embeds`"
|
318
|
+
)
|
319
|
+
|
320
|
+
if prompt_embeds_pooled is not None and negative_prompt_embeds_pooled is not None:
|
321
|
+
if prompt_embeds_pooled.shape != negative_prompt_embeds_pooled.shape:
|
322
|
+
raise ValueError(
|
323
|
+
"`prompt_embeds_pooled` and `negative_prompt_embeds_pooled` must have the same shape when passed"
|
324
|
+
f"directly, but got: `prompt_embeds_pooled` {prompt_embeds_pooled.shape} !="
|
325
|
+
f"`negative_prompt_embeds_pooled` {negative_prompt_embeds_pooled.shape}."
|
326
|
+
)
|
327
|
+
|
328
|
+
if image_embeds is not None and images is not None:
|
329
|
+
raise ValueError(
|
330
|
+
f"Cannot forward both `images`: {images} and `image_embeds`: {image_embeds}. Please make sure to"
|
331
|
+
" only forward one of the two."
|
332
|
+
)
|
333
|
+
|
334
|
+
if images:
|
335
|
+
for i, image in enumerate(images):
|
336
|
+
if not isinstance(image, torch.Tensor) and not isinstance(image, PIL.Image.Image):
|
337
|
+
raise TypeError(
|
338
|
+
f"'images' must contain images of type 'torch.Tensor' or 'PIL.Image.Image, but got"
|
339
|
+
f"{type(image)} for image number {i}."
|
340
|
+
)
|
341
|
+
|
342
|
+
@property
|
343
|
+
def guidance_scale(self):
|
344
|
+
return self._guidance_scale
|
345
|
+
|
346
|
+
@property
|
347
|
+
def do_classifier_free_guidance(self):
|
348
|
+
return self._guidance_scale > 1
|
349
|
+
|
350
|
+
@property
|
351
|
+
def num_timesteps(self):
|
352
|
+
return self._num_timesteps
|
353
|
+
|
354
|
+
def get_timestep_ratio_conditioning(self, t, alphas_cumprod):
|
355
|
+
s = torch.tensor([0.003])
|
356
|
+
clamp_range = [0, 1]
|
357
|
+
min_var = torch.cos(s / (1 + s) * torch.pi * 0.5) ** 2
|
358
|
+
var = alphas_cumprod[t]
|
359
|
+
var = var.clamp(*clamp_range)
|
360
|
+
s, min_var = s.to(var.device), min_var.to(var.device)
|
361
|
+
ratio = (((var * min_var) ** 0.5).acos() / (torch.pi * 0.5)) * (1 + s) - s
|
362
|
+
return ratio
|
363
|
+
|
364
|
+
@torch.no_grad()
|
365
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
366
|
+
def __call__(
|
367
|
+
self,
|
368
|
+
prompt: Optional[Union[str, List[str]]] = None,
|
369
|
+
images: Union[torch.Tensor, PIL.Image.Image, List[torch.Tensor], List[PIL.Image.Image]] = None,
|
370
|
+
height: int = 1024,
|
371
|
+
width: int = 1024,
|
372
|
+
num_inference_steps: int = 20,
|
373
|
+
timesteps: List[float] = None,
|
374
|
+
guidance_scale: float = 4.0,
|
375
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
376
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
377
|
+
prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
378
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
379
|
+
negative_prompt_embeds_pooled: Optional[torch.FloatTensor] = None,
|
380
|
+
image_embeds: Optional[torch.FloatTensor] = None,
|
381
|
+
num_images_per_prompt: Optional[int] = 1,
|
382
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
383
|
+
latents: Optional[torch.FloatTensor] = None,
|
384
|
+
output_type: Optional[str] = "pt",
|
385
|
+
return_dict: bool = True,
|
386
|
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
387
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
388
|
+
):
|
389
|
+
"""
|
390
|
+
Function invoked when calling the pipeline for generation.
|
391
|
+
|
392
|
+
Args:
|
393
|
+
prompt (`str` or `List[str]`):
|
394
|
+
The prompt or prompts to guide the image generation.
|
395
|
+
height (`int`, *optional*, defaults to 1024):
|
396
|
+
The height in pixels of the generated image.
|
397
|
+
width (`int`, *optional*, defaults to 1024):
|
398
|
+
The width in pixels of the generated image.
|
399
|
+
num_inference_steps (`int`, *optional*, defaults to 60):
|
400
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
401
|
+
expense of slower inference.
|
402
|
+
guidance_scale (`float`, *optional*, defaults to 8.0):
|
403
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
404
|
+
`decoder_guidance_scale` is defined as `w` of equation 2. of [Imagen
|
405
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting
|
406
|
+
`decoder_guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely
|
407
|
+
linked to the text `prompt`, usually at the expense of lower image quality.
|
408
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
409
|
+
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
|
410
|
+
if `decoder_guidance_scale` is less than `1`).
|
411
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
412
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
413
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
414
|
+
prompt_embeds_pooled (`torch.FloatTensor`, *optional*):
|
415
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
416
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
417
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
418
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
419
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
420
|
+
argument.
|
421
|
+
negative_prompt_embeds_pooled (`torch.FloatTensor`, *optional*):
|
422
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
423
|
+
weighting. If not provided, negative_prompt_embeds_pooled will be generated from `negative_prompt` input
|
424
|
+
argument.
|
425
|
+
image_embeds (`torch.FloatTensor`, *optional*):
|
426
|
+
Pre-generated image embeddings. Can be used to easily tweak image inputs, *e.g.* prompt weighting.
|
427
|
+
If not provided, image embeddings will be generated from `image` input argument if existing.
|
428
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
429
|
+
The number of images to generate per prompt.
|
430
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
431
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
432
|
+
to make generation deterministic.
|
433
|
+
latents (`torch.FloatTensor`, *optional*):
|
434
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
435
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
436
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
437
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
438
|
+
The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"`
|
439
|
+
(`np.array`) or `"pt"` (`torch.Tensor`).
|
440
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
441
|
+
Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
|
442
|
+
callback_on_step_end (`Callable`, *optional*):
|
443
|
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
444
|
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
445
|
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
446
|
+
`callback_on_step_end_tensor_inputs`.
|
447
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
448
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
449
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
450
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
451
|
+
|
452
|
+
Examples:
|
453
|
+
|
454
|
+
Returns:
|
455
|
+
[`StableCascadePriorPipelineOutput`] or `tuple` [`StableCascadePriorPipelineOutput`] if
|
456
|
+
`return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
|
457
|
+
generated image embeddings.
|
458
|
+
"""
|
459
|
+
|
460
|
+
# 0. Define commonly used variables
|
461
|
+
device = self._execution_device
|
462
|
+
dtype = next(self.prior.parameters()).dtype
|
463
|
+
self._guidance_scale = guidance_scale
|
464
|
+
if prompt is not None and isinstance(prompt, str):
|
465
|
+
batch_size = 1
|
466
|
+
elif prompt is not None and isinstance(prompt, list):
|
467
|
+
batch_size = len(prompt)
|
468
|
+
else:
|
469
|
+
batch_size = prompt_embeds.shape[0]
|
470
|
+
|
471
|
+
# 1. Check inputs. Raise error if not correct
|
472
|
+
self.check_inputs(
|
473
|
+
prompt,
|
474
|
+
images=images,
|
475
|
+
image_embeds=image_embeds,
|
476
|
+
negative_prompt=negative_prompt,
|
477
|
+
prompt_embeds=prompt_embeds,
|
478
|
+
prompt_embeds_pooled=prompt_embeds_pooled,
|
479
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
480
|
+
negative_prompt_embeds_pooled=negative_prompt_embeds_pooled,
|
481
|
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
482
|
+
)
|
483
|
+
|
484
|
+
# 2. Encode caption + images
|
485
|
+
(
|
486
|
+
prompt_embeds,
|
487
|
+
prompt_embeds_pooled,
|
488
|
+
negative_prompt_embeds,
|
489
|
+
negative_prompt_embeds_pooled,
|
490
|
+
) = self.encode_prompt(
|
491
|
+
prompt=prompt,
|
492
|
+
device=device,
|
493
|
+
batch_size=batch_size,
|
494
|
+
num_images_per_prompt=num_images_per_prompt,
|
495
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
496
|
+
negative_prompt=negative_prompt,
|
497
|
+
prompt_embeds=prompt_embeds,
|
498
|
+
prompt_embeds_pooled=prompt_embeds_pooled,
|
499
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
500
|
+
negative_prompt_embeds_pooled=negative_prompt_embeds_pooled,
|
501
|
+
)
|
502
|
+
|
503
|
+
if images is not None:
|
504
|
+
image_embeds_pooled, uncond_image_embeds_pooled = self.encode_image(
|
505
|
+
images=images,
|
506
|
+
device=device,
|
507
|
+
dtype=dtype,
|
508
|
+
batch_size=batch_size,
|
509
|
+
num_images_per_prompt=num_images_per_prompt,
|
510
|
+
)
|
511
|
+
elif image_embeds is not None:
|
512
|
+
image_embeds_pooled = image_embeds.repeat(batch_size * num_images_per_prompt, 1, 1)
|
513
|
+
uncond_image_embeds_pooled = torch.zeros_like(image_embeds_pooled)
|
514
|
+
else:
|
515
|
+
image_embeds_pooled = torch.zeros(
|
516
|
+
batch_size * num_images_per_prompt,
|
517
|
+
1,
|
518
|
+
self.prior.config.clip_image_in_channels,
|
519
|
+
device=device,
|
520
|
+
dtype=dtype,
|
521
|
+
)
|
522
|
+
uncond_image_embeds_pooled = torch.zeros(
|
523
|
+
batch_size * num_images_per_prompt,
|
524
|
+
1,
|
525
|
+
self.prior.config.clip_image_in_channels,
|
526
|
+
device=device,
|
527
|
+
dtype=dtype,
|
528
|
+
)
|
529
|
+
|
530
|
+
if self.do_classifier_free_guidance:
|
531
|
+
image_embeds = torch.cat([image_embeds_pooled, uncond_image_embeds_pooled], dim=0)
|
532
|
+
else:
|
533
|
+
image_embeds = image_embeds_pooled
|
534
|
+
|
535
|
+
# For classifier free guidance, we need to do two forward passes.
|
536
|
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
537
|
+
# to avoid doing two forward passes
|
538
|
+
text_encoder_hidden_states = (
|
539
|
+
torch.cat([prompt_embeds, negative_prompt_embeds]) if negative_prompt_embeds is not None else prompt_embeds
|
540
|
+
)
|
541
|
+
text_encoder_pooled = (
|
542
|
+
torch.cat([prompt_embeds_pooled, negative_prompt_embeds_pooled])
|
543
|
+
if negative_prompt_embeds is not None
|
544
|
+
else prompt_embeds_pooled
|
545
|
+
)
|
546
|
+
|
547
|
+
# 4. Prepare and set timesteps
|
548
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
549
|
+
timesteps = self.scheduler.timesteps
|
550
|
+
|
551
|
+
# 5. Prepare latents
|
552
|
+
latents = self.prepare_latents(
|
553
|
+
batch_size, height, width, num_images_per_prompt, dtype, device, generator, latents, self.scheduler
|
554
|
+
)
|
555
|
+
|
556
|
+
if isinstance(self.scheduler, DDPMWuerstchenScheduler):
|
557
|
+
timesteps = timesteps[:-1]
|
558
|
+
else:
|
559
|
+
if self.scheduler.config.clip_sample:
|
560
|
+
self.scheduler.config.clip_sample = False # disample sample clipping
|
561
|
+
logger.warning(" set `clip_sample` to be False")
|
562
|
+
# 6. Run denoising loop
|
563
|
+
if hasattr(self.scheduler, "betas"):
|
564
|
+
alphas = 1.0 - self.scheduler.betas
|
565
|
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
566
|
+
else:
|
567
|
+
alphas_cumprod = []
|
568
|
+
|
569
|
+
self._num_timesteps = len(timesteps)
|
570
|
+
for i, t in enumerate(self.progress_bar(timesteps)):
|
571
|
+
if not isinstance(self.scheduler, DDPMWuerstchenScheduler):
|
572
|
+
if len(alphas_cumprod) > 0:
|
573
|
+
timestep_ratio = self.get_timestep_ratio_conditioning(t.long().cpu(), alphas_cumprod)
|
574
|
+
timestep_ratio = timestep_ratio.expand(latents.size(0)).to(dtype).to(device)
|
575
|
+
else:
|
576
|
+
timestep_ratio = t.float().div(self.scheduler.timesteps[-1]).expand(latents.size(0)).to(dtype)
|
577
|
+
else:
|
578
|
+
timestep_ratio = t.expand(latents.size(0)).to(dtype)
|
579
|
+
# 7. Denoise image embeddings
|
580
|
+
predicted_image_embedding = self.prior(
|
581
|
+
sample=torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents,
|
582
|
+
timestep_ratio=torch.cat([timestep_ratio] * 2) if self.do_classifier_free_guidance else timestep_ratio,
|
583
|
+
clip_text_pooled=text_encoder_pooled,
|
584
|
+
clip_text=text_encoder_hidden_states,
|
585
|
+
clip_img=image_embeds,
|
586
|
+
return_dict=False,
|
587
|
+
)[0]
|
588
|
+
|
589
|
+
# 8. Check for classifier free guidance and apply it
|
590
|
+
if self.do_classifier_free_guidance:
|
591
|
+
predicted_image_embedding_text, predicted_image_embedding_uncond = predicted_image_embedding.chunk(2)
|
592
|
+
predicted_image_embedding = torch.lerp(
|
593
|
+
predicted_image_embedding_uncond, predicted_image_embedding_text, self.guidance_scale
|
594
|
+
)
|
595
|
+
|
596
|
+
# 9. Renoise latents to next timestep
|
597
|
+
if not isinstance(self.scheduler, DDPMWuerstchenScheduler):
|
598
|
+
timestep_ratio = t
|
599
|
+
latents = self.scheduler.step(
|
600
|
+
model_output=predicted_image_embedding, timestep=timestep_ratio, sample=latents, generator=generator
|
601
|
+
).prev_sample
|
602
|
+
|
603
|
+
if callback_on_step_end is not None:
|
604
|
+
callback_kwargs = {}
|
605
|
+
for k in callback_on_step_end_tensor_inputs:
|
606
|
+
callback_kwargs[k] = locals()[k]
|
607
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
608
|
+
|
609
|
+
latents = callback_outputs.pop("latents", latents)
|
610
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
611
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
612
|
+
|
613
|
+
# Offload all models
|
614
|
+
self.maybe_free_model_hooks()
|
615
|
+
|
616
|
+
if output_type == "np":
|
617
|
+
latents = latents.cpu().float().numpy() # float() as bfloat16-> numpy doesnt work
|
618
|
+
prompt_embeds = prompt_embeds.cpu().float().numpy() # float() as bfloat16-> numpy doesnt work
|
619
|
+
negative_prompt_embeds = (
|
620
|
+
negative_prompt_embeds.cpu().float().numpy() if negative_prompt_embeds is not None else None
|
621
|
+
) # float() as bfloat16-> numpy doesnt work
|
622
|
+
|
623
|
+
if not return_dict:
|
624
|
+
return (
|
625
|
+
latents,
|
626
|
+
prompt_embeds,
|
627
|
+
prompt_embeds_pooled,
|
628
|
+
negative_prompt_embeds,
|
629
|
+
negative_prompt_embeds_pooled,
|
630
|
+
)
|
631
|
+
|
632
|
+
return StableCascadePriorPipelineOutput(
|
633
|
+
image_embeddings=latents,
|
634
|
+
prompt_embeds=prompt_embeds,
|
635
|
+
prompt_embeds_pooled=prompt_embeds_pooled,
|
636
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
637
|
+
negative_prompt_embeds_pooled=negative_prompt_embeds_pooled,
|
638
|
+
)
|
@@ -1,4 +1,4 @@
|
|
1
|
-
# Copyright
|
1
|
+
# Copyright 2024 The GLIGEN Authors and HuggingFace Team. All rights reserved.
|
2
2
|
#
|
3
3
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
4
|
# you may not use this file except in compliance with the License.
|
@@ -1,5 +1,5 @@
|
|
1
1
|
# coding=utf-8
|
2
|
-
# Copyright
|
2
|
+
# Copyright 2024 The HuggingFace Inc. team.
|
3
3
|
#
|
4
4
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
5
5
|
# you may not use this file except in compliance with the License.
|
@@ -1320,6 +1320,9 @@ def download_from_original_stable_diffusion_ckpt(
|
|
1320
1320
|
else:
|
1321
1321
|
with open(original_config_file, "r") as f:
|
1322
1322
|
original_config_file = f.read()
|
1323
|
+
else:
|
1324
|
+
with open(original_config_file, "r") as f:
|
1325
|
+
original_config_file = f.read()
|
1323
1326
|
|
1324
1327
|
original_config = yaml.safe_load(original_config_file)
|
1325
1328
|
|