
    bi                     Z   d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	m
Z
 d dlZd dlZd dlmc mZ d dlmZ ddlmZmZmZmZmZmZ dd	lmZ dd
lmZ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) ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2 ddlm3Z3  e)jh                  e5      Z6dZ7dZ8 G d d      Z9y)    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                       e Zd ZdZeZeZede	e
ee
ej                  f   f   fd       Zd Zd Zed        Z	 	 	 	 dde	e
ej(                  f   d	ed
e
dedef
dZd ZefdZefdZefdZd Zy)UNet2DConditionLoadersMixinz:
    Load LoRA layers into a [`UNet2DCondtionModel`].
    %pretrained_model_name_or_path_or_dictc                 j   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      }|j                  dd      }|j                  dd      }|j                  dt              }d}|rt	        dd      rt        d      |d}d}ddd}d}t        |t              s|r||P|j                  d      r?	 t        ||xs t        ||||||	|
|
      }t        j                  j                  |d      }|+t        ||xs t        ||||||	|
|
      }t!        |      }n|}t#        d j%                         D              }t'        d |j%                         D              }d}d}d}|rd}t)        d d!|       |r| j+                  |"      }n6|r&| j-                  || j.                  ||||#      \  }}}nt        | d$      |rP|N| j1                  |%      \  }}}| j3                         | j5                  | j6                  | j8                  &       |r|j;                          y|r|j=                          y|rM|j>                  jA                         D ]/  }t        |t        jB                  jD                        s( ||       1 yy# t        $ r}|s|Y d}~d}~ww xY w)'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.   r/   r0   r1   r2   
user_agentcpu)devicec              3   $   K   | ]  }d |v  
 yw)custom_diffusionN .0ks     Q/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/loaders/unet.py	<genexpr>z>UNet2DConditionLoadersMixin.load_attn_procs.<locals>.<genexpr>   s     !Ua"4"9!U   c              3   J   K   | ]  }d |v xs |j                  d        yw)loraz.alphaN)endswithrE   s     rH   rI   z>UNet2DConditionLoadersMixin.load_attn_procs.<locals>.<genexpr>   s%     Wv{:ajj&::Ws   !#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)rP   unet_identifier_keyr7   r5   r6   r8   zQ does not seem to be in the correct format expected by Custom Diffusion training.r6   dtyperA   )#hooks.group_offloadingr+   popr   r   
ValueError
isinstancedictrM   r   r#   safetensorstorch	load_fileIOErrorr"   r   anykeysallr   _process_custom_diffusion_process_lora	unet_name_optionally_disable_offloadingset_attn_processortorT   rA   enable_model_cpu_offloadenable_sequential_cpu_offload
componentsvaluesnnModule)selfr)   kwargsr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   allow_pickler?   
model_filerP   eis_custom_diffusionis_lorais_model_cpu_offloadis_sequential_cpu_offloadis_group_offloaddeprecation_messageattn_processors	components                                 rH   rN   z+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K$7'K,@,@,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: J	i9>yIJ G  '	s   >L 	L2#L--L2c                    ddl m} i }t        t              }|j	                         D ]  \  }}t        |      dk(  ri ||<   d|v rGdj                  |j                  d      d d       dj                  |j                  d      dd        }}nFdj                  |j                  d      d d       dj                  |j                  d      dd        }}|||   |<    |j	                         D ]r  \  }}	t        |	      dk(  r |ddd d 	      ||<   $|	d
   j                  d   }
|	d
   j                  d   }d|	v rdnd} |d|||
	      ||<   ||   j                  |	       t |S )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   rY   itemslenjoinsplitshaper   )rm   rP   r{   rx   custom_diffusion_grouped_dictkeyvalueattn_processor_keysub_key
value_dictr   r   r   s                rH   ra   z5UNet2DConditionLoadersMixin._process_custom_diffusion  s   M(3D(9%$**, 	SJC5zQ57-c2s?25((399S>#2;N2OQTQYQYZ]ZcZcdgZhikilZmQn&25((399S>#2;N2OQTQYQYZ]ZcZcdgZhikilZmQn&MR-.@A'J	S  =BBD 	AOC:!#'C"4]a($ '11O&P&V&VWX&Y#()GHNNqQ&D
&RdX]'C! + +(;	($  $44Z@	A"     c                 R   t         st        d      ddlm}m}m}	 t        |j                               }
|
D cg c]  }|j                  |      s| }}|j                         D ci c]   \  }}||v s|j                  | dd      |" }}}|j|j                         D cg c]  }|j                  |      s| }}|j                         D ci c]   \  }}||v s|j                  | dd      |" }}}d}d}d}t        |      dkD  r|n|}t        |      dkD  r|t        | di       v rt        d| d	      t        |      }|t        |      }i }|j                         D ]  \  }}d
|v s|j                  d   ||<    t        |||d      }d|v r9|d   rt!        dd      r(t        d      t!        dd      r|j#                  d       d|v r9|d   rt!        dd      r(t        d      t!        dd      r|j#                  d        |d!i |}|t%        |       }| j'                  |      \  }}}i }t!        dd      r||d<    ||| fd|i|  |	| ||fi |}d}|t        |dd       }|r0|D cg c]  }d|v s||v s| }}|rddj)                  |       d}t        |dd       }|r3|D cg c]  }d|v s||v s| }}|r|d dj)                  |       dz  }|rt*        j-                  |       |||fS c c}w c c}}w c c}w c c}}w c c}w c c}w )"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_biasr9   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.1r8   r5   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: rD   )r   rW   peftr   r   r   listr_   
startswithr   replacer   getattrr   r   r   r   rV   r   rd   r   loggerwarning) rm   rP   rQ   r7   r5   r6   r8   r   r   r   r_   rG   	unet_keysvunet_state_dict
alpha_keysrt   ru   rv   state_dict_to_be_usedrankr   vallora_config_kwargslora_configpeft_kwargsincompatible_keyswarn_msgr   lora_unexpected_keysr   lora_missing_keyss                                    rH   rb   z)UNet2DConditionLoadersMixin._process_lora#  s     HIIWWJOO%& $J15H(IQJ	JDNDTDTDV
<@AqZ[_hZhAII,-Q/4a7
 
 %%3%8%8%:`allK^>_!`J`HVH\H\H^@D1bcgqbq		013R8!;N   %$)! 363G!3KQ[$%)wt]B?? #L>1pq  99NOJ) "A!PD&,,. -Ss? #		!DI- "1~z[_!`//%j1&sG4( D  'sG4*..z:00%k2&tX6( B  'tX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,[gkl[lA+m(+m+  $		*> ?@D !  ''8.$O4@(gqGqLUaefUf(g%(g(   $		*; <=Q@
 x(#%>@PPPE K

 aN ,n )hsS   L	L	)L6L%L<LL"L?	L	LL>	L$L$L$c                     t        |      S )NrR   r    )clsr6   s     rH   rd   z:UNet2DConditionLoadersMixin._optionally_disable_offloading  s     3YGGr   Nsave_directoryis_main_processr3   save_functionsafe_serializationc                    ddl mmm t        j
                  j                  |      rt        j                  d| d       yt        fd| j                  j                         D              }|r| j                         }||r|j                         D 	
ci c]#  \  }	}
t        |
t        j                        r!|	|
% }}	}
t!        |      dkD  r&t        j#                  d|j%                                 |j                         D 	
ci c]#  \  }	}
t        |
t        j                        s!|	|
% }}	}
n.d	}t'        d
d|       t(        st+        d      ddlm}  ||       }||rd }nt        j0                  }t	        j2                  |d       ||r|rt4        nt6        }n|rt8        nt:        }t=        ||      j?                         } |||       t        jA                  d|        yc c}
}	w c c}
}	w )az  
        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   B   K   | ]  \  }}t        |f        y w)N)rX   )rF   _xr{   r   r   s      rH   rI   z>UNet2DConditionLoadersMixin.save_attn_procs.<locals>.<genexpr>  s3      "

 A	 -/NPtu"
s   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_procsrO   zOPEFT backend is required for saving LoRAs using the `save_attn_procs()` method.)get_peft_model_state_dictc                 J    t         j                  j                  | |ddi      S )Nformatpt)metadata)rZ   r[   	save_file)weightsfilenames     rH   r   zBUNet2DConditionLoadersMixin.save_attn_procs.<locals>.save_function  s'    &,,66wT\^bSc6ddr   T)exist_okzModel weights saved in )!r   r{   r   r   ospathisfiler   errorr^   rx   r    _get_custom_diffusion_state_dictrX   r[   Tensorr   r   r_   r   r   rW   
peft.utilsr   savemakedirs!CUSTOM_DIFFUSION_WEIGHT_NAME_SAFEr#   CUSTOM_DIFFUSION_WEIGHT_NAMEr"   r   as_posixinfo)rm   r   r   r3   r   r   rn   rr   rP   rG   r   empty_state_dictrw   r   	save_pathr{   r   r   s                  @@@rH   r   z+UNet2DConditionLoadersMixin.save_attn_procs  s   R	
 	
 77>>.)LL?>*::]^_! "

 ..446"
 
 >>@J$);5?5E5E5G#kTQzZ[]b]i]iOjAqD#k #k'(1,NN??O?T?T?V>WY 0:/?/?/Aatq!ZPQSXS_S_E`ad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   "G6G6"G<3G<c                 Z   ddl m}m}m} t	        | j
                  j                         D ci c]  \  }}t        ||||f      r|| c}}      }|j                         }| j
                  j                         D ]'  \  }}	t        |	j                               dk(  s#i ||<   ) |S c c}}w )Nr
   r   r   )
r   r{   r   r   r&   rx   r   rX   rP   r   )
rm   r{   r   r   yr   model_to_saverP   nameattns
             rH   r   z<UNet2DConditionLoadersMixin._get_custom_diffusion_state_dict  s    	
 	
 ( #2288:Q47< 1
 #--/
..446 	&JD$4??$%*#%
4 	& %s   B'
c                    |r(t               rddlm} nd}t        j	                  d       |du rt        dd      st        d      i }d }|rnt        }d	|v rxd
}|d	   j                  d   }|d	   j                  d   d
z  }	 |       5  t        |	||      }d d d        |j                         D ]  \  }
}|
j                  dd      }|||<    nnd|v r|d   j                  d   }|d   j                  d   }	 |       5  t        |	|      }d d d        |j                         D ]@  \  }
}|
j                  dd      }|j                  dd      }|j                  dd      }|||<   B nd|v r|d   j                  d   }|d   j                  d   }|d   j                  d   }|d   j                  d   }|d   j                  d   dz  } |       5  t        |||||      }d d d        |j                         D ]a  \  }
}|
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                  d0d1      }|j                  d2d3      }|j                  d4d5      }|j                  d6d7      }|j                  d8d9      }|j                  d:d;      }|j                  d<d=      }|j                  d>d?      }|j                  d@dA      }|j                  dBdC      }|j                  dDdE      }|j                  dFdG      }|j                  dHdI      }dJ|v r|||j                  dKdL      <   dM|v r|||j                  dNdO      <   dP|v rE|j                  dQdR      }|d   ||j                  dPdS      <   |d   ||j                  dPdT      <   dU|v r|||j                  dUdV      <   -d|k(  r||dW<   9dX|k(  r||dY<   EdZ|k(  r||d[<   Qd\|k(  r||d]<   ]|||<   d nd^|v r|d   j                  d   }|d   j                  d   }||z  }d^}||   j                  d   }	|dZ   j                  d   |	z  } |       5  t        |	|||_      }d d d        |j                         D ].  \  }
}|
j                  dd      }|j                  dd      }|||<   0 n#|d`   j                  d   }|da   j                  d   }|db   j                  d   }|d`   j                  dQ   }t!        dc |D              }|r|dd   j                  d   dz  n|de   j                  d   dz  } |       5  t#        |||||f      }d d d        |j                         D ]i  \  }
}|
j                  d dg      }|j                  dhdi      }|j                  djdk      }|j                  dldm      }|j                  dndo      }|j                  dpdq      }|j                  drds      }|j                  dtdu      }|j                  dvdw      }dP|v rl|j%                  dx      }dy|dQ<   dxj'                  |      }|j                  dQdR      }|d   ||j                  dPdS      <   |d   ||j                  dPdT      <   dz|v r.|j%                  dx      }dy|dQ<   dxj'                  |      }|||<   KdU|v r>|j%                  dx      }dy|dQ<   dxj'                  |      }|||j                  dUdV      <   |j                  d{d|      }|j                  d}d~      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|||<   l |s|j)                  |d       |S d| j*                  i}t-        |||| j.                         t1                |S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)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   $   K   | ]  }d |v  
 yw)r   NrD   rE   s     rH   rI   zZUNet2DConditionLoadersMixin._convert_ip_adapter_image_proj_to_diffusers.<locals>.<genexpr>  s     "C16Q;"CrJ   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_maprT   )r   
accelerater   r   r   r   NotImplementedErrorr   r   r   r   r   r   r   chunkr   r^   r   r   r   r   rA   r   rT   r   )rm   rP   r8   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                              rH   +_convert_ip_adapter_image_proj_to_diffuserszGUNet2DConditionLoadersMixin._convert_ip_adapter_image_proj_to_diffusers  s
   &(9 %*!2 $-=dG-L%. 
  ->)KJ&$%!",]";"A"A""E",]";"A"A!"D"I #2(;$7*?$  )..0 ;
U!$V^!D5:">2; 
*",_"="C"CA"F",_"="C"CA"F #?(;M`$ 
 )..0 ;
U!$X!G!/!7!7*!M!/!7!7&!I5:">2	; 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 +?
U!$-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+?Z j(#-o#>#D#DQ#G $.$?$E$Ea$H!.2FFJ&J",Z"8">">q"A#O4::1=ATTJ #A(;$8#)	$  )..0 ;
U!$X!G!/!7!7*!M5:">2; %/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 -?
U!$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[-?^ !,,-?,M  	 dkk*J%&68JWaimisist w   & ~ 4 s<   b?bb" b/(b<bb"b,/b9<cc                 |   ddl m}m}m} |r(t	               rddlm} nd}t        j                  d       |du rt        dd	      st        d
      i }d}|rnt        }	| j                  j                         D ]  }
|
j                  d      rd n| j                  j                   }|
j#                  d      r| j                  j$                  d   }n|
j#                  d      rCt'        |
t)        d               }t+        t-        | j                  j$                              |   }nA|
j#                  d      r0t'        |
t)        d               }| j                  j$                  |   }|d|
v r%| j                  |
   j.                  } |       ||
<   dt1        | j                  |
   j.                        v r|}nt3        t4        d      r|n|}g }|D ]S  }d|d   v r|dgz  }d|d   v r|dgz  }d|d   v r|dgz  }-d|d   v r|dgz  };||d   d   j6                  d   gz  }U  |	       5   ||d|      ||
<   d d d        i }t9        |      D ]E  \  }}|j;                  d | d!|d"   | d#   i       |j;                  d$| d!|d"   | d%   i       G |s||
   j=                  |       nnt?        tA        |jC                                     jD                  }t?        tA        |jC                                     jF                  }d&|i}tI        ||
   |||'       |dz  } tK                |S # 1 sw Y   xY w)(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   rx   r_   rM   configr   r   block_out_channelsintr   r   reversed	__class__strhasattrFr   	enumerateupdater   nextiterrj   rA   rT   r   r   )rm   state_dictsr8   r  r  r  r   
attn_procskey_idr  r   r   r   block_idattn_processor_classr   rP   r   irA   rT   r  s                         rH   %_convert_ip_adapter_attn_to_diffuserszAUNet2DConditionLoadersMixin._convert_ip_adapter_attn_to_diffusers  s   	
 	
 &(9 %*!2 $-=dG-L%.  
->)K((--/ >	D*.--8I*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
4 T%9%9$%?%I%I!JJ+I( #1&DE 23 )
 )+%"- `J$
<(@@-!4-(J|,DD-#6-=LAYY-!4-&*\*BB-!4- .*\2J92U2[2[\]2^1__-`" "^ ';$/,?!#8	(Jt$  
%.{%; uMAz%%!G'<j>VZ`YaapWq>r&st%%!G'<j>VZ`YaapWq>r&stu )t$44Z@!$z'8'8':";<CCF j&7&7&9!:;AAE"$fJ-j.>
Waino!}>	@ 	3 s   ,L22L;	c                    t        |t              s|g}| j                  6| j                  j                  dk(  rt        | d      s| j                  | _        d | _        | j                  ||      }| j                  |       g }|D ])  }| j                  |d   |      }|j                  |       + t        |      | _        d| j                  _        | j                  | j                  | j                         y )N	text_projtext_encoder_hid_proj)r8   r"  ip_image_projrS   )rX   r   encoder_hid_projr%  encoder_hid_dim_typer+  r:  r7  re   r  appendr   rf   rT   rA   )rm   r1  r8   r2  image_projection_layersrP   image_projection_layers          rH   _load_ip_adapter_weightsz4UNet2DConditionLoadersMixin._load_ip_adapter_weights\  s    +t,&-K !!-00K?D"9:)-)>)>D& !%??_p?q

+ #%% 	CJ%)%U%U<(<M &V &" $**+AB		C !>>U V+:(djj5r   c                    i }t        | j                  j                               D ]G  \  }}t        |      D ]2  \  }}| d|d   v s||vri ||<   ||   j                  d| d|d   | d   i       ||   j                  d| d|d   | d   i       ||   j                  d| d|d   | d   i       ||   j                  d| d|d   | d   i       ||   j                  d| d|d   | d   i       ||   j                  d| d|d   | d   i       ||   j                  d| d	|d   | d	   i       ||   j                  d| d
|d   | d
   i       5 J |S )Nz.to_k_lora.down.weightr$  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)r-  rx   r_   r.  )rm   r1  
lora_dictsr3  r   r6  rP   s          rH   _load_ip_adapter_lorasz2UNet2DConditionLoadersMixin._load_ip_adapter_loras|  sX   
%d&:&:&?&?&AB 0	LFD!*;!7 /:X34
<8PP
*(*
1qM((#D6)?@*\BZ#)(*@ AC qM((#D6)?@*\BZ#)(*@ AC qM((#D6)?@*\BZ#)(*@ AC qM((#D6)ABJ|D\#)(*B CE qM(( &:;Z=UY_X``tVu=vw qM(( &:;Z=UY_X``tVu=vw qM(( &:;Z=UY_X``tVu=vw qM((#D6)?@*\BZ#)(*@ ACS/0	b r   )TNNT)__name__
__module____qualname____doc__r$   text_encoder_namer%   rc   r	   r   r*  r   r[   r   rN   ra   rb   classmethodrd   r   PathLikeboolr   r   r   r   r  r7  rA  rD  rD   r   rH   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   rZ   r[   torch.nn.functionalrk   
functionalr,  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_loggerrE  r   r   r   r(   rD   r   rH   <module>r\     s    
 # "  ( (     6  C O   3 : ` ` " 
		H	%  F $R !s sr   