Ë
    (täi,�  ã            
       ó¦  — d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ d dl	Z	d dl
Z
ddlmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZ d	d
lmZmZ d	dl m!Z!  ejD                  e#«      Z$i de!“de!“dd„ “dd„ “dd„ “dd„ “dd„ “dd„ “dd„ “dd„ “dd„ “d d!„ “d"d#„ “d$d%„ “d&d'„ “d(d)„ “d*d+„ “d,„ d-„ d.„ d/„ d0„ d1„ d2„ d3„ d4œ¥Z% G d5„ d6«      Z&y)7é    N)Úpartial)ÚPath)ÚLiteralé   ©Ú*_maybe_remove_and_reapply_group_offloading)ÚMIN_PEFT_VERSIONÚUSE_PEFT_BACKENDÚcheck_peft_versionÚ.convert_sai_sd_control_lora_state_dict_to_peftÚconvert_unet_state_dict_to_peftÚdelete_adapter_layersÚget_adapter_nameÚis_peft_availableÚis_peft_versionÚloggingÚset_adapter_layersÚ!set_weights_and_activate_adapters)Ú_create_lora_configÚ_maybe_warn_for_unhandled_keysé   )Ú_fetch_state_dictÚ#_func_optionally_disable_offloading)Ú_maybe_expand_lora_scalesÚUNet2DConditionModelÚUNetMotionModelÚSD3Transformer2DModelc                 ó   — |S ©N© ©Ú	model_clsÚweightss     úe/Volumes/fast/ai/experiments/MLX_z-image/.venv/lib/python3.12/site-packages/diffusers/loaders/peft.pyÚ<lambda>r%   2   ó   € ¹ó    ÚFluxTransformer2DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   3   ó   € ¹r'   ÚCogVideoXTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   4   ó   € ¹gr'   ÚConsisIDTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   5   ó   € ¹Wr'   ÚHeliosTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   6   ó   € ¹7r'   ÚMochiTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   7   ó   € ¹'r'   ÚHunyuanVideoTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   8   ó   € Ár'   ÚLTXVideoTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   9   r0   r'   ÚSanaTransformer2DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   :   r*   r'   ÚAuraFlowTransformer2DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   ;   r0   r'   ÚLumina2Transformer2DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   <   ó   € ¹Gr'   ÚWanTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   =   r&   r'   ÚCogView4Transformer2DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   >   r0   r'   ÚHiDreamImageTransformer2DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   ?   r9   r'   Ú'HunyuanVideoFramepackTransformer3DModelc                 ó   — |S r   r    r!   s     r$   r%   r%   @   s   € É'r'   c                 ó   — |S r   r    r!   s     r$   r%   r%   A   rB   r'   c                 ó   — |S r   r    r!   s     r$   r%   r%   B   r3   r'   c                 ó   — |S r   r    r!   s     r$   r%   r%   C   s   € ¹wr'   c                 ó   — |S r   r    r!   s     r$   r%   r%   D   r-   r'   c                 ó   — |S r   r    r!   s     r$   r%   r%   E   r6   r'   c                 ó   — |S r   r    r!   s     r$   r%   r%   F   r3   r'   c                 ó   — |S r   r    r!   s     r$   r%   r%   G   r-   r'   c                 ó   — |S r   r    r!   s     r$   r%   r%   H   s   € ±Wr'   )ÚWanVACETransformer3DModelÚChromaTransformer2DModelÚChronoEditTransformer3DModelÚQwenImageTransformer2DModelÚFlux2Transformer2DModelÚZImageTransformer2DModelÚLTX2VideoTransformer3DModelÚLTX2TextConnectorsc            
       óv  — e Zd ZU dZdZdZedz  ed<   ed„ «       Z		 d"de
fd„Z	 	 	 	 d#ded	e
d
e
dedz  fd„Z	 d$dee   ez  deez  ee   z  ee   z  ed   z  dz  fd„Zd%deddfd„Zdeee   z  ddfd„Zd&d„Zd&d„Zdee   fd„Zd'd„Zd$d„Zd„ Zd„ Zd„ Zd„ Zd„ Zdee   ez  fd„Z	 d(deded    ddfd!„Z y))ÚPeftAdapterMixina  
    A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
    more details about adapters and injecting them in a base model, check out the PEFT
    [documentation](https://huggingface.co/docs/peft/index).

    Install the latest version of PEFT, and use this mixin to:

    - Attach new adapters in the model.
    - Attach multiple adapters and iteratively activate/deactivate them.
    - Activate/deactivate all adapters from the model.
    - Get a list of the active adapters.
    FNÚ_prepare_lora_hotswap_kwargsc                 ó   — t        |¬«      S )N)Ú	_pipeline)r   )Úclsr_   s     r$   Ú_optionally_disable_offloadingz/PeftAdapterMixin._optionally_disable_offloading^   s   € ô 3¸YÔGÐGr'   Úhotswapc                 óŽ  ‡2— ddl m}m} ddlm} ddlm} |j                  dd«      }	|j                  dd	«      }
|j                  d
d«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      Š2|j                  dd«      }|j                  dd«      }|j                  dd	«      }|j                  dd«      }d	}|rt        dd«      rt        d«      ‚dddœ}t        |||||	|
|||||||¬«      \  }}|�|€t        d«      ‚|r|rt        d«      ‚|�–|j                  «       D ��ci c]/  \  }}|j                  |› d�«      sŒ|j                  |› d�«      |“Œ1 }}}|�J|j                  «       D ��ci c]/  \  }}|j                  |› d�«      sŒ|j                  |› d�«      |“Œ1 }}}t        |«      dkD  �r‰2t        | d i «      v r|st        d!‰2› d"�«      ‚‰2t        | d i «      vr|rt        d#‰2› d$�«      ‚t!        t#        |j%                  «       «      «      }d%|vrt'        |«      }d&|v }|rt)        |«      }i }|j                  «       D ]/  \  }}d'|v sŒ|j*                  d(kD  sŒ|j,                  d(   |d)|› �<   Œ1 |�zt        |«      d(k\  rl|j%                  «       D �cg c]  }|j                  |› d�«      sŒ|‘Œ } }|j                  «       D ��ci c]  \  }}|| v sŒ|j                  |› d�«      |“Œ! }}}‰2€t/        | «      Š2t1        ||||| j3                  «       ‰2¬*«      }!|rA|!j4                  |!_        |!j8                  |!_        d+|!_        |!j>                  |!_         d|!_        | jC                  |«      \  }"}#}$i }%t        d,d-«      r||%d<   |s| jD                  �$t        d.d/«      rdd0l#m$}&m%}'m&}( nd1})tO        |)«      ‚|rˆ2fd2„}*	 |r. *|«      } &| jP                  ‰2   |!«       	  '| |‰2|!¬3«       d},n@ ||!| f‰2|d6œ|%¤Ž  || |‰2fi |%¤Ž},| jD                  � (| fd7|!i| jD                  ¤Ž d| _"        | jX                  sd8| _,        te        |,‰2«       |"r|jg                  «        na|#r|ji                  «        nN|$rL|jj                  jm                  «       D ]/  }0t_        |0tn        jp                  jr                  «      sŒ( ||0«       Œ1 |�9|s6| jt                  jv                  }1tT        jy                  d:|1› d;|›d<|1› d=�«       yyyc c}}w c c}}w c c}w c c}}w # tR        $ r!}+tT        jW                  d4‰2› d5|+› �«       ‚ d}+~+ww xY w# tR        $ r“}+t[        | d «      rf| j]                  «       D ]8  }-t_        |-|«      sŒ|-j`                  }.|.D ]  }/‰2|/v sŒ|-jc                  ‰2«       Œ Œ: | jP                  j                  ‰2«       tT        jW                  d9‰2› d5|+› �«       ‚ d}+~+ww xY w)>ah  
        Loads a LoRA adapter into the underlying model.

        Parameters:
            pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
                Can be either:

                    - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
                      the Hub.
                    - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
                      with [`ModelMixin.save_pretrained`].
                    - A [torch state
                      dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

            prefix (`str`, *optional*): Prefix to filter the state dict.

            cache_dir (`str | os.PathLike`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
            token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            network_alphas (`dict[str, float]`):
                The value of the network alpha used for stable learning and preventing underflow. This value has the
                same meaning as the `--network_alpha` option in the kohya-ss trainer script. Refer to [this
                link](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning).
            low_cpu_mem_usage (`bool`, *optional*):
                Speed up model loading by only loading the pretrained LoRA weights and not initializing the random
                weights.
            hotswap : (`bool`, *optional*)
                Defaults to `False`. Whether to substitute an existing (LoRA) adapter with the newly loaded adapter
                in-place. This means that, instead of loading an additional adapter, this will take the existing
                adapter weights and replace them with the weights of the new adapter. This can be faster and more
                memory efficient. However, the main advantage of hotswapping is that when the model is compiled with
                torch.compile, loading the new adapter does not require recompilation of the model. When using
                hotswapping, the passed `adapter_name` should be the name of an already loaded adapter.

                If the new adapter and the old adapter have different ranks and/or LoRA alphas (i.e. scaling), you need
                to call an additional method before loading the adapter:

                ```py
                pipeline = ...  # load diffusers pipeline
                max_rank = ...  # the highest rank among all LoRAs that you want to load
                # call *before* compiling and loading the LoRA adapter
                pipeline.enable_lora_hotswap(target_rank=max_rank)
                pipeline.load_lora_weights(file_name)
                # optionally compile the model now
                ```

                Note that hotswapping adapters of the text encoder is not yet supported. There are some further
                limitations to this technique, which are documented here:
                https://huggingface.co/docs/peft/main/en/package_reference/hotswap
            metadata:
                LoRA adapter metadata. When supplied, the metadata inferred through the state dict isn't used to
                initialize `LoraConfig`.
        r   )Úinject_adapter_in_modelÚset_peft_model_state_dict©ÚBaseTunerLayerr   r   Ú	cache_dirNÚforce_downloadFÚproxiesÚlocal_files_onlyÚtokenÚrevisionÚ	subfolderÚweight_nameÚuse_safetensorsÚadapter_nameÚnetwork_alphasr_   Úlow_cpu_mem_usageÚmetadataz<=z0.13.0zq`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`.Úattn_procs_weightsÚpytorch)Ú	file_typeÚ	framework)Ú%pretrained_model_name_or_path_or_dictro   rp   rk   rh   ri   rj   rl   rm   rn   Ú
user_agentÚallow_picklert   z6`network_alphas` cannot be None when `prefix` is None.z9Both `network_alphas` and `metadata` cannot be specified.Ú.Úpeft_configúAdapter name z@ already in use in the model - please select a new adapter name.z Trying to hotswap LoRA adapter 'z†' but there is no existing adapter by that name. Please choose an existing adapter name or set `hotswap=False` to prevent hotswapping.Úlora_AÚlora_controlnetÚlora_Br   Ú^)Úmodel_state_dictrq   Úallz>=z0.13.1Ú>z0.14.0)Ú check_hotswap_configs_compatibleÚhotswap_adapter_from_state_dictÚ"prepare_model_for_compiled_hotswapzeHotswapping requires PEFT > v0.14. Please upgrade PEFT to a higher version or install it from source.c                 ó  •— i }| j                  «       D ]j  \  }}|j                  d«      s|j                  d«      r|d t        d«        d‰› d�z   }n'|j                  d«      r|d t        d«        d‰› d�z   }|||<   Œl |S )Nzlora_A.weightzlora_B.weightz.weightr|   zlora_B.biasz.bias)ÚitemsÚendswithÚlen)ÚsdÚnew_sdÚkÚvrq   s       €r$   Úmap_state_dict_for_hotswapzFPeftAdapterMixin.load_lora_adapter.<locals>.map_state_dict_for_hotswap;  s�   ø€ à�FØ "§¡¦
™˜˜1ØŸ:™: oÔ6¸!¿*¹*À_Ô:UØ !Ð"3¤S¨£^ OÐ 4¸¸<¸.ÈÐ7PÑ P™AØŸZ™Z¨Ô6Ø ! /¤S¨£\ MÐ 2°q¸¸ÀeÐ5LÑ L˜AØ$%˜˜qš	ð !+ð "�Mr'   )ÚmodelÚ
state_dictrq   ÚconfigzHotswapping z- was unsuccessful with the following error: 
)rq   r“   r”   TzLoading zNo LoRA keys associated to z found with the prefix=zG. This is safe to ignore if LoRA state dict didn't originally have any z½ related params. You can also try specifying `prefix=None` to resolve the warning. Otherwise, open an issue if you think it's unexpected: https://github.com/huggingface/diffusers/issues/new)=Úpeftrd   re   Úpeft.tuners.tuners_utilsrg   Úhooks.group_offloadingr   Úpopr   Ú
ValueErrorr   rŠ   Ú
startswithÚremoveprefixrŒ   ÚgetattrÚnextÚiterÚkeysr   r   ÚndimÚshaper   r   r“   ÚrÚ
lora_alphaÚrank_patternÚalpha_patternÚbiasÚexclude_modulesÚmodules_to_savera   r]   Úpeft.utils.hotswapr†   r‡   rˆ   ÚImportErrorr}   Ú	ExceptionÚloggerÚerrorÚ_hf_peft_config_loadedÚhasattrÚmodulesÚ
isinstanceÚactive_adaptersÚdelete_adapterr   Úenable_model_cpu_offloadÚenable_sequential_cpu_offloadÚ
componentsÚvaluesÚtorchÚnnÚModuleÚ	__class__Ú__name__Úwarning)3Úselfry   Úprefixrb   Úkwargsrd   re   rg   r   rh   ri   rj   rk   rl   rm   rn   ro   rp   rr   r_   rs   rt   r{   rz   r“   r�   r�   Ú	first_keyÚis_sai_sd_control_loraÚrankÚkeyÚvalÚ
alpha_keysÚlora_configÚis_model_cpu_offloadÚis_sequential_cpu_offloadÚis_group_offloadÚpeft_kwargsr†   r‡   rˆ   Úmsgr‘   ÚeÚincompatible_keysÚmoduler²   Úactive_adapterÚ	componentÚmodel_class_namerq   s3                                                     @r$   Úload_lora_adapterz"PeftAdapterMixin.load_lora_adapterc   s  ø€ ÷R 	LÝ;åWà—J‘J˜{¨DÓ1ˆ	ØŸ™Ð$4°eÓ<ˆØ—*‘*˜Y¨Ó-ˆØ!Ÿ:™:Ð&8¸$Ó?ÐØ—
‘
˜7 DÓ)ˆØ—:‘:˜j¨$Ó/ˆØ—J‘J˜{¨DÓ1ˆ	Ø—j‘j °Ó5ˆØ Ÿ*™*Ð%6¸Ó=ˆØ—z‘z .°$Ó7ˆØŸ™Ð$4°dÓ;ˆØ—J‘J˜{¨DÓ1ˆ	Ø"ŸJ™JÐ':¸EÓBÐØ—:‘:˜j¨$Ó/ˆØˆá¤°°xÔ!@Üð Dóð ð $8ÀiÑPˆ
Ü0Ø2WØ#Ø+Ø-ØØ)ØØØØØ!Ø%Øô 
Ñˆ
�Hð Ð%¨&¨.ÜÐUÓVÐVÙ™hÜÐXÓYÐYàÐØFP×FVÑFVÔFXÔwÑFX¹d¸aÀÐ\]×\hÑ\hÐlrÐksÐstÐiuÕ\v˜!Ÿ.™.¨F¨8°1¨Ó6¸Ñ9ÐFXˆJÑwØÐ#ØHPÏÉÔHXÔwÑHXÁÀÀ1Ð\]×\hÑ\hÐlrÐksÐstÐiuÕ\v˜AŸN™N¨f¨X°Q¨<Ó8¸!Ñ;ÐHX�Ñwäˆz‹?˜QÓØœw t¨]¸BÓ?Ñ?ÉÜ Ø# L >Ð1qÐróð ð ¤W¨T°=À"Ó%EÑEÉ'Ü Ø6°|°nð Elð lóð ô œT *§/¡/Ó"3Ó4Ó5ˆIØ˜yÑ(Ü<¸ZÓH�
ð
 &7¸*Ð%DÐ"Ù%ÜKÈJÓW�
àˆDØ&×,Ñ,Ö.‘��Sð ˜s’? s§x¡x°!£|ð
 '*§i¡i°¡l�D˜1˜S˜E˜’Oð /ð Ð)¬c°.Ó.AÀQÒ.FØ)7×)<Ñ)<Ô)>Ó]Ñ)> AÀ!Ç,Á,ÐRXÐQYÐYZÈ|ÕB\šaÐ)>�
Ð]à@N×@TÑ@TÔ@Vô"Ù@V¹¸¸1ÐZ[Ð_iÒZi�A—N‘N f X¨Q <Ó0°!Ñ3Ð@Vð ñ "ð
 Ð#Ü/°Ó5�ô .ØØØØØ!%§¡Ó!2Ø)ôˆKñ &Ø)4¯©�Ô&Ø,7×,DÑ,D�Ô)Ø#(�Ô Ø.9×.IÑ.I�Ô+Ø.2�Ô+ð QU×PsÑPsØóQÑMÐ Ð";Ð=Mð ˆKÜ˜t XÔ.Ø3D�Ð/Ñ0á˜4×<Ñ<ÐHÜ" 3¨Ô1÷ò ð'ð ô & cÓ*Ð*áô	"ð2ÙÙ!;¸JÓ!G�JÙ4°T×5EÑ5EÀlÑ5SÐU`Ôað	Ù7Ø"&Ø'1Ø)5Ø#.õ	ð )-Ñ%á+Ø# TðØ8DÐQ[ñØ_jòñ )BÀ$È
ÐT`Ñ(pÐdoÑ(pÐ%à×8Ñ8ÐDñ ;Ø ñØ)4ðØ8<×8YÑ8Yòð =A˜Ô9ð ×2Ò2Ø26�DÔ/ô +Ð+<¸lÔKñ $Ø×2Ñ2Õ4Ù*Ø×7Ñ7Õ9Ù!Ø!*×!5Ñ!5×!<Ñ!<Ö!>�IÜ! )¬U¯X©X¯_©_Õ=ÙBÀ9ÕMð "?ð
 Ð¡jØ#Ÿ~™~×6Ñ6ÐÜ�N‰NØ-Ð.>Ð-?Ð?WÐPVÈyð YXà#Ð$ð %FðFõð '1Ðùó[ xùãwùòJ ^ùó"øô^ %ò ÜŸ™ |°L°>ÐAoÐpqÐorÐ%sÔtØûðûô6 ò ä˜4 Ô/Ø"&§,¡,¦.˜Ü% f¨nÕ=Ø.4×.DÑ.D˜OÛ2A Ø#/°>Ò#AØ$*×$9Ñ$9¸,Õ$Gñ 3Bð #1ð ×$Ñ$×(Ñ(¨Ô6Ü—‘˜x¨ ~Ð5cÐdeÐcfÐgÔhØûðúsz   Æ U$ÆU$ÇU*Ç)U*Ë:U0ÌU0Ì-U5Ì:U5Ð% V( ÑU; ÑAV( Õ;	V%ÖV Ö V%Ö%V( Ö(	YÖ1+X?×X?×3AX?Ø?Yrq   Úupcast_before_savingÚsafe_serializationro   c                 óT  ‡‡— ddl m} ddlmŠm}m} |€t        | «      }|t        | di «      vrt        d|› d�«      ‚| j                  |   j                  «       Š || j                  |rt        j                  nd¬	«      |¬
«      }	t        j                  j!                  |«      rt        d|› d�«      ‚|rˆˆfd„}
nt        j"                  }
t        j$                  |d¬«       |€|r|}n|}t'        ||«      j)                  «       } |
|	|«       t*        j-                  d|› �«       y)al  
        Save the LoRA parameters corresponding to the underlying model.

        Arguments:
            save_directory (`str` or `os.PathLike`):
                Directory to save LoRA parameters to. Will be created if it doesn't exist.
            adapter_name: (`str`, defaults to "default"): The name of the adapter to serialize. Useful when the
                underlying model has multiple adapters loaded.
            upcast_before_saving (`bool`, defaults to `False`):
                Whether to cast the underlying model to `torch.float32` before serialization.
            safe_serialization (`bool`, *optional*, defaults to `True`):
                Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
            weight_name: (`str`, *optional*, defaults to `None`): Name of the file to serialize the state dict with.
        r   )Úget_peft_model_state_dictr   )ÚLORA_ADAPTER_METADATA_KEYÚLORA_WEIGHT_NAMEÚLORA_WEIGHT_NAME_SAFENr}   r~   z not found in the model.)Údtype)rq   zProvided path (z#) should be a directory, not a filec                 óø   •— ddi}‰�R‰j                  «       D ]$  \  }}t        |t        «      sŒt        |«      ‰|<   Œ& t	        j
                  ‰dd¬«      |‰<   t        j                  j                  | ||¬«      S )NÚformatÚptr   T)ÚindentÚ	sort_keys)rt   )	rŠ   r±   ÚsetÚlistÚjsonÚdumpsÚsafetensorsr¸   Ú	save_file)r#   Úfilenamert   rÄ   ÚvaluerØ   Úlora_adapter_metadatas        €€r$   Úsave_functionz9PeftAdapterMixin.save_lora_adapter.<locals>.save_function½  s   ø€ à$ dÐ+�Ø(Ð4Ø&;×&AÑ&AÖ&C™
˜˜UÜ% e¬SÕ1Ü9=¸e»Ð1°#Ò6ð 'Dô ;?¿*¹*ÐEZÐcdÐptÔ:u�HÐ6Ñ7ä"×(Ñ(×2Ñ2°7¸HÈxÐ2ÓXÐXr'   T)Úexist_okzModel weights saved in )Ú
peft.utilsr×   Ú	lora_baserØ   rÙ   rÚ   r   rœ   r™   r}   Úto_dictÚtor¸   Úfloat32ÚosÚpathÚisfileÚsaveÚmakedirsr   Úas_posixr¬   Úinfo)r¾   Úsave_directoryrq   rÔ   rÕ   ro   r×   rÙ   rÚ   Úlora_layers_to_saverê   Ú	save_pathrØ   ré   s               @@r$   Úsave_lora_adapterz"PeftAdapterMixin.save_lora_adapter“  s  ù€ õ, 	9çaÑaàÐÜ+¨DÓ1ˆLàœw t¨]¸BÓ?Ñ?Ü˜}¨\¨NÐ:RÐSÓTÐTà $× 0Ñ 0°Ñ >× FÑ FÓ HÐá7Ø�G‰GÑ+?œ%Ÿ-š-ÀTˆGÓJÐYeô
Ðô �7‰7�>‰>˜.Ô)Ü˜¨~Ð.>Ð>aÐbÓcÐcáö	Yô "ŸJ™JˆMä
�‰�N¨TÕ2àÐÙ!Ø3‘à.�ä˜¨Ó5×>Ñ>Ó@ˆ	ÙÐ)¨9Ô5Ü�‰Ð-¨i¨[Ð9Õ:r'   Úadapter_namesr#   c                 óš  — t         st        d«      ‚t        |t        «      r|gn|}t        |t        «      s|gt        |«      z  }t        |«      t        |«      k7  r$t        dt        |«      › dt        |«      › d�«      ‚|D �cg c]  }|�|nd‘Œ
 }}t        | j                  j                     } || |«      }t        | ||«       yc c}w )a:  
        Set the currently active adapters for use in the diffusion network (e.g. unet, transformer, etc.).

        Args:
            adapter_names (`list[str]` or `str`):
                The names of the adapters to use.
            weights (`Union[List[float], float]`, *optional*):
                The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
                adapters.

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
        pipeline.unet.set_adapters(["cinematic", "pixel"], weights=[0.5, 0.5])
        ```
        z.PEFT backend is required for `set_adapters()`.zLength of adapter names z- is not equal to the length of their weights r|   Nç      ð?)
r
   r™   r±   Ústrrâ   rŒ   Ú_SET_ADAPTER_SCALE_FN_MAPPINGr»   r¼   r   )r¾   rü   r#   ÚwÚscale_expansion_fns        r$   Úset_adapterszPeftAdapterMixin.set_adapters×  s×   € õ>  ÜÐMÓNÐNä+5°mÄSÔ+I˜™È}ˆô ˜'¤4Ô(Ø�i¤# mÓ"4Ñ4ˆGäˆ}Ó¤ W£Ò-ÜØ*¬3¨}Ó+=Ð*>Ð>kÔloÐpwÓlxÐkyÐyzÐ{óð ñ 9@Ó@¹°1˜˜‘1¨3Ñ.¸ˆÐ@ô ;¸4¿>¹>×;RÑ;RÑSÐÙ$ T¨7Ó3ˆä)¨$°¸wÕGùò As   ÂCÚreturnc                 óL  — t        t        ¬«       t        «       st        d«      ‚ddlm}m} | j                  sd| _        n|| j                  v rt        d|› d�«      ‚t        ||«      st        dt        |«      › d	�«      ‚d
|_         ||| |«       | j                  |«       y
)aü  
        Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
        to the adapter to follow the convention of the PEFT library.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
        [documentation](https://huggingface.co/docs/peft).

        Args:
            adapter_config (`[~peft.PeftConfig]`):
                The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
                methods.
            adapter_name (`str`, *optional*, defaults to `"default"`):
                The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
        ©Úmin_versionúTPEFT is not available. Please install PEFT to use this function: `pip install peft`.r   )Ú
PeftConfigrd   TzAdapter with name z- already exists. Please use a different name.z8adapter_config should be an instance of PeftConfig. Got z	 instead.N)r   r	   r   rª   r•   r	  rd   r®   r}   r™   r±   ÚtypeÚbase_model_name_or_pathÚset_adapter)r¾   Úadapter_configrq   r	  rd   s        r$   Úadd_adapterzPeftAdapterMixin.add_adapter  s¦   € ô 	Ô'7Õ8ä Ô"ÜÐtÓuÐuç<à×*Ò*Ø*.ˆDÕ'Ø˜T×-Ñ-Ñ-ÜÐ1°,°Ð?lÐmÓnÐnä˜.¨*Ô5ÜØJÌ4ÐP^ÓK_ÐJ`Ð`iÐjóð ð 26ˆÔ.Ù °°lÔCØ×Ñ˜Õ&r'   c           	      ód  — t        t        ¬«       | j                  st        d«      ‚t	        |t
        «      r|g}t        |«      t        | j                  «      z
  }t        |«      dkD  rAt        ddj                  |«      › dt        | j                  j                  «       «      › �«      ‚ddlm} d}| j                  «       D ]^  \  }}t	        ||«      sŒt        |d	«      r|j!                  |«       n,t        |d	«      st        |«      d
k7  rt        d«      ‚||_        d}Œ` |st        d«      ‚y)aÃ  
        Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).

        Args:
            adapter_name (str | list[str])):
                The list of adapters to set or the adapter name in the case of a single adapter.
        r  ú0No adapter loaded. Please load an adapter first.r   z)Following adapter(s) could not be found: z, zV. Make sure you are passing the correct adapter name(s). current loaded adapters are: rf   Fr  r   zöYou are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT. `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`TzhDid not succeeded in setting the adapter. Please make sure you are using a model that supports adapters.N)r   r	   r®   r™   r±   rÿ   rá   r}   rŒ   Újoinrâ   rŸ   r–   rg   Únamed_modulesr¯   r  rÐ   )r¾   rq   Úmissingrg   Ú_adapters_has_been_setÚ_rÏ   s          r$   r  zPeftAdapterMixin.set_adapter5  s5  € ô 	Ô'7Õ8à×*Ò*ÜÐOÓPÐPä�l¤CÔ(Ø(˜>ˆLä�lÓ#¤c¨$×*:Ñ*:Ó&;Ñ;ˆÜˆw‹<˜!ÒÜØ;¸D¿I¹IÀgÓ<NÐ;Oð P1Ü15°d×6FÑ6F×6KÑ6KÓ6MÓ1NÐ0OðQóð õ
 	<à!&Ðà×+Ñ+Ö-‰IˆAˆvÜ˜& .Õ1Ü˜6 =Ô1Ø×&Ñ& |Õ4ä  ¨Ô7¼CÀÓ<MÐQRÒ<RÜ$ðqóð ð
 -9�FÔ)Ø)-Ñ&ð .ñ &ÜØzóð ð &r'   c                 óô   — t        t        ¬«       | j                  st        d«      ‚ddlm} | j                  «       D ]8  \  }}t        ||«      sŒt        |d«      r|j                  d¬«       Œ2d|_
        Œ: y	)
a  
        Disable all adapters attached to the model and fallback to inference with the base model only.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        r  r  r   rf   Úenable_adaptersF©ÚenabledTN©r   r	   r®   r™   r–   rg   r  r±   r¯   r  Údisable_adapters©r¾   rg   r  rÏ   s       r$   r  z!PeftAdapterMixin.disable_adaptersf  sl   € ô 	Ô'7Õ8à×*Ò*ÜÐOÓPÐPå;à×+Ñ+Ö-‰IˆAˆvÜ˜& .Õ1Ü˜6Ð#4Ô5Ø×*Ñ*°5Ð*Õ9ð /3�FÕ+ñ .r'   c                 óô   — t        t        ¬«       | j                  st        d«      ‚ddlm} | j                  «       D ]8  \  }}t        ||«      sŒt        |d«      r|j                  d¬«       Œ2d|_
        Œ: y	)
aK  
        Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the list of
        adapters to enable.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        r  r  r   rf   r  Tr  FNr  r  s       r$   r  z PeftAdapterMixin.enable_adapters|  sl   € ô 	Ô'7Õ8à×*Ò*ÜÐOÓPÐPå;à×+Ñ+Ö-‰IˆAˆvÜ˜& .Õ1Ü˜6Ð#4Ô5Ø×*Ñ*°4Ð*Õ8ð /4�FÕ+ñ .r'   c                 óì   — t        t        ¬«       t        «       st        d«      ‚| j                  st        d«      ‚ddlm} | j                  «       D ]  \  }}t        ||«      sŒ|j                  c S  y)zö
        Gets the current list of active adapters of the model.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        r  r  r  r   rf   N)r   r	   r   rª   r®   r™   r–   rg   r  r±   rÐ   r  s       r$   r²   z PeftAdapterMixin.active_adapters“  sd   € ô 	Ô'7Õ8ä Ô"ÜÐtÓuÐuà×*Ò*ÜÐOÓPÐPå;à×+Ñ+Ö-‰IˆAˆvÜ˜& .Õ1Ø×,Ñ,Ò,ñ .r'   c                 óŽ   — t         st        d«      ‚|| _        || _        | j	                  t        | j                  |¬«      «       y )Nz+PEFT backend is required for `fuse_lora()`.)rü   )r
   r™   Ú
lora_scaleÚ_safe_fusingÚapplyr   Ú_fuse_lora_apply)r¾   r   Úsafe_fusingrü   s       r$   Ú	fuse_lorazPeftAdapterMixin.fuse_lora¨  s9   € ÝÜÐJÓKÐKà$ˆŒØ'ˆÔØ�
‰
”7˜4×0Ñ0ÀÔNÕOr'   c                 óX  — ddl m} d| j                  i}t        ||«      rŠ| j                  dk7  r|j                  | j                  «       t        t        j                  |j                  «      j                  «      }d|v r||d<   nd|vr|�t        d«      ‚ |j                  di |¤Ž y y )Nr   rf   Ú
safe_mergerþ   rü   z‰The `adapter_names` argument is not supported with your PEFT version. Please upgrade to the latest version of PEFT. `pip install -U peft`r    )r–   rg   r!  r±   r   Úscale_layerrâ   ÚinspectÚ	signatureÚmergeÚ
parametersr™   )r¾   rÏ   rü   rg   Úmerge_kwargsÚsupported_merge_kwargss         r$   r#  z!PeftAdapterMixin._fuse_lora_apply°  s«   € Ý;à$ d×&7Ñ&7Ð8ˆä�f˜nÔ-Ø�‰ #Ò%Ø×"Ñ" 4§?¡?Ô3ô &*¬'×*;Ñ*;¸F¿L¹LÓ*I×*TÑ*TÓ%UÐ"ØÐ"8Ñ8Ø0=�˜_Ò-Ø Ð(>Ñ>À=ÐC\Ü ðLóð ð
 ˆF�L‰LÑ(˜<Ó(ð .r'   c                 ó\   — t         st        d«      ‚| j                  | j                  «       y )Nz-PEFT backend is required for `unfuse_lora()`.)r
   r™   r"  Ú_unfuse_lora_apply©r¾   s    r$   Úunfuse_lorazPeftAdapterMixin.unfuse_loraÆ  s#   € ÝÜÐLÓMÐMØ�
‰
�4×*Ñ*Õ+r'   c                 óJ   — ddl m} t        ||«      r|j                  «        y y )Nr   rf   )r–   rg   r±   Úunmerge)r¾   rÏ   rg   s      r$   r0  z#PeftAdapterMixin._unfuse_lora_applyË  s   € Ý;ä�f˜nÔ-Ø�N‰NÕð .r'   c                 ó    — t         st        d«      ‚ddlm} ddlm}  || «       t        | d«      r| `t        | d«      rd | _         || «       y )Nz-PEFT backend is required for `unload_lora()`.r   r   )Úrecurse_remove_peft_layersr}   r®   )	r
   r™   r—   r   Úutilsr6  r¯   r}   r®   )r¾   r   r6  s      r$   Úunload_lorazPeftAdapterMixin.unload_loraÑ  sJ   € ÝÜÐLÓMÐMåWÝ6á" 4Ô(Ü�4˜Ô'ØÐ Ü�4Ð1Ô2Ø*.ˆDÔ'á2°4Õ8r'   c                 ó@   — t         st        d«      ‚t        | d¬«       y)a1  
        Disables the active LoRA layers of the underlying model.

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.unet.disable_lora()
        ```
        ú)PEFT backend is required for this method.Fr  N©r
   r™   r   r1  s    r$   Údisable_lorazPeftAdapterMixin.disable_loraà  s   € õ&  ÜÐHÓIÐIÜ˜4¨Ö/r'   c                 ó@   — t         st        d«      ‚t        | d¬«       y)a/  
        Enables the active LoRA layers of the underlying model.

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.unet.enable_lora()
        ```
        r:  Tr  Nr;  r1  s    r$   Úenable_lorazPeftAdapterMixin.enable_lora÷  s   € õ&  ÜÐHÓIÐIÜ˜4¨Ö.r'   c                 óÚ   — t         st        d«      ‚t        |t        «      r|g}|D ]7  }t	        | |«       t        | d«      sŒ| j                  j                  |d«       Œ9 t        | «       y)aÖ  
        Delete an adapter's LoRA layers from the underlying model.

        Args:
            adapter_names (`list[str, str]`):
                The names (single string or list of strings) of the adapter to delete.

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
        )
        pipeline.unet.delete_adapters("cinematic")
        ```
        r:  r}   N)	r
   r™   r±   rÿ   r   r¯   r}   r˜   r   )r¾   rü   rq   s      r$   Údelete_adaptersz PeftAdapterMixin.delete_adapters  sd   € õ.  ÜÐHÓIÐIä�m¤SÔ)Ø*˜OˆMã)ˆLÜ! $¨Ô5ô �t˜]Õ+Ø× Ñ ×$Ñ$ \°4Õ8ð *ô 	3°4Õ8r'   Útarget_rankÚcheck_compiled)r­   ÚwarnÚignorec                 ó°   — t        | di «      r?|dk(  rt        d«      ‚|dk(  rt        j                  d«       n|dk7  rt	        d|› d�«      ‚||d	œ| _        y
)aÔ  Enables the possibility to hotswap LoRA adapters.

        Calling this method is only required when hotswapping adapters and if the model is compiled or if the ranks of
        the loaded adapters differ.

        Args:
            target_rank (`int`, *optional*, defaults to `128`):
                The highest rank among all the adapters that will be loaded.

            check_compiled (`str`, *optional*, defaults to `"error"`):
                How to handle the case when the model is already compiled, which should generally be avoided. The
                options are:
                  - "error" (default): raise an error
                  - "warn": issue a warning
                  - "ignore": do nothing
        r}   r­   z<Call `enable_lora_hotswap` before loading the first adapter.rC  zhIt is recommended to call `enable_lora_hotswap` before loading the first adapter to avoid recompilation.rD  zCcheck_compiles should be one of 'error', 'warn', or 'ignore', got 'z
' instead.)rA  rB  N)rœ   ÚRuntimeErrorr¬   r½   r™   r]   )r¾   rA  rB  s      r$   Úenable_lora_hotswapz$PeftAdapterMixin.enable_lora_hotswap4  sr   € ô& �4˜¨Ô+Ø Ò(Ü"Ð#aÓbÐbØ 6Ò)Ü—‘Ø~õð   8Ò+Ü ØYÐZhÐYiÐisÐtóð ð =HÐ[iÑ,jˆÕ)r'   )ÚtransformerF)ÚdefaultFTNr   )rI  )r  N)rþ   FN)é€   r­   )!r¼   Ú
__module__Ú__qualname__Ú__doc__r®   r]   ÚdictÚ__annotations__Úclassmethodra   ÚboolrÓ   rÿ   rû   râ   Úfloatr  r  r  r  r  r²   r%  r#  r2  r0  r8  r<  r>  r@  Úintr   rG  r    r'   r$   r\   r\   L   s�  … ñð #Ðà04Ð  $¨¡+Ó4àñHó ðHð \añnØTXónðf	 &Ø%*Ø#'Ø"&ñB;ð ðB;ð #ð	B;ð
 !ðB;ð ˜4‘ZóB;ðN PTñ6Hà˜C‘y 3‘ð6Hð ˜‘  U¡Ñ+¨d°4©jÑ8¸4À¹:ÑEÈÑLó6Hñp$'¸ð $'ÈDó $'ðL/¨¨d°3©i©ð /¸Dó /ób3ó,4ð.-  c¡ó -ó*Pó)ò,,ò
ò9ò0ò./ð.$9¨T°#©Y¸©_ó $9ðN \cñkØðkØ6=Ð>WÑ6Xðkà	ôkr'   r\   )'r)  rã   rñ   Ú	functoolsr   Úpathlibr   Útypingr   rå   r¸   r—   r   r7  r	   r
   r   r   r   r   r   r   r   r   r   r   Úutils.peft_utilsr   r   rí   r   r   Úunet_loader_utilsr   Ú
get_loggerr¼   r¬   r   r\   r    r'   r$   Ú<module>rZ     se  ðó Û Û 	Ý Ý Ý ã Û å O÷÷ ÷ ó ÷ Sß MÝ 8ð 
ˆ×	Ñ	˜HÓ	%€ð!ØÐ5ð!àÐ0ð!ð Ñ?ð!ð Ñ@ð	!ð
 "Ñ#Eð!ð !Ñ"Dð!ð Ñ Bð!ð ÑAð!ð %Ñ&Hð!ð !Ñ"Dð!ð Ñ@ð!ð !Ñ"Dð!ð  Ñ!Cð!ð Ñ?ð!ð !Ñ"Dð!ð  %Ñ&Hð!!ð" .Ñ/Qð#!ñ$ "DÙ BÙ$FÙ#EÙAÙ BÙ#EÙ<ò3!Ð ÷:Gkò Gkr'   