
    +h                     Z   S SK r S SKJr  S SKJr  S SKJr  S SKJrJ	r	J
r
  S SKrS SKrS SKJs  Jr  S SKJr  SSKJrJrJrJrJrJr  SS	KJr  SS
KJrJr  SSKJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)  SSK*J+r+  SSK,J-r-  SSK.J/r/J0r0J1r1J2r2  SSKJ3r3  \)Rh                  " \55      r6Sr7Sr8 " S S5      r9g)    N)defaultdict)nullcontext)Path)CallableDictUnion)validate_hf_hub_args   )ImageProjectionIPAdapterFaceIDImageProjection"IPAdapterFaceIDPlusImageProjectionIPAdapterFullImageProjectionIPAdapterPlusImageProjectionMultiIPAdapterImageProjection)load_model_dict_into_meta)_LOW_CPU_MEM_USAGE_DEFAULTload_state_dict)
USE_PEFT_BACKEND_get_model_fileconvert_unet_state_dict_to_peft	deprecateget_adapter_nameget_peft_kwargsis_accelerate_availableis_peft_versionis_torch_versionlogging)empty_device_cache   #_func_optionally_disable_offloading)LORA_WEIGHT_NAMELORA_WEIGHT_NAME_SAFETEXT_ENCODER_NAME	UNET_NAME)AttnProcsLayersz$pytorch_custom_diffusion_weights.binz,pytorch_custom_diffusion_weights.safetensorsc                       \ rS rSrSr\r\r\	S\
\\\\R                  4   4   4S j5       rS rS r\S 5       r    SS	\
\\R*                  4   S
\S\S\S\4
S jjrS r\4S jr\4S jr\4S jrS rSrg)UNet2DConditionLoadersMixin<   z2
Load LoRA layers into a [`UNet2DCondtionModel`].
%pretrained_model_name_or_path_or_dictc                    SSK Jn  UR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  S	S5      nUR                  S
S5      n	UR                  SS5      n
UR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  S[        5      nSnU(       a  [	        SS5      (       a  [        S5      eUc  SnSnSSS.nSn[        U[        5      (       d  U(       a  Ub  UbT  UR                  S5      (       a>   [        UU=(       d    [        UUUUUU	U
US9
n[        R                  R                  USS9nUc*  [        UU=(       d    [        UUUUUU	U
US9
n[!        U5      nOUn[#        S WR%                  5        5       5      n['        S UR%                  5        5       5      nSnSnSnU(       a  Sn[)        S S!U5        U(       a  U R+                  US"9nO8U(       a#  U R-                  UU R.                  UUUUS#9u  nnnO[        U S$35      eU(       aK  UbH  U R1                  US%9u  nnnU R3                  W5        U R5                  U R6                  U R8                  S&9  U(       a  UR;                  5         gU(       a  UR=                  5         gU(       aU  UR>                  RA                  5        H6  n[        U[        RB                  RD                  5      (       d  M.  U" U5        M8     gg! [         a  nU(       d  Ue SnAGNSnAff = f)'a  
Load pretrained attention processor layers into [`UNet2DConditionModel`]. Attention processor layers have to be
defined in
[`attention_processor.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)
and be a `torch.nn.Module` class. Currently supported: LoRA, Custom Diffusion. For LoRA, one must install
`peft`: `pip install -U peft`.

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).

    cache_dir (`Union[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).
    adapter_name (`str`, *optional*, defaults to None):
        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
        `default_{i}` where i is the total number of adapters being loaded.
    weight_name (`str`, *optional*, defaults to None):
        Name of the serialized state dict file.
    low_cpu_mem_usage (`bool`, *optional*):
        Speed up model loading by only loading the pretrained LoRA weights and not initializing the random
        weights.

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.unet.load_attn_procs(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
```
r
   )*_maybe_remove_and_reapply_group_offloading	cache_dirNforce_downloadFproxieslocal_files_onlytokenrevision	subfolderweight_nameuse_safetensorsadapter_name	_pipelinenetwork_alphaslow_cpu_mem_usage<=z0.13.0zq`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`.Tattn_procs_weightspytorch)	file_type	frameworkz.safetensors)	weights_namer-   r.   r/   r0   r1   r2   r3   
user_agentcpu)devicec              3   ,   #    U  H
  nS U;   v   M     g7f)custom_diffusionN .0ks     P/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/loaders/unet.py	<genexpr>>UNet2DConditionLoadersMixin.load_attn_procs.<locals>.<genexpr>   s     !UCTa"4"9CT   c              3   \   #    U  H"  nS U;   =(       d    UR                  S5      v   M$     g7f)loraz.alphaN)endswithrF   s     rI   rJ   rK      s'     WEVv{:ajj&::EVs   *,zUsing the `load_attn_procs()` method has been deprecated and will be removed in a future version. Please use `load_lora_adapter()`.load_attn_procs0.40.0)
state_dict)rR   unet_identifier_keyr8   r6   r7   r9   zQ does not seem to be in the correct format expected by Custom Diffusion training.r7   dtyperB   )#hooks.group_offloadingr,   popr   r   
ValueError
isinstancedictrO   r   r#   safetensorstorch	load_fileIOErrorr"   r   anykeysallr   _process_custom_diffusion_process_lora	unet_name_optionally_disable_offloadingset_attn_processortorV   rB   enable_model_cpu_offloadenable_sequential_cpu_offload
componentsvaluesnnModule)selfr*   kwargsr,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   allow_pickler@   
model_filerR   eis_custom_diffusionis_lorais_model_cpu_offloadis_sequential_cpu_offloadis_group_offloaddeprecation_messageattn_processors	components                                 rI   rP   +UNet2DConditionLoadersMixin.load_attn_procsD   s   H 	XJJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=zz.$7JJ{D1	$4d;"JJ':<VWx!@!@ D  ""OL#7iP

?FFK$7'K,@,@,P,P!0=%0%I4I"+'5 ')9#!)"+#-"J "-!2!2!<!<ZPU!<!VJ !,9!,!@0@'#1#%5%')
 -Z8
>J!!U:??CT!UUWZ__EVWW$$)!  #h'3FG"<<
<SOPTPbPb%$(NN-)#"3 Qc QM ";=M ,op  9#8PTPsPs# Qt QM ";=M
 ##O4GG$**T[[G9  ..0&335&1188:	i99>yI ; G  '	s   !=M 
M6"	M11M6c                    SSK Jn  0 n[        [        5      nUR	                  5        H  u  pV[        U5      S:X  a  0 XE'   M  SU;   aF  SR                  UR                  S5      S S 5      SR                  UR                  S5      SS  5      pOESR                  UR                  S5      S S 5      SR                  UR                  S5      SS  5      pXdU   U'   M     UR	                  5        Hm  u  pY[        U	5      S:X  a  U" SSS S S	9X5'   M!  U	S
   R                  S   n
U	S
   R                  S   nSU	;   a  SOSnU" SUUU
S	9X5'   X5   R                  U	5        Mo     U$ )Nr
   )CustomDiffusionAttnProcessorr   to_out.F)train_kvtrain_q_outhidden_sizecross_attention_dimzto_k_custom_diffusion.weightr   zto_q_custom_diffusion.weightT)
models.attention_processorr~   r   r[   itemslenjoinsplitshaper   )ro   rR   r~   rz   custom_diffusion_grouped_dictkeyvalueattn_processor_keysub_key
value_dictr   r   r   s                rI   rc   5UNet2DConditionLoadersMixin._process_custom_diffusion  s   M(3D(9%$**,JC5zQ57-2s?25((399S>#2;N2OQTQYQYZ]ZcZcdgZhikilZmQn25((399S>#2;N2OQTQYQYZ]ZcZcdgZhikilZmQnMR.@A'J -  =BBDOC:!#'C"4]a($ '11O&P&V&VWX&Y#()GHNNqQ&D
&RdX]'C! + +(;	($  $44Z@  E"     c                 @   [         (       d  [        S5      eSSKJnJnJn	  [        UR                  5       5      n
U
 Vs/ s H  oR                  U5      (       d  M  UPM     nnUR                  5        VVs0 s H"  u  pX;   d  M  UR                  U S3S5      U_M$     nnnUbv  UR                  5        Vs/ s H  oR                  U5      (       d  M  UPM     nnUR                  5        VVs0 s H"  u  pX;   d  M  UR                  U S3S5      U_M$     nnnSnSnSn[        U5      S:  a  UOUn[        U5      S:  Ga7  U[        U S0 5      ;   a  [        SU S	35      e[        U5      nUb  [        U5      n0 nUR                  5        H   u  nnS
U;   d  M  UR                  S   UU'   M"     [        UX1SS9nSU;   aI  US   (       a  [!        SS5      (       a  [        S5      eO"[!        SS5      (       a  UR#                  S5        SU;   aI  US   (       a  [!        SS5      (       a  [        S5      eO"[!        SS5      (       a  UR#                  S5        U" S!0 UD6nUc  [%        U 5      nU R'                  U5      u  nnn0 n[!        SS5      (       a  UUS'   U" UU 4SU0UD6  U	" XU40 UD6nSnUb  [        USS 5      nU(       a=  U Vs/ s H  nSU;   d  M  XK;   d  M  UPM     nnU(       a  SSR)                  U5       S3n[        USS 5      nU(       a@  U Vs/ s H  nSU;   d  M  XK;   d  M  UPM     nnU(       a  US SR)                  U5       S3-  nU(       a  [*        R-                  U5        UUU4$ s  snf s  snnf s  snf s  snnf s  snf s  snf )"Nz)PEFT backend is required for this method.r   )
LoraConfiginject_adapter_in_modelset_peft_model_state_dictr    Fpeft_configzAdapter name z? already in use in the Unet - please select a new adapter name.lora_Br   T)is_unetuse_dora<z0.9.0zeYou need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`.	lora_biasr:   z0.13.2zcYou need `peft` 0.14.0 at least to use `bias` in LoRAs. Please upgrade your installation of `peft`.>=z0.13.1r9   r6   unexpected_keyslora_zSLoading adapter weights from state_dict led to unexpected keys found in the model: z, z. missing_keyszJLoading adapter weights from state_dict led to missing keys in the model: rE   )r   rY   peftr   r   r   listra   
startswithr   replacer   getattrr   r   r   r   rX   r   rf   r   loggerwarning) ro   rR   rS   r8   r6   r7   r9   r   r   r   ra   rH   	unet_keysvunet_state_dict
alpha_keysrv   rw   rx   state_dict_to_be_usedrankr   vallora_config_kwargslora_configpeft_kwargsincompatible_keyswarn_msgr   lora_unexpected_keysr   lora_missing_keyss                                    rI   rd   )UNet2DConditionLoadersMixin._process_lora#  s     HIIWWJOO%& $J15H(IQ	JDNDTDTDV
DVDAZ[Zh7AII,-Q/4a7DV 	 
 %%3%8%8%:`%:llK^>_!%:J`HVH\H\H^H^bcbq;		013R8!;H^    %$)! 363G!3KQ[$%)wt]B?? #L>1pq  99NOJ) "A!PD&,,.Ss? #		!DI / "1~[_!`//%j1&sG44( D  5
 'sG44*..z:00%k2&tX66( B  7
 'tX66*..{;$:'9:K #/5 QUPsPsQM ";=M KtX..3D/0#K`L`T_` 9$L h\g hH ,")*;=NPT"U"7F+m!'UV,A[g[lA(+m+  $		*> ?@D !  ''8.$O4@(gLqGqLUaUfL%(g(   $		*; <=Q@
 x(#%>@PPPE K

 aN ,n )hsS   N N 6NN7NN/N>N
N N'N#
N1N8Nc                     [        US9$ )NrT   r    )clsr7   s     rI   rf   :UNet2DConditionLoadersMixin._optionally_disable_offloading  s     3YGGr   Nsave_directoryis_main_processr4   save_functionsafe_serializationc                 r  ^^^ SSK JmJmJm  [        R
                  R                  U5      (       a  [        R                  SU S35        g[        UUU4S jU R                  R                  5        5       5      nU(       a  U R                  5       nUc  U(       a  UR                  5        V	V
s0 s H(  u  p[        U
[        R                  5      (       a  M&  X_M*     nn	n
[!        U5      S:  a&  [        R#                  SUR%                  5        35        UR                  5        V	V
s0 s H(  u  p[        U
[        R                  5      (       d  M&  X_M*     nn	n
O3S	n['        S
SU5        [(        (       d  [+        S5      eSSKJn  U" U 5      nUc  U(       a  S nO[        R0                  n[        R2                  " USS9  Uc.  U(       a  U(       a  [4        O[6        nOU(       a  [8        O[:        n[=        X5      R?                  5       nU" X5        [        RA                  SU 35        gs  sn
n	f s  sn
n	f )a  
Save attention processor layers to a directory so that it can be reloaded with the
[`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] method.

Arguments:
    save_directory (`str` or `os.PathLike`):
        Directory to save an attention processor to (will be created if it doesn't exist).
    is_main_process (`bool`, *optional*, defaults to `True`):
        Whether the process calling this is the main process or not. Useful during distributed training and you
        need to call this function on all processes. In this case, set `is_main_process=True` only on the main
        process to avoid race conditions.
    save_function (`Callable`):
        The function to use to save the state dictionary. Useful during distributed training when you need to
        replace `torch.save` with another method. Can be configured with the environment variable
        `DIFFUSERS_SAVE_MODE`.
    safe_serialization (`bool`, *optional*, defaults to `True`):
        Whether to save the model using `safetensors` or with `pickle`.

Example:

```py
import torch
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "CompVis/stable-diffusion-v1-4",
    torch_dtype=torch.float16,
).to("cuda")
pipeline.unet.load_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
pipeline.unet.save_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
```
r
   r~   CustomDiffusionAttnProcessor2_0$CustomDiffusionXFormersAttnProcessorzProvided path (z#) should be a directory, not a fileNc              3   F   >#    U  H  u  p[        UTTT45      v   M     g 7f)N)rZ   )rG   _xr~   r   r   s      rI   rJ   >UNet2DConditionLoadersMixin.save_attn_procs.<locals>.<genexpr>  s7      "

 7	 -/NPtu  7s   !r   zfSafetensors does not support saving dicts with non-tensor values. The following keys will be ignored: zUsing the `save_attn_procs()` method has been deprecated and will be removed in a future version. Please use `save_lora_adapter()`.save_attn_procsrQ   zOPEFT backend is required for saving LoRAs using the `save_attn_procs()` method.)get_peft_model_state_dictc                 B    [         R                  R                  XSS0S9$ )Nformatpt)metadata)r\   r]   	save_file)weightsfilenames     rI   r   BUNet2DConditionLoadersMixin.save_attn_procs.<locals>.save_function  s%    &,,66wT\^bSc6ddr   T)exist_okzModel weights saved in )!r   r~   r   r   ospathisfiler   errorr`   rz   r    _get_custom_diffusion_state_dictrZ   r]   Tensorr   r   ra   r   r   rY   
peft.utilsr   savemakedirs!CUSTOM_DIFFUSION_WEIGHT_NAME_SAFEr#   CUSTOM_DIFFUSION_WEIGHT_NAMEr"   r   as_posixinfo)ro   r   r   r4   r   r   rp   rt   rR   rH   r   empty_state_dictry   r   	save_pathr~   r   r   s                  @@@rI   r   +UNet2DConditionLoadersMixin.save_attn_procs  s   R	
 	
 77>>.))LL?>*::]^_! "

 ..446"
 
 >>@J$);5?5E5E5G#k5GTQzZ[]b]i]iOjDAD5G #k'(1,NN??O?T?T?V>WY 0:/?/?/Aa/AtqZPQSXS_S_E`dad/A
a #h'3FG## !rss<248J !e !&


NT2!CV?\q>Q:Wg 5>>@	j,-i[9:M $l bs   /%H-H-)%H3H3c                 n   SSK JnJnJn  [	        U R
                  R                  5        VVs0 s H  u  pE[        UUUU45      (       d  M  XE_M     snn5      nUR                  5       nU R
                  R                  5        H(  u  p[        U	R                  5       5      S:X  d  M$  0 Xx'   M*     U$ s  snnf )Nr
   r   r   )
r   r~   r   r   r&   rz   r   rZ   rR   r   )
ro   r~   r   r   yr   model_to_saverR   nameattns
             rI   r   <UNet2DConditionLoadersMixin._get_custom_diffusion_state_dict  s    	
 	
 ( #2288::FQ47< :
 #--/
..446JD4??$%*#%
  7 %s   B1
B1
c           	         U(       a-  [        5       (       a  SSKJn  OSn[        R	                  S5        USL a  [        SS5      (       d  [        S5      e0 nS nU(       a  WO[        nS	U;   au  S
nUS	   R                  S   nUS	   R                  S   S
-  n	U" 5          [        U	UUS9nS S S 5        UR                  5        H  u  pU
R                  SS5      nXU'   M     GOvSU;   a  US   R                  S   nUS   R                  S   n	U" 5          [        XS9nS S S 5        UR                  5        H?  u  pU
R                  SS5      nUR                  SS5      nUR                  SS5      nXU'   MA     GOSU;   Ga  US   R                  S   nUS   R                  S   nUS   R                  S   nUS   R                  S   nUS   R                  S   S-  nU" 5          [        UUUUUS9nS S S 5        UR                  5        GHh  u  pU
R                  SS5      nUR                  S S!5      nUR                  S"S#5      nUR                  S$S%5      nUR                  S&S'5      nUR                  S(S)5      nUR                  S*S+5      nUR                  S,S-5      nUR                  S.S/5      nUR                  S0S15      nUR                  S2S35      nUR                  S4S55      nUR                  S6S75      nUR                  S8S95      nUR                  S:S;5      nUR                  S<S=5      nUR                  S>S?5      nUR                  S@SA5      nUR                  SBSC5      nUR                  SDSE5      nUR                  SFSG5      nUR                  SHSI5      nSJU;   a  XUR                  SKSL5      '   GM  SMU;   a  XUR                  SNSO5      '   GM  SPU;   aA  UR                  SQSSR9nUS   XLR                  SPSS5      '   US   XLR                  SPST5      '   GM  SUU;   a  XUR                  SUSV5      '   GM0  SU:X  a  XSW'   GM=  SXU:X  a  XSY'   GMJ  SZU:X  a  XS['   GMW  S\U:X  a  XS]'   GMd  XU'   GMk     GOS^U;   a  US   R                  S   nUS   R                  S   nUU-  nS^nUU   R                  S   n	USZ   R                  S   U	-  nU" 5          [        U	UUUS_9nS S S 5        UR                  5        H-  u  pU
R                  SS5      nUR                  SS5      nXU'   M/     GO'US`   R                  S   nUSa   R                  S   nUSb   R                  S   nUS`   R                  SQ   n[!        Sc U 5       5      nU(       a  USd   R                  S   S-  OUSe   R                  S   S-  nU" 5          [#        UUUUUSf9nS S S 5        UR                  5        GHj  u  pU
R                  S Sg5      nUR                  ShSi5      nUR                  SjSk5      nUR                  SlSm5      nUR                  SnSo5      nUR                  SpSq5      nUR                  SrSs5      nUR                  StSu5      nUR                  SvSw5      nSPU;   ah  UR%                  Sx5      nSyUSQ'   SxR'                  U5      nUR                  SQSSR9nUS   XLR                  SPSS5      '   US   XLR                  SPST5      '   GM  SzU;   a.  UR%                  Sx5      nSyUSQ'   SxR'                  U5      nXU'   GMJ  SUU;   a>  UR%                  Sx5      nSyUSQ'   SxR'                  U5      nXUR                  SUSV5      '   GM  UR                  S{S|5      nUR                  S}S~5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nXU'   GMm     U(       d  UR)                  USS9  U$ SU R*                  0n[-        XTUU R.                  S9  [1        5         U$ ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= f)Nr   init_empty_weightsF,  Cannot initialize model with low cpu memory usage because `accelerate` was not found in the environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install `accelerate` for faster and less memory-intense model loading. You can do so with: 
```
pip install accelerate
```
.Tr   1.9.0~Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set `low_cpu_mem_usage=False`.proj.weight   )r   image_embed_dimnum_image_text_embedsprojimage_embedsproj.3.weightzproj.0.weight)r   r   zproj.0zff.net.0.projzproj.2zff.net.2zproj.3norm"perceiver_resampler.proj_in.weightr   z#perceiver_resampler.proj_out.weightz*perceiver_resampler.layers.0.0.to_q.weight@   )
embed_dimsoutput_dimshidden_dimsheadsid_embeddings_dimzperceiver_resampler.r   z0.tozattn.toz0.1.0.z0.ff.0.z0.1.1.weightz0.ff.1.net.0.proj.weightz0.1.3.weightz0.ff.1.net.2.weightz1.1.0.z1.ff.0.z1.1.1.weightz1.ff.1.net.0.proj.weightz1.1.3.weightz1.ff.1.net.2.weightz2.1.0.z2.ff.0.z2.1.1.weightz2.ff.1.net.0.proj.weightz2.1.3.weightz2.ff.1.net.2.weightz3.1.0.z3.ff.0.z3.1.1.weightz3.ff.1.net.0.proj.weightz3.1.3.weightz3.ff.1.net.2.weightz
layers.0.0zlayers.0.ln0z
layers.0.1zlayers.0.ln1z
layers.1.0zlayers.1.ln0z
layers.1.1zlayers.1.ln1z
layers.2.0zlayers.2.ln0z
layers.2.1zlayers.2.ln1z
layers.3.0zlayers.3.ln0z
layers.3.1zlayers.3.ln1norm1z0.norm10norm2z0.norm21to_kvr
   )dimto_kto_vr   zto_out.0zproj.net.0.proj.weightzproj.0.biaszproj.net.0.proj.biaszproj.2.weightzproj.net.2.weightzproj.2.biaszproj.net.2.biasnorm.weight)r   r   mult
num_tokenslatentszproj_in.weightzproj_out.weightc              3   ,   #    U  H
  nS U;   v   M     g7f)r   NrE   rF   s     rI   rJ   ZUNet2DConditionLoadersMixin._convert_ip_adapter_image_proj_to_diffusers.<locals>.<genexpr>  s     "C
16Q;
rL   zlayers.0.attn.to_q.weightzlayers.0.0.to_q.weight)r   r   r   r   num_queriesz2.toz	0.0.norm1z0.ln0z	0.0.norm2z0.ln1z	1.0.norm1z1.ln0z	1.0.norm2z1.ln1z	2.0.norm1z2.ln0z	2.0.norm2z2.ln1z	3.0.norm1z3.ln0z	3.0.norm2z3.ln1r   r   to_qz0.1.0z0.ff.0z0.1.1z0.ff.1.net.0.projz0.1.3z0.ff.1.net.2z1.1.0z1.ff.0z1.1.1z1.ff.1.net.0.projz1.1.3z1.ff.1.net.2z2.1.0z2.ff.0z2.1.1z2.ff.1.net.0.projz2.1.3z2.ff.1.net.2z3.1.0z3.ff.0z3.1.1z3.ff.1.net.0.projz3.1.3z3.ff.1.net.2)strict
device_maprV   )r   
accelerater   r   r   r   NotImplementedErrorr   r   r   r   r   r   r   chunkr   r`   r   r   r   r   rB   r   rV   r   )ro   rR   r9   r   updated_state_dictimage_projectioninit_contextr   clip_embeddings_dimr   r   r   diffusers_namer   r   r   r   r   v_chunkid_embeddings_dim_inid_embeddings_dim_out
multiplier
norm_layerr
  attn_key_presentpartsr  s                              rI   +_convert_ip_adapter_image_proj_to_diffusersGUNet2DConditionLoadersMixin._convert_ip_adapter_image_proj_to_diffusers  s	   &((9 %*!2 $-=dG-L-L%. 
  ->)KJ&$%!",]";"A"A""E",]";"A"A!"D"I#2(;$7*?$    )..0
!$V^!D5:>2 1 
*",_"="C"CA"F",_"="C"CA"F#?(;$   
 )..0
!$X!G!/!7!7*!M!/!7!7&!I5:>2	 1 2Z? *? ; A A! D#$HIOOPQRJ$%IJPPQRSK$%JKQQRSTKKLRRSTUY[[E#E) + +&7$    )..0
!$-CR!H!/!7!7	!J!/!7!7)!L!/!7!7Hb!c!/!7!7H]!^!/!7!7)!L!/!7!7Hb!c!/!7!7H]!^!/!7!7)!L!/!7!7Hb!c!/!7!7H]!^!/!7!7)!L!/!7!7Hb!c!/!7!7H]!^!/!7!7n!U!/!7!7n!U!/!7!7n!U!/!7!7n!U!/!7!7n!U!/!7!7n!U!/!7!7n!U!/!7!7n!Un,QV~'='=i'MN.QV~'='=i'MN.#kk!k3GRYZ[R\&'='=gv'NORYZ[R\&'='=gv'NO/W\~'='=h
'ST$6CH'?@"n4AF'=>$6>C':;"n4<A'899>~6W 1Z j(#-o#>#D#DQ#G $.$?$E$Ea$H!.2FFJ&J",Z"8">">q"A#O4::1=ATTJ#A(;$8#)	$    )..0
!$X!G!/!7!7*!M5:>2 1 %/y$9$?$?$B!#$45;;A>J$%67==a@K$Y/55a8K""C
"CC $ 67==a@BF 89??BbH  #?) + + 5$    )..0
!$VV!<!/!7!7W!M!/!7!7W!M!/!7!7W!M!/!7!7W!M!/!7!7W!M!/!7!7W!M!/!7!7W!M!/!7!7W!Mn,*005E%E!H%(XXe_N#kk!k3GRYZ[R\&'='=gv'NORYZ[R\&'='=gv'NO~-*005E%E!H%(XXe_N9>~6/*005E%E!H%(XXe_NW\~'='=h
'ST%3%;%;GX%NN%3%;%;GEX%YN%3%;%;G^%TN%3%;%;GX%NN%3%;%;GEX%YN%3%;%;G^%TN%3%;%;GX%NN%3%;%;GEX%YN%3%;%;G^%TN%3%;%;GX%NN%3%;%;GEX%YN%3%;%;G^%TN9>~6[ 1^ !,,-?,M  	 dkk*J%&6Waimisist w     &  ~  4  s<   b"
b4'ccc*"
b14
c
c
c'*
c9c           	      
   SSK JnJnJn  U(       a-  [	        5       (       a  SSKJn  OSn[        R                  S5        USL a  [        SS	5      (       d  [        S
5      e0 nSnU(       a  WO[        n	U R                  R                  5        GH  n
U
R                  S5      (       a  S OU R                  R                   nU
R#                  S5      (       a  U R                  R$                  S   nOU
R#                  S5      (       aC  ['        U
[)        S5         5      n[+        [-        U R                  R$                  5      5      U   nOFU
R#                  S5      (       a0  ['        U
[)        S5         5      nU R                  R$                  U   nUb  SU
;   a%  U R                  U
   R.                  nU" 5       Xz'   GM/  S[1        U R                  U
   R.                  5      ;   a  UnO[3        [4        S5      (       a  UOUn/ nU H`  nSUS   ;   a  US/-  nM  SUS   ;   a  US/-  nM%  SUS   ;   a  US/-  nM6  SUS   ;   a  US/-  nMG  UUS   S   R6                  S   /-  nMb     U	" 5          U" WUSUS9Xz'   S S S 5        0 n[9        U5       HF  u  nnUR;                  S U S!3US"   U S#3   05        UR;                  S$U S!3US"   U S%3   05        MH     U(       d  Xz   R=                  U5        Oj[?        [A        URC                  5       5      5      RD                  n[?        [A        URC                  5       5      5      RF                  nS&U0n[I        Xz   UUUS'9  US-  nGM     [K        5         U$ ! , (       d  f       GN= f)(Nr
   )IPAdapterAttnProcessorIPAdapterAttnProcessor2_0IPAdapterXFormersAttnProcessorr   r   Fr   Tr   r   r   r   zattn1.processor	mid_blockr   	up_blocksz
up_blocks.down_blockszdown_blocks.motion_modulesXFormersscaled_dot_product_attentionr   
image_projr   r   i  r   r  r  g      ?)r   r   scaler
  zto_k_ip.z.weight
ip_adapterz.to_k_ip.weightzto_v_ip.z.to_v_ip.weightr   r  )&r   r%  r&  r'  r   r  r   r   r   r   r  r   rz   ra   rO   configr   r   block_out_channelsintr   r   reversed	__class__strhasattrFr   	enumerateupdater   nextiterrl   rB   rV   r   r   )ro   state_dictsr9   r%  r&  r'  r   
attn_procskey_idr  r   r   r   block_idattn_processor_classr   rR   r   irB   rV   r  s                         rI   %_convert_ip_adapter_attn_to_diffusersAUNet2DConditionLoadersMixin._convert_ip_adapter_attn_to_diffusers  s   	
 	
 &((9 %*!2 $-=dG-L-L%.  
->)K((--/D*.--8I*J*J$PTP[P[PoPo{++"kk<<R@--tC$567"8DKK,J,J#KLXV//tC$789"kk<<XF"*.>$.F'+';';D'A'K'K$#7#9
 T%9%9$%?%I%I!JJ+I( #1&DEE 23 )
 )+%"-J$
<(@@-!4-(J|,DD-#6-=LAYY-!4-&*\*BB-!4- .*\2J92U2[2[\]2^1__- #." "^';$/,?!#8	(J$ $  
%.{%;MAz%%!G'<j>VZ`YaapWq>r&st%%!G'<j>VZ`YaapWq>r&st &< )$44Z@!$z'8'8':";<CCF j&7&7&9!:;AAE"$fJ-j.>
Waino!} 0@ 	3 $^s   -M33
N	c                    [        U[        5      (       d  U/nU R                  b<  U R                  R                  S:X  a"  [        U S5      (       d  U R                  U l        S U l        U R                  XS9nU R                  U5        / nU H'  nU R                  US   US9nUR                  U5        M)     [        U5      U l        SU R                  l        U R                  U R                  U R                  S9  g )N	text_projtext_encoder_hid_proj)r9   r.  ip_image_projrU   )rZ   r   encoder_hid_projr1  encoder_hid_dim_typer7  rG  rC  rg   r"  appendr   rh   rV   rB   )ro   r=  r9   r>  image_projection_layersrR   image_projection_layers          rI   _load_ip_adapter_weights4UNet2DConditionLoadersMixin._load_ip_adapter_weights\  s    +t,,&-K !!-00K?D"9::)-)>)>D& !%???q

+ #%%J%)%U%U<(<M &V &" $**+AB	 & !>>U V+:(djj5r   c                    0 n[        U R                  R                  5       5       GHC  u  p4[        U5       GH-  u  pVU S3US   ;   d  M  XR;  a  0 X%'   X%   R                  SU S3US   U S3   05        X%   R                  SU S3US   U S3   05        X%   R                  SU S3US   U S3   05        X%   R                  SU S3US   U S3   05        X%   R                  SU S3US   U S3   05        X%   R                  SU S3US   U S3   05        X%   R                  SU S	3US   U S	3   05        X%   R                  SU S
3US   U S
3   05        GM0     GMF     U$ )Nz.to_k_lora.down.weightr0  zunet.z.to_q_lora.down.weightz.to_v_lora.down.weightz.to_out_lora.down.weightz.to_k_lora.up.weightz.to_q_lora.up.weightz.to_v_lora.up.weightz.to_out_lora.up.weight)r9  rz   ra   r:  )ro   r=  
lora_dictsr?  r   rB  rR   s          rI   _load_ip_adapter_loras2UNet2DConditionLoadersMixin._load_ip_adapter_loras|  s7   
%d&:&:&?&?&ABLF!*;!7X34
<8PP*(*
M((#D6)?@*\BZ#)(*@ AC M((#D6)?@*\BZ#)(*@ AC M((#D6)?@*\BZ#)(*@ AC M((#D6)ABJ|D\#)(*B CE M(( &:;Z=UY_X``tVu=vw M(( &:;Z=UY_X``tVu=vw M(( &:;Z=UY_X``tVu=vw M((#D6)?@*\BZ#)(*@ ACS "8 Cb r   )rI  rG  )TNNT) __name__
__module____qualname____firstlineno____doc__r$   text_encoder_namer%   re   r	   r   r6  r   r]   r   rP   rc   rd   classmethodrf   r   PathLikeboolr   r   r   r   r"  rC  rN  rR  __static_attributes__rE   r   rI   r(   r(   <   s     *IyJU3PTUXZ_ZfZfUfPgKgEh yJ yJx DsQj H H !%"&#'d;c2;;./d; d; 	d;
  d; !d;L8 Ys Y v Tn `D Ga 6@3r   r(   ):r   collectionsr   
contextlibr   pathlibr   typingr   r   r   r\   r]   torch.nn.functionalrm   
functionalr8  huggingface_hub.utilsr	   models.embeddingsr   r   r   r   r   r   models.model_loading_utilsr   models.modeling_utilsr   r   utilsr   r   r   r   r   r   r   r   r   r   utils.torch_utilsr   	lora_baser!   lora_pipeliner"   r#   r$   r%   r&   
get_loggerrT  r   r   r   r(   rE   r   rI   <module>rm     s    
 # "  ( (     6  C O   3 : ` ` " 
		H	%  F $R !s sr   