diffusers 0.27.1__py3-none-any.whl → 0.32.2__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diffusers/__init__.py +233 -6
- diffusers/callbacks.py +209 -0
- diffusers/commands/env.py +102 -6
- diffusers/configuration_utils.py +45 -16
- diffusers/dependency_versions_table.py +4 -3
- diffusers/image_processor.py +434 -110
- diffusers/loaders/__init__.py +42 -9
- diffusers/loaders/ip_adapter.py +626 -36
- diffusers/loaders/lora_base.py +900 -0
- diffusers/loaders/lora_conversion_utils.py +991 -125
- diffusers/loaders/lora_pipeline.py +3812 -0
- diffusers/loaders/peft.py +571 -7
- diffusers/loaders/single_file.py +405 -173
- diffusers/loaders/single_file_model.py +385 -0
- diffusers/loaders/single_file_utils.py +1783 -713
- diffusers/loaders/textual_inversion.py +41 -23
- diffusers/loaders/transformer_flux.py +181 -0
- diffusers/loaders/transformer_sd3.py +89 -0
- diffusers/loaders/unet.py +464 -540
- diffusers/loaders/unet_loader_utils.py +163 -0
- diffusers/models/__init__.py +76 -7
- diffusers/models/activations.py +65 -10
- diffusers/models/adapter.py +53 -53
- diffusers/models/attention.py +605 -18
- diffusers/models/attention_flax.py +1 -1
- diffusers/models/attention_processor.py +4304 -687
- diffusers/models/autoencoders/__init__.py +8 -0
- diffusers/models/autoencoders/autoencoder_asym_kl.py +15 -17
- diffusers/models/autoencoders/autoencoder_dc.py +620 -0
- diffusers/models/autoencoders/autoencoder_kl.py +110 -28
- diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1482 -0
- diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
- diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
- diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +19 -24
- diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
- diffusers/models/autoencoders/autoencoder_tiny.py +21 -18
- diffusers/models/autoencoders/consistency_decoder_vae.py +45 -20
- diffusers/models/autoencoders/vae.py +41 -29
- diffusers/models/autoencoders/vq_model.py +182 -0
- diffusers/models/controlnet.py +47 -800
- diffusers/models/controlnet_flux.py +70 -0
- diffusers/models/controlnet_sd3.py +68 -0
- diffusers/models/controlnet_sparsectrl.py +116 -0
- diffusers/models/controlnets/__init__.py +23 -0
- diffusers/models/controlnets/controlnet.py +872 -0
- diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +9 -9
- diffusers/models/controlnets/controlnet_flux.py +536 -0
- diffusers/models/controlnets/controlnet_hunyuan.py +401 -0
- diffusers/models/controlnets/controlnet_sd3.py +489 -0
- diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
- diffusers/models/controlnets/controlnet_union.py +832 -0
- diffusers/models/controlnets/controlnet_xs.py +1946 -0
- diffusers/models/controlnets/multicontrolnet.py +183 -0
- diffusers/models/downsampling.py +85 -18
- diffusers/models/embeddings.py +1856 -158
- diffusers/models/embeddings_flax.py +23 -9
- diffusers/models/model_loading_utils.py +480 -0
- diffusers/models/modeling_flax_pytorch_utils.py +2 -1
- diffusers/models/modeling_flax_utils.py +2 -7
- diffusers/models/modeling_outputs.py +14 -0
- diffusers/models/modeling_pytorch_flax_utils.py +1 -1
- diffusers/models/modeling_utils.py +611 -146
- diffusers/models/normalization.py +361 -20
- diffusers/models/resnet.py +18 -23
- diffusers/models/transformers/__init__.py +16 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +544 -0
- diffusers/models/transformers/cogvideox_transformer_3d.py +542 -0
- diffusers/models/transformers/dit_transformer_2d.py +240 -0
- diffusers/models/transformers/dual_transformer_2d.py +9 -8
- diffusers/models/transformers/hunyuan_transformer_2d.py +578 -0
- diffusers/models/transformers/latte_transformer_3d.py +327 -0
- diffusers/models/transformers/lumina_nextdit2d.py +340 -0
- diffusers/models/transformers/pixart_transformer_2d.py +445 -0
- diffusers/models/transformers/prior_transformer.py +13 -13
- diffusers/models/transformers/sana_transformer.py +488 -0
- diffusers/models/transformers/stable_audio_transformer.py +458 -0
- diffusers/models/transformers/t5_film_transformer.py +17 -19
- diffusers/models/transformers/transformer_2d.py +297 -187
- diffusers/models/transformers/transformer_allegro.py +422 -0
- diffusers/models/transformers/transformer_cogview3plus.py +386 -0
- diffusers/models/transformers/transformer_flux.py +593 -0
- diffusers/models/transformers/transformer_hunyuan_video.py +791 -0
- diffusers/models/transformers/transformer_ltx.py +469 -0
- diffusers/models/transformers/transformer_mochi.py +499 -0
- diffusers/models/transformers/transformer_sd3.py +461 -0
- diffusers/models/transformers/transformer_temporal.py +21 -19
- diffusers/models/unets/unet_1d.py +8 -8
- diffusers/models/unets/unet_1d_blocks.py +31 -31
- diffusers/models/unets/unet_2d.py +17 -10
- diffusers/models/unets/unet_2d_blocks.py +225 -149
- diffusers/models/unets/unet_2d_condition.py +41 -40
- diffusers/models/unets/unet_2d_condition_flax.py +6 -5
- diffusers/models/unets/unet_3d_blocks.py +192 -1057
- diffusers/models/unets/unet_3d_condition.py +22 -27
- diffusers/models/unets/unet_i2vgen_xl.py +22 -18
- diffusers/models/unets/unet_kandinsky3.py +2 -2
- diffusers/models/unets/unet_motion_model.py +1413 -89
- diffusers/models/unets/unet_spatio_temporal_condition.py +40 -16
- diffusers/models/unets/unet_stable_cascade.py +19 -18
- diffusers/models/unets/uvit_2d.py +2 -2
- diffusers/models/upsampling.py +95 -26
- diffusers/models/vq_model.py +12 -164
- diffusers/optimization.py +1 -1
- diffusers/pipelines/__init__.py +202 -3
- diffusers/pipelines/allegro/__init__.py +48 -0
- diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
- diffusers/pipelines/allegro/pipeline_output.py +23 -0
- diffusers/pipelines/amused/pipeline_amused.py +12 -12
- diffusers/pipelines/amused/pipeline_amused_img2img.py +14 -12
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +13 -11
- diffusers/pipelines/animatediff/__init__.py +8 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +122 -109
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1106 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +1288 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1010 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +236 -180
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
- diffusers/pipelines/animatediff/pipeline_output.py +3 -2
- diffusers/pipelines/audioldm/pipeline_audioldm.py +14 -14
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +58 -39
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +121 -36
- diffusers/pipelines/aura_flow/__init__.py +48 -0
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +584 -0
- diffusers/pipelines/auto_pipeline.py +196 -28
- diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_blip2.py +6 -6
- diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +1 -1
- diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
- diffusers/pipelines/cogvideo/__init__.py +54 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +772 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +825 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +885 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +851 -0
- diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
- diffusers/pipelines/cogview3/__init__.py +47 -0
- diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
- diffusers/pipelines/cogview3/pipeline_output.py +21 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +6 -6
- diffusers/pipelines/controlnet/__init__.py +86 -80
- diffusers/pipelines/controlnet/multicontrolnet.py +7 -182
- diffusers/pipelines/controlnet/pipeline_controlnet.py +134 -87
- diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +93 -77
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +88 -197
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +136 -90
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +176 -80
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +125 -89
- diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
- diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1060 -0
- diffusers/pipelines/controlnet_sd3/__init__.py +57 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +1133 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
- diffusers/pipelines/controlnet_xs/__init__.py +68 -0
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +916 -0
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +1111 -0
- diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +16 -30
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +20 -35
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +23 -41
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +22 -38
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +25 -41
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +19 -34
- diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
- diffusers/pipelines/deepfloyd_if/watermark.py +1 -1
- diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +11 -11
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +70 -30
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +48 -25
- diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +2 -2
- diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +7 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +21 -20
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +27 -29
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +33 -27
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +33 -23
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +36 -30
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +102 -69
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +13 -13
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +10 -5
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +11 -6
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +10 -5
- diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +5 -5
- diffusers/pipelines/dit/pipeline_dit.py +7 -4
- diffusers/pipelines/flux/__init__.py +69 -0
- diffusers/pipelines/flux/modeling_flux.py +47 -0
- diffusers/pipelines/flux/pipeline_flux.py +957 -0
- diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
- diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
- diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet.py +1006 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +998 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1204 -0
- diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
- diffusers/pipelines/flux/pipeline_flux_img2img.py +856 -0
- diffusers/pipelines/flux/pipeline_flux_inpaint.py +1022 -0
- diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
- diffusers/pipelines/flux/pipeline_output.py +37 -0
- diffusers/pipelines/free_init_utils.py +41 -38
- diffusers/pipelines/free_noise_utils.py +596 -0
- diffusers/pipelines/hunyuan_video/__init__.py +48 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
- diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
- diffusers/pipelines/hunyuandit/__init__.py +48 -0
- diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +916 -0
- diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +33 -48
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +8 -8
- diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +32 -29
- diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +11 -11
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +12 -12
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +34 -31
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +8 -8
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +7 -7
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +6 -6
- diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +3 -3
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +22 -35
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +26 -37
- diffusers/pipelines/kolors/__init__.py +54 -0
- diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1250 -0
- diffusers/pipelines/kolors/pipeline_output.py +21 -0
- diffusers/pipelines/kolors/text_encoder.py +889 -0
- diffusers/pipelines/kolors/tokenizer.py +338 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +82 -62
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +77 -60
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +12 -12
- diffusers/pipelines/latte/__init__.py +48 -0
- diffusers/pipelines/latte/pipeline_latte.py +881 -0
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +80 -74
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +85 -76
- diffusers/pipelines/ledits_pp/pipeline_output.py +2 -2
- diffusers/pipelines/ltx/__init__.py +50 -0
- diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
- diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
- diffusers/pipelines/ltx/pipeline_output.py +20 -0
- diffusers/pipelines/lumina/__init__.py +48 -0
- diffusers/pipelines/lumina/pipeline_lumina.py +890 -0
- diffusers/pipelines/marigold/__init__.py +50 -0
- diffusers/pipelines/marigold/marigold_image_processing.py +576 -0
- diffusers/pipelines/marigold/pipeline_marigold_depth.py +813 -0
- diffusers/pipelines/marigold/pipeline_marigold_normals.py +690 -0
- diffusers/pipelines/mochi/__init__.py +48 -0
- diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
- diffusers/pipelines/mochi/pipeline_output.py +20 -0
- diffusers/pipelines/musicldm/pipeline_musicldm.py +14 -14
- diffusers/pipelines/pag/__init__.py +80 -0
- diffusers/pipelines/pag/pag_utils.py +243 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1328 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1543 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1610 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1683 -0
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +969 -0
- diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +865 -0
- diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
- diffusers/pipelines/pag/pipeline_pag_sd.py +1062 -0
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +994 -0
- diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +866 -0
- diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1094 -0
- diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1345 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1544 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1776 -0
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +17 -12
- diffusers/pipelines/pia/pipeline_pia.py +74 -164
- diffusers/pipelines/pipeline_flax_utils.py +5 -10
- diffusers/pipelines/pipeline_loading_utils.py +515 -53
- diffusers/pipelines/pipeline_utils.py +411 -222
- diffusers/pipelines/pixart_alpha/__init__.py +8 -1
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +76 -93
- diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +873 -0
- diffusers/pipelines/sana/__init__.py +47 -0
- diffusers/pipelines/sana/pipeline_output.py +21 -0
- diffusers/pipelines/sana/pipeline_sana.py +884 -0
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +27 -23
- diffusers/pipelines/shap_e/pipeline_shap_e.py +3 -3
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +14 -14
- diffusers/pipelines/shap_e/renderer.py +1 -1
- diffusers/pipelines/stable_audio/__init__.py +50 -0
- diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +756 -0
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +71 -25
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +23 -19
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +35 -34
- diffusers/pipelines/stable_diffusion/__init__.py +0 -1
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +20 -11
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +6 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +145 -79
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +43 -28
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +13 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +100 -68
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +109 -201
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +131 -32
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +247 -87
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +30 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +35 -27
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +49 -42
- diffusers/pipelines/stable_diffusion/safety_checker.py +2 -1
- diffusers/pipelines/stable_diffusion_3/__init__.py +54 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_output.py +21 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +1140 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +1036 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1250 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +29 -20
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +59 -58
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +31 -25
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +38 -22
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -24
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +24 -23
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +107 -67
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +316 -69
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +10 -5
- diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +98 -30
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +121 -83
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +161 -105
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +142 -218
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +45 -29
- diffusers/pipelines/stable_diffusion_xl/watermark.py +9 -3
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +110 -57
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +69 -39
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +105 -74
- diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +3 -2
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +29 -49
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +32 -93
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +37 -25
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +54 -40
- diffusers/pipelines/unclip/pipeline_unclip.py +6 -6
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +6 -6
- diffusers/pipelines/unidiffuser/modeling_text_decoder.py +1 -1
- diffusers/pipelines/unidiffuser/modeling_uvit.py +12 -12
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +29 -28
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +5 -5
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +5 -10
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +6 -8
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +4 -4
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +12 -12
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +15 -14
- diffusers/{models/dual_transformer_2d.py → quantizers/__init__.py} +2 -6
- diffusers/quantizers/auto.py +139 -0
- diffusers/quantizers/base.py +233 -0
- diffusers/quantizers/bitsandbytes/__init__.py +2 -0
- diffusers/quantizers/bitsandbytes/bnb_quantizer.py +561 -0
- diffusers/quantizers/bitsandbytes/utils.py +306 -0
- diffusers/quantizers/gguf/__init__.py +1 -0
- diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
- diffusers/quantizers/gguf/utils.py +456 -0
- diffusers/quantizers/quantization_config.py +669 -0
- diffusers/quantizers/torchao/__init__.py +15 -0
- diffusers/quantizers/torchao/torchao_quantizer.py +292 -0
- diffusers/schedulers/__init__.py +12 -2
- diffusers/schedulers/deprecated/__init__.py +1 -1
- diffusers/schedulers/deprecated/scheduling_karras_ve.py +25 -25
- diffusers/schedulers/scheduling_amused.py +5 -5
- diffusers/schedulers/scheduling_consistency_decoder.py +11 -11
- diffusers/schedulers/scheduling_consistency_models.py +23 -25
- diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
- diffusers/schedulers/scheduling_ddim.py +27 -26
- diffusers/schedulers/scheduling_ddim_cogvideox.py +452 -0
- diffusers/schedulers/scheduling_ddim_flax.py +2 -1
- diffusers/schedulers/scheduling_ddim_inverse.py +16 -16
- diffusers/schedulers/scheduling_ddim_parallel.py +32 -31
- diffusers/schedulers/scheduling_ddpm.py +27 -30
- diffusers/schedulers/scheduling_ddpm_flax.py +7 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +33 -36
- diffusers/schedulers/scheduling_ddpm_wuerstchen.py +14 -14
- diffusers/schedulers/scheduling_deis_multistep.py +150 -50
- diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +221 -84
- diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +2 -2
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +158 -52
- diffusers/schedulers/scheduling_dpmsolver_sde.py +153 -34
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +275 -86
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +81 -57
- diffusers/schedulers/scheduling_edm_euler.py +62 -39
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +30 -29
- diffusers/schedulers/scheduling_euler_discrete.py +255 -74
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +458 -0
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +320 -0
- diffusers/schedulers/scheduling_heun_discrete.py +174 -46
- diffusers/schedulers/scheduling_ipndm.py +9 -9
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +138 -29
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +132 -26
- diffusers/schedulers/scheduling_karras_ve_flax.py +6 -6
- diffusers/schedulers/scheduling_lcm.py +23 -29
- diffusers/schedulers/scheduling_lms_discrete.py +105 -28
- diffusers/schedulers/scheduling_pndm.py +20 -20
- diffusers/schedulers/scheduling_repaint.py +21 -21
- diffusers/schedulers/scheduling_sasolver.py +157 -60
- diffusers/schedulers/scheduling_sde_ve.py +19 -19
- diffusers/schedulers/scheduling_tcd.py +41 -36
- diffusers/schedulers/scheduling_unclip.py +19 -16
- diffusers/schedulers/scheduling_unipc_multistep.py +243 -47
- diffusers/schedulers/scheduling_utils.py +12 -5
- diffusers/schedulers/scheduling_utils_flax.py +1 -3
- diffusers/schedulers/scheduling_vq_diffusion.py +10 -10
- diffusers/training_utils.py +214 -30
- diffusers/utils/__init__.py +17 -1
- diffusers/utils/constants.py +3 -0
- diffusers/utils/doc_utils.py +1 -0
- diffusers/utils/dummy_pt_objects.py +592 -7
- diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
- diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +1001 -71
- diffusers/utils/dynamic_modules_utils.py +34 -29
- diffusers/utils/export_utils.py +50 -6
- diffusers/utils/hub_utils.py +131 -17
- diffusers/utils/import_utils.py +210 -8
- diffusers/utils/loading_utils.py +118 -5
- diffusers/utils/logging.py +4 -2
- diffusers/utils/peft_utils.py +37 -7
- diffusers/utils/state_dict_utils.py +13 -2
- diffusers/utils/testing_utils.py +193 -11
- diffusers/utils/torch_utils.py +4 -0
- diffusers/video_processor.py +113 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/METADATA +82 -91
- diffusers-0.32.2.dist-info/RECORD +550 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/WHEEL +1 -1
- diffusers/loaders/autoencoder.py +0 -146
- diffusers/loaders/controlnet.py +0 -136
- diffusers/loaders/lora.py +0 -1349
- diffusers/models/prior_transformer.py +0 -12
- diffusers/models/t5_film_transformer.py +0 -70
- diffusers/models/transformer_2d.py +0 -25
- diffusers/models/transformer_temporal.py +0 -34
- diffusers/models/unet_1d.py +0 -26
- diffusers/models/unet_1d_blocks.py +0 -203
- diffusers/models/unet_2d.py +0 -27
- diffusers/models/unet_2d_blocks.py +0 -375
- diffusers/models/unet_2d_condition.py +0 -25
- diffusers-0.27.1.dist-info/RECORD +0 -399
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/LICENSE +0 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/entry_points.txt +0 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/top_level.txt +0 -0
@@ -14,39 +14,63 @@
|
|
14
14
|
# See the License for the specific language governing permissions and
|
15
15
|
# limitations under the License.
|
16
16
|
|
17
|
+
import copy
|
17
18
|
import inspect
|
18
19
|
import itertools
|
20
|
+
import json
|
19
21
|
import os
|
20
22
|
import re
|
21
23
|
from collections import OrderedDict
|
22
|
-
from functools import partial
|
24
|
+
from functools import partial, wraps
|
25
|
+
from pathlib import Path
|
23
26
|
from typing import Any, Callable, List, Optional, Tuple, Union
|
24
27
|
|
25
28
|
import safetensors
|
26
29
|
import torch
|
27
|
-
from huggingface_hub import create_repo
|
30
|
+
from huggingface_hub import create_repo, split_torch_state_dict_into_shards
|
28
31
|
from huggingface_hub.utils import validate_hf_hub_args
|
29
32
|
from torch import Tensor, nn
|
30
33
|
|
31
34
|
from .. import __version__
|
35
|
+
from ..quantizers import DiffusersAutoQuantizer, DiffusersQuantizer
|
36
|
+
from ..quantizers.quantization_config import QuantizationMethod
|
32
37
|
from ..utils import (
|
33
38
|
CONFIG_NAME,
|
34
39
|
FLAX_WEIGHTS_NAME,
|
35
|
-
|
40
|
+
SAFE_WEIGHTS_INDEX_NAME,
|
36
41
|
SAFETENSORS_WEIGHTS_NAME,
|
42
|
+
WEIGHTS_INDEX_NAME,
|
37
43
|
WEIGHTS_NAME,
|
38
44
|
_add_variant,
|
45
|
+
_get_checkpoint_shard_files,
|
39
46
|
_get_model_file,
|
40
47
|
deprecate,
|
41
48
|
is_accelerate_available,
|
49
|
+
is_bitsandbytes_available,
|
50
|
+
is_bitsandbytes_version,
|
42
51
|
is_torch_version,
|
43
52
|
logging,
|
44
53
|
)
|
45
|
-
from ..utils.hub_utils import
|
54
|
+
from ..utils.hub_utils import (
|
55
|
+
PushToHubMixin,
|
56
|
+
load_or_create_model_card,
|
57
|
+
populate_model_card,
|
58
|
+
)
|
59
|
+
from .model_loading_utils import (
|
60
|
+
_determine_device_map,
|
61
|
+
_fetch_index_file,
|
62
|
+
_fetch_index_file_legacy,
|
63
|
+
_load_state_dict_into_model,
|
64
|
+
_merge_sharded_checkpoints,
|
65
|
+
load_model_dict_into_meta,
|
66
|
+
load_state_dict,
|
67
|
+
)
|
46
68
|
|
47
69
|
|
48
70
|
logger = logging.get_logger(__name__)
|
49
71
|
|
72
|
+
_REGEX_SHARD = re.compile(r"(.*?)-\d{5}-of-\d{5}")
|
73
|
+
|
50
74
|
|
51
75
|
if is_torch_version(">=", "1.9.0"):
|
52
76
|
_LOW_CPU_MEM_USAGE_DEFAULT = True
|
@@ -56,8 +80,6 @@ else:
|
|
56
80
|
|
57
81
|
if is_accelerate_available():
|
58
82
|
import accelerate
|
59
|
-
from accelerate.utils import set_module_tensor_to_device
|
60
|
-
from accelerate.utils.versions import is_torch_version
|
61
83
|
|
62
84
|
|
63
85
|
def get_parameter_device(parameter: torch.nn.Module) -> torch.device:
|
@@ -77,108 +99,39 @@ def get_parameter_device(parameter: torch.nn.Module) -> torch.device:
|
|
77
99
|
|
78
100
|
|
79
101
|
def get_parameter_dtype(parameter: torch.nn.Module) -> torch.dtype:
|
80
|
-
try:
|
81
|
-
params = tuple(parameter.parameters())
|
82
|
-
if len(params) > 0:
|
83
|
-
return params[0].dtype
|
84
|
-
|
85
|
-
buffers = tuple(parameter.buffers())
|
86
|
-
if len(buffers) > 0:
|
87
|
-
return buffers[0].dtype
|
88
|
-
|
89
|
-
except StopIteration:
|
90
|
-
# For torch.nn.DataParallel compatibility in PyTorch 1.5
|
91
|
-
|
92
|
-
def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
|
93
|
-
tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
|
94
|
-
return tuples
|
95
|
-
|
96
|
-
gen = parameter._named_members(get_members_fn=find_tensor_attributes)
|
97
|
-
first_tuple = next(gen)
|
98
|
-
return first_tuple[1].dtype
|
99
|
-
|
100
|
-
|
101
|
-
def load_state_dict(checkpoint_file: Union[str, os.PathLike], variant: Optional[str] = None):
|
102
102
|
"""
|
103
|
-
|
103
|
+
Returns the first found floating dtype in parameters if there is one, otherwise returns the last dtype it found.
|
104
104
|
"""
|
105
|
-
|
106
|
-
|
107
|
-
|
108
|
-
|
109
|
-
|
110
|
-
|
111
|
-
|
112
|
-
|
113
|
-
|
114
|
-
|
115
|
-
|
116
|
-
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
|
133
|
-
|
134
|
-
|
135
|
-
dtype: Optional[Union[str, torch.dtype]] = None,
|
136
|
-
model_name_or_path: Optional[str] = None,
|
137
|
-
) -> List[str]:
|
138
|
-
device = device or torch.device("cpu")
|
139
|
-
dtype = dtype or torch.float32
|
140
|
-
|
141
|
-
accepts_dtype = "dtype" in set(inspect.signature(set_module_tensor_to_device).parameters.keys())
|
142
|
-
|
143
|
-
unexpected_keys = []
|
144
|
-
empty_state_dict = model.state_dict()
|
145
|
-
for param_name, param in state_dict.items():
|
146
|
-
if param_name not in empty_state_dict:
|
147
|
-
unexpected_keys.append(param_name)
|
148
|
-
continue
|
149
|
-
|
150
|
-
if empty_state_dict[param_name].shape != param.shape:
|
151
|
-
model_name_or_path_str = f"{model_name_or_path} " if model_name_or_path is not None else ""
|
152
|
-
raise ValueError(
|
153
|
-
f"Cannot load {model_name_or_path_str}because {param_name} expected shape {empty_state_dict[param_name]}, but got {param.shape}. If you want to instead overwrite randomly initialized weights, please make sure to pass both `low_cpu_mem_usage=False` and `ignore_mismatched_sizes=True`. For more information, see also: https://github.com/huggingface/diffusers/issues/1619#issuecomment-1345604389 as an example."
|
154
|
-
)
|
155
|
-
|
156
|
-
if accepts_dtype:
|
157
|
-
set_module_tensor_to_device(model, param_name, device, value=param, dtype=dtype)
|
158
|
-
else:
|
159
|
-
set_module_tensor_to_device(model, param_name, device, value=param)
|
160
|
-
return unexpected_keys
|
161
|
-
|
162
|
-
|
163
|
-
def _load_state_dict_into_model(model_to_load, state_dict: OrderedDict) -> List[str]:
|
164
|
-
# Convert old format to new format if needed from a PyTorch state_dict
|
165
|
-
# copy state_dict so _load_from_state_dict can modify it
|
166
|
-
state_dict = state_dict.copy()
|
167
|
-
error_msgs = []
|
168
|
-
|
169
|
-
# PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
|
170
|
-
# so we need to apply the function recursively.
|
171
|
-
def load(module: torch.nn.Module, prefix: str = ""):
|
172
|
-
args = (state_dict, prefix, {}, True, [], [], error_msgs)
|
173
|
-
module._load_from_state_dict(*args)
|
174
|
-
|
175
|
-
for name, child in module._modules.items():
|
176
|
-
if child is not None:
|
177
|
-
load(child, prefix + name + ".")
|
178
|
-
|
179
|
-
load(model_to_load)
|
180
|
-
|
181
|
-
return error_msgs
|
105
|
+
last_dtype = None
|
106
|
+
for param in parameter.parameters():
|
107
|
+
last_dtype = param.dtype
|
108
|
+
if param.is_floating_point():
|
109
|
+
return param.dtype
|
110
|
+
|
111
|
+
for buffer in parameter.buffers():
|
112
|
+
last_dtype = buffer.dtype
|
113
|
+
if buffer.is_floating_point():
|
114
|
+
return buffer.dtype
|
115
|
+
|
116
|
+
if last_dtype is not None:
|
117
|
+
# if no floating dtype was found return whatever the first dtype is
|
118
|
+
return last_dtype
|
119
|
+
|
120
|
+
# For nn.DataParallel compatibility in PyTorch > 1.5
|
121
|
+
def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]:
|
122
|
+
tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
|
123
|
+
return tuples
|
124
|
+
|
125
|
+
gen = parameter._named_members(get_members_fn=find_tensor_attributes)
|
126
|
+
last_tuple = None
|
127
|
+
for tuple in gen:
|
128
|
+
last_tuple = tuple
|
129
|
+
if tuple[1].is_floating_point():
|
130
|
+
return tuple[1].dtype
|
131
|
+
|
132
|
+
if last_tuple is not None:
|
133
|
+
# fallback to the last dtype
|
134
|
+
return last_tuple[1].dtype
|
182
135
|
|
183
136
|
|
184
137
|
class ModelMixin(torch.nn.Module, PushToHubMixin):
|
@@ -195,6 +148,8 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
195
148
|
_automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
|
196
149
|
_supports_gradient_checkpointing = False
|
197
150
|
_keys_to_ignore_on_load_unexpected = None
|
151
|
+
_no_split_modules = None
|
152
|
+
_keep_in_fp32_modules = None
|
198
153
|
|
199
154
|
def __init__(self):
|
200
155
|
super().__init__()
|
@@ -241,6 +196,65 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
241
196
|
if self._supports_gradient_checkpointing:
|
242
197
|
self.apply(partial(self._set_gradient_checkpointing, value=False))
|
243
198
|
|
199
|
+
def set_use_npu_flash_attention(self, valid: bool) -> None:
|
200
|
+
r"""
|
201
|
+
Set the switch for the npu flash attention.
|
202
|
+
"""
|
203
|
+
|
204
|
+
def fn_recursive_set_npu_flash_attention(module: torch.nn.Module):
|
205
|
+
if hasattr(module, "set_use_npu_flash_attention"):
|
206
|
+
module.set_use_npu_flash_attention(valid)
|
207
|
+
|
208
|
+
for child in module.children():
|
209
|
+
fn_recursive_set_npu_flash_attention(child)
|
210
|
+
|
211
|
+
for module in self.children():
|
212
|
+
if isinstance(module, torch.nn.Module):
|
213
|
+
fn_recursive_set_npu_flash_attention(module)
|
214
|
+
|
215
|
+
def enable_npu_flash_attention(self) -> None:
|
216
|
+
r"""
|
217
|
+
Enable npu flash attention from torch_npu
|
218
|
+
|
219
|
+
"""
|
220
|
+
self.set_use_npu_flash_attention(True)
|
221
|
+
|
222
|
+
def disable_npu_flash_attention(self) -> None:
|
223
|
+
r"""
|
224
|
+
disable npu flash attention from torch_npu
|
225
|
+
|
226
|
+
"""
|
227
|
+
self.set_use_npu_flash_attention(False)
|
228
|
+
|
229
|
+
def set_use_xla_flash_attention(
|
230
|
+
self, use_xla_flash_attention: bool, partition_spec: Optional[Callable] = None
|
231
|
+
) -> None:
|
232
|
+
# Recursively walk through all the children.
|
233
|
+
# Any children which exposes the set_use_xla_flash_attention method
|
234
|
+
# gets the message
|
235
|
+
def fn_recursive_set_flash_attention(module: torch.nn.Module):
|
236
|
+
if hasattr(module, "set_use_xla_flash_attention"):
|
237
|
+
module.set_use_xla_flash_attention(use_xla_flash_attention, partition_spec)
|
238
|
+
|
239
|
+
for child in module.children():
|
240
|
+
fn_recursive_set_flash_attention(child)
|
241
|
+
|
242
|
+
for module in self.children():
|
243
|
+
if isinstance(module, torch.nn.Module):
|
244
|
+
fn_recursive_set_flash_attention(module)
|
245
|
+
|
246
|
+
def enable_xla_flash_attention(self, partition_spec: Optional[Callable] = None):
|
247
|
+
r"""
|
248
|
+
Enable the flash attention pallals kernel for torch_xla.
|
249
|
+
"""
|
250
|
+
self.set_use_xla_flash_attention(True, partition_spec)
|
251
|
+
|
252
|
+
def disable_xla_flash_attention(self):
|
253
|
+
r"""
|
254
|
+
Disable the flash attention pallals kernel for torch_xla.
|
255
|
+
"""
|
256
|
+
self.set_use_xla_flash_attention(False)
|
257
|
+
|
244
258
|
def set_use_memory_efficient_attention_xformers(
|
245
259
|
self, valid: bool, attention_op: Optional[Callable] = None
|
246
260
|
) -> None:
|
@@ -307,6 +321,7 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
307
321
|
save_function: Optional[Callable] = None,
|
308
322
|
safe_serialization: bool = True,
|
309
323
|
variant: Optional[str] = None,
|
324
|
+
max_shard_size: Union[int, str] = "10GB",
|
310
325
|
push_to_hub: bool = False,
|
311
326
|
**kwargs,
|
312
327
|
):
|
@@ -329,6 +344,13 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
329
344
|
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
330
345
|
variant (`str`, *optional*):
|
331
346
|
If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
|
347
|
+
max_shard_size (`int` or `str`, defaults to `"10GB"`):
|
348
|
+
The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
|
349
|
+
lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5GB"`).
|
350
|
+
If expressed as an integer, the unit is bytes. Note that this limit will be decreased after a certain
|
351
|
+
period of time (starting from Oct 2024) to allow users to upgrade to the latest version of `diffusers`.
|
352
|
+
This is to establish a common default size for this argument across different libraries in the Hugging
|
353
|
+
Face ecosystem (`transformers`, and `accelerate`, for example).
|
332
354
|
push_to_hub (`bool`, *optional*, defaults to `False`):
|
333
355
|
Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
|
334
356
|
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
@@ -340,11 +362,30 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
340
362
|
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
341
363
|
return
|
342
364
|
|
365
|
+
hf_quantizer = getattr(self, "hf_quantizer", None)
|
366
|
+
if hf_quantizer is not None:
|
367
|
+
quantization_serializable = (
|
368
|
+
hf_quantizer is not None
|
369
|
+
and isinstance(hf_quantizer, DiffusersQuantizer)
|
370
|
+
and hf_quantizer.is_serializable
|
371
|
+
)
|
372
|
+
if not quantization_serializable:
|
373
|
+
raise ValueError(
|
374
|
+
f"The model is quantized with {hf_quantizer.quantization_config.quant_method} and is not serializable - check out the warnings from"
|
375
|
+
" the logger on the traceback to understand the reason why the quantized model is not serializable."
|
376
|
+
)
|
377
|
+
|
378
|
+
weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
|
379
|
+
weights_name = _add_variant(weights_name, variant)
|
380
|
+
weights_name_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(
|
381
|
+
".safetensors", "{suffix}.safetensors"
|
382
|
+
)
|
383
|
+
|
343
384
|
os.makedirs(save_directory, exist_ok=True)
|
344
385
|
|
345
386
|
if push_to_hub:
|
346
387
|
commit_message = kwargs.pop("commit_message", None)
|
347
|
-
private = kwargs.pop("private",
|
388
|
+
private = kwargs.pop("private", None)
|
348
389
|
create_pr = kwargs.pop("create_pr", False)
|
349
390
|
token = kwargs.pop("token", None)
|
350
391
|
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
@@ -361,24 +402,64 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
361
402
|
# Save the model
|
362
403
|
state_dict = model_to_save.state_dict()
|
363
404
|
|
364
|
-
weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
|
365
|
-
weights_name = _add_variant(weights_name, variant)
|
366
|
-
|
367
405
|
# Save the model
|
368
|
-
|
369
|
-
|
370
|
-
|
406
|
+
state_dict_split = split_torch_state_dict_into_shards(
|
407
|
+
state_dict, max_shard_size=max_shard_size, filename_pattern=weights_name_pattern
|
408
|
+
)
|
409
|
+
|
410
|
+
# Clean the folder from a previous save
|
411
|
+
if is_main_process:
|
412
|
+
for filename in os.listdir(save_directory):
|
413
|
+
if filename in state_dict_split.filename_to_tensors.keys():
|
414
|
+
continue
|
415
|
+
full_filename = os.path.join(save_directory, filename)
|
416
|
+
if not os.path.isfile(full_filename):
|
417
|
+
continue
|
418
|
+
weights_without_ext = weights_name_pattern.replace(".bin", "").replace(".safetensors", "")
|
419
|
+
weights_without_ext = weights_without_ext.replace("{suffix}", "")
|
420
|
+
filename_without_ext = filename.replace(".bin", "").replace(".safetensors", "")
|
421
|
+
# make sure that file to be deleted matches format of sharded file, e.g. pytorch_model-00001-of-00005
|
422
|
+
if (
|
423
|
+
filename.startswith(weights_without_ext)
|
424
|
+
and _REGEX_SHARD.fullmatch(filename_without_ext) is not None
|
425
|
+
):
|
426
|
+
os.remove(full_filename)
|
427
|
+
|
428
|
+
for filename, tensors in state_dict_split.filename_to_tensors.items():
|
429
|
+
shard = {tensor: state_dict[tensor] for tensor in tensors}
|
430
|
+
filepath = os.path.join(save_directory, filename)
|
431
|
+
if safe_serialization:
|
432
|
+
# At some point we will need to deal better with save_function (used for TPU and other distributed
|
433
|
+
# joyfulness), but for now this enough.
|
434
|
+
safetensors.torch.save_file(shard, filepath, metadata={"format": "pt"})
|
435
|
+
else:
|
436
|
+
torch.save(shard, filepath)
|
437
|
+
|
438
|
+
if state_dict_split.is_sharded:
|
439
|
+
index = {
|
440
|
+
"metadata": state_dict_split.metadata,
|
441
|
+
"weight_map": state_dict_split.tensor_to_filename,
|
442
|
+
}
|
443
|
+
save_index_file = SAFE_WEIGHTS_INDEX_NAME if safe_serialization else WEIGHTS_INDEX_NAME
|
444
|
+
save_index_file = os.path.join(save_directory, _add_variant(save_index_file, variant))
|
445
|
+
# Save the index as well
|
446
|
+
with open(save_index_file, "w", encoding="utf-8") as f:
|
447
|
+
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
448
|
+
f.write(content)
|
449
|
+
logger.info(
|
450
|
+
f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be "
|
451
|
+
f"split in {len(state_dict_split.filename_to_tensors)} checkpoint shards. You can find where each parameters has been saved in the "
|
452
|
+
f"index located at {save_index_file}."
|
371
453
|
)
|
372
454
|
else:
|
373
|
-
|
374
|
-
|
375
|
-
logger.info(f"Model weights saved in {os.path.join(save_directory, weights_name)}")
|
455
|
+
path_to_weights = os.path.join(save_directory, weights_name)
|
456
|
+
logger.info(f"Model weights saved in {path_to_weights}")
|
376
457
|
|
377
458
|
if push_to_hub:
|
378
459
|
# Create a new empty model card and eventually tag it
|
379
460
|
model_card = load_or_create_model_card(repo_id, token=token)
|
380
461
|
model_card = populate_model_card(model_card)
|
381
|
-
model_card.save(
|
462
|
+
model_card.save(Path(save_directory, "README.md").as_posix())
|
382
463
|
|
383
464
|
self._upload_folder(
|
384
465
|
save_directory,
|
@@ -388,6 +469,18 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
388
469
|
create_pr=create_pr,
|
389
470
|
)
|
390
471
|
|
472
|
+
def dequantize(self):
|
473
|
+
"""
|
474
|
+
Potentially dequantize the model in case it has been quantized by a quantization method that support
|
475
|
+
dequantization.
|
476
|
+
"""
|
477
|
+
hf_quantizer = getattr(self, "hf_quantizer", None)
|
478
|
+
|
479
|
+
if hf_quantizer is None:
|
480
|
+
raise ValueError("You need to first quantize your model in order to dequantize it")
|
481
|
+
|
482
|
+
return hf_quantizer.dequantize(self)
|
483
|
+
|
391
484
|
@classmethod
|
392
485
|
@validate_hf_hub_args
|
393
486
|
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
|
@@ -415,9 +508,6 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
415
508
|
force_download (`bool`, *optional*, defaults to `False`):
|
416
509
|
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
417
510
|
cached versions if they exist.
|
418
|
-
resume_download (`bool`, *optional*, defaults to `False`):
|
419
|
-
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
420
|
-
incompletely downloaded files are deleted.
|
421
511
|
proxies (`Dict[str, str]`, *optional*):
|
422
512
|
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
423
513
|
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
@@ -443,7 +533,7 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
443
533
|
device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
|
444
534
|
A map that specifies where each submodule should go. It doesn't need to be defined for each
|
445
535
|
parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
|
446
|
-
same device.
|
536
|
+
same device. Defaults to `None`, meaning that the model will be loaded on CPU.
|
447
537
|
|
448
538
|
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
|
449
539
|
more information about each option see [designing a device
|
@@ -499,7 +589,6 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
499
589
|
ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False)
|
500
590
|
force_download = kwargs.pop("force_download", False)
|
501
591
|
from_flax = kwargs.pop("from_flax", False)
|
502
|
-
resume_download = kwargs.pop("resume_download", False)
|
503
592
|
proxies = kwargs.pop("proxies", None)
|
504
593
|
output_loading_info = kwargs.pop("output_loading_info", False)
|
505
594
|
local_files_only = kwargs.pop("local_files_only", None)
|
@@ -514,6 +603,7 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
514
603
|
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
515
604
|
variant = kwargs.pop("variant", None)
|
516
605
|
use_safetensors = kwargs.pop("use_safetensors", None)
|
606
|
+
quantization_config = kwargs.pop("quantization_config", None)
|
517
607
|
|
518
608
|
allow_pickle = False
|
519
609
|
if use_safetensors is None:
|
@@ -554,6 +644,36 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
554
644
|
" dispatching. Please make sure to set `low_cpu_mem_usage=True`."
|
555
645
|
)
|
556
646
|
|
647
|
+
# change device_map into a map if we passed an int, a str or a torch.device
|
648
|
+
if isinstance(device_map, torch.device):
|
649
|
+
device_map = {"": device_map}
|
650
|
+
elif isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
|
651
|
+
try:
|
652
|
+
device_map = {"": torch.device(device_map)}
|
653
|
+
except RuntimeError:
|
654
|
+
raise ValueError(
|
655
|
+
"When passing device_map as a string, the value needs to be a device name (e.g. cpu, cuda:0) or "
|
656
|
+
f"'auto', 'balanced', 'balanced_low_0', 'sequential' but found {device_map}."
|
657
|
+
)
|
658
|
+
elif isinstance(device_map, int):
|
659
|
+
if device_map < 0:
|
660
|
+
raise ValueError(
|
661
|
+
"You can't pass device_map as a negative int. If you want to put the model on the cpu, pass device_map = 'cpu' "
|
662
|
+
)
|
663
|
+
else:
|
664
|
+
device_map = {"": device_map}
|
665
|
+
|
666
|
+
if device_map is not None:
|
667
|
+
if low_cpu_mem_usage is None:
|
668
|
+
low_cpu_mem_usage = True
|
669
|
+
elif not low_cpu_mem_usage:
|
670
|
+
raise ValueError("Passing along a `device_map` requires `low_cpu_mem_usage=True`")
|
671
|
+
|
672
|
+
if low_cpu_mem_usage:
|
673
|
+
if device_map is not None and not is_torch_version(">=", "1.10"):
|
674
|
+
# The max memory utils require PyTorch >= 1.10 to have torch.cuda.mem_get_info.
|
675
|
+
raise ValueError("`low_cpu_mem_usage` and `device_map` require PyTorch >= 1.10.")
|
676
|
+
|
557
677
|
# Load config if we don't provide a configuration
|
558
678
|
config_path = pretrained_model_name_or_path
|
559
679
|
|
@@ -570,19 +690,99 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
570
690
|
return_unused_kwargs=True,
|
571
691
|
return_commit_hash=True,
|
572
692
|
force_download=force_download,
|
573
|
-
resume_download=resume_download,
|
574
693
|
proxies=proxies,
|
575
694
|
local_files_only=local_files_only,
|
576
695
|
token=token,
|
577
696
|
revision=revision,
|
578
697
|
subfolder=subfolder,
|
579
|
-
device_map=device_map,
|
580
|
-
max_memory=max_memory,
|
581
|
-
offload_folder=offload_folder,
|
582
|
-
offload_state_dict=offload_state_dict,
|
583
698
|
user_agent=user_agent,
|
584
699
|
**kwargs,
|
585
700
|
)
|
701
|
+
# no in-place modification of the original config.
|
702
|
+
config = copy.deepcopy(config)
|
703
|
+
|
704
|
+
# determine initial quantization config.
|
705
|
+
#######################################
|
706
|
+
pre_quantized = "quantization_config" in config and config["quantization_config"] is not None
|
707
|
+
if pre_quantized or quantization_config is not None:
|
708
|
+
if pre_quantized:
|
709
|
+
config["quantization_config"] = DiffusersAutoQuantizer.merge_quantization_configs(
|
710
|
+
config["quantization_config"], quantization_config
|
711
|
+
)
|
712
|
+
else:
|
713
|
+
config["quantization_config"] = quantization_config
|
714
|
+
hf_quantizer = DiffusersAutoQuantizer.from_config(
|
715
|
+
config["quantization_config"], pre_quantized=pre_quantized
|
716
|
+
)
|
717
|
+
else:
|
718
|
+
hf_quantizer = None
|
719
|
+
|
720
|
+
if hf_quantizer is not None:
|
721
|
+
if device_map is not None:
|
722
|
+
raise NotImplementedError(
|
723
|
+
"Currently, providing `device_map` is not supported for quantized models. Providing `device_map` as an input will be added in the future."
|
724
|
+
)
|
725
|
+
|
726
|
+
hf_quantizer.validate_environment(torch_dtype=torch_dtype, from_flax=from_flax, device_map=device_map)
|
727
|
+
torch_dtype = hf_quantizer.update_torch_dtype(torch_dtype)
|
728
|
+
|
729
|
+
# In order to ensure popular quantization methods are supported. Can be disable with `disable_telemetry`
|
730
|
+
user_agent["quant"] = hf_quantizer.quantization_config.quant_method.value
|
731
|
+
|
732
|
+
# Force-set to `True` for more mem efficiency
|
733
|
+
if low_cpu_mem_usage is None:
|
734
|
+
low_cpu_mem_usage = True
|
735
|
+
logger.info("Set `low_cpu_mem_usage` to True as `hf_quantizer` is not None.")
|
736
|
+
elif not low_cpu_mem_usage:
|
737
|
+
raise ValueError("`low_cpu_mem_usage` cannot be False or None when using quantization.")
|
738
|
+
|
739
|
+
# Check if `_keep_in_fp32_modules` is not None
|
740
|
+
use_keep_in_fp32_modules = (cls._keep_in_fp32_modules is not None) and (
|
741
|
+
(torch_dtype == torch.float16) or hasattr(hf_quantizer, "use_keep_in_fp32_modules")
|
742
|
+
)
|
743
|
+
if use_keep_in_fp32_modules:
|
744
|
+
keep_in_fp32_modules = cls._keep_in_fp32_modules
|
745
|
+
if not isinstance(keep_in_fp32_modules, list):
|
746
|
+
keep_in_fp32_modules = [keep_in_fp32_modules]
|
747
|
+
|
748
|
+
if low_cpu_mem_usage is None:
|
749
|
+
low_cpu_mem_usage = True
|
750
|
+
logger.info("Set `low_cpu_mem_usage` to True as `_keep_in_fp32_modules` is not None.")
|
751
|
+
elif not low_cpu_mem_usage:
|
752
|
+
raise ValueError("`low_cpu_mem_usage` cannot be False when `keep_in_fp32_modules` is True.")
|
753
|
+
else:
|
754
|
+
keep_in_fp32_modules = []
|
755
|
+
#######################################
|
756
|
+
|
757
|
+
# Determine if we're loading from a directory of sharded checkpoints.
|
758
|
+
is_sharded = False
|
759
|
+
index_file = None
|
760
|
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
761
|
+
index_file_kwargs = {
|
762
|
+
"is_local": is_local,
|
763
|
+
"pretrained_model_name_or_path": pretrained_model_name_or_path,
|
764
|
+
"subfolder": subfolder or "",
|
765
|
+
"use_safetensors": use_safetensors,
|
766
|
+
"cache_dir": cache_dir,
|
767
|
+
"variant": variant,
|
768
|
+
"force_download": force_download,
|
769
|
+
"proxies": proxies,
|
770
|
+
"local_files_only": local_files_only,
|
771
|
+
"token": token,
|
772
|
+
"revision": revision,
|
773
|
+
"user_agent": user_agent,
|
774
|
+
"commit_hash": commit_hash,
|
775
|
+
}
|
776
|
+
index_file = _fetch_index_file(**index_file_kwargs)
|
777
|
+
# In case the index file was not found we still have to consider the legacy format.
|
778
|
+
# this becomes applicable when the variant is not None.
|
779
|
+
if variant is not None and (index_file is None or not os.path.exists(index_file)):
|
780
|
+
index_file = _fetch_index_file_legacy(**index_file_kwargs)
|
781
|
+
if index_file is not None and index_file.is_file():
|
782
|
+
is_sharded = True
|
783
|
+
|
784
|
+
if is_sharded and from_flax:
|
785
|
+
raise ValueError("Loading of sharded checkpoints is not supported when `from_flax=True`.")
|
586
786
|
|
587
787
|
# load model
|
588
788
|
model_file = None
|
@@ -592,7 +792,6 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
592
792
|
weights_name=FLAX_WEIGHTS_NAME,
|
593
793
|
cache_dir=cache_dir,
|
594
794
|
force_download=force_download,
|
595
|
-
resume_download=resume_download,
|
596
795
|
proxies=proxies,
|
597
796
|
local_files_only=local_files_only,
|
598
797
|
token=token,
|
@@ -608,14 +807,31 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
608
807
|
|
609
808
|
model = load_flax_checkpoint_in_pytorch_model(model, model_file)
|
610
809
|
else:
|
611
|
-
if
|
810
|
+
if is_sharded:
|
811
|
+
sharded_ckpt_cached_folder, sharded_metadata = _get_checkpoint_shard_files(
|
812
|
+
pretrained_model_name_or_path,
|
813
|
+
index_file,
|
814
|
+
cache_dir=cache_dir,
|
815
|
+
proxies=proxies,
|
816
|
+
local_files_only=local_files_only,
|
817
|
+
token=token,
|
818
|
+
user_agent=user_agent,
|
819
|
+
revision=revision,
|
820
|
+
subfolder=subfolder or "",
|
821
|
+
)
|
822
|
+
# TODO: https://github.com/huggingface/diffusers/issues/10013
|
823
|
+
if hf_quantizer is not None:
|
824
|
+
model_file = _merge_sharded_checkpoints(sharded_ckpt_cached_folder, sharded_metadata)
|
825
|
+
logger.info("Merged sharded checkpoints as `hf_quantizer` is not None.")
|
826
|
+
is_sharded = False
|
827
|
+
|
828
|
+
elif use_safetensors and not is_sharded:
|
612
829
|
try:
|
613
830
|
model_file = _get_model_file(
|
614
831
|
pretrained_model_name_or_path,
|
615
832
|
weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant),
|
616
833
|
cache_dir=cache_dir,
|
617
834
|
force_download=force_download,
|
618
|
-
resume_download=resume_download,
|
619
835
|
proxies=proxies,
|
620
836
|
local_files_only=local_files_only,
|
621
837
|
token=token,
|
@@ -624,17 +840,21 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
624
840
|
user_agent=user_agent,
|
625
841
|
commit_hash=commit_hash,
|
626
842
|
)
|
843
|
+
|
627
844
|
except IOError as e:
|
845
|
+
logger.error(f"An error occurred while trying to fetch {pretrained_model_name_or_path}: {e}")
|
628
846
|
if not allow_pickle:
|
629
|
-
raise
|
630
|
-
|
631
|
-
|
847
|
+
raise
|
848
|
+
logger.warning(
|
849
|
+
"Defaulting to unsafe serialization. Pass `allow_pickle=False` to raise an error instead."
|
850
|
+
)
|
851
|
+
|
852
|
+
if model_file is None and not is_sharded:
|
632
853
|
model_file = _get_model_file(
|
633
854
|
pretrained_model_name_or_path,
|
634
855
|
weights_name=_add_variant(WEIGHTS_NAME, variant),
|
635
856
|
cache_dir=cache_dir,
|
636
857
|
force_download=force_download,
|
637
|
-
resume_download=resume_download,
|
638
858
|
proxies=proxies,
|
639
859
|
local_files_only=local_files_only,
|
640
860
|
token=token,
|
@@ -649,13 +869,27 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
649
869
|
with accelerate.init_empty_weights():
|
650
870
|
model = cls.from_config(config, **unused_kwargs)
|
651
871
|
|
872
|
+
if hf_quantizer is not None:
|
873
|
+
hf_quantizer.preprocess_model(
|
874
|
+
model=model, device_map=device_map, keep_in_fp32_modules=keep_in_fp32_modules
|
875
|
+
)
|
876
|
+
|
652
877
|
# if device_map is None, load the state dict and move the params from meta device to the cpu
|
653
|
-
if device_map is None:
|
654
|
-
|
878
|
+
if device_map is None and not is_sharded:
|
879
|
+
# `torch.cuda.current_device()` is fine here when `hf_quantizer` is not None.
|
880
|
+
# It would error out during the `validate_environment()` call above in the absence of cuda.
|
881
|
+
if hf_quantizer is None:
|
882
|
+
param_device = "cpu"
|
883
|
+
# TODO (sayakpaul, SunMarc): remove this after model loading refactor
|
884
|
+
else:
|
885
|
+
param_device = torch.device(torch.cuda.current_device())
|
655
886
|
state_dict = load_state_dict(model_file, variant=variant)
|
656
887
|
model._convert_deprecated_attention_blocks(state_dict)
|
888
|
+
|
657
889
|
# move the params from meta device to cpu
|
658
890
|
missing_keys = set(model.state_dict().keys()) - set(state_dict.keys())
|
891
|
+
if hf_quantizer is not None:
|
892
|
+
missing_keys = hf_quantizer.update_missing_keys(model, missing_keys, prefix="")
|
659
893
|
if len(missing_keys) > 0:
|
660
894
|
raise ValueError(
|
661
895
|
f"Cannot load {cls} from {pretrained_model_name_or_path} because the following keys are"
|
@@ -670,6 +904,8 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
670
904
|
device=param_device,
|
671
905
|
dtype=torch_dtype,
|
672
906
|
model_name_or_path=pretrained_model_name_or_path,
|
907
|
+
hf_quantizer=hf_quantizer,
|
908
|
+
keep_in_fp32_modules=keep_in_fp32_modules,
|
673
909
|
)
|
674
910
|
|
675
911
|
if cls._keys_to_ignore_on_load_unexpected is not None:
|
@@ -684,15 +920,25 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
684
920
|
else: # else let accelerate handle loading and dispatching.
|
685
921
|
# Load weights and dispatch according to the device_map
|
686
922
|
# by default the device_map is None and the weights are loaded on the CPU
|
923
|
+
force_hook = True
|
924
|
+
device_map = _determine_device_map(
|
925
|
+
model, device_map, max_memory, torch_dtype, keep_in_fp32_modules, hf_quantizer
|
926
|
+
)
|
927
|
+
if device_map is None and is_sharded:
|
928
|
+
# we load the parameters on the cpu
|
929
|
+
device_map = {"": "cpu"}
|
930
|
+
force_hook = False
|
687
931
|
try:
|
688
932
|
accelerate.load_checkpoint_and_dispatch(
|
689
933
|
model,
|
690
|
-
model_file,
|
934
|
+
model_file if not is_sharded else index_file,
|
691
935
|
device_map,
|
692
936
|
max_memory=max_memory,
|
693
937
|
offload_folder=offload_folder,
|
694
938
|
offload_state_dict=offload_state_dict,
|
695
939
|
dtype=torch_dtype,
|
940
|
+
force_hooks=force_hook,
|
941
|
+
strict=True,
|
696
942
|
)
|
697
943
|
except AttributeError as e:
|
698
944
|
# When using accelerate loading, we do not have the ability to load the state
|
@@ -715,12 +961,14 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
715
961
|
model._temp_convert_self_to_deprecated_attention_blocks()
|
716
962
|
accelerate.load_checkpoint_and_dispatch(
|
717
963
|
model,
|
718
|
-
model_file,
|
964
|
+
model_file if not is_sharded else index_file,
|
719
965
|
device_map,
|
720
966
|
max_memory=max_memory,
|
721
967
|
offload_folder=offload_folder,
|
722
968
|
offload_state_dict=offload_state_dict,
|
723
969
|
dtype=torch_dtype,
|
970
|
+
force_hooks=force_hook,
|
971
|
+
strict=True,
|
724
972
|
)
|
725
973
|
model._undo_temp_convert_self_to_deprecated_attention_blocks()
|
726
974
|
else:
|
@@ -753,14 +1001,25 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
753
1001
|
"error_msgs": error_msgs,
|
754
1002
|
}
|
755
1003
|
|
1004
|
+
if hf_quantizer is not None:
|
1005
|
+
hf_quantizer.postprocess_model(model)
|
1006
|
+
model.hf_quantizer = hf_quantizer
|
1007
|
+
|
756
1008
|
if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype):
|
757
1009
|
raise ValueError(
|
758
1010
|
f"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}."
|
759
1011
|
)
|
760
|
-
|
1012
|
+
# When using `use_keep_in_fp32_modules` if we do a global `to()` here, then we will
|
1013
|
+
# completely lose the effectivity of `use_keep_in_fp32_modules`.
|
1014
|
+
elif torch_dtype is not None and hf_quantizer is None and not use_keep_in_fp32_modules:
|
761
1015
|
model = model.to(torch_dtype)
|
762
1016
|
|
763
|
-
|
1017
|
+
if hf_quantizer is not None:
|
1018
|
+
# We also make sure to purge `_pre_quantization_dtype` when we serialize
|
1019
|
+
# the model config because `_pre_quantization_dtype` is `torch.dtype`, not JSON serializable.
|
1020
|
+
model.register_to_config(_name_or_path=pretrained_model_name_or_path, _pre_quantization_dtype=torch_dtype)
|
1021
|
+
else:
|
1022
|
+
model.register_to_config(_name_or_path=pretrained_model_name_or_path)
|
764
1023
|
|
765
1024
|
# Set model in evaluation mode to deactivate DropOut modules by default
|
766
1025
|
model.eval()
|
@@ -769,6 +1028,76 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
769
1028
|
|
770
1029
|
return model
|
771
1030
|
|
1031
|
+
# Adapted from `transformers`.
|
1032
|
+
@wraps(torch.nn.Module.cuda)
|
1033
|
+
def cuda(self, *args, **kwargs):
|
1034
|
+
# Checks if the model has been loaded in 4-bit or 8-bit with BNB
|
1035
|
+
if getattr(self, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES:
|
1036
|
+
if getattr(self, "is_loaded_in_8bit", False):
|
1037
|
+
raise ValueError(
|
1038
|
+
"Calling `cuda()` is not supported for `8-bit` quantized models. "
|
1039
|
+
" Please use the model as it is, since the model has already been set to the correct devices."
|
1040
|
+
)
|
1041
|
+
elif is_bitsandbytes_version("<", "0.43.2"):
|
1042
|
+
raise ValueError(
|
1043
|
+
"Calling `cuda()` is not supported for `4-bit` quantized models with the installed version of bitsandbytes. "
|
1044
|
+
f"The current device is `{self.device}`. If you intended to move the model, please install bitsandbytes >= 0.43.2."
|
1045
|
+
)
|
1046
|
+
return super().cuda(*args, **kwargs)
|
1047
|
+
|
1048
|
+
# Adapted from `transformers`.
|
1049
|
+
@wraps(torch.nn.Module.to)
|
1050
|
+
def to(self, *args, **kwargs):
|
1051
|
+
dtype_present_in_args = "dtype" in kwargs
|
1052
|
+
|
1053
|
+
if not dtype_present_in_args:
|
1054
|
+
for arg in args:
|
1055
|
+
if isinstance(arg, torch.dtype):
|
1056
|
+
dtype_present_in_args = True
|
1057
|
+
break
|
1058
|
+
|
1059
|
+
if getattr(self, "is_quantized", False):
|
1060
|
+
if dtype_present_in_args:
|
1061
|
+
raise ValueError(
|
1062
|
+
"Casting a quantized model to a new `dtype` is unsupported. To set the dtype of unquantized layers, please "
|
1063
|
+
"use the `torch_dtype` argument when loading the model using `from_pretrained` or `from_single_file`"
|
1064
|
+
)
|
1065
|
+
|
1066
|
+
if getattr(self, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES:
|
1067
|
+
if getattr(self, "is_loaded_in_8bit", False):
|
1068
|
+
raise ValueError(
|
1069
|
+
"`.to` is not supported for `8-bit` bitsandbytes models. Please use the model as it is, since the"
|
1070
|
+
" model has already been set to the correct devices and casted to the correct `dtype`."
|
1071
|
+
)
|
1072
|
+
elif is_bitsandbytes_version("<", "0.43.2"):
|
1073
|
+
raise ValueError(
|
1074
|
+
"Calling `to()` is not supported for `4-bit` quantized models with the installed version of bitsandbytes. "
|
1075
|
+
f"The current device is `{self.device}`. If you intended to move the model, please install bitsandbytes >= 0.43.2."
|
1076
|
+
)
|
1077
|
+
return super().to(*args, **kwargs)
|
1078
|
+
|
1079
|
+
# Taken from `transformers`.
|
1080
|
+
def half(self, *args):
|
1081
|
+
# Checks if the model is quantized
|
1082
|
+
if getattr(self, "is_quantized", False):
|
1083
|
+
raise ValueError(
|
1084
|
+
"`.half()` is not supported for quantized model. Please use the model as it is, since the"
|
1085
|
+
" model has already been cast to the correct `dtype`."
|
1086
|
+
)
|
1087
|
+
else:
|
1088
|
+
return super().half(*args)
|
1089
|
+
|
1090
|
+
# Taken from `transformers`.
|
1091
|
+
def float(self, *args):
|
1092
|
+
# Checks if the model is quantized
|
1093
|
+
if getattr(self, "is_quantized", False):
|
1094
|
+
raise ValueError(
|
1095
|
+
"`.float()` is not supported for quantized model. Please use the model as it is, since the"
|
1096
|
+
" model has already been cast to the correct `dtype`."
|
1097
|
+
)
|
1098
|
+
else:
|
1099
|
+
return super().float(*args)
|
1100
|
+
|
772
1101
|
@classmethod
|
773
1102
|
def _load_pretrained_model(
|
774
1103
|
cls,
|
@@ -873,6 +1202,45 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
873
1202
|
|
874
1203
|
return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs
|
875
1204
|
|
1205
|
+
@classmethod
|
1206
|
+
def _get_signature_keys(cls, obj):
|
1207
|
+
parameters = inspect.signature(obj.__init__).parameters
|
1208
|
+
required_parameters = {k: v for k, v in parameters.items() if v.default == inspect._empty}
|
1209
|
+
optional_parameters = set({k for k, v in parameters.items() if v.default != inspect._empty})
|
1210
|
+
expected_modules = set(required_parameters.keys()) - {"self"}
|
1211
|
+
|
1212
|
+
return expected_modules, optional_parameters
|
1213
|
+
|
1214
|
+
# Adapted from `transformers` modeling_utils.py
|
1215
|
+
def _get_no_split_modules(self, device_map: str):
|
1216
|
+
"""
|
1217
|
+
Get the modules of the model that should not be spit when using device_map. We iterate through the modules to
|
1218
|
+
get the underlying `_no_split_modules`.
|
1219
|
+
|
1220
|
+
Args:
|
1221
|
+
device_map (`str`):
|
1222
|
+
The device map value. Options are ["auto", "balanced", "balanced_low_0", "sequential"]
|
1223
|
+
|
1224
|
+
Returns:
|
1225
|
+
`List[str]`: List of modules that should not be split
|
1226
|
+
"""
|
1227
|
+
_no_split_modules = set()
|
1228
|
+
modules_to_check = [self]
|
1229
|
+
while len(modules_to_check) > 0:
|
1230
|
+
module = modules_to_check.pop(-1)
|
1231
|
+
# if the module does not appear in _no_split_modules, we also check the children
|
1232
|
+
if module.__class__.__name__ not in _no_split_modules:
|
1233
|
+
if isinstance(module, ModelMixin):
|
1234
|
+
if module._no_split_modules is None:
|
1235
|
+
raise ValueError(
|
1236
|
+
f"{module.__class__.__name__} does not support `device_map='{device_map}'`. To implement support, the model "
|
1237
|
+
"class needs to implement the `_no_split_modules` attribute."
|
1238
|
+
)
|
1239
|
+
else:
|
1240
|
+
_no_split_modules = _no_split_modules | set(module._no_split_modules)
|
1241
|
+
modules_to_check += list(module.children())
|
1242
|
+
return list(_no_split_modules)
|
1243
|
+
|
876
1244
|
@property
|
877
1245
|
def device(self) -> torch.device:
|
878
1246
|
"""
|
@@ -912,19 +1280,63 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
912
1280
|
859520964
|
913
1281
|
```
|
914
1282
|
"""
|
1283
|
+
is_loaded_in_4bit = getattr(self, "is_loaded_in_4bit", False)
|
1284
|
+
|
1285
|
+
if is_loaded_in_4bit:
|
1286
|
+
if is_bitsandbytes_available():
|
1287
|
+
import bitsandbytes as bnb
|
1288
|
+
else:
|
1289
|
+
raise ValueError(
|
1290
|
+
"bitsandbytes is not installed but it seems that the model has been loaded in 4bit precision, something went wrong"
|
1291
|
+
" make sure to install bitsandbytes with `pip install bitsandbytes`. You also need a GPU. "
|
1292
|
+
)
|
915
1293
|
|
916
1294
|
if exclude_embeddings:
|
917
1295
|
embedding_param_names = [
|
918
|
-
f"{name}.weight"
|
919
|
-
for name, module_type in self.named_modules()
|
920
|
-
if isinstance(module_type, torch.nn.Embedding)
|
1296
|
+
f"{name}.weight" for name, module_type in self.named_modules() if isinstance(module_type, nn.Embedding)
|
921
1297
|
]
|
922
|
-
|
1298
|
+
total_parameters = [
|
923
1299
|
parameter for name, parameter in self.named_parameters() if name not in embedding_param_names
|
924
1300
|
]
|
925
|
-
return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable)
|
926
1301
|
else:
|
927
|
-
|
1302
|
+
total_parameters = list(self.parameters())
|
1303
|
+
|
1304
|
+
total_numel = []
|
1305
|
+
|
1306
|
+
for param in total_parameters:
|
1307
|
+
if param.requires_grad or not only_trainable:
|
1308
|
+
# For 4bit models, we need to multiply the number of parameters by 2 as half of the parameters are
|
1309
|
+
# used for the 4bit quantization (uint8 tensors are stored)
|
1310
|
+
if is_loaded_in_4bit and isinstance(param, bnb.nn.Params4bit):
|
1311
|
+
if hasattr(param, "element_size"):
|
1312
|
+
num_bytes = param.element_size()
|
1313
|
+
elif hasattr(param, "quant_storage"):
|
1314
|
+
num_bytes = param.quant_storage.itemsize
|
1315
|
+
else:
|
1316
|
+
num_bytes = 1
|
1317
|
+
total_numel.append(param.numel() * 2 * num_bytes)
|
1318
|
+
else:
|
1319
|
+
total_numel.append(param.numel())
|
1320
|
+
|
1321
|
+
return sum(total_numel)
|
1322
|
+
|
1323
|
+
def get_memory_footprint(self, return_buffers=True):
|
1324
|
+
r"""
|
1325
|
+
Get the memory footprint of a model. This will return the memory footprint of the current model in bytes.
|
1326
|
+
Useful to benchmark the memory footprint of the current model and design some tests. Solution inspired from the
|
1327
|
+
PyTorch discussions: https://discuss.pytorch.org/t/gpu-memory-that-model-uses/56822/2
|
1328
|
+
|
1329
|
+
Arguments:
|
1330
|
+
return_buffers (`bool`, *optional*, defaults to `True`):
|
1331
|
+
Whether to return the size of the buffer tensors in the computation of the memory footprint. Buffers
|
1332
|
+
are tensors that do not require gradients and not registered as parameters. E.g. mean and std in batch
|
1333
|
+
norm layers. Please see: https://discuss.pytorch.org/t/what-pytorch-means-by-buffers/120266/2
|
1334
|
+
"""
|
1335
|
+
mem = sum([param.nelement() * param.element_size() for param in self.parameters()])
|
1336
|
+
if return_buffers:
|
1337
|
+
mem_bufs = sum([buf.nelement() * buf.element_size() for buf in self.buffers()])
|
1338
|
+
mem = mem + mem_bufs
|
1339
|
+
return mem
|
928
1340
|
|
929
1341
|
def _convert_deprecated_attention_blocks(self, state_dict: OrderedDict) -> None:
|
930
1342
|
deprecated_attention_block_paths = []
|
@@ -1019,3 +1431,56 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
|
|
1019
1431
|
del module.key
|
1020
1432
|
del module.value
|
1021
1433
|
del module.proj_attn
|
1434
|
+
|
1435
|
+
|
1436
|
+
class LegacyModelMixin(ModelMixin):
|
1437
|
+
r"""
|
1438
|
+
A subclass of `ModelMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more
|
1439
|
+
pipeline-specific classes (like `DiTTransformer2DModel`).
|
1440
|
+
"""
|
1441
|
+
|
1442
|
+
@classmethod
|
1443
|
+
@validate_hf_hub_args
|
1444
|
+
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
|
1445
|
+
# To prevent dependency import problem.
|
1446
|
+
from .model_loading_utils import _fetch_remapped_cls_from_config
|
1447
|
+
|
1448
|
+
# Create a copy of the kwargs so that we don't mess with the keyword arguments in the downstream calls.
|
1449
|
+
kwargs_copy = kwargs.copy()
|
1450
|
+
|
1451
|
+
cache_dir = kwargs.pop("cache_dir", None)
|
1452
|
+
force_download = kwargs.pop("force_download", False)
|
1453
|
+
proxies = kwargs.pop("proxies", None)
|
1454
|
+
local_files_only = kwargs.pop("local_files_only", None)
|
1455
|
+
token = kwargs.pop("token", None)
|
1456
|
+
revision = kwargs.pop("revision", None)
|
1457
|
+
subfolder = kwargs.pop("subfolder", None)
|
1458
|
+
|
1459
|
+
# Load config if we don't provide a configuration
|
1460
|
+
config_path = pretrained_model_name_or_path
|
1461
|
+
|
1462
|
+
user_agent = {
|
1463
|
+
"diffusers": __version__,
|
1464
|
+
"file_type": "model",
|
1465
|
+
"framework": "pytorch",
|
1466
|
+
}
|
1467
|
+
|
1468
|
+
# load config
|
1469
|
+
config, _, _ = cls.load_config(
|
1470
|
+
config_path,
|
1471
|
+
cache_dir=cache_dir,
|
1472
|
+
return_unused_kwargs=True,
|
1473
|
+
return_commit_hash=True,
|
1474
|
+
force_download=force_download,
|
1475
|
+
proxies=proxies,
|
1476
|
+
local_files_only=local_files_only,
|
1477
|
+
token=token,
|
1478
|
+
revision=revision,
|
1479
|
+
subfolder=subfolder,
|
1480
|
+
user_agent=user_agent,
|
1481
|
+
**kwargs,
|
1482
|
+
)
|
1483
|
+
# resolve remapping
|
1484
|
+
remapped_class = _fetch_remapped_cls_from_config(config, cls)
|
1485
|
+
|
1486
|
+
return remapped_class.from_pretrained(pretrained_model_name_or_path, **kwargs_copy)
|