diffusers 0.32.2__py3-none-any.whl → 0.33.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffusers/__init__.py +186 -3
- diffusers/configuration_utils.py +40 -12
- diffusers/dependency_versions_table.py +9 -2
- diffusers/hooks/__init__.py +9 -0
- diffusers/hooks/faster_cache.py +653 -0
- diffusers/hooks/group_offloading.py +793 -0
- diffusers/hooks/hooks.py +236 -0
- diffusers/hooks/layerwise_casting.py +245 -0
- diffusers/hooks/pyramid_attention_broadcast.py +311 -0
- diffusers/loaders/__init__.py +6 -0
- diffusers/loaders/ip_adapter.py +38 -30
- diffusers/loaders/lora_base.py +121 -86
- diffusers/loaders/lora_conversion_utils.py +504 -44
- diffusers/loaders/lora_pipeline.py +1769 -181
- diffusers/loaders/peft.py +167 -57
- diffusers/loaders/single_file.py +17 -2
- diffusers/loaders/single_file_model.py +53 -5
- diffusers/loaders/single_file_utils.py +646 -72
- diffusers/loaders/textual_inversion.py +9 -9
- diffusers/loaders/transformer_flux.py +8 -9
- diffusers/loaders/transformer_sd3.py +120 -39
- diffusers/loaders/unet.py +20 -7
- diffusers/models/__init__.py +22 -0
- diffusers/models/activations.py +9 -9
- diffusers/models/attention.py +0 -1
- diffusers/models/attention_processor.py +163 -25
- diffusers/models/auto_model.py +169 -0
- diffusers/models/autoencoders/__init__.py +2 -0
- diffusers/models/autoencoders/autoencoder_asym_kl.py +2 -0
- diffusers/models/autoencoders/autoencoder_dc.py +106 -4
- diffusers/models/autoencoders/autoencoder_kl.py +0 -4
- diffusers/models/autoencoders/autoencoder_kl_allegro.py +5 -23
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +17 -55
- diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +17 -97
- diffusers/models/autoencoders/autoencoder_kl_ltx.py +326 -107
- diffusers/models/autoencoders/autoencoder_kl_magvit.py +1094 -0
- diffusers/models/autoencoders/autoencoder_kl_mochi.py +21 -56
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +11 -42
- diffusers/models/autoencoders/autoencoder_kl_wan.py +855 -0
- diffusers/models/autoencoders/autoencoder_oobleck.py +1 -0
- diffusers/models/autoencoders/autoencoder_tiny.py +0 -4
- diffusers/models/autoencoders/consistency_decoder_vae.py +3 -1
- diffusers/models/autoencoders/vae.py +31 -141
- diffusers/models/autoencoders/vq_model.py +3 -0
- diffusers/models/cache_utils.py +108 -0
- diffusers/models/controlnets/__init__.py +1 -0
- diffusers/models/controlnets/controlnet.py +3 -8
- diffusers/models/controlnets/controlnet_flux.py +14 -42
- diffusers/models/controlnets/controlnet_sd3.py +58 -34
- diffusers/models/controlnets/controlnet_sparsectrl.py +4 -7
- diffusers/models/controlnets/controlnet_union.py +27 -18
- diffusers/models/controlnets/controlnet_xs.py +7 -46
- diffusers/models/controlnets/multicontrolnet_union.py +196 -0
- diffusers/models/embeddings.py +18 -7
- diffusers/models/model_loading_utils.py +122 -80
- 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 +617 -272
- diffusers/models/normalization.py +67 -14
- diffusers/models/resnet.py +1 -1
- diffusers/models/transformers/__init__.py +6 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +9 -35
- diffusers/models/transformers/cogvideox_transformer_3d.py +13 -24
- diffusers/models/transformers/consisid_transformer_3d.py +789 -0
- diffusers/models/transformers/dit_transformer_2d.py +5 -19
- diffusers/models/transformers/hunyuan_transformer_2d.py +4 -3
- diffusers/models/transformers/latte_transformer_3d.py +20 -15
- diffusers/models/transformers/lumina_nextdit2d.py +3 -1
- diffusers/models/transformers/pixart_transformer_2d.py +4 -19
- diffusers/models/transformers/prior_transformer.py +5 -1
- diffusers/models/transformers/sana_transformer.py +144 -40
- diffusers/models/transformers/stable_audio_transformer.py +5 -20
- diffusers/models/transformers/transformer_2d.py +7 -22
- diffusers/models/transformers/transformer_allegro.py +9 -17
- diffusers/models/transformers/transformer_cogview3plus.py +6 -17
- diffusers/models/transformers/transformer_cogview4.py +462 -0
- diffusers/models/transformers/transformer_easyanimate.py +527 -0
- diffusers/models/transformers/transformer_flux.py +68 -110
- diffusers/models/transformers/transformer_hunyuan_video.py +404 -46
- diffusers/models/transformers/transformer_ltx.py +53 -35
- diffusers/models/transformers/transformer_lumina2.py +548 -0
- diffusers/models/transformers/transformer_mochi.py +6 -17
- diffusers/models/transformers/transformer_omnigen.py +469 -0
- diffusers/models/transformers/transformer_sd3.py +56 -86
- diffusers/models/transformers/transformer_temporal.py +5 -11
- diffusers/models/transformers/transformer_wan.py +469 -0
- diffusers/models/unets/unet_1d.py +3 -1
- diffusers/models/unets/unet_2d.py +21 -20
- diffusers/models/unets/unet_2d_blocks.py +19 -243
- diffusers/models/unets/unet_2d_condition.py +4 -6
- diffusers/models/unets/unet_3d_blocks.py +14 -127
- diffusers/models/unets/unet_3d_condition.py +8 -12
- diffusers/models/unets/unet_i2vgen_xl.py +5 -13
- diffusers/models/unets/unet_kandinsky3.py +0 -4
- diffusers/models/unets/unet_motion_model.py +20 -114
- diffusers/models/unets/unet_spatio_temporal_condition.py +7 -8
- diffusers/models/unets/unet_stable_cascade.py +8 -35
- diffusers/models/unets/uvit_2d.py +1 -4
- diffusers/optimization.py +2 -2
- diffusers/pipelines/__init__.py +57 -8
- diffusers/pipelines/allegro/pipeline_allegro.py +22 -2
- diffusers/pipelines/amused/pipeline_amused.py +15 -2
- diffusers/pipelines/amused/pipeline_amused_img2img.py +15 -2
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +15 -2
- diffusers/pipelines/animatediff/pipeline_animatediff.py +15 -2
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +15 -3
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +24 -4
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +15 -2
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +16 -4
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +16 -4
- diffusers/pipelines/audioldm/pipeline_audioldm.py +13 -2
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +13 -68
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +39 -9
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +63 -7
- diffusers/pipelines/auto_pipeline.py +35 -14
- diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_blip2.py +5 -8
- diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +12 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +22 -6
- diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +22 -6
- diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +22 -5
- diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +22 -6
- diffusers/pipelines/cogview3/pipeline_cogview3plus.py +12 -4
- diffusers/pipelines/cogview4/__init__.py +49 -0
- diffusers/pipelines/cogview4/pipeline_cogview4.py +684 -0
- diffusers/pipelines/cogview4/pipeline_cogview4_control.py +732 -0
- diffusers/pipelines/cogview4/pipeline_output.py +21 -0
- diffusers/pipelines/consisid/__init__.py +49 -0
- diffusers/pipelines/consisid/consisid_utils.py +357 -0
- diffusers/pipelines/consisid/pipeline_consisid.py +974 -0
- diffusers/pipelines/consisid/pipeline_output.py +20 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +11 -0
- diffusers/pipelines/controlnet/pipeline_controlnet.py +6 -5
- diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +13 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +17 -5
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +31 -12
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +26 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +20 -3
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +22 -3
- diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +26 -25
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +224 -109
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +25 -29
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +7 -4
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +3 -5
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +121 -10
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +122 -11
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -1
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +20 -3
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +14 -2
- diffusers/pipelines/ddim/pipeline_ddim.py +14 -1
- diffusers/pipelines/ddpm/pipeline_ddpm.py +15 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +12 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +12 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +14 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +12 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +14 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +14 -1
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -7
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -7
- diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +10 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +2 -2
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +11 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +10 -105
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +1 -1
- 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 -1
- diffusers/pipelines/dit/pipeline_dit.py +15 -2
- diffusers/pipelines/easyanimate/__init__.py +52 -0
- diffusers/pipelines/easyanimate/pipeline_easyanimate.py +770 -0
- diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +994 -0
- diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +1234 -0
- diffusers/pipelines/easyanimate/pipeline_output.py +20 -0
- diffusers/pipelines/flux/pipeline_flux.py +53 -21
- diffusers/pipelines/flux/pipeline_flux_control.py +9 -12
- diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -10
- diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +8 -10
- diffusers/pipelines/flux/pipeline_flux_controlnet.py +185 -13
- diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +8 -10
- diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +16 -16
- diffusers/pipelines/flux/pipeline_flux_fill.py +107 -39
- diffusers/pipelines/flux/pipeline_flux_img2img.py +193 -15
- diffusers/pipelines/flux/pipeline_flux_inpaint.py +199 -19
- diffusers/pipelines/free_noise_utils.py +3 -3
- diffusers/pipelines/hunyuan_video/__init__.py +4 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +804 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +90 -23
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +924 -0
- diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +3 -5
- diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +13 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +12 -0
- diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +1 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +12 -0
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +13 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +12 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +12 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +13 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +12 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +12 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +12 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +12 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +12 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +12 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +12 -0
- diffusers/pipelines/kolors/pipeline_kolors.py +10 -8
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +6 -4
- diffusers/pipelines/kolors/text_encoder.py +7 -34
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +12 -1
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +13 -1
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +14 -13
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +12 -1
- diffusers/pipelines/latte/pipeline_latte.py +36 -7
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +67 -13
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +60 -15
- diffusers/pipelines/ltx/__init__.py +2 -0
- diffusers/pipelines/ltx/pipeline_ltx.py +25 -13
- diffusers/pipelines/ltx/pipeline_ltx_condition.py +1194 -0
- diffusers/pipelines/ltx/pipeline_ltx_image2video.py +31 -17
- diffusers/pipelines/lumina/__init__.py +2 -2
- diffusers/pipelines/lumina/pipeline_lumina.py +83 -20
- diffusers/pipelines/lumina2/__init__.py +48 -0
- diffusers/pipelines/lumina2/pipeline_lumina2.py +790 -0
- diffusers/pipelines/marigold/__init__.py +2 -0
- diffusers/pipelines/marigold/marigold_image_processing.py +127 -14
- diffusers/pipelines/marigold/pipeline_marigold_depth.py +31 -16
- diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py +721 -0
- diffusers/pipelines/marigold/pipeline_marigold_normals.py +31 -16
- diffusers/pipelines/mochi/pipeline_mochi.py +14 -18
- diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -1
- diffusers/pipelines/omnigen/__init__.py +50 -0
- diffusers/pipelines/omnigen/pipeline_omnigen.py +512 -0
- diffusers/pipelines/omnigen/processor_omnigen.py +327 -0
- diffusers/pipelines/onnx_utils.py +5 -3
- diffusers/pipelines/pag/pag_utils.py +1 -1
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -1
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +15 -4
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +20 -3
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +20 -3
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +1 -3
- diffusers/pipelines/pag/pipeline_pag_kolors.py +6 -4
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +16 -3
- diffusers/pipelines/pag/pipeline_pag_sana.py +65 -8
- diffusers/pipelines/pag/pipeline_pag_sd.py +23 -7
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +3 -5
- diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +3 -5
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +13 -1
- diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +23 -7
- diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +26 -10
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +12 -4
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +7 -3
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +10 -6
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +13 -3
- diffusers/pipelines/pia/pipeline_pia.py +13 -1
- diffusers/pipelines/pipeline_flax_utils.py +7 -7
- diffusers/pipelines/pipeline_loading_utils.py +193 -83
- diffusers/pipelines/pipeline_utils.py +221 -106
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +17 -5
- diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +17 -4
- diffusers/pipelines/sana/__init__.py +2 -0
- diffusers/pipelines/sana/pipeline_sana.py +183 -58
- diffusers/pipelines/sana/pipeline_sana_sprint.py +889 -0
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +12 -2
- diffusers/pipelines/shap_e/pipeline_shap_e.py +12 -0
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +12 -0
- diffusers/pipelines/shap_e/renderer.py +6 -6
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +1 -1
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +15 -4
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +12 -8
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +12 -1
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +3 -2
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +14 -10
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +3 -3
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +14 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +4 -3
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +5 -4
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +18 -13
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +30 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +24 -10
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +28 -12
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +39 -18
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +13 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +20 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +14 -2
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +13 -1
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +16 -17
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +136 -18
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +150 -21
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +15 -3
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +26 -11
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +15 -3
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +22 -4
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -13
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +12 -4
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +15 -3
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -3
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +26 -12
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +16 -4
- diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +12 -4
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +7 -3
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +10 -6
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +11 -4
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +13 -2
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +18 -4
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +26 -5
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +13 -1
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +13 -1
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +28 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +26 -4
- diffusers/pipelines/transformers_loading_utils.py +121 -0
- diffusers/pipelines/unclip/pipeline_unclip.py +11 -1
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +11 -1
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +19 -2
- diffusers/pipelines/wan/__init__.py +51 -0
- diffusers/pipelines/wan/pipeline_output.py +20 -0
- diffusers/pipelines/wan/pipeline_wan.py +595 -0
- diffusers/pipelines/wan/pipeline_wan_i2v.py +724 -0
- diffusers/pipelines/wan/pipeline_wan_video2video.py +727 -0
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +7 -31
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +12 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +12 -1
- diffusers/quantizers/auto.py +5 -1
- diffusers/quantizers/base.py +5 -9
- diffusers/quantizers/bitsandbytes/bnb_quantizer.py +41 -29
- diffusers/quantizers/bitsandbytes/utils.py +30 -20
- diffusers/quantizers/gguf/gguf_quantizer.py +1 -0
- diffusers/quantizers/gguf/utils.py +4 -2
- diffusers/quantizers/quantization_config.py +59 -4
- diffusers/quantizers/quanto/__init__.py +1 -0
- diffusers/quantizers/quanto/quanto_quantizer.py +177 -0
- diffusers/quantizers/quanto/utils.py +60 -0
- diffusers/quantizers/torchao/__init__.py +1 -1
- diffusers/quantizers/torchao/torchao_quantizer.py +47 -2
- diffusers/schedulers/__init__.py +2 -1
- diffusers/schedulers/scheduling_consistency_models.py +1 -2
- diffusers/schedulers/scheduling_ddim_inverse.py +1 -1
- diffusers/schedulers/scheduling_ddpm.py +2 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +1 -2
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -4
- diffusers/schedulers/scheduling_edm_euler.py +45 -10
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +116 -28
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +7 -6
- diffusers/schedulers/scheduling_heun_discrete.py +1 -1
- diffusers/schedulers/scheduling_lcm.py +1 -2
- diffusers/schedulers/scheduling_lms_discrete.py +1 -1
- diffusers/schedulers/scheduling_repaint.py +5 -1
- diffusers/schedulers/scheduling_scm.py +265 -0
- diffusers/schedulers/scheduling_tcd.py +1 -2
- diffusers/schedulers/scheduling_utils.py +2 -1
- diffusers/training_utils.py +14 -7
- diffusers/utils/__init__.py +9 -1
- diffusers/utils/constants.py +13 -1
- diffusers/utils/deprecation_utils.py +1 -1
- diffusers/utils/dummy_bitsandbytes_objects.py +17 -0
- diffusers/utils/dummy_gguf_objects.py +17 -0
- diffusers/utils/dummy_optimum_quanto_objects.py +17 -0
- diffusers/utils/dummy_pt_objects.py +233 -0
- diffusers/utils/dummy_torch_and_transformers_and_opencv_objects.py +17 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +270 -0
- diffusers/utils/dummy_torchao_objects.py +17 -0
- diffusers/utils/dynamic_modules_utils.py +1 -1
- diffusers/utils/export_utils.py +28 -3
- diffusers/utils/hub_utils.py +52 -102
- diffusers/utils/import_utils.py +121 -221
- diffusers/utils/loading_utils.py +2 -1
- diffusers/utils/logging.py +1 -2
- diffusers/utils/peft_utils.py +6 -14
- diffusers/utils/remote_utils.py +425 -0
- diffusers/utils/source_code_parsing_utils.py +52 -0
- diffusers/utils/state_dict_utils.py +15 -1
- diffusers/utils/testing_utils.py +243 -13
- diffusers/utils/torch_utils.py +10 -0
- diffusers/utils/typing_utils.py +91 -0
- diffusers/video_processor.py +1 -1
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/METADATA +21 -4
- diffusers-0.33.1.dist-info/RECORD +608 -0
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/WHEEL +1 -1
- diffusers-0.32.2.dist-info/RECORD +0 -550
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/LICENSE +0 -0
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/entry_points.txt +0 -0
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,793 @@
|
|
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 contextlib import contextmanager, nullcontext
|
16
|
+
from typing import Dict, List, Optional, Set, Tuple
|
17
|
+
|
18
|
+
import torch
|
19
|
+
|
20
|
+
from ..utils import get_logger, is_accelerate_available
|
21
|
+
from .hooks import HookRegistry, ModelHook
|
22
|
+
|
23
|
+
|
24
|
+
if is_accelerate_available():
|
25
|
+
from accelerate.hooks import AlignDevicesHook, CpuOffload
|
26
|
+
from accelerate.utils import send_to_device
|
27
|
+
|
28
|
+
|
29
|
+
logger = get_logger(__name__) # pylint: disable=invalid-name
|
30
|
+
|
31
|
+
|
32
|
+
# fmt: off
|
33
|
+
_GROUP_OFFLOADING = "group_offloading"
|
34
|
+
_LAYER_EXECUTION_TRACKER = "layer_execution_tracker"
|
35
|
+
_LAZY_PREFETCH_GROUP_OFFLOADING = "lazy_prefetch_group_offloading"
|
36
|
+
|
37
|
+
_SUPPORTED_PYTORCH_LAYERS = (
|
38
|
+
torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d,
|
39
|
+
torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d,
|
40
|
+
torch.nn.Linear,
|
41
|
+
# TODO(aryan): look into torch.nn.LayerNorm, torch.nn.GroupNorm later, seems to be causing some issues with CogVideoX
|
42
|
+
# because of double invocation of the same norm layer in CogVideoXLayerNorm
|
43
|
+
)
|
44
|
+
# fmt: on
|
45
|
+
|
46
|
+
|
47
|
+
class ModuleGroup:
|
48
|
+
def __init__(
|
49
|
+
self,
|
50
|
+
modules: List[torch.nn.Module],
|
51
|
+
offload_device: torch.device,
|
52
|
+
onload_device: torch.device,
|
53
|
+
offload_leader: torch.nn.Module,
|
54
|
+
onload_leader: Optional[torch.nn.Module] = None,
|
55
|
+
parameters: Optional[List[torch.nn.Parameter]] = None,
|
56
|
+
buffers: Optional[List[torch.Tensor]] = None,
|
57
|
+
non_blocking: bool = False,
|
58
|
+
stream: Optional[torch.cuda.Stream] = None,
|
59
|
+
record_stream: Optional[bool] = False,
|
60
|
+
low_cpu_mem_usage=False,
|
61
|
+
onload_self: bool = True,
|
62
|
+
) -> None:
|
63
|
+
self.modules = modules
|
64
|
+
self.offload_device = offload_device
|
65
|
+
self.onload_device = onload_device
|
66
|
+
self.offload_leader = offload_leader
|
67
|
+
self.onload_leader = onload_leader
|
68
|
+
self.parameters = parameters or []
|
69
|
+
self.buffers = buffers or []
|
70
|
+
self.non_blocking = non_blocking or stream is not None
|
71
|
+
self.stream = stream
|
72
|
+
self.record_stream = record_stream
|
73
|
+
self.onload_self = onload_self
|
74
|
+
self.low_cpu_mem_usage = low_cpu_mem_usage
|
75
|
+
self.cpu_param_dict = self._init_cpu_param_dict()
|
76
|
+
|
77
|
+
if self.stream is None and self.record_stream:
|
78
|
+
raise ValueError("`record_stream` cannot be True when `stream` is None.")
|
79
|
+
|
80
|
+
def _init_cpu_param_dict(self):
|
81
|
+
cpu_param_dict = {}
|
82
|
+
if self.stream is None:
|
83
|
+
return cpu_param_dict
|
84
|
+
|
85
|
+
for module in self.modules:
|
86
|
+
for param in module.parameters():
|
87
|
+
cpu_param_dict[param] = param.data.cpu() if self.low_cpu_mem_usage else param.data.cpu().pin_memory()
|
88
|
+
for buffer in module.buffers():
|
89
|
+
cpu_param_dict[buffer] = (
|
90
|
+
buffer.data.cpu() if self.low_cpu_mem_usage else buffer.data.cpu().pin_memory()
|
91
|
+
)
|
92
|
+
|
93
|
+
for param in self.parameters:
|
94
|
+
cpu_param_dict[param] = param.data.cpu() if self.low_cpu_mem_usage else param.data.cpu().pin_memory()
|
95
|
+
|
96
|
+
for buffer in self.buffers:
|
97
|
+
cpu_param_dict[buffer] = buffer.data.cpu() if self.low_cpu_mem_usage else buffer.data.cpu().pin_memory()
|
98
|
+
|
99
|
+
return cpu_param_dict
|
100
|
+
|
101
|
+
@contextmanager
|
102
|
+
def _pinned_memory_tensors(self):
|
103
|
+
pinned_dict = {}
|
104
|
+
try:
|
105
|
+
for param, tensor in self.cpu_param_dict.items():
|
106
|
+
if not tensor.is_pinned():
|
107
|
+
pinned_dict[param] = tensor.pin_memory()
|
108
|
+
else:
|
109
|
+
pinned_dict[param] = tensor
|
110
|
+
|
111
|
+
yield pinned_dict
|
112
|
+
|
113
|
+
finally:
|
114
|
+
pinned_dict = None
|
115
|
+
|
116
|
+
def onload_(self):
|
117
|
+
r"""Onloads the group of modules to the onload_device."""
|
118
|
+
context = nullcontext() if self.stream is None else torch.cuda.stream(self.stream)
|
119
|
+
current_stream = torch.cuda.current_stream() if self.record_stream else None
|
120
|
+
|
121
|
+
if self.stream is not None:
|
122
|
+
# Wait for previous Host->Device transfer to complete
|
123
|
+
self.stream.synchronize()
|
124
|
+
|
125
|
+
with context:
|
126
|
+
if self.stream is not None:
|
127
|
+
with self._pinned_memory_tensors() as pinned_memory:
|
128
|
+
for group_module in self.modules:
|
129
|
+
for param in group_module.parameters():
|
130
|
+
param.data = pinned_memory[param].to(self.onload_device, non_blocking=self.non_blocking)
|
131
|
+
if self.record_stream:
|
132
|
+
param.data.record_stream(current_stream)
|
133
|
+
for buffer in group_module.buffers():
|
134
|
+
buffer.data = pinned_memory[buffer].to(self.onload_device, non_blocking=self.non_blocking)
|
135
|
+
if self.record_stream:
|
136
|
+
buffer.data.record_stream(current_stream)
|
137
|
+
|
138
|
+
for param in self.parameters:
|
139
|
+
param.data = pinned_memory[param].to(self.onload_device, non_blocking=self.non_blocking)
|
140
|
+
if self.record_stream:
|
141
|
+
param.data.record_stream(current_stream)
|
142
|
+
|
143
|
+
for buffer in self.buffers:
|
144
|
+
buffer.data = pinned_memory[buffer].to(self.onload_device, non_blocking=self.non_blocking)
|
145
|
+
if self.record_stream:
|
146
|
+
buffer.data.record_stream(current_stream)
|
147
|
+
|
148
|
+
else:
|
149
|
+
for group_module in self.modules:
|
150
|
+
for param in group_module.parameters():
|
151
|
+
param.data = param.data.to(self.onload_device, non_blocking=self.non_blocking)
|
152
|
+
for buffer in group_module.buffers():
|
153
|
+
buffer.data = buffer.data.to(self.onload_device, non_blocking=self.non_blocking)
|
154
|
+
|
155
|
+
for param in self.parameters:
|
156
|
+
param.data = param.data.to(self.onload_device, non_blocking=self.non_blocking)
|
157
|
+
|
158
|
+
for buffer in self.buffers:
|
159
|
+
buffer.data = buffer.data.to(self.onload_device, non_blocking=self.non_blocking)
|
160
|
+
if self.record_stream:
|
161
|
+
buffer.data.record_stream(current_stream)
|
162
|
+
|
163
|
+
def offload_(self):
|
164
|
+
r"""Offloads the group of modules to the offload_device."""
|
165
|
+
if self.stream is not None:
|
166
|
+
if not self.record_stream:
|
167
|
+
torch.cuda.current_stream().synchronize()
|
168
|
+
for group_module in self.modules:
|
169
|
+
for param in group_module.parameters():
|
170
|
+
param.data = self.cpu_param_dict[param]
|
171
|
+
for param in self.parameters:
|
172
|
+
param.data = self.cpu_param_dict[param]
|
173
|
+
for buffer in self.buffers:
|
174
|
+
buffer.data = self.cpu_param_dict[buffer]
|
175
|
+
|
176
|
+
else:
|
177
|
+
for group_module in self.modules:
|
178
|
+
group_module.to(self.offload_device, non_blocking=self.non_blocking)
|
179
|
+
for param in self.parameters:
|
180
|
+
param.data = param.data.to(self.offload_device, non_blocking=self.non_blocking)
|
181
|
+
for buffer in self.buffers:
|
182
|
+
buffer.data = buffer.data.to(self.offload_device, non_blocking=self.non_blocking)
|
183
|
+
|
184
|
+
|
185
|
+
class GroupOffloadingHook(ModelHook):
|
186
|
+
r"""
|
187
|
+
A hook that offloads groups of torch.nn.Module to the CPU for storage and onloads to accelerator device for
|
188
|
+
computation. Each group has one "onload leader" module that is responsible for onloading, and an "offload leader"
|
189
|
+
module that is responsible for offloading. If prefetching is enabled, the onload leader of the previous module
|
190
|
+
group is responsible for onloading the current module group.
|
191
|
+
"""
|
192
|
+
|
193
|
+
_is_stateful = False
|
194
|
+
|
195
|
+
def __init__(
|
196
|
+
self,
|
197
|
+
group: ModuleGroup,
|
198
|
+
next_group: Optional[ModuleGroup] = None,
|
199
|
+
) -> None:
|
200
|
+
self.group = group
|
201
|
+
self.next_group = next_group
|
202
|
+
|
203
|
+
def initialize_hook(self, module: torch.nn.Module) -> torch.nn.Module:
|
204
|
+
if self.group.offload_leader == module:
|
205
|
+
self.group.offload_()
|
206
|
+
return module
|
207
|
+
|
208
|
+
def pre_forward(self, module: torch.nn.Module, *args, **kwargs):
|
209
|
+
# If there wasn't an onload_leader assigned, we assume that the submodule that first called its forward
|
210
|
+
# method is the onload_leader of the group.
|
211
|
+
if self.group.onload_leader is None:
|
212
|
+
self.group.onload_leader = module
|
213
|
+
|
214
|
+
# If the current module is the onload_leader of the group, we onload the group if it is supposed
|
215
|
+
# to onload itself. In the case of using prefetching with streams, we onload the next group if
|
216
|
+
# it is not supposed to onload itself.
|
217
|
+
if self.group.onload_leader == module:
|
218
|
+
if self.group.onload_self:
|
219
|
+
self.group.onload_()
|
220
|
+
if self.next_group is not None and not self.next_group.onload_self:
|
221
|
+
self.next_group.onload_()
|
222
|
+
|
223
|
+
args = send_to_device(args, self.group.onload_device, non_blocking=self.group.non_blocking)
|
224
|
+
kwargs = send_to_device(kwargs, self.group.onload_device, non_blocking=self.group.non_blocking)
|
225
|
+
return args, kwargs
|
226
|
+
|
227
|
+
def post_forward(self, module: torch.nn.Module, output):
|
228
|
+
if self.group.offload_leader == module:
|
229
|
+
self.group.offload_()
|
230
|
+
return output
|
231
|
+
|
232
|
+
|
233
|
+
class LazyPrefetchGroupOffloadingHook(ModelHook):
|
234
|
+
r"""
|
235
|
+
A hook, used in conjuction with GroupOffloadingHook, that applies lazy prefetching to groups of torch.nn.Module.
|
236
|
+
This hook is used to determine the order in which the layers are executed during the forward pass. Once the layer
|
237
|
+
invocation order is known, assignments of the next_group attribute for prefetching can be made, which allows
|
238
|
+
prefetching groups in the correct order.
|
239
|
+
"""
|
240
|
+
|
241
|
+
_is_stateful = False
|
242
|
+
|
243
|
+
def __init__(self):
|
244
|
+
self.execution_order: List[Tuple[str, torch.nn.Module]] = []
|
245
|
+
self._layer_execution_tracker_module_names = set()
|
246
|
+
|
247
|
+
def initialize_hook(self, module):
|
248
|
+
def make_execution_order_update_callback(current_name, current_submodule):
|
249
|
+
def callback():
|
250
|
+
logger.debug(f"Adding {current_name} to the execution order")
|
251
|
+
self.execution_order.append((current_name, current_submodule))
|
252
|
+
|
253
|
+
return callback
|
254
|
+
|
255
|
+
# To every submodule that contains a group offloading hook (at this point, no prefetching is enabled for any
|
256
|
+
# of the groups), we add a layer execution tracker hook that will be used to determine the order in which the
|
257
|
+
# layers are executed during the forward pass.
|
258
|
+
for name, submodule in module.named_modules():
|
259
|
+
if name == "" or not hasattr(submodule, "_diffusers_hook"):
|
260
|
+
continue
|
261
|
+
|
262
|
+
registry = HookRegistry.check_if_exists_or_initialize(submodule)
|
263
|
+
group_offloading_hook = registry.get_hook(_GROUP_OFFLOADING)
|
264
|
+
|
265
|
+
if group_offloading_hook is not None:
|
266
|
+
# For the first forward pass, we have to load in a blocking manner
|
267
|
+
group_offloading_hook.group.non_blocking = False
|
268
|
+
layer_tracker_hook = LayerExecutionTrackerHook(make_execution_order_update_callback(name, submodule))
|
269
|
+
registry.register_hook(layer_tracker_hook, _LAYER_EXECUTION_TRACKER)
|
270
|
+
self._layer_execution_tracker_module_names.add(name)
|
271
|
+
|
272
|
+
return module
|
273
|
+
|
274
|
+
def post_forward(self, module, output):
|
275
|
+
# At this point, for the current modules' submodules, we know the execution order of the layers. We can now
|
276
|
+
# remove the layer execution tracker hooks and apply prefetching by setting the next_group attribute for each
|
277
|
+
# group offloading hook.
|
278
|
+
num_executed = len(self.execution_order)
|
279
|
+
execution_order_module_names = {name for name, _ in self.execution_order}
|
280
|
+
|
281
|
+
# It may be possible that some layers were not executed during the forward pass. This can happen if the layer
|
282
|
+
# is not used in the forward pass, or if the layer is not executed due to some other reason. In such cases, we
|
283
|
+
# may not be able to apply prefetching in the correct order, which can lead to device-mismatch related errors
|
284
|
+
# if the missing layers end up being executed in the future.
|
285
|
+
if execution_order_module_names != self._layer_execution_tracker_module_names:
|
286
|
+
unexecuted_layers = list(self._layer_execution_tracker_module_names - execution_order_module_names)
|
287
|
+
logger.warning(
|
288
|
+
"It seems like some layers were not executed during the forward pass. This may lead to problems when "
|
289
|
+
"applying lazy prefetching with automatic tracing and lead to device-mismatch related errors. Please "
|
290
|
+
"make sure that all layers are executed during the forward pass. The following layers were not executed:\n"
|
291
|
+
f"{unexecuted_layers=}"
|
292
|
+
)
|
293
|
+
|
294
|
+
# Remove the layer execution tracker hooks from the submodules
|
295
|
+
base_module_registry = module._diffusers_hook
|
296
|
+
registries = [submodule._diffusers_hook for _, submodule in self.execution_order]
|
297
|
+
group_offloading_hooks = [registry.get_hook(_GROUP_OFFLOADING) for registry in registries]
|
298
|
+
|
299
|
+
for i in range(num_executed):
|
300
|
+
registries[i].remove_hook(_LAYER_EXECUTION_TRACKER, recurse=False)
|
301
|
+
|
302
|
+
# Remove the current lazy prefetch group offloading hook so that it doesn't interfere with the next forward pass
|
303
|
+
base_module_registry.remove_hook(_LAZY_PREFETCH_GROUP_OFFLOADING, recurse=False)
|
304
|
+
|
305
|
+
# LazyPrefetchGroupOffloadingHook is only used with streams, so we know that non_blocking should be True.
|
306
|
+
# We disable non_blocking for the first forward pass, but need to enable it for the subsequent passes to
|
307
|
+
# see the benefits of prefetching.
|
308
|
+
for hook in group_offloading_hooks:
|
309
|
+
hook.group.non_blocking = True
|
310
|
+
|
311
|
+
# Set required attributes for prefetching
|
312
|
+
if num_executed > 0:
|
313
|
+
base_module_group_offloading_hook = base_module_registry.get_hook(_GROUP_OFFLOADING)
|
314
|
+
base_module_group_offloading_hook.next_group = group_offloading_hooks[0].group
|
315
|
+
base_module_group_offloading_hook.next_group.onload_self = False
|
316
|
+
|
317
|
+
for i in range(num_executed - 1):
|
318
|
+
name1, _ = self.execution_order[i]
|
319
|
+
name2, _ = self.execution_order[i + 1]
|
320
|
+
logger.debug(f"Applying lazy prefetch group offloading from {name1} to {name2}")
|
321
|
+
group_offloading_hooks[i].next_group = group_offloading_hooks[i + 1].group
|
322
|
+
group_offloading_hooks[i].next_group.onload_self = False
|
323
|
+
|
324
|
+
return output
|
325
|
+
|
326
|
+
|
327
|
+
class LayerExecutionTrackerHook(ModelHook):
|
328
|
+
r"""
|
329
|
+
A hook that tracks the order in which the layers are executed during the forward pass by calling back to the
|
330
|
+
LazyPrefetchGroupOffloadingHook to update the execution order.
|
331
|
+
"""
|
332
|
+
|
333
|
+
_is_stateful = False
|
334
|
+
|
335
|
+
def __init__(self, execution_order_update_callback):
|
336
|
+
self.execution_order_update_callback = execution_order_update_callback
|
337
|
+
|
338
|
+
def pre_forward(self, module, *args, **kwargs):
|
339
|
+
self.execution_order_update_callback()
|
340
|
+
return args, kwargs
|
341
|
+
|
342
|
+
|
343
|
+
def apply_group_offloading(
|
344
|
+
module: torch.nn.Module,
|
345
|
+
onload_device: torch.device,
|
346
|
+
offload_device: torch.device = torch.device("cpu"),
|
347
|
+
offload_type: str = "block_level",
|
348
|
+
num_blocks_per_group: Optional[int] = None,
|
349
|
+
non_blocking: bool = False,
|
350
|
+
use_stream: bool = False,
|
351
|
+
record_stream: bool = False,
|
352
|
+
low_cpu_mem_usage: bool = False,
|
353
|
+
) -> None:
|
354
|
+
r"""
|
355
|
+
Applies group offloading to the internal layers of a torch.nn.Module. To understand what group offloading is, and
|
356
|
+
where it is beneficial, we need to first provide some context on how other supported offloading methods work.
|
357
|
+
|
358
|
+
Typically, offloading is done at two levels:
|
359
|
+
- Module-level: In Diffusers, this can be enabled using the `ModelMixin::enable_model_cpu_offload()` method. It
|
360
|
+
works by offloading each component of a pipeline to the CPU for storage, and onloading to the accelerator device
|
361
|
+
when needed for computation. This method is more memory-efficient than keeping all components on the accelerator,
|
362
|
+
but the memory requirements are still quite high. For this method to work, one needs memory equivalent to size of
|
363
|
+
the model in runtime dtype + size of largest intermediate activation tensors to be able to complete the forward
|
364
|
+
pass.
|
365
|
+
- Leaf-level: In Diffusers, this can be enabled using the `ModelMixin::enable_sequential_cpu_offload()` method. It
|
366
|
+
works by offloading the lowest leaf-level parameters of the computation graph to the CPU for storage, and
|
367
|
+
onloading only the leafs to the accelerator device for computation. This uses the lowest amount of accelerator
|
368
|
+
memory, but can be slower due to the excessive number of device synchronizations.
|
369
|
+
|
370
|
+
Group offloading is a middle ground between the two methods. It works by offloading groups of internal layers,
|
371
|
+
(either `torch.nn.ModuleList` or `torch.nn.Sequential`). This method uses lower memory than module-level
|
372
|
+
offloading. It is also faster than leaf-level/sequential offloading, as the number of device synchronizations is
|
373
|
+
reduced.
|
374
|
+
|
375
|
+
Another supported feature (for CUDA devices with support for asynchronous data transfer streams) is the ability to
|
376
|
+
overlap data transfer and computation to reduce the overall execution time compared to sequential offloading. This
|
377
|
+
is enabled using layer prefetching with streams, i.e., the layer that is to be executed next starts onloading to
|
378
|
+
the accelerator device while the current layer is being executed - this increases the memory requirements slightly.
|
379
|
+
Note that this implementation also supports leaf-level offloading but can be made much faster when using streams.
|
380
|
+
|
381
|
+
Args:
|
382
|
+
module (`torch.nn.Module`):
|
383
|
+
The module to which group offloading is applied.
|
384
|
+
onload_device (`torch.device`):
|
385
|
+
The device to which the group of modules are onloaded.
|
386
|
+
offload_device (`torch.device`, defaults to `torch.device("cpu")`):
|
387
|
+
The device to which the group of modules are offloaded. This should typically be the CPU. Default is CPU.
|
388
|
+
offload_type (`str`, defaults to "block_level"):
|
389
|
+
The type of offloading to be applied. Can be one of "block_level" or "leaf_level". Default is
|
390
|
+
"block_level".
|
391
|
+
num_blocks_per_group (`int`, *optional*):
|
392
|
+
The number of blocks per group when using offload_type="block_level". This is required when using
|
393
|
+
offload_type="block_level".
|
394
|
+
non_blocking (`bool`, defaults to `False`):
|
395
|
+
If True, offloading and onloading is done with non-blocking data transfer.
|
396
|
+
use_stream (`bool`, defaults to `False`):
|
397
|
+
If True, offloading and onloading is done asynchronously using a CUDA stream. This can be useful for
|
398
|
+
overlapping computation and data transfer.
|
399
|
+
record_stream (`bool`, defaults to `False`): When enabled with `use_stream`, it marks the current tensor
|
400
|
+
as having been used by this stream. It is faster at the expense of slightly more memory usage. Refer to the
|
401
|
+
[PyTorch official docs](https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html) more
|
402
|
+
details.
|
403
|
+
low_cpu_mem_usage (`bool`, defaults to `False`):
|
404
|
+
If True, the CPU memory usage is minimized by pinning tensors on-the-fly instead of pre-pinning them. This
|
405
|
+
option only matters when using streamed CPU offloading (i.e. `use_stream=True`). This can be useful when
|
406
|
+
the CPU memory is a bottleneck but may counteract the benefits of using streams.
|
407
|
+
|
408
|
+
Example:
|
409
|
+
```python
|
410
|
+
>>> from diffusers import CogVideoXTransformer3DModel
|
411
|
+
>>> from diffusers.hooks import apply_group_offloading
|
412
|
+
|
413
|
+
>>> transformer = CogVideoXTransformer3DModel.from_pretrained(
|
414
|
+
... "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
|
415
|
+
... )
|
416
|
+
|
417
|
+
>>> apply_group_offloading(
|
418
|
+
... transformer,
|
419
|
+
... onload_device=torch.device("cuda"),
|
420
|
+
... offload_device=torch.device("cpu"),
|
421
|
+
... offload_type="block_level",
|
422
|
+
... num_blocks_per_group=2,
|
423
|
+
... use_stream=True,
|
424
|
+
... )
|
425
|
+
```
|
426
|
+
"""
|
427
|
+
|
428
|
+
stream = None
|
429
|
+
if use_stream:
|
430
|
+
if torch.cuda.is_available():
|
431
|
+
stream = torch.cuda.Stream()
|
432
|
+
else:
|
433
|
+
raise ValueError("Using streams for data transfer requires a CUDA device.")
|
434
|
+
|
435
|
+
_raise_error_if_accelerate_model_or_sequential_hook_present(module)
|
436
|
+
|
437
|
+
if offload_type == "block_level":
|
438
|
+
if num_blocks_per_group is None:
|
439
|
+
raise ValueError("num_blocks_per_group must be provided when using offload_type='block_level'.")
|
440
|
+
|
441
|
+
_apply_group_offloading_block_level(
|
442
|
+
module=module,
|
443
|
+
num_blocks_per_group=num_blocks_per_group,
|
444
|
+
offload_device=offload_device,
|
445
|
+
onload_device=onload_device,
|
446
|
+
non_blocking=non_blocking,
|
447
|
+
stream=stream,
|
448
|
+
record_stream=record_stream,
|
449
|
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
450
|
+
)
|
451
|
+
elif offload_type == "leaf_level":
|
452
|
+
_apply_group_offloading_leaf_level(
|
453
|
+
module=module,
|
454
|
+
offload_device=offload_device,
|
455
|
+
onload_device=onload_device,
|
456
|
+
non_blocking=non_blocking,
|
457
|
+
stream=stream,
|
458
|
+
record_stream=record_stream,
|
459
|
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
460
|
+
)
|
461
|
+
else:
|
462
|
+
raise ValueError(f"Unsupported offload_type: {offload_type}")
|
463
|
+
|
464
|
+
|
465
|
+
def _apply_group_offloading_block_level(
|
466
|
+
module: torch.nn.Module,
|
467
|
+
num_blocks_per_group: int,
|
468
|
+
offload_device: torch.device,
|
469
|
+
onload_device: torch.device,
|
470
|
+
non_blocking: bool,
|
471
|
+
stream: Optional[torch.cuda.Stream] = None,
|
472
|
+
record_stream: Optional[bool] = False,
|
473
|
+
low_cpu_mem_usage: bool = False,
|
474
|
+
) -> None:
|
475
|
+
r"""
|
476
|
+
This function applies offloading to groups of torch.nn.ModuleList or torch.nn.Sequential blocks. In comparison to
|
477
|
+
the "leaf_level" offloading, which is more fine-grained, this offloading is done at the top-level blocks.
|
478
|
+
|
479
|
+
Args:
|
480
|
+
module (`torch.nn.Module`):
|
481
|
+
The module to which group offloading is applied.
|
482
|
+
offload_device (`torch.device`):
|
483
|
+
The device to which the group of modules are offloaded. This should typically be the CPU.
|
484
|
+
onload_device (`torch.device`):
|
485
|
+
The device to which the group of modules are onloaded.
|
486
|
+
non_blocking (`bool`):
|
487
|
+
If True, offloading and onloading is done asynchronously. This can be useful for overlapping computation
|
488
|
+
and data transfer.
|
489
|
+
stream (`torch.cuda.Stream`, *optional*):
|
490
|
+
If provided, offloading and onloading is done asynchronously using the provided stream. This can be useful
|
491
|
+
for overlapping computation and data transfer.
|
492
|
+
record_stream (`bool`, defaults to `False`): When enabled with `use_stream`, it marks the current tensor
|
493
|
+
as having been used by this stream. It is faster at the expense of slightly more memory usage. Refer to the
|
494
|
+
[PyTorch official docs](https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html) more
|
495
|
+
details.
|
496
|
+
low_cpu_mem_usage (`bool`, defaults to `False`):
|
497
|
+
If True, the CPU memory usage is minimized by pinning tensors on-the-fly instead of pre-pinning them. This
|
498
|
+
option only matters when using streamed CPU offloading (i.e. `use_stream=True`). This can be useful when
|
499
|
+
the CPU memory is a bottleneck but may counteract the benefits of using streams.
|
500
|
+
"""
|
501
|
+
|
502
|
+
# Create module groups for ModuleList and Sequential blocks
|
503
|
+
modules_with_group_offloading = set()
|
504
|
+
unmatched_modules = []
|
505
|
+
matched_module_groups = []
|
506
|
+
for name, submodule in module.named_children():
|
507
|
+
if not isinstance(submodule, (torch.nn.ModuleList, torch.nn.Sequential)):
|
508
|
+
unmatched_modules.append((name, submodule))
|
509
|
+
modules_with_group_offloading.add(name)
|
510
|
+
continue
|
511
|
+
|
512
|
+
for i in range(0, len(submodule), num_blocks_per_group):
|
513
|
+
current_modules = submodule[i : i + num_blocks_per_group]
|
514
|
+
group = ModuleGroup(
|
515
|
+
modules=current_modules,
|
516
|
+
offload_device=offload_device,
|
517
|
+
onload_device=onload_device,
|
518
|
+
offload_leader=current_modules[-1],
|
519
|
+
onload_leader=current_modules[0],
|
520
|
+
non_blocking=non_blocking,
|
521
|
+
stream=stream,
|
522
|
+
record_stream=record_stream,
|
523
|
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
524
|
+
onload_self=stream is None,
|
525
|
+
)
|
526
|
+
matched_module_groups.append(group)
|
527
|
+
for j in range(i, i + len(current_modules)):
|
528
|
+
modules_with_group_offloading.add(f"{name}.{j}")
|
529
|
+
|
530
|
+
# Apply group offloading hooks to the module groups
|
531
|
+
for i, group in enumerate(matched_module_groups):
|
532
|
+
next_group = (
|
533
|
+
matched_module_groups[i + 1] if i + 1 < len(matched_module_groups) and stream is not None else None
|
534
|
+
)
|
535
|
+
|
536
|
+
for group_module in group.modules:
|
537
|
+
_apply_group_offloading_hook(group_module, group, next_group)
|
538
|
+
|
539
|
+
# Parameters and Buffers of the top-level module need to be offloaded/onloaded separately
|
540
|
+
# when the forward pass of this module is called. This is because the top-level module is not
|
541
|
+
# part of any group (as doing so would lead to no VRAM savings).
|
542
|
+
parameters = _gather_parameters_with_no_group_offloading_parent(module, modules_with_group_offloading)
|
543
|
+
buffers = _gather_buffers_with_no_group_offloading_parent(module, modules_with_group_offloading)
|
544
|
+
parameters = [param for _, param in parameters]
|
545
|
+
buffers = [buffer for _, buffer in buffers]
|
546
|
+
|
547
|
+
# Create a group for the unmatched submodules of the top-level module so that they are on the correct
|
548
|
+
# device when the forward pass is called.
|
549
|
+
unmatched_modules = [unmatched_module for _, unmatched_module in unmatched_modules]
|
550
|
+
unmatched_group = ModuleGroup(
|
551
|
+
modules=unmatched_modules,
|
552
|
+
offload_device=offload_device,
|
553
|
+
onload_device=onload_device,
|
554
|
+
offload_leader=module,
|
555
|
+
onload_leader=module,
|
556
|
+
parameters=parameters,
|
557
|
+
buffers=buffers,
|
558
|
+
non_blocking=False,
|
559
|
+
stream=None,
|
560
|
+
record_stream=False,
|
561
|
+
onload_self=True,
|
562
|
+
)
|
563
|
+
next_group = matched_module_groups[0] if len(matched_module_groups) > 0 else None
|
564
|
+
_apply_group_offloading_hook(module, unmatched_group, next_group)
|
565
|
+
|
566
|
+
|
567
|
+
def _apply_group_offloading_leaf_level(
|
568
|
+
module: torch.nn.Module,
|
569
|
+
offload_device: torch.device,
|
570
|
+
onload_device: torch.device,
|
571
|
+
non_blocking: bool,
|
572
|
+
stream: Optional[torch.cuda.Stream] = None,
|
573
|
+
record_stream: Optional[bool] = False,
|
574
|
+
low_cpu_mem_usage: bool = False,
|
575
|
+
) -> None:
|
576
|
+
r"""
|
577
|
+
This function applies offloading to groups of leaf modules in a torch.nn.Module. This method has minimal memory
|
578
|
+
requirements. However, it can be slower compared to other offloading methods due to the excessive number of device
|
579
|
+
synchronizations. When using devices that support streams to overlap data transfer and computation, this method can
|
580
|
+
reduce memory usage without any performance degradation.
|
581
|
+
|
582
|
+
Args:
|
583
|
+
module (`torch.nn.Module`):
|
584
|
+
The module to which group offloading is applied.
|
585
|
+
offload_device (`torch.device`):
|
586
|
+
The device to which the group of modules are offloaded. This should typically be the CPU.
|
587
|
+
onload_device (`torch.device`):
|
588
|
+
The device to which the group of modules are onloaded.
|
589
|
+
non_blocking (`bool`):
|
590
|
+
If True, offloading and onloading is done asynchronously. This can be useful for overlapping computation
|
591
|
+
and data transfer.
|
592
|
+
stream (`torch.cuda.Stream`, *optional*):
|
593
|
+
If provided, offloading and onloading is done asynchronously using the provided stream. This can be useful
|
594
|
+
for overlapping computation and data transfer.
|
595
|
+
record_stream (`bool`, defaults to `False`): When enabled with `use_stream`, it marks the current tensor
|
596
|
+
as having been used by this stream. It is faster at the expense of slightly more memory usage. Refer to the
|
597
|
+
[PyTorch official docs](https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html) more
|
598
|
+
details.
|
599
|
+
low_cpu_mem_usage (`bool`, defaults to `False`):
|
600
|
+
If True, the CPU memory usage is minimized by pinning tensors on-the-fly instead of pre-pinning them. This
|
601
|
+
option only matters when using streamed CPU offloading (i.e. `use_stream=True`). This can be useful when
|
602
|
+
the CPU memory is a bottleneck but may counteract the benefits of using streams.
|
603
|
+
"""
|
604
|
+
|
605
|
+
# Create module groups for leaf modules and apply group offloading hooks
|
606
|
+
modules_with_group_offloading = set()
|
607
|
+
for name, submodule in module.named_modules():
|
608
|
+
if not isinstance(submodule, _SUPPORTED_PYTORCH_LAYERS):
|
609
|
+
continue
|
610
|
+
group = ModuleGroup(
|
611
|
+
modules=[submodule],
|
612
|
+
offload_device=offload_device,
|
613
|
+
onload_device=onload_device,
|
614
|
+
offload_leader=submodule,
|
615
|
+
onload_leader=submodule,
|
616
|
+
non_blocking=non_blocking,
|
617
|
+
stream=stream,
|
618
|
+
record_stream=record_stream,
|
619
|
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
620
|
+
onload_self=True,
|
621
|
+
)
|
622
|
+
_apply_group_offloading_hook(submodule, group, None)
|
623
|
+
modules_with_group_offloading.add(name)
|
624
|
+
|
625
|
+
# Parameters and Buffers at all non-leaf levels need to be offloaded/onloaded separately when the forward pass
|
626
|
+
# of the module is called
|
627
|
+
module_dict = dict(module.named_modules())
|
628
|
+
parameters = _gather_parameters_with_no_group_offloading_parent(module, modules_with_group_offloading)
|
629
|
+
buffers = _gather_buffers_with_no_group_offloading_parent(module, modules_with_group_offloading)
|
630
|
+
|
631
|
+
# Find closest module parent for each parameter and buffer, and attach group hooks
|
632
|
+
parent_to_parameters = {}
|
633
|
+
for name, param in parameters:
|
634
|
+
parent_name = _find_parent_module_in_module_dict(name, module_dict)
|
635
|
+
if parent_name in parent_to_parameters:
|
636
|
+
parent_to_parameters[parent_name].append(param)
|
637
|
+
else:
|
638
|
+
parent_to_parameters[parent_name] = [param]
|
639
|
+
|
640
|
+
parent_to_buffers = {}
|
641
|
+
for name, buffer in buffers:
|
642
|
+
parent_name = _find_parent_module_in_module_dict(name, module_dict)
|
643
|
+
if parent_name in parent_to_buffers:
|
644
|
+
parent_to_buffers[parent_name].append(buffer)
|
645
|
+
else:
|
646
|
+
parent_to_buffers[parent_name] = [buffer]
|
647
|
+
|
648
|
+
parent_names = set(parent_to_parameters.keys()) | set(parent_to_buffers.keys())
|
649
|
+
for name in parent_names:
|
650
|
+
parameters = parent_to_parameters.get(name, [])
|
651
|
+
buffers = parent_to_buffers.get(name, [])
|
652
|
+
parent_module = module_dict[name]
|
653
|
+
assert getattr(parent_module, "_diffusers_hook", None) is None
|
654
|
+
group = ModuleGroup(
|
655
|
+
modules=[],
|
656
|
+
offload_device=offload_device,
|
657
|
+
onload_device=onload_device,
|
658
|
+
offload_leader=parent_module,
|
659
|
+
onload_leader=parent_module,
|
660
|
+
parameters=parameters,
|
661
|
+
buffers=buffers,
|
662
|
+
non_blocking=non_blocking,
|
663
|
+
stream=stream,
|
664
|
+
record_stream=record_stream,
|
665
|
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
666
|
+
onload_self=True,
|
667
|
+
)
|
668
|
+
_apply_group_offloading_hook(parent_module, group, None)
|
669
|
+
|
670
|
+
if stream is not None:
|
671
|
+
# When using streams, we need to know the layer execution order for applying prefetching (to overlap data transfer
|
672
|
+
# and computation). Since we don't know the order beforehand, we apply a lazy prefetching hook that will find the
|
673
|
+
# execution order and apply prefetching in the correct order.
|
674
|
+
unmatched_group = ModuleGroup(
|
675
|
+
modules=[],
|
676
|
+
offload_device=offload_device,
|
677
|
+
onload_device=onload_device,
|
678
|
+
offload_leader=module,
|
679
|
+
onload_leader=module,
|
680
|
+
parameters=None,
|
681
|
+
buffers=None,
|
682
|
+
non_blocking=False,
|
683
|
+
stream=None,
|
684
|
+
record_stream=False,
|
685
|
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
686
|
+
onload_self=True,
|
687
|
+
)
|
688
|
+
_apply_lazy_group_offloading_hook(module, unmatched_group, None)
|
689
|
+
|
690
|
+
|
691
|
+
def _apply_group_offloading_hook(
|
692
|
+
module: torch.nn.Module,
|
693
|
+
group: ModuleGroup,
|
694
|
+
next_group: Optional[ModuleGroup] = None,
|
695
|
+
) -> None:
|
696
|
+
registry = HookRegistry.check_if_exists_or_initialize(module)
|
697
|
+
|
698
|
+
# We may have already registered a group offloading hook if the module had a torch.nn.Parameter whose parent
|
699
|
+
# is the current module. In such cases, we don't want to overwrite the existing group offloading hook.
|
700
|
+
if registry.get_hook(_GROUP_OFFLOADING) is None:
|
701
|
+
hook = GroupOffloadingHook(group, next_group)
|
702
|
+
registry.register_hook(hook, _GROUP_OFFLOADING)
|
703
|
+
|
704
|
+
|
705
|
+
def _apply_lazy_group_offloading_hook(
|
706
|
+
module: torch.nn.Module,
|
707
|
+
group: ModuleGroup,
|
708
|
+
next_group: Optional[ModuleGroup] = None,
|
709
|
+
) -> None:
|
710
|
+
registry = HookRegistry.check_if_exists_or_initialize(module)
|
711
|
+
|
712
|
+
# We may have already registered a group offloading hook if the module had a torch.nn.Parameter whose parent
|
713
|
+
# is the current module. In such cases, we don't want to overwrite the existing group offloading hook.
|
714
|
+
if registry.get_hook(_GROUP_OFFLOADING) is None:
|
715
|
+
hook = GroupOffloadingHook(group, next_group)
|
716
|
+
registry.register_hook(hook, _GROUP_OFFLOADING)
|
717
|
+
|
718
|
+
lazy_prefetch_hook = LazyPrefetchGroupOffloadingHook()
|
719
|
+
registry.register_hook(lazy_prefetch_hook, _LAZY_PREFETCH_GROUP_OFFLOADING)
|
720
|
+
|
721
|
+
|
722
|
+
def _gather_parameters_with_no_group_offloading_parent(
|
723
|
+
module: torch.nn.Module, modules_with_group_offloading: Set[str]
|
724
|
+
) -> List[torch.nn.Parameter]:
|
725
|
+
parameters = []
|
726
|
+
for name, parameter in module.named_parameters():
|
727
|
+
has_parent_with_group_offloading = False
|
728
|
+
atoms = name.split(".")
|
729
|
+
while len(atoms) > 0:
|
730
|
+
parent_name = ".".join(atoms)
|
731
|
+
if parent_name in modules_with_group_offloading:
|
732
|
+
has_parent_with_group_offloading = True
|
733
|
+
break
|
734
|
+
atoms.pop()
|
735
|
+
if not has_parent_with_group_offloading:
|
736
|
+
parameters.append((name, parameter))
|
737
|
+
return parameters
|
738
|
+
|
739
|
+
|
740
|
+
def _gather_buffers_with_no_group_offloading_parent(
|
741
|
+
module: torch.nn.Module, modules_with_group_offloading: Set[str]
|
742
|
+
) -> List[torch.Tensor]:
|
743
|
+
buffers = []
|
744
|
+
for name, buffer in module.named_buffers():
|
745
|
+
has_parent_with_group_offloading = False
|
746
|
+
atoms = name.split(".")
|
747
|
+
while len(atoms) > 0:
|
748
|
+
parent_name = ".".join(atoms)
|
749
|
+
if parent_name in modules_with_group_offloading:
|
750
|
+
has_parent_with_group_offloading = True
|
751
|
+
break
|
752
|
+
atoms.pop()
|
753
|
+
if not has_parent_with_group_offloading:
|
754
|
+
buffers.append((name, buffer))
|
755
|
+
return buffers
|
756
|
+
|
757
|
+
|
758
|
+
def _find_parent_module_in_module_dict(name: str, module_dict: Dict[str, torch.nn.Module]) -> str:
|
759
|
+
atoms = name.split(".")
|
760
|
+
while len(atoms) > 0:
|
761
|
+
parent_name = ".".join(atoms)
|
762
|
+
if parent_name in module_dict:
|
763
|
+
return parent_name
|
764
|
+
atoms.pop()
|
765
|
+
return ""
|
766
|
+
|
767
|
+
|
768
|
+
def _raise_error_if_accelerate_model_or_sequential_hook_present(module: torch.nn.Module) -> None:
|
769
|
+
if not is_accelerate_available():
|
770
|
+
return
|
771
|
+
for name, submodule in module.named_modules():
|
772
|
+
if not hasattr(submodule, "_hf_hook"):
|
773
|
+
continue
|
774
|
+
if isinstance(submodule._hf_hook, (AlignDevicesHook, CpuOffload)):
|
775
|
+
raise ValueError(
|
776
|
+
f"Cannot apply group offloading to a module that is already applying an alternative "
|
777
|
+
f"offloading strategy from Accelerate. If you want to apply group offloading, please "
|
778
|
+
f"disable the existing offloading strategy first. Offending module: {name} ({type(submodule)})"
|
779
|
+
)
|
780
|
+
|
781
|
+
|
782
|
+
def _is_group_offload_enabled(module: torch.nn.Module) -> bool:
|
783
|
+
for submodule in module.modules():
|
784
|
+
if hasattr(submodule, "_diffusers_hook") and submodule._diffusers_hook.get_hook(_GROUP_OFFLOADING) is not None:
|
785
|
+
return True
|
786
|
+
return False
|
787
|
+
|
788
|
+
|
789
|
+
def _get_group_onload_device(module: torch.nn.Module) -> torch.device:
|
790
|
+
for submodule in module.modules():
|
791
|
+
if hasattr(submodule, "_diffusers_hook") and submodule._diffusers_hook.get_hook(_GROUP_OFFLOADING) is not None:
|
792
|
+
return submodule._diffusers_hook.get_hook(_GROUP_OFFLOADING).group.onload_device
|
793
|
+
raise ValueError("Group offloading is not enabled for the provided module.")
|