
    +h                    "   S SK r S SKJrJrJrJrJr  S SKrS SK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Jr  SSKJrJrJrJr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'J(r(J)r)J*r*  S	r+\" S
S5      (       a6  \" 5       (       a*  \" S
S5      (       a  \" 5       (       a  \" SS5      (       a  Sr+\RX                  " \-5      r.Sr/Sr0Sr1SS0r2S r3 " S S\5      r4 " S S\5      r5 " S S\5      r6 " S S\5      r7 " S S\5      r8 " S  S!\45      r9 " S" S#\5      r: " S$ S%\5      r; " S& S'\5      r< " S( S)\5      r= " S* S+\5      r> " S, S-\5      r? " S. S/\5      r@ " S0 S1\5      rA " S2 S3\5      rB " S4 S5\5      rC " S6 S7\5      rD " S8 S9\45      rEg):    N)CallableDictListOptionalUnion)validate_hf_hub_args   )USE_PEFT_BACKEND	deprecateget_submodule_by_nameis_bitsandbytes_availableis_gguf_availableis_peft_availableis_peft_versionis_torch_versionis_transformers_availableis_transformers_versionlogging   )LORA_WEIGHT_NAMELORA_WEIGHT_NAME_SAFELoraBaseMixin_fetch_state_dict_load_lora_into_text_encoder_pack_dict_with_prefix)+_convert_bfl_flux_control_lora_to_diffusers&_convert_fal_kontext_lora_to_diffusers(_convert_hunyuan_video_lora_to_diffusers%_convert_kohya_flux_lora_to_diffusers%_convert_musubi_wan_lora_to_diffusers0_convert_non_diffusers_hidream_lora_to_diffusers(_convert_non_diffusers_lora_to_diffusers-_convert_non_diffusers_ltxv_lora_to_diffusers0_convert_non_diffusers_lumina2_lora_to_diffusers-_convert_non_diffusers_qwen_lora_to_diffusers,_convert_non_diffusers_wan_lora_to_diffusers%_convert_xlabs_flux_lora_to_diffusers"_maybe_map_sgm_blocks_to_diffusersF>=z1.9.00.13.1>z4.45.2Ttext_encoderunettransformer
x_embedderin_channelsc                    [        5       (       a  SSKJn  [        5       (       a  SSKJn  UR                  R                  R                  S:H  nUR                  R                  R                  S:H  nUR                  R                  R                  S:H  nU(       a  [        5       (       d  [        S5      eU(       a  [        5       (       d  [        S5      eU(       a  [        5       (       d  [        S	5      eS
nUR                  R                  R                  S:X  a  Sn[        [        S5      (       a(  [        R                  R                  5       R                  OSnU(       d  U(       ap  W" U(       a  UR                  R!                  U5      OUR                  U(       a  UR                  R"                  OUR$                  U R&                  S9R(                  n	OmU(       aP  W" U(       a  UR                  R!                  U5      OUR                  5      n	U	R!                  U R&                  5      n	OUR                  R(                  n	U(       a  U	R+                  5       n	U	$ )Nr	   )dequantize_bnb_weight)dequantize_gguf_tensor
Params4bit
Int8ParamsGGUFParameterz~The checkpoint seems to have been quantized with `bitsandbytes` (4bits). Install `bitsandbytes` to load quantized checkpoints.z~The checkpoint seems to have been quantized with `bitsandbytes` (8bits). Install `bitsandbytes` to load quantized checkpoints.zfThe checkpoint seems to have been quantized with `gguf`. Install `gguf` to load quantized checkpoints.FcpuTacceleratorcuda)statedtype)r   quantizers.bitsandbytesr2   r   quantizers.gguf.utilsr3   weight	__class____name__
ValueErrordevicetypehasattrtorchr8   current_acceleratortoquant_stater:   r;   datar7   )
modelmoduler2   r3   is_bnb_4bit_quantizedis_bnb_8bit_quantizedis_gguf_quantizedweight_on_cpurB   module_weights
             Y/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/loaders/lora_pipeline.py*_maybe_dequantize_weight_for_expanded_lorarR   O   s    ""CB"MM33<<L"MM33<<L//88OK%>%@%@ M
 	
 %>%@%@ M
 	
 !2!4!4t
 	
 M}}  E)=DUM=Z=ZU22499`fF 5-(5FMMV$6==/D&--++&,,++
 $	 	
 
.(5FMMV$6==
 &((5**%))+    c                   `  ^  \ rS rSrSrSS/r\r\r	  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\\S\
\\\\R                  4   4   4S j5       5       r\     SS	\4S jj5       r\       S S	\4S jj5       r\        S!S\
\\R0                  4   S\\\
\R2                  R4                  \R                  4   4   S\\\R2                  R4                  4   S\S\S\S\4S jj5       rSS/SSS4S\\   S\S\S\\\      4U 4S jjjrSS/4S\\   4U 4S jjjr Sr!U =r"$ )"StableDiffusionLoraLoaderMixin   z
Load LoRA layers into Stable Diffusion [`UNet2DConditionModel`] and
[`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
r-   r,   NF%pretrained_model_name_or_path_or_dictadapter_namehotswapc                    [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       d  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pgn[        S UR                  5        5       5      n	U	(       d  [        S	5      eU R                  UU[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  U R!                  UU[        U S5      (       d  [        X R"                  5      OU R$                  U R&                  UU UUUS9	  g)aw
  Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
`self.text_encoder`.

All kwargs are forwarded to `self.lora_state_dict`.

See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`] for more details on how the state dict is
loaded.

See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is
loaded into `self.unet`.

See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state
dict is loaded into `self.text_encoder`.

Parameters:
    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
    adapter_name (`str`, *optional*):
        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.
    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
    kwargs (`dict`, *optional*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
)PEFT backend is required for this method.low_cpu_mem_usager)   r*   q`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`.Treturn_lora_metadatac              3   ,   #    U  H
  nS U;   v   M     g7floraN .0keys     rQ   	<genexpr>CStableDiffusionLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>        K9J##9J   Invalid LoRA checkpoint.r-   network_alphasr-   rX   metadata	_pipeliner\   rY   r,   )rl   r,   
lora_scalerX   rn   rm   r\   rY   N)r
   rA   pop_LOW_CPU_MEM_USAGE_DEFAULT_LORAr   
isinstancedictcopylora_state_dictallkeysload_lora_into_unetrD   getattr	unet_namer-   load_lora_into_text_encodertext_encoder_namer,   ro   
selfrW   rX   rY   kwargsr\   
state_dictrl   rm   is_correct_formats
             rQ   load_lora_weights0StableDiffusionLoraLoaderMixin.load_lora_weights   s[   p  HII"JJ':<[\_T8%D%D D 
 ;TBB4Y4^4^4`1 *.%&/3/C/CDi/tms/t,
HK9JKK 788  )6=dF6K6K~~.QUQZQZ%/ 	! 		
 	(()400 !'='=>""%/ 	) 	
rS   c                 P   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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnSn[        S UR                  5        5       5      (       a  Ub  [        UU5      n[        U5      u  nnU(       a  UUU4nU$ UU4nU$ s  snnf )	  
Return state dict for lora weights and the network alphas.

<Tip warning={true}>

We support loading A1111 formatted LoRA checkpoints in a limited capacity.

This function is experimental and might change in the future.

</Tip>

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.
    weight_name (`str`, *optional*, defaults to None):
        Name of the serialized state dict file.
    return_lora_metadata (`bool`, *optional*, defaults to False):
        When enabled, additionally return the LoRA adapter metadata, typically found in the state dict.
	cache_dirNforce_downloadFproxieslocal_files_onlytokenrevision	subfolderweight_nameunet_configuse_safetensorsr^   Tattn_procs_weightspytorch	file_type	frameworkrW   r   r   r   r   r   r   r   r   r   
user_agentallow_picklec              3   ,   #    U  H
  nS U;   v   M     g7f
dora_scaleNrb   rd   ks     rQ   rf   AStableDiffusionLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>I       #Jz!LA$5zri   !  It seems like you are using a DoRA checkpoint that is not compatible in Diffusers at the moment. So, we are going to filter out the keys associated to 'dora_scale` from the state dict. If you think this is a mistake please open an issue https://github.com/huggingface/diffusers/issues/new.r   c              3      #    U  H^  nUR                  S 5      =(       dA    UR                  S5      =(       d)    UR                  S5      =(       d    UR                  S5      v   M`     g7flora_te_
lora_unet_	lora_te1_	lora_te2_N
startswithr   s     rQ   rf   r   Q  ^      
 ' Z( -<<--<<,- <<,-
 '   A&A(
rp   r   anyloggerwarningitemsrv   rw   r(   r"   clsrW   r   r   r   r   r   r   r   r   r   r   r   r^   r   r   r   rm   is_dora_scale_presentwarn_msgr   vrl   outs                           rQ   ru   .StableDiffusionLoraLoaderMixin.lora_state_dict   s   r JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW 
  __&
 
 
 &?
KX
)QR\)]&J8Lz>84
 T^_mRn
) X   /F" F"c	                     [         (       d  [        S5      eU(       a  [        SS5      (       d  [        S5      e[        R	                  SU R
                   S35        UR                  UU R
                  UUUUUUS9  g	a  
This will load the LoRA layers specified in `state_dict` into `unet`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    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).
    unet (`UNet2DConditionModel`):
        The UNet model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    low_cpu_mem_usage (`bool`, *optional*):
        Speed up model loading only loading the pretrained LoRA weights and not initializing the random
        weights.
    hotswap (`bool`, *optional*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r[   r)   r*   r]   Loading .)prefixrl   rX   rm   rn   r\   rY   Nr
   rA   r   r   inforz   load_lora_adapter	r   r   rl   r-   rX   rn   r\   rY   rm   s	            rQ   rx   2StableDiffusionLoraLoaderMixin.load_lora_into_unetc  s    L  HII_T8%D%D D  	hs}}oQ/0==)%/ 	 		
rS         ?c                 >    [        UUUUUU R                  UU
UUU	S9  ga}  
This will load the LoRA layers specified in `state_dict` into `text_encoder`

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The key should be prefixed with an
        additional `text_encoder` to distinguish between unet lora layers.
    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).
    text_encoder (`CLIPTextModel`):
        The text encoder model to load the LoRA layers into.
    prefix (`str`):
        Expected prefix of the `text_encoder` in the `state_dict`.
    lora_scale (`float`):
        How much to scale the output of the lora linear layer before it is added with the output of the regular
        lora layer.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
)r   rl   ro   r,   r   r|   rX   rm   rn   r\   rY   Nr   r|   r   r   rl   r,   r   ro   rX   rn   r\   rY   rm   s              rQ   r{   :StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder  s4    X 	%!)!%!33%/	
rS   save_directoryunet_lora_layerstext_encoder_lora_layersis_main_processr   save_functionsafe_serializationc
           
         0 n
0 nU(       d  U(       d  [        S5      eU(       a*  U
R                  U R                  X R                  5      5        U(       a*  U
R                  U R                  X0R                  5      5        U(       a$  UR                  [        XR                  5      5        U	(       a$  UR                  [        XR                  5      5        U R                  U
UUUUUUS9  g)ux  
Save the LoRA parameters corresponding to the UNet and text encoder.

Arguments:
    save_directory (`str` or `os.PathLike`):
        Directory to save LoRA parameters to. Will be created if it doesn't exist.
    unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `unet`.
    text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
        encoder LoRA state dict because it comes from 🤗 Transformers.
    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 the traditional PyTorch way with `pickle`.
    unet_lora_adapter_metadata:
        LoRA adapter metadata associated with the unet to be serialized with the state dict.
    text_encoder_lora_adapter_metadata:
        LoRA adapter metadata associated with the text encoder to be serialized with the state dict.
zPYou must pass at least one of `unet_lora_layers` and `text_encoder_lora_layers`.r   r   r   r   r   r   lora_adapter_metadataN)rA   updatepack_weightsrz   r|   r   write_lora_layers)r   r   r   r   r   r   r   r   unet_lora_adapter_metadata"text_encoder_lora_adapter_metadatar   r   s               rQ   save_lora_weights0StableDiffusionLoraLoaderMixin.save_lora_weights  s    N 
 " $<oppc../?OP#c../GI^I^_`%!(()?@Z\i\i)jk-!((&'IK`K`a
 	!)+#'1"7 	 	
rS   
componentsro   safe_fusingadapter_namesc                 0   > [         TU ]  " SUUUUS.UD6  g  
Fuses the LoRA parameters into the original parameters of the corresponding blocks.

<Tip warning={true}>

This is an experimental API.

</Tip>

Args:
    components: (`List[str]`): List of LoRA-injectable components to fuse the LoRAs into.
    lora_scale (`float`, defaults to 1.0):
        Controls how much to influence the outputs with the LoRA parameters.
    safe_fusing (`bool`, defaults to `False`):
        Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
    adapter_names (`List[str]`, *optional*):
        Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.

Example:

```py
from diffusers import DiffusionPipeline
import torch

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.fuse_lora(lora_scale=0.7)
```
r   ro   r   r   Nrb   super	fuse_lorar~   r   ro   r   r   r   r?   s         rQ   r   (StableDiffusionLoraLoaderMixin.fuse_lora   .    N 	 	
!!#'		

 	
rS   c                 *   > [         TU ]  " SSU0UD6  gab  
Reverses the effect of
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora).

<Tip warning={true}>

This is an experimental API.

</Tip>

Args:
    components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from.
    unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
    unfuse_text_encoder (`bool`, defaults to `True`):
        Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
        LoRA parameters then it won't have any effect.
r   Nrb   r   unfuse_lorar~   r   r   r?   s      rQ   r   *StableDiffusionLoraLoaderMixin.unfuse_loraO      $ 	<z<V<rS   rb   NFNNFFNNr   NNFFNNNTNNTNN#r@   
__module____qualname____firstlineno____doc___lora_loadable_modules	UNET_NAMErz   TEXT_ENCODER_NAMEr|   r   strr   rE   Tensorr   boolr   classmethodr   ru   rx   r{   osPathLikennModuler   r   r   floatr   r   __static_attributes____classcell__r?   s   @rQ   rU   rU      s>   
 %n5I)
 '+	c
/4S$sELL?P:Q5Q/Rc
 smc
 	c
J p/4S$sELL?P:Q5Q/Rp  pd  :
 :
 :
x  7
 7
 7
r  MQ?C $"&#'#'+/C
c2;;./C
 sE%((//5<<*G$HHIC
 #'sEHHOO';"<	C

 C
 C
  C
 !C
 C
N "( 8!-1-
I-
 -
 	-

  S	*-
 -
^ 4:>2J =d3i = =rS   rU   c                     ^  \ rS rSrSr/ SQr\r\r	  SS\
\\\\R                  4   4   S\\   S\4S	 jjr\\S\
\\\\R                  4   4   4S
 j5       5       r\     SS\4S jj5       r\       S S\4S jj5       r\          S!S\
\\R0                  4   S\\\
\R2                  R4                  \R                  4   4   S\\\
\R2                  R4                  \R                  4   4   S\\\
\R2                  R4                  \R                  4   4   S\S\S\S\4S jj5       r/ SQSSS4S\\   S\S\S\\\      4U 4S jjjr/ SQ4S\\   4U 4S jjjr Sr!U =r"$ )" StableDiffusionXLLoraLoaderMixinid  a3  
Load LoRA layers into Stable Diffusion XL [`UNet2DConditionModel`],
[`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), and
[`CLIPTextModelWithProjection`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection).
)r-   r,   text_encoder_2NFrW   rX   rY   c                    [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       d  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U4SU R                  R                  0UD6u  pgn[        S	 UR                  5        5       5      n	U	(       d  [        S
5      eU R                  UUU R                  UUU UUS9  U R                  UUU R                  U R                   U R"                  UUU UUS9
  U R                  UUU R$                  U R                    S3U R"                  UUU UUS9
  g)a7  
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
`self.text_encoder`.

All kwargs are forwarded to `self.lora_state_dict`.

See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`] for more details on how the state dict is
loaded.

See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is
loaded into `self.unet`.

See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state
dict is loaded into `self.text_encoder`.

Parameters:
    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    kwargs (`dict`, *optional*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
r[   r\   r)   r*   r]   Tr^   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   EStableDiffusionXLLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   rk   	rl   r,   r   ro   rX   rm   rn   r\   rY   _2N)r
   rA   rp   rq   r   rr   rs   rt   ru   r-   configrv   rw   rx   r{   r,   r|   ro   r  r}   s
             rQ   r   2StableDiffusionXLLoraLoaderMixin.load_lora_weightso  s   H  HII"JJ':<[\_T8%D%D D  ;TBB4Y4^4^4`1 *.%&/3/C/C10
		((0
 0
,
H  K9JKK 788  )%/ 	! 		
 	(()**))%/ 	) 	
 	((),,,,-R0%/ 	) 	
rS   c                 P   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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnSn[        S UR                  5        5       5      (       a  Ub  [        UU5      n[        U5      u  nnU(       a  UUU4nU$ UU4nU$ s  snnf )r   r   Nr   Fr   r   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   CStableDiffusionXLLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>.  r   ri   r   r   c              3      #    U  H^  nUR                  S 5      =(       dA    UR                  S5      =(       d)    UR                  S5      =(       d    UR                  S5      v   M`     g7fr   r   r   s     rQ   rf   r  6  r   r   r   r   s                           rQ   ru   0StableDiffusionXLLoraLoaderMixin.lora_state_dict  s   t JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW 
  __&
 
 
 &?
KX
)QR\)]&J8Lz>84
 T^_mRn
) Xr   c	                     [         (       d  [        S5      eU(       a  [        SS5      (       d  [        S5      e[        R	                  SU R
                   S35        UR                  UU R
                  UUUUUUS9  gr   r   r   s	            rQ   rx   4StableDiffusionXLLoraLoaderMixin.load_lora_into_unetH  s    N  HII_T8%D%D D  	hs}}oQ/0==)%/ 	 		
rS   r   c                 >    [        UUUUUU R                  UU
UUU	S9  gr   r   r   s              rQ   r{   <StableDiffusionXLLoraLoaderMixin.load_lora_into_text_encoder  4    Z 	%!)!%!33%/	
rS   r   r   r   text_encoder_2_lora_layersr   r   r   r   c           
      `   0 n0 nU(       d  U(       d  U(       d  [        S5      eU(       a*  UR                  U R                  X R                  5      5        U(       a!  UR                  U R                  US5      5        U(       a!  UR                  U R                  US5      5        U	b$  UR                  [	        XR                  5      5        U
(       a$  UR                  [	        XR
                  5      5        U(       a  UR                  [	        US5      5        U R                  UUUUUUUS9  g)u  
Save the LoRA parameters corresponding to the UNet and text encoder.

Arguments:
    save_directory (`str` or `os.PathLike`):
        Directory to save LoRA parameters to. Will be created if it doesn't exist.
    unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `unet`.
    text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
        encoder LoRA state dict because it comes from 🤗 Transformers.
    text_encoder_2_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `text_encoder_2`. Must explicitly pass the text
        encoder LoRA state dict because it comes from 🤗 Transformers.
    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 the traditional PyTorch way with `pickle`.
    unet_lora_adapter_metadata:
        LoRA adapter metadata associated with the unet to be serialized with the state dict.
    text_encoder_lora_adapter_metadata:
        LoRA adapter metadata associated with the text encoder to be serialized with the state dict.
    text_encoder_2_lora_adapter_metadata:
        LoRA adapter metadata associated with the second text encoder to be serialized with the state dict.
zkYou must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, `text_encoder_2_lora_layers`.r,   r  Nr   )rA   r   r   rz   r   r|   r   )r   r   r   r   r  r   r   r   r   r   r   $text_encoder_2_lora_adapter_metadatar   r   s                 rQ   r   2StableDiffusionXLLoraLoaderMixin.save_lora_weights  s   \ 
 " $<@Z}  c../?OP#c../GXY%c../IK[\]%1!(()?@Z\i\i)jk-!((&'IK`K`a 0!((&'KM]^ 	!)+#'1"7 	 	
rS   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   *StableDiffusionXLLoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr   r   r   s      rQ   r   ,StableDiffusionXLLoraLoaderMixin.unfuse_loraF  r   rS   rb   r   r   r   
NNNTNNTNNNr   r  s   @rQ   r  r  d  sq    HI)
 '+	b
/4S$sELL?P:Q5Q/Rb
 smb
 	b
H p/4S$sELL?P:Q5Q/Rp  pd  :
 :
 :
x  7
 7
 7
r  MQTXVZ $"&#'#'+/-1S
c2;;./S
 sE%((//5<<*G$HHIS
 #'sE%((//5<<2O,P'P"Q	S

 %)eEHHOOU\\4Q.R)R$SS
 S
 S
  S
 !S
 S
n !K!-1-
I-
 -
 	-

  S	*-
 -
^ 3] =d3i = =rS   r  c                     ^  \ rS rSrSr/ SQr\r\r	\
\S\\\\\R                   4   4   4S j5       5       r  SS\\\\\R                   4   4   S\4S	 jjr\
     SS\4S
 jj5       r\
       SS\4S jj5       r\
          S S\\\R.                  4   S\\\\R0                  R2                  \R                   4   4   S\\\\R0                  R2                  \R                   4   4   S\\\\R0                  R2                  \R                   4   4   S\S\S\S\4S jj5       r/ SQSSS4S\\   S\S\S\\\      4U 4S jjjr/ SQ4S\\   4U 4S jjjr Sr!U =r"$ )!SD3LoraLoaderMixini[  aK  
Load LoRA layers into [`SD3Transformer2DModel`],
[`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), and
[`CLIPTextModelWithProjection`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection).

Specific to [`StableDiffusion3Pipeline`].
)r.   r,   r  rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )<	  
Return state dict for lora weights and the network alphas.

<Tip warning={true}>

We support loading A1111 formatted LoRA checkpoints in a limited capacity.

This function is experimental and might change in the future.

</Tip>

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.
    return_lora_metadata (`bool`, *optional*, defaults to False):
        When enabled, additionally return the LoRA adapter metadata, typically found in the state dict.

r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   5SD3LoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r   ri   r   r   rp   r   r   r   r   r   r   rW   r   r   r   r   r   r   r   r   r   r   r^   r   r   r   rm   r   r   r   r   r   s                         rQ   ru   "SD3LoraLoaderMixin.lora_state_dicth  s}   p JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW(<z8$
 CM
 X   E	.E	NFrY   c                    [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  U R!                  USU R"                  U R$                  U R&                  UUU UUS9
  U R!                  USU R(                  U R$                   S3U R&                  UUU UUS9
  g)a  
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
`self.text_encoder`.

All kwargs are forwarded to `self.lora_state_dict`.

See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`] for more details on how the state dict is
loaded.

See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_transformer`] for more details on how the state
dict is loaded into `self.transformer`.

Parameters:
    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    kwargs (`dict`, *optional*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
r[   r\   <0.13.0r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   7SD3LoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   r.   r.   rX   rm   rn   r\   rY   Nr	  r
  )r
   rA   rp   rq   r   rr   rs   rt   ru   rv   rw   load_lora_into_transformerrD   ry   transformer_namer.   r{   r,   r|   ro   r  	r~   rW   rX   rY   r   r\   r   rm   r   s	            rQ   r   $SD3LoraLoaderMixin.load_lora_weights  s   B  HII"JJ':<[\h!?!? D 
 ;TBB4Y4^4^4`1 *.%&#334Yd]cd
K9JKK 788''DKDR_D`D`&;&;<fjfvfv%/ 	( 	
 	((**))%/ 	) 	
 	((,,,,-R0%/ 	) 	
rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)a^  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`SD3Transformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nrl   rX   rm   rn   r\   rY   r   rA   r   r   r1  r   r   r   r.   rX   rn   r\   rY   rm   s           rQ   r0  -SD3LoraLoaderMixin.load_lora_into_transformer"  sm    B h!?!? D 
 	hs334A67%%%/ 	& 	
rS   r   c                 >    [        UUUUUU R                  UU
UUU	S9  gr   r   r   s              rQ   r{   .SD3LoraLoaderMixin.load_lora_into_text_encoderT  r  rS   r   transformer_lora_layersr   r  r   r   r   r   c           
      `   0 n0 nU(       d  U(       d  U(       d  [        S5      eU(       a*  UR                  U R                  X R                  5      5        U(       a!  UR                  U R                  US5      5        U(       a!  UR                  U R                  US5      5        U	b$  UR                  [	        XR                  5      5        U
(       a$  UR                  [	        XR
                  5      5        U(       a  UR                  [	        US5      5        U R                  UUUUUUUS9  g)u:  
Save the LoRA parameters corresponding to the UNet and text encoder.

Arguments:
    save_directory (`str` or `os.PathLike`):
        Directory to save LoRA parameters to. Will be created if it doesn't exist.
    transformer_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `transformer`.
    text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
        encoder LoRA state dict because it comes from 🤗 Transformers.
    text_encoder_2_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `text_encoder_2`. Must explicitly pass the text
        encoder LoRA state dict because it comes from 🤗 Transformers.
    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 the traditional PyTorch way with `pickle`.
    transformer_lora_adapter_metadata:
        LoRA adapter metadata associated with the transformer to be serialized with the state dict.
    text_encoder_lora_adapter_metadata:
        LoRA adapter metadata associated with the text encoder to be serialized with the state dict.
    text_encoder_2_lora_adapter_metadata:
        LoRA adapter metadata associated with the second text encoder to be serialized with the state dict.
zrYou must pass at least one of `transformer_lora_layers`, `text_encoder_lora_layers`, `text_encoder_2_lora_layers`.r,   r  Nr   )rA   r   r   r1  r   r|   r   )r   r   r;  r   r  r   r   r   r   !transformer_lora_adapter_metadatar   r  r   r   s                 rQ   r   $SD3LoraLoaderMixin.save_lora_weights  s   ^ 
 "'+CGa E  #c../FH\H\]^#c../GXY%c../IK[\],8!((&'HJ^J^_ .!((&'IK`K`a 0!((&'KM]^ 	!)+#'1"7 	 	
rS   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   SD3LoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  g)ai  
Reverses the effect of
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora).

<Tip warning={true}>

This is an experimental API.

</Tip>

Args:
    components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from.
    unfuse_transformer (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
    unfuse_text_encoder (`bool`, defaults to `True`):
        Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
        LoRA parameters then it won't have any effect.
r   Nrb   r   r   s      rQ   r   SD3LoraLoaderMixin.unfuse_lora  r   rS   rb   r   r   r   r  )#r@   r   r   r   r   r   TRANSFORMER_NAMEr1  r   r|   r   r   r   r   r   rE   r   ru   r   r   r0  r{   r   r   r   r   r   r   r   r   r   r   r   r   r  r  s   @rQ   r!  r!  [  sa    O')^/4S$sELL?P:Q5Q/R^  ^F 	V
/4S$sELL?P:Q5Q/RV
 	V
p 
 /
 /
 /
b  7
 7
 7
r 
 TXTXVZ $"&#'*.+/-1U
c2;;./U
 "&c5%,,1N+O&O!PU
 #'sE%((//5<<2O,P'P"Q	U

 %)eEHHOOU\\4Q.R)R$SU
 U
 U
  U
 !U
 U
t !R!-1-
I-
 -
 	-

  S	*-
 -
` 3d =d3i = =rS   r!  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrSS/4S\\   4U 4S jjjrSrU =r $ ) AuraFlowLoraLoaderMixini.  zX
Load LoRA layers into [`AuraFlowTransformer2DModel`] Specific to [`AuraFlowPipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )r#  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   :AuraFlowLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r   ri   r   r   r&  r'  s                         rQ   ru   'AuraFlowLoraLoaderMixin.lora_state_dict6  }   r JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW(<z8$
 CM
 Xr)  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)  
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.transformer` and
`self.text_encoder`. All kwargs are forwarded to `self.lora_state_dict`. See
[`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_transformer`] for more details on how the state
dict is loaded into `self.transformer`.

Parameters:
    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    kwargs (`dict`, *optional*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   <AuraFlowLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   r.   r/  Nr
   rA   rp   rq   r   rr   rs   rt   ru   rv   rw   r0  rD   ry   r1  r.   r2  s	            rQ   r   )AuraFlowLoraLoaderMixin.load_lora_weights     8  HII"JJ':<[\h!?!? D 
 ;TBB4Y4^4^4`1 *.%&#334Yd]cd
K9JKK 788''DKDR_D`D`&;&;<fjfvfv%/ 	( 	
rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ac  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`AuraFlowTransformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  2AuraFlowLoraLoaderMixin.load_lora_into_transformer  m    D h!?!? D 
 	hs334A67%%%/ 	& 	
rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  ga  
Save the LoRA parameters corresponding to the transformer.

Arguments:
    save_directory (`str` or `os.PathLike`):
        Directory to save LoRA parameters to. Will be created if it doesn't exist.
    transformer_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `transformer`.
    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 the traditional PyTorch way with `pickle`.
    transformer_lora_adapter_metadata:
        LoRA adapter metadata associated with the transformer to be serialized with the state dict.
z(You must pass `transformer_lora_layers`.Nr   rA   r   r   r1  r   r   
r   r   r;  r   r   r   r   r=  r   r   s
             rQ   r   )AuraFlowLoraLoaderMixin.save_lora_weights      B 
 "&GHH#**+BDXDXYZ,8!((&'HJ^J^_
 	!)+#'1"7 	 	
rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   !AuraFlowLoraLoaderMixin.fuse_loraB  r   rS   r,   c                 *   > [         TU ]  " SSU0UD6  ga  
Reverses the effect of
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora).

<Tip warning={true}>

This is an experimental API.

</Tip>

Args:
    components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from.
    unfuse_transformer (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
r   Nrb   r   r   s      rQ   r   #AuraFlowLoraLoaderMixin.unfuse_lorar       	<z<V<rS   rb   r   r   NTNNTN!r@   r   r   r   r   r   rC  r1  r   r   r   r   r   rE   r   ru   r   r   r   r0  r   r   r   r   r   rs   r   r   r   r   r   r   r  r  s   @rQ   rE  rE  .  s    ,_'^/4S$sELL?P:Q5Q/R^  ^H '+	9
/4S$sELL?P:Q5Q/R9
 sm9
 	9
v  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
t "/!-1-
I-
 -
 	-

  S	*-
 -
` 4A.2Q =d3i = =rS   rE  c                   \  ^  \ rS rSrSrSS/r\r\r	/ SQr
\\ S-S\\\\\R"                  4   4   S\4S	 jj5       5       r  S.S\\\\\R"                  4   4   S\\   S\4S jjr\     S/S\4S jj5       r\  S.S\\\R"                  4   4S jj5       r\       S0S\4S jj5       r\        S1S\\\R4                  4   S\\\\R6                  R8                  \R"                  4   4   S\\\R6                  R8                  4   S\S\S\S\4S jj5       rS/SSS
4S\\   S\ S\S\\\      4U 4S jjjr!SS/4S\\   4U 4S  jjjr"S-U 4S! jjr#\   S2S\R6                  R8                  S\4S" jj5       r$\S# 5       r%\&  S3S$S%S&S'S(\SS)4S* jj5       r'\&S4S+ j5       r(S,r)U =r*$ )5FluxLoraLoaderMixini  z
Load LoRA layers into [`FluxTransformer2DModel`],
[`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).

Specific to [`StableDiffusion3Pipeline`].
r.   r,   )norm_qnorm_knorm_added_qnorm_added_kFrW   return_alphasc                    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SnUc  SnSnSSS.n[        UUUUUUUUU	U
UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnn[        S U 5       5      nU(       a  [        U5      nU R                  UUSUUS9$ [        S U 5       5      nU(       a  [        U5      nU R                  UUSUUS9$ [        S U 5       5      nU(       a  [        U5      nU R                  UUSUUS9$ [        S U 5       5      nU(       a  [        U5      nU R                  UUSUUS9$ [        UR                  5       5      n0 nU H  nSU;   d  M  UR                  U5      n[        R                  " U5      (       a  [        R                   " U5      (       d  [#        U[$        5      (       a  UR                  U5      UU'   M}  ['        SU S35      e   U(       d  U(       a  U R                  UUUUUS9$ U$ s  snnf );	  
Return state dict for lora weights and the network alphas.

<Tip warning={true}>

We support loading A1111 formatted LoRA checkpoints in a limited capacity.

This function is experimental and might change in the future.

</Tip>

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.
    return_lora_metadata (`bool`, *optional*, defaults to False):
        When enabled, additionally return the LoRA adapter metadata, typically found in the state dict.
r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   6FluxLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r   ri   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7f)z.lora_down.weightNrb   r   s     rQ   rf   rm    s     DA*a/ri   )rm   alphasri  return_metadatac              3   ,   #    U  H
  nS U;   v   M     g7f)	processorNrb   r   s     rQ   rf   rm    s     <A{a'ri   c              3   ,   #    U  H
  nS U;   v   M     g7f)zquery_norm.scaleNrb   r   s     rQ   rf   rm    s     Ij/14jri   c              3   ,   #    U  H
  nS U;   v   M     g7f)
base_modelNrb   r   s     rQ   rf   rm    s     C
1\Q.
ri   alphazThe alpha key (zU) seems to be incorrect. If you think this error is unexpected, please open as issue.)rp   r   r   r   r   r   r   _prepare_outputsr'   r   r   listrw   getrE   	is_tensoris_floating_pointrr   r   rA   )r   rW   ri  r   r   r   r   r   r   r   r   r   r   r^   r   r   r   rm   r   r   r   r   is_kohyais_xlabsis_bfl_controlis_fal_kontextrw   rl   alpha_values                                rQ   ru   #FluxLoraLoaderMixin.lora_state_dict  sM   p JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW DDD>zJJ''!+ 4 (   <<<>zJJ''!+ 4 (   IjIIDZPJ''!+ 4 (   C
CC?
KJ''!+ 4 (   JOO%&A!|(nnQ/OOK00U5L5L[5Y5Y^h_ _ )3q(9N1%$)!  -B  C   0''!%+ 4 (   U Xs   K".K"NrX   rY   c                 
  ^ ^ [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       d  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   T R                  " U4SS0UD6u  pgn[        S	 UR                  5        5       5      n	[        U 4S
 jUR                  5        5       5      n
U	(       d  U
(       d  [        S5      e[        UR                  5       5       Vs0 s HA  nUR                  T R                   S35      (       d  M(  SU;   d  M0  XR                  U5      _MC     nn[        UR                  5       5       V^s0 s H`  mTR                  T R                   S35      (       d  M(  [        U4S jT R                   5       5      (       d  MN  TUR                  T5      _Mb     nn[!        T S5      (       d  [#        T T R                  5      OT R$                  nSn['        U5      S:  a  T R)                  XU5      nU(       a  [*        R-                  S5        ['        U5      S:  a.  T R/                  XS9nU H  mUR1                  TUT   05        M     T R3                  UUUUUT UUS9  ['        U5      S:  a  T R5                  UUSS9Ul        T R9                  UUT R:                  T R<                  T R>                  UUT UUS9
  gs  snf s  snf )a  
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.transformer` and
`self.text_encoder`.

All kwargs are forwarded to `self.lora_state_dict`.

See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`] for more details on how the state dict is
loaded.

See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_transformer`] for more details on how the state
dict is loaded into `self.transformer`.

Parameters:
    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    kwargs (`dict`, *optional*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
r[   r\   r)   r*   r]   Tr^   ri  c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   8FluxLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>m  s     G5FcFcM5Fri   c              3   T   >#    U  H  nTR                     H	  o"U;   v   M     M     g 7fN!_control_lora_supported_norm_keys)rd   re   norm_keyr~   s      rQ   rf   r  p  s&      
'8IoIoXOIoO'8   %(rj   r   ra   c              3   ,   >#    U  H	  oT;   v   M     g 7fr  rb   )rd   r  r   s     rQ   rf   r    s     Y2XhM2Xs   r.   Fr   a  The LoRA weights contain parameters that have different shapes that expected by the transformer. As a result, the state_dict of the transformer has been expanded to match the LoRA parameter shapes. To get a comprehensive list of parameter names that were modified, enable debug logging.)r.   ru   )rl   r.   rX   rm   rn   r\   rY   )r.   discard_original_layersr	  N) r
   rA   rp   rq   r   rr   rs   rt   ru   r   rw   rx  r   r1  ry  r  rD   ry   r.   len/_maybe_expand_transformer_param_shape_or_error_r   r   _maybe_expand_lora_state_dictr   r0  _load_norm_into_transformer_transformer_norm_layersr{   r,   r|   ro   )r~   rW   rX   rY   r   r\   r   rl   rm   has_lora_keyshas_norm_keysr   transformer_lora_state_dicttransformer_norm_state_dictr.   has_param_with_expanded_shapes   `          `    rQ   r   %FluxLoraLoaderMixin.load_lora_weights9  s,   B  HII"JJ':<[\_T8%D%D D 
 ;TBB4Y4^4^4`1 *.%&/3/C/C10
AE0
IO0
,
H GZ__5FGG  
'1'8
 
 788 *//+,'
,||t445Q78 !=Cq[ !A~~a  , 	$ '
 *//+,'
,||t445Q78 ! Y$2X2XYY !Az~~a  , 	$ '
 CJ$P]B^B^gdD$9$9:dhdtdt(-%*+a/,0,`,`:U-) )KKk
 *+a/*.*L*L' +M +' 1!!1&A!&D"EF 1 	'')#%/ 	( 		
 *+a/373S3S+'(- 4T 4K0 	(()**))%/ 	) 	
e'

'
s$   'K;6K;>K;1'L "L L c	           
          U(       a  [        SS5      (       d  [        S5      e[        R                  SU R                   S35        UR                  UUUUUUUS9  g)a  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    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).
    transformer (`FluxTransformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r)   r*   r]   r   r   r5  Nr6  	r   r   rl   r.   rX   rm   rn   r\   rY   s	            rQ   r0  .FluxLoraLoaderMixin.load_lora_into_transformer  sm    L _T8%D%D D 
 	hs334A67%%)%/ 	& 	
rS   returnc                 .  ^  U=(       d    T R                   n[        UR                  5       5       HB  nUR                  S5      S   U:X  d  M  UR	                  U5      XR                  U S35      '   MD     UR                  5       n[        UR                  5       5      n[        UR                  5       5      n[        X-
  5      n	U	(       a  [        R                  SU	 S35        U	 H  nUR	                  U5        M     0 n
U(       d+  UR                  5        H  nXe   R                  5       X'   M     [        R                  S5        UR                  USS9n[        USS 5      nU(       a)  [        U 4S jU 5       5      (       a  [        S	U S
35      eU
$ )Nr   r   zUnsupported keys found in state dict when trying to load normalization layers into the transformer. The following keys will be ignored:
aW  The provided state dict contains normalization layers in addition to LoRA layers. The normalization layers will directly update the state_dict of the transformer as opposed to the LoRA layers that will co-exist separately until the "fuse_lora()" method is called. That is to say, the normalization layers will always be directly fused into the transformer and can only be unfused if `discard_original_layers=True` is passed. This might also have implications when dealing with multiple LoRAs. If you notice something unexpected, please open an issue: https://github.com/huggingface/diffusers/issues.Fstrictunexpected_keysc              3   T   >#    U  H  nTR                     H	  o"U;   v   M     M     g 7fr  r  )rd   r   r  r   s      rQ   rf   BFluxLoraLoaderMixin._load_norm_into_transformer.<locals>.<genexpr>	  s"     p/Q#JoJohq=Jo=/r  zFound zJ as unexpected keys while trying to load norm layers into the transformer.)r1  rx  rw   splitrp   removeprefixr   setr   r   cloner   load_state_dictry   r   rA   )r   r   r.   r   r  re   transformer_state_dicttransformer_keysstate_dict_keys
extra_keysoverwritten_layers_state_dictincompatible_keysr  s   `            rQ   r  /FluxLoraLoaderMixin._load_norm_into_transformer  s    /3//
)*Cyy~a F*=G^^C=P
++vhaL9: +
 "-!7!7!95::<=joo/0/<=
NN \  ]g  \h  hi  j CNN3  )+%&!(5K5P5V5V5X-2 ) 	y	
 (77
57Q!"35FM p/ppp _--wx  -,rS   r   c                 >    [        UUUUUU R                  UU
UUU	S9  gr   r   r   s              rQ   r{   /FluxLoraLoaderMixin.load_lora_into_text_encoder#	  r  rS   r   r;  r   r   r   r   r   c
           
         0 n
0 nU(       d  U(       d  [        S5      eU(       a*  U
R                  U R                  X R                  5      5        U(       a*  U
R                  U R                  X0R                  5      5        U(       a$  UR                  [        XR                  5      5        U	(       a$  UR                  [        XR                  5      5        U R                  U
UUUUUUS9  g)u  
Save the LoRA parameters corresponding to the UNet and text encoder.

Arguments:
    save_directory (`str` or `os.PathLike`):
        Directory to save LoRA parameters to. Will be created if it doesn't exist.
    transformer_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `transformer`.
    text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
        encoder LoRA state dict because it comes from 🤗 Transformers.
    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 the traditional PyTorch way with `pickle`.
    transformer_lora_adapter_metadata:
        LoRA adapter metadata associated with the transformer to be serialized with the state dict.
    text_encoder_lora_adapter_metadata:
        LoRA adapter metadata associated with the text encoder to be serialized with the state dict.
zWYou must pass at least one of `transformer_lora_layers` and `text_encoder_lora_layers`.r   N)rA   r   r   r1  r|   r   r   )r   r   r;  r   r   r   r   r   r=  r   r   r   s               rQ   r   %FluxLoraLoaderMixin.save_lora_weights^	  s    P 
 "'+Cvww"c../FH\H\]^#c../GI^I^_`,!((&'HJ^J^_ .!((&'IK`K`a
 	!)+#'1"7 	 	
rS   r   ro   r   r   c                 l  > [        U S5      (       d  [        X R                  5      OU R                  n[        US5      (       a[  [	        UR
                  [        5      (       a<  [        UR
                  R                  5       5      S:  a  [        R                  S5        [        TU ]0  " SUUUUS.UD6  g)r   r.   r  r   a  The provided state dict contains normalization layers in addition to LoRA layers. The normalization layers will be directly updated the state_dict of the transformer as opposed to the LoRA layers that will co-exist separately until the 'fuse_lora()' method is called. That is to say, the normalization layers will always be directly fused into the transformer and can only be unfused if `discard_original_layers=True` is passed.r   Nrb   )rD   ry   r1  r.   rr   r  rs   r  rw   r   r   r   r   )r~   r   ro   r   r   r   r.   r?   s          rQ   r   FluxLoraLoaderMixin.fuse_lora	  s    P CJ$P]B^B^gd$9$9:dhdtdtK!;<<;??FFK88==?@1DKKr 	 	
!!#'		

 	
rS   c                   > [        U S5      (       d  [        X R                  5      OU R                  n[        US5      (       a+  UR                  (       a  UR                  UR                  SS9  [        TU ]  " SSU0UD6  g)a,  
Reverses the effect of
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora).

<Tip warning={true}>

This is an experimental API.

</Tip>

Args:
    components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from.
r.   r  Fr  r   Nrb   )rD   ry   r1  r.   r  r  r   r   )r~   r   r   r.   r?   s       rQ   r   FluxLoraLoaderMixin.unfuse_lora	  sr     CJ$P]B^B^gd$9$9:dhdtdt; :;;@d@d''(L(LUZ'[<z<V<rS   c           
        > [         TU ]  5         [        U S5      (       d  [        X R                  5      OU R
                  n[        US5      (       a2  UR                  (       a!  UR                  UR                  SS9  SUl        U(       Ga?  [        USS5      Gb/  UR                  n[        5       nU H<  nUR                  S5      (       d  M  UR                  UR                  SS5      5        M>     UR                  5        GH  u  pg[        U[        R                   R"                  5      (       d  M1  Xd;   d  M8  UR$                  R&                  nUR(                  b  UR(                  R&                  OSn	U	SLn
UR+                  S	5      u  pnUR-                  U5      nX6 S3   nUR.                  S
   UR.                  S   nn[        R0                  " S5         [        R                   R#                  UUU
UR2                  S9nSSS5        SU0nU	b  UR5                  SX6 S3   05        WR                  USSS9  [7        XU5        AU[8        ;   d  GMT  [8        U   n[;        UR.                  S
   5      n[        UR<                  U5      n[7        UR<                  UU5        [>        RA                  SU SU SU S	35        GM     ggg! , (       d  f       N= f)a  
Unloads the LoRA parameters.

Args:
    reset_to_overwritten_params (`bool`, defaults to `False`): Whether to reset the LoRA-loaded modules
        to their original params. Refer to the [Flux
        documentation](https://huggingface.co/docs/diffusers/main/en/api/pipelines/flux) to learn more.

Examples:

```python
>>> # Assuming `pipeline` is already loaded with the LoRA parameters.
>>> pipeline.unload_lora_weights()
>>> ...
```
r.   r  Fr  N_overwritten_params.weight r   r   r   metabiasr;   r>   r  .biasT)assignr  Set the  attribute of the model to  from )!r   unload_lora_weightsrD   ry   r1  r.   r  r  r  r  endswithaddreplacenamed_modulesrr   rE   r   Linearr>   rI   r  
rpartitionget_submoduleshaperB   r;   r   setattr"_MODULE_NAME_TO_ATTRIBUTE_MAP_FLUXintr  r   r   )r~   reset_to_overwritten_paramsr.   overwritten_paramsmodule_names
param_namenamerK   rP   module_biasr  parent_module_name_current_module_nameparent_modulecurrent_param_weightin_featuresout_featuresoriginal_moduletmp_state_dictattribute_name	new_value	old_valuer?   s                          rQ   r  'FluxLoraLoaderMixin.unload_lora_weights	  s   " 	#%BI$P]B^B^gd$9$9:dhdtdt; :;;@d@d''(L(LUZ'[37K0&7;@UW[+\+h!,!@!@5L0
&&y11 $$Z%7%7	2%FG 1 !, 9 9 ;fehhoo664;O$*MM$6$6M6<kk6M&++"2"2SWK&d2DAEQTAU>&+>$/$=$=>P$QM+=g>N+O(0D0J0J10MOcOiOijkOlKf-*/((//'(!%"/"5"5	 +: + . '/0D%EN".&--v7IFRW.7Y.Z[#33N4X\3]MP&*.PP)KL_)`$'(<(B(B1(E$F	$+K,>,>$O	 2 2NIN&~&66QR[Q\\bclbmmnoA !< ,i&& .-s   +K
K	c           
         0 nUb  UR                  U5        Ub  UR                  U5        U=(       d    U R                  n[        UR                  5       5       HB  nUR	                  S5      S   U:X  d  M  UR                  U5      XVR                  U S35      '   MD     Sn0 n[        USS5      SLn	[        US5      n
UR                  5        GH  u  p[        U[        R                  R                  5      (       d  M1  UR                  R                  nUR                   b  UR                   R                  OSnUSLnU	(       a  UR#                  SS5      OUnU S	3nU S
3nUU;  a  M  UU   R$                  S   nUU   R$                  S   nU R'                  XS9n[)        U5      UU4:X  a  M  Uu  nnSnUU:  a  USU SU SU 3-  nUU:  a  USU SU S3-  nOUS-  nU(       a  [*        R-                  U5        UU:  d	  UU:  d  GMA  SnUR/                  S5      u  nnnUR1                  U5      nU
(       a  [3        X5      n[        R4                  " S5         [        R                  R                  UUXR6                  S9nSSS5        [        R8                  " WR                  R                  UR4                  UR6                  S9n[)        S U 5       5      nUUU'   SU0n Ub  UU S'   UR;                  U SSS9  [=        UUU5        A U[>        ;   a  [>        U   n![A        UR                  R                  R$                  S   5      n"[        URB                  U!5      n#[=        URB                  U!U"5        [*        RE                  SU! SU" SU# S35        XU S3'   Uc  GM  XU S3'   GM     [G        U5      S:  a  Xl$        U$ ! , (       d  f       GNJ= f)z
Control LoRA expands the shape of the input layer from (3072, 64) to (3072, 128). This method handles that and
generalizes things a bit so that any parameter that needs expansion receives appropriate treatment.
Nr   r   Fpeft_confighf_quantizerz.base_layerr  .lora_A.weight.lora_B.weightr   )rJ   base_modulez:Expanding the nn.Linear input/output features for module="z" because the provided LoRA checkpoint contains higher number of features than expected. The number of input_features will be expanded from z to z:, and the number of output features will be expanded from Tr  r  )rB   r;   c              3   :   #    U  H  n[        S U5      v   M     g7f)r   N)slice)rd   dims     rQ   rf   VFluxLoraLoaderMixin._maybe_expand_transformer_param_shape_or_error_.<locals>.<genexpr>
  s     "P<OS5C==<Os   r>   r  )r  r  r  r  r  r  r  )%r   r1  rx  rw   r  rp   r  ry   rD   r  rr   rE   r   r  r>   rI   r  r  r  _calculate_module_shapetupler   debugr  r  rR   rB   r;   
zeros_liker  r  r  r  r  r   r  r  )$r   r.   ru   norm_state_dictr   r   re   has_param_with_shape_updater  is_peft_loadedis_quantizedr  rK   rP   r  r  lora_base_namelora_A_weight_namelora_B_weight_namer  r  module_weight_shapemodule_out_featuresmodule_in_featuresdebug_messager  r  r  r  expanded_module
new_weightslicesr  r  r  r  s$                                       rQ   r  CFluxLoraLoaderMixin._maybe_expand_transformer_param_shape_or_error_<
  s+    
&o.&o. /3//
)*Cyy~a F*=G^^C=P
++vhaL9: +
 ',# mTB$N{N;'557LD&%((//22 & 2 228++2Ifkk..t"$.DRmR!@X\(6'7~%F"(6'7~%F"%Z7();<BB1E)*<=CCAF
 '*&A&A&A&h# ,-,1LL:M7#%7 "!33!TUYTZ [));(<DOM
  "55!))<(=T,qRM
 "S(M LL/"55GY9Y26/AEQTAU>&+>$/$=$=>P$QM#(RS^(g f-*/((//'DH[H[ +: + . "'!1!1'..33M<P<PXeXkXk"J #"P<O"PPF)6Jv&&.
%;N".1<v.#33N4X\3]M+>P&*.PP)KL_)`$'(>(>(C(C(I(I!(L$M	$+K,>,>$O	 2 2NIN&~&66QR[Q\\bclbmmno KX*=)>g'FG".LW.A-B%+HIo 8r !"Q&.@+**S .-s   *O
O	c                    [        5       nUR                  5       nU R                   S3nU Vs/ s H)  ofR                  S5      (       d  M  US [	        S5      *  PM+     nnU Vs/ s H(  oR                  U5      (       d  M  U[	        U5      S  PM*     nn[        [        U5      5      n[        UR                  5        VV	s1 s H  u  pUiM	     sn	n5      n
[        U5      [        U
5      -
  nU(       a  [        R                  SU S35        U GH3  nX;   a  M  UR                  US5       S3U;   a  UR                  US5       S3OUR                  US5       S3nXM   nX% U S3   nU R                  XS9nUS	   UR                  S	   :  a  UR                  S
   UR                  S	   4n[        R                  " UUR                  S9nUS S 2S UR                  S	   24   R!                  U5        UX% U S3'   UR#                  U5        GM  US	   UR                  S	   :  d  GM  [%        SU SUR                   S35      e   U(       a&  [        R'                  SU R                   SU S35        U$ s  snf s  snf s  sn	nf )Nr   r  zFound unexpected modules: z. These will be ignored.r  z.base_layer.weightr  )rJ   base_weight_param_namer   r   rB   zThis LoRA param (z*.lora_A.weight) has an incompatible shape zk. Please open an issue to file for a feature request - https://github.com/huggingface/diffusers/issues/new.zGThe following LoRA modules were zero padded to match the state dict of z: zn. Please open an issue if you think this was unexpected - https://github.com/huggingface/diffusers/issues/new.)r  r   r1  r  r  r   sortedr  r   r  r  r  r  rE   zerosrB   copy_r  NotImplementedErrorr   )r   r.   ru   expanded_module_namesr  r   re   lora_module_namesr  r  transformer_module_namesunexpected_modulesr   base_param_namebase_weight_paramlora_A_parambase_module_shaper  expanded_state_dict_weights                      rQ   r  1FluxLoraLoaderMixin._maybe_expand_lora_state_dict
  s    #!,!7!7!9(()+ 6E
5DcUeHf)C(3'(()_ 	 
 >Oj=NTRaRabhRi0T#f+-0=Nj"3'8#9:#){?X?X?Z*[?ZGD4?Z*[#\  !23c:R6SSLL56H5IIabc"A& ii+,,>?CYY 99VR());<		&"-.g6 
 !7 G*XaS+GHL !$ ; ;+ ; v #l&8&8&;;%++A.0A0G0G0JK-2[[GXG_G_-`**1.E0B0B10E.E+EFLL\Z@Z(1#^ <=%))!,"1%(:(:1(==)'s*TUaUgUgTh  iT  U - #4 !KKYZ]ZnZnYooq  sH  rI  Iw  x S
 k*[s   I7I7$I<I<J
rJ   ztorch.nn.Moduler  ztorch.nn.Linearr  z
torch.Sizec                 "   S[         R                  4S jnUb  U" UR                  5      $ UbX  UR                  S5      (       d  [	        SU< S35      eUR                  SS5      S   n[        X5      nU" UR                  5      $ [	        S5      e)	Nr>   c                     U R                   R                  S:X  a  U R                  R                  $ U R                   R                  S:X  a  U R                  $ U R                  $ )Nr4   r6   )r?   r@   rH   r  quant_shape)r>   s    rQ   _get_weight_shapeFFluxLoraLoaderMixin._calculate_module_shape.<locals>._get_weight_shape
  sR    ((L8))///!!**o=)))||#rS   r  zaInvalid `base_weight_param_name` passed as it does not end with '.weight' base_weight_param_name=r   r   r   zBEither `base_module` or `base_weight_param_name` must be provided.)rE   r   r>   r  rA   rsplitr   )rJ   r  r  r  module_path	submodules         rQ   r  +FluxLoraLoaderMixin._calculate_module_shape
  s    	$ell 	$ "$[%7%788#/)229== xaw`yyz{  177	1EaHK-eAI$Y%5%566]^^rS   c                     U /nU(       a  UR                  U5        U(       a  UR                  U5        U(       d  U(       a  [        U5      $ U $ r  )appendr  )r   rm   ro  ri  rp  outputss         rQ   rw  $FluxLoraLoaderMixin._prepare_outputs  s:    ,NN6"NN8$"/?uW~SSrS   rb   )Fr   NNNFFr   r   )NNN)NN)NFF)+r@   r   r   r   r   r   rC  r1  r   r|   r  r   r   r   r   r   rE   r   r   ru   r   r   r0  r  r{   r   r   r   r   r   r   r   r   r   r   r  r  r  staticmethodr  rw  r   r  r  s   @rQ   rd  rd    s<    ,^<')(\% $d/4S$sELL?P:Q5Q/Rd d  dR '+	{
/4S$sELL?P:Q5Q/R{
 sm{
 	{
z  4
 4
 4
l 
  %3- 
c5<<	 3- 3-j  7
 7
 7
r 
 TX?C $"&#'*.+/E
c2;;./E
 "&c5%,,1N+O&O!PE
 #'sEHHOO';"<	E

 E
 E
  E
 !E
 E
R "/!-1:
I:
 :
 	:

  S	*:
 :
x 4A.2Q =d3i = =*BH  y+XX__y+ 
y+ y+v . .`  *.&*_ _&_ !$_ 
	_ _4 T TrS   rd  c                   6   \ rS rSrSS/r\r\r\	     SS\
4S jj5       r\	       SS\
4S jj5       r\	      SS\\\R                   4   S	\\\R&                  R(                  4   S
\\\R&                  R(                  4   S\
S\S\S\
4S jj5       rSrg)AmusedLoraLoaderMixini  r.   r,   NrY   c	           
          U(       a  [        SS5      (       d  [        S5      e[        R                  SU R                   S35        UR                  UUUUUUUS9  g)a  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    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).
    transformer (`UVit2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r)   r*   r]   r   r   r5  Nr6  r  s	            rQ   r0  0AmusedLoraLoaderMixin.load_lora_into_transformer  sm    N _T8%D%D D 
 	hs334A67%%)%/ 	& 	
rS   c                 >    [        UUUUUU R                  UU
UUU	S9  gr   r   r   s              rQ   r{   1AmusedLoraLoaderMixin.load_lora_into_text_encoderM  r  rS   r   r   r;  r   r   r   r   c           	      &   0 nU(       d  U(       d  [        S5      eU(       a*  UR                  U R                  X0R                  5      5        U(       a*  UR                  U R                  X R                  5      5        U R                  UUUUUUS9  g)un  
Save the LoRA parameters corresponding to the UNet and text encoder.

Arguments:
    save_directory (`str` or `os.PathLike`):
        Directory to save LoRA parameters to. Will be created if it doesn't exist.
    unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `unet`.
    text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
        State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
        encoder LoRA state dict because it comes from 🤗 Transformers.
    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 the traditional PyTorch way with `pickle`.
zVYou must pass at least one of `transformer_lora_layers` or `text_encoder_lora_layers`.)r   r   r   r   r   r   N)rA   r   r   r1  r|   r   )	r   r   r   r;  r   r   r   r   r   s	            rQ   r   'AmusedLoraLoaderMixin.save_lora_weights  s    B 
'+Cuvv"c../FH\H\]^#c../GI^I^_` 	!)+#'1 	 	
rS   rb   r  r   )NNTNNT)r@   r   r   r   r   rC  r1  r   r|   r   r   r0  r{   r   r   r   r   r   rE   r   r   r   r   r   rb   rS   rQ   r  r    s   +^<') 4
 4
 4
l  7
 7
 7
r  @D>B $"&#'3
c2;;./3
 #'sEHHOO';"<3
 "&c588??&:!;	3

 3
 3
  3
 !3
 3
rS   r  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )CogVideoXLoraLoaderMixini  z[
Load LoRA layers into [`CogVideoXTransformer3DModel`]. Specific to [`CogVideoXPipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )r#  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   ;CogVideoXLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>!  r   ri   r   r   r&  r'  s                         rQ   ru   (CogVideoXLoraLoaderMixin.lora_state_dict  rJ  r)  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   =CogVideoXLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>W  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   *CogVideoXLoraLoaderMixin.load_lora_weights*  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ad  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`CogVideoXTransformer3DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  3CogVideoXLoraLoaderMixin.load_lora_into_transformere  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   *CogVideoXLoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   "CogVideoXLoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   $CogVideoXLoraLoaderMixin.unfuse_lora   r`  rS   rb   r   r   ra  rb  r  s   @rQ   r'  r'    s    ,_'^/4S$sELL?P:Q5Q/R^  ^F '+	9
/4S$sELL?P:Q5Q/R9
 sm9
 	9
v  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
r "/!-1-
I-
 -
 	-

  S	*-
 -
^ 4A/ =d3i = =rS   r'  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )Mochi1LoraLoaderMixini  zS
Load LoRA layers into [`MochiTransformer3DModel`]. Specific to [`MochiPipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )r#  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   8Mochi1LoraLoaderMixin.lora_state_dict.<locals>.<genexpr>t  r   ri   r   r   r&  r'  s                         rQ   ru   %Mochi1LoraLoaderMixin.lora_state_dict  rJ  r)  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   :Mochi1LoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   'Mochi1LoraLoaderMixin.load_lora_weights~  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)a`  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`MochiTransformer3DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  0Mochi1LoraLoaderMixin.load_lora_into_transformer  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   'Mochi1LoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   Mochi1LoraLoaderMixin.fuse_lora&  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   !Mochi1LoraLoaderMixin.unfuse_loraV  r`  rS   rb   r   r   ra  rb  r  s   @rQ   r9  r9        ,_'^/4S$sELL?P:Q5Q/R^  ^H '+	9
/4S$sELL?P:Q5Q/R9
 sm9
 	9
v  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
t "/!-1-
I-
 -
 	-

  S	*-
 -
` 4A/ =d3i = =rS   r9  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )LTXVideoLoraLoaderMixinih  zT
Load LoRA layers into [`LTXVideoTransformer3DModel`]. Specific to [`LTXPipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnn[        S U 5       5      nU(       a  [        U5      nU(       a  UU4nU$ UnU$ s  snnf )rk  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   :LTXVideoLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r   ri   r   r   c              3   B   #    U  H  oR                  S 5      v   M     g7fzdiffusion_model.Nr   r   s     rQ   rf   rO    s     %[PZ1ll3E&F&FPZ   )rp   r   r   r   r   r   r#   r   rW   r   r   r   r   r   r   r   r   r   r   r^   r   r   r   rm   r   r   r   r   is_non_diffusers_formatr   s                          rQ   ru   'LTXVideoLoraLoaderMixin.lora_state_dictp  s   n JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW"%%[PZ%["["FzRJ(<z8$
 CM
 X   E-.E-NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   <LTXVideoLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   )LTXVideoLoraLoaderMixin.load_lora_weights  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ac  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`LTXVideoTransformer3DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  2LTXVideoLoraLoaderMixin.load_lora_into_transformer  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   )LTXVideoLoraLoaderMixin.save_lora_weightsD  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   !LTXVideoLoraLoaderMixin.fuse_lora~  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   #LTXVideoLoraLoaderMixin.unfuse_lora  r`  rS   rb   r   r   ra  rb  r  s   @rQ   rL  rL  h      ,_'a/4S$sELL?P:Q5Q/Ra  aN '+	9
/4S$sELL?P:Q5Q/R9
 sm9
 	9
v  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
t "/!-1-
I-
 -
 	-

  S	*-
 -
` 4A/ =d3i = =rS   rL  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )SanaLoraLoaderMixini  zQ
Load LoRA layers into [`SanaTransformer2DModel`]. Specific to [`SanaPipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )r#  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   6SanaLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>"  r   ri   r   r   r&  r'  s                         rQ   ru   #SanaLoraLoaderMixin.lora_state_dict  rJ  r)  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   8SanaLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>Y  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   %SanaLoraLoaderMixin.load_lora_weights,  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)a_  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`SanaTransformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  .SanaLoraLoaderMixin.load_lora_into_transformerg  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   %SanaLoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   SanaLoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   SanaLoraLoaderMixin.unfuse_lora  r`  rS   rb   r   r   ra  rb  r  s   @rQ   re  re    rJ  rS   re  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )HunyuanVideoLoraLoaderMixini  za
Load LoRA layers into [`HunyuanVideoTransformer3DModel`]. Specific to [`HunyuanVideoPipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnn[        S U 5       5      nU(       a  [        U5      nU(       a  UU4nU$ UnU$ s  snnf )a2	  
Return state dict for lora weights and the network alphas.

<Tip warning={true}>

We support loading original format HunyuanVideo LoRA checkpoints.

This function is experimental and might change in the future.

</Tip>

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.
    return_lora_metadata (`bool`, *optional*, defaults to False):
        When enabled, additionally return the LoRA adapter metadata, typically found in the state dict.
r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   >HunyuanVideoLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>v  r   ri   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7f)img_attn_qkvNrb   r   s     rQ   rf   rz  |  s     'PZ!(;Zri   )rp   r   r   r   r   r   r   )r   rW   r   r   r   r   r   r   r   r   r   r   r^   r   r   r   rm   r   r   r   r   is_original_hunyuan_videor   s                          rQ   ru   +HunyuanVideoLoraLoaderMixin.lora_state_dict  s   n JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW$''PZ'P$P!$A*MJ(<z8$
 CM
 XrV  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   @HunyuanVideoLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   -HunyuanVideoLoraLoaderMixin.load_lora_weights  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ag  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`HunyuanVideoTransformer3DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  6HunyuanVideoLoraLoaderMixin.load_lora_into_transformer  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   -HunyuanVideoLoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   %HunyuanVideoLoraLoaderMixin.fuse_lora,  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   'HunyuanVideoLoraLoaderMixin.unfuse_lora\  r`  rS   rb   r   r   ra  rb  r  s   @rQ   rw  rw    rc  rS   rw  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )Lumina2LoraLoaderMixinin  z_
Load LoRA layers into [`Lumina2Transformer2DModel`]. Specific to [`Lumina2Text2ImgPipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnn[        S U 5       5      nU(       a  [        U5      nU(       a  UU4nU$ UnU$ s  snnf )rk  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   9Lumina2LoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r   ri   r   r   c              3   B   #    U  H  oR                  S 5      v   M     g7frQ  r   r   s     rQ   rf   r    s     QjLL);<<jrR  )rp   r   r   r   r   r   r$   )r   rW   r   r   r   r   r   r   r   r   r   r   r^   r   r   r   rm   r   r   r   r   non_diffusersr   s                          rQ   ru   &Lumina2LoraLoaderMixin.lora_state_dictv  s   n JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW QjQQI*UJ(<z8$
 CM
 XrV  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   ;Lumina2LoraLoaderMixin.load_lora_weights.<locals>.<genexpr>
  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   (Lumina2LoraLoaderMixin.load_lora_weights  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ab  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`Lumina2Transformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  1Lumina2LoraLoaderMixin.load_lora_into_transformer  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   (Lumina2LoraLoaderMixin.save_lora_weightsK  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r    Lumina2LoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   "Lumina2LoraLoaderMixin.unfuse_lora  r`  rS   rb   r   r   ra  rb  r  s   @rQ   r  r  n  s    ,_'b/4S$sELL?P:Q5Q/Rb  bP '+	9
/4S$sELL?P:Q5Q/R9
 sm9
 	9
v  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
t "/!-1-
I-
 -
 	-

  S	*-
 -
` 4A/ =d3i = =rS   r  c                   >  ^  \ rS rSrSrSS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r\S\R                   R"                  4S j5       r  SS\
\\\\R                  4   4   S
\\   S\4S jjr\     SS\4S jj5       r\      S S\
\\R0                  4   S\\\
\R                   R"                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SS	S4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSr U =r!$ )!WanLoraLoaderMixini  zo
Load LoRA layers into [`WanTransformer3DModel`]. Specific to [`WanPipeline`] and `[WanImageToVideoPipeline`].
r.   transformer_2rW   c                 (   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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      (       a  [        U5      nO"[        S U 5       5      (       a  [	        U5      n[        S U 5       5      nU(       aE  Sn[
        R                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )rk  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   B   #    U  H  oR                  S 5      v   M     g7frQ  r   r   s     rQ   rf   5WanLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>&       DA||.//rR  c              3   B   #    U  H  oR                  S 5      v   M     g7fr   Nr   r   s     rQ   rf   r  (       @Zl++ZrR  c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   r  +  r   ri   r   r   rp   r   r   r&   r    r   r   r   r'  s                         rQ   ru   "WanLoraLoaderMixin.lora_state_dict  s   n JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H DDDDEjQJ@Z@@@>zJJ ##Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW(<z8$
 CM
 X   "F3Fc           	      6   UR                   R                  c  U$ UR                  n[        S U 5       5      (       GaV  [	        U Vs1 s H1  nSU;   d  M  UR                  S5      S   R                  S5      S   iM3     sn5      n[        S U 5       5      =(       a    [        S U 5       5      n[        S U 5       5      nU(       a  U$ [        U5       H  n[        S	S
/SS/5       H  u  pSU S3nSU S3nX;  d  X;  a  M  [        R                  " USU S3   US9USU SU
 S3'   [        R                  " USU S3   US9USU SU
 S3'   SU S3nU(       d  Mx  X;   d  M  X-   n[        R                  " UUS9USU SU
 S3'   M     M     U$ s  snf )Nc              3   B   #    U  H  oR                  S 5      v   M     g7ftransformer.blocks.Nr   r   s     rQ   rf   DWanLoraLoaderMixin._maybe_expand_t2v_lora_for_i2v.<locals>.<genexpr>?       GJq||122JrR  blocks.r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7f
add_k_projNrb   r   s     rQ   rf   r  A       DAla/ri   c              3   ,   #    U  H
  nS U;   v   M     g7f
add_v_projNrb   r   s     rQ   rf   r  A       Lshrcd\]^M^hrri   c              3   ,   #    U  H
  nS U;   v   M     g7f.lora_B.biasNrb   r   s     rQ   rf   r  B       C
1>Q.
ri   k_imgv_imgr  r  r  .attn2.to_k.lora_A.weight.attn2.to_k.lora_B.weightr   .attn2.r  r  .attn2.to_k.lora_B.biasr  
r  	image_dimrB   r   r  r  rangeziprE   r  r   r.   r   target_devicer   
num_blocksis_i2v_lorahas_biasiocref_key_lora_Aref_key_lora_Bref_key_lora_B_biasref_lora_B_bias_tensors                  rQ   _maybe_expand_t2v_lora_for_i2v1WanLoraLoaderMixin._maybe_expand_t2v_lora_for_i2v4  s    ''/#**GJGGG:h:aYbfgYgAaggi0399#>qA:hiJDDDsLshrLsIsKC
CCH!!:&' 2\<4PQDA':1#=V%WN':1#=V%WN%7>;[ TYTdTd"%8;T#UV_lUJ!4QCwqcPQ UZTdTd"%8;T#UV_lUJ!4QCwqcPQ -@sBY*Z'x$7$E1;1P.V[VfVf2#0W
%871#\#RS+ R '6 E i   
F*FNFrX   rY   c           
      f   [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pgU R                  [        U S5      (       d  [        X R                  5      OU R                  US	9n[        S
 UR                  5        5       5      nU(       d  [        S5      eUR                  SS5      n	U	(       aS  [        U S5      (       d"  [!        S[#        U 5      R$                   S35      eU R'                  UU R(                  UUU UUS9  gU R'                  U[        U S5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   r.   r.   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   7WanLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   load_into_transformer_2Fr  '' object has no attribute transformer_2Note that Wan2.1 models do not have a transformer_2 component.Ensure the model has a transformer_2 component before setting load_into_transformer_2=True.r/  Nr
   rA   rp   rq   r   rr   rs   rt   ru   r  rD   ry   r1  r.   rv   rw   AttributeErrorrC   r@   r0  r  
r~   rW   rX   rY   r   r\   r   rm   r   r  s
             rQ   r   $WanLoraLoaderMixin.load_lora_weightsd     8  HII"JJ':<[\h!?!? D 
 ;TBB4Y4^4^4`1 *.%&#334Yd]cd
88DKDR_D`D`&;&;<fjfvfv! 9 

  K9JKK 788"(**-F"N"411$T
++, -r r 
 ++ ..)!"3 ,  ++t]33 $D*?*?@%%)!"3 , 
rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)a^  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`WanTransformer3DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  -WanLoraLoaderMixin.load_lora_into_transformer  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   $WanLoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   WanLoraLoaderMixin.fuse_lora$  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   WanLoraLoaderMixin.unfuse_loraT  r`  rS   rb   r   r   ra  "r@   r   r   r   r   r   rC  r1  r   r   r   r   r   rE   r   ru   r   r   r  r   r   r   r0  r   r   r   rs   r   r   r   r   r   r   r  r  s   @rQ   r  r    s    ,_='a/4S$sELL?P:Q5Q/Ra  aF -XX__- -d '+	Q/4S$sELL?P:Q5Q/RQ smQ 	Qf  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
t "/!-1-
I-
 -
 	-

  S	*-
 -
` 4A/ =d3i = =rS   r  c                   <  ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r\S\R                   R"                  4S j5       r  SS\
\\\\R                  4   4   S	\\   S
\4S jjr\     SS
\4S jj5       r\      SS\
\\R0                  4   S\\\
\R                   R"                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSr U =r!$ ) SkyReelsV2LoraLoaderMixinif  z9
Load LoRA layers into [`SkyReelsV2Transformer3DModel`].
r.   rW   c                 (   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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      (       a  [        U5      nO"[        S U 5       5      (       a  [	        U5      n[        S U 5       5      nU(       aE  Sn[
        R                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )rk  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   B   #    U  H  oR                  S 5      v   M     g7frQ  r   r   s     rQ   rf   <SkyReelsV2LoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r  rR  c              3   B   #    U  H  oR                  S 5      v   M     g7fr  r   r   s     rQ   rf   r    r  rR  c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   r    r   ri   r   r   r  r'  s                         rQ   ru   )SkyReelsV2LoraLoaderMixin.lora_state_dictn  s   p JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H DDDDEjQJ@Z@@@>zJJ ##Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW(<z8$
 CM
 Xr  c           	      6   UR                   R                  c  U$ UR                  n[        S U 5       5      (       GaV  [	        U Vs1 s H1  nSU;   d  M  UR                  S5      S   R                  S5      S   iM3     sn5      n[        S U 5       5      =(       a    [        S U 5       5      n[        S U 5       5      nU(       a  U$ [        U5       H  n[        S	S
/SS/5       H  u  pSU S3nSU S3nX;  d  X;  a  M  [        R                  " USU S3   US9USU SU
 S3'   [        R                  " USU S3   US9USU SU
 S3'   SU S3nU(       d  Mx  X;   d  M  X-   n[        R                  " UUS9USU SU
 S3'   M     M     U$ s  snf )Nc              3   B   #    U  H  oR                  S 5      v   M     g7fr  r   r   s     rQ   rf   KSkyReelsV2LoraLoaderMixin._maybe_expand_t2v_lora_for_i2v.<locals>.<genexpr>  r  rR  r  r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr  rb   r   s     rQ   rf   r    r  ri   c              3   ,   #    U  H
  nS U;   v   M     g7fr  rb   r   s     rQ   rf   r    r  ri   c              3   ,   #    U  H
  nS U;   v   M     g7fr  rb   r   s     rQ   rf   r    r  ri   r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  s                  rQ   r  8SkyReelsV2LoraLoaderMixin._maybe_expand_t2v_lora_for_i2v  s    ''/#**GJGGG:h:aYbfgYgAaggi0399#>qA:hiJDDDsLshrLsIsKC
CCH!!:&' 2\<4PQDA':1#=V%WN':1#=V%WN%7>;[ TYTdTd"%8;T#UV_lUJ!4QCwqcPQ UZTdTd"%8;T#UV_lUJ!4QCwqcPQ -@sBY*Z'x$7$E1;1P.V[VfVf2#0W
%871#\#RS+ R '6 E ir  NFrX   rY   c           
      f   [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pgU R                  [        U S5      (       d  [        X R                  5      OU R                  US	9n[        S
 UR                  5        5       5      nU(       d  [        S5      eUR                  SS5      n	U	(       aS  [        U S5      (       d"  [!        S[#        U 5      R$                   S35      eU R'                  UU R(                  UUU UUS9  gU R'                  U[        U S5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   r.   r  c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   >SkyReelsV2LoraLoaderMixin.load_lora_weights.<locals>.<genexpr>7  rh   ri   rj   r  Fr  r  r  r/  Nr  r  s
             rQ   r   +SkyReelsV2LoraLoaderMixin.load_lora_weights  r  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ae  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`SkyReelsV2Transformer3DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  4SkyReelsV2LoraLoaderMixin.load_lora_into_transformerY  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   +SkyReelsV2LoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   #SkyReelsV2LoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   %SkyReelsV2LoraLoaderMixin.unfuse_lora  r`  rS   rb   r   r   ra  r  r  s   @rQ   r  r  f  s    ,_'a/4S$sELL?P:Q5Q/Ra  aF -XX__- -f '+	Q/4S$sELL?P:Q5Q/RQ smQ 	Qf  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
t "/!-1-
I-
 -
 	-

  S	*-
 -
` 4A/ =d3i = =rS   r  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )CogView4LoraLoaderMixini  zT
Load LoRA layers into [`WanTransformer3DModel`]. Specific to [`CogView4Pipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnnU(       a  UU4nU$ UnU$ s  snnf )r#  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   :CogView4LoraLoaderMixin.lora_state_dict.<locals>.<genexpr>j  r   ri   r   r   r&  r'  s                         rQ   ru   'CogView4LoraLoaderMixin.lora_state_dict  rJ  r)  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   <CogView4LoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   )CogView4LoraLoaderMixin.load_lora_weightst  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ac  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`CogView4Transformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  2CogView4LoraLoaderMixin.load_lora_into_transformer  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   )CogView4LoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   !CogView4LoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   #CogView4LoraLoaderMixin.unfuse_loraL  r`  rS   rb   r   r   ra  rb  r  s   @rQ   r
  r
    rJ  rS   r
  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )HiDreamImageLoraLoaderMixini^  za
Load LoRA layers into [`HiDreamImageTransformer2DModel`]. Specific to [`HiDreamImagePipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnn[        S U 5       5      nU(       a  [        U5      nU(       a  UU4nU$ UnU$ s  snnf )rk  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   >HiDreamImageLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r   ri   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7f)diffusion_modelNrb   r   s     rQ   rf   r    s     %Qj&71&<jri   )rp   r   r   r   r   r   r!   rS  s                          rQ   ru   +HiDreamImageLoraLoaderMixin.lora_state_dictf  s   n JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JW"%%Qj%Q"Q"I*UJ(<z8$
 CM
 XrV  NFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   @HiDreamImageLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   -HiDreamImageLoraLoaderMixin.load_lora_weights  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ag  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`HiDreamImageTransformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  6HiDreamImageLoraLoaderMixin.load_lora_into_transformer  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   -HiDreamImageLoraLoaderMixin.save_lora_weights:  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   %HiDreamImageLoraLoaderMixin.fuse_lorat  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   'HiDreamImageLoraLoaderMixin.unfuse_lora  r`  rS   rb   r   r   ra  rb  r  s   @rQ   r  r  ^  rc  rS   r  c                     ^  \ rS rSrSrS/r\r\\	S\
\\\\R                  4   4   4S j5       5       r  SS\
\\\\R                  4   4   S\\   S	\4S
 jjr\     SS	\4S jj5       r\      SS\
\\R*                  4   S\\\
\R,                  R.                  \R                  4   4   S\S\S\S\S\\   4S jj5       rS/SSS4S\\   S\S\S\\\      4U 4S jjjrS/4S\\   4U 4S jjjrSrU =r $ )QwenImageLoraLoaderMixini  z[
Load LoRA layers into [`QwenImageTransformer2DModel`]. Specific to [`QwenImagePipeline`].
r.   rW   c                    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SnUc  SnSnSSS.n[        UU
UUUUUUUU	UUS9u  nn[        S U 5       5      nU(       aE  Sn[        R	                  U5        UR                  5        VVs0 s H  u  nnSU;  d  M  UU_M     nnn[        S U 5       5      n[        S U 5       5      nU(       d  U(       a  [        U5      nU(       a  UU4nU$ UnU$ s  snnf )r#  r   Nr   Fr   r   r   r   r   r   r   r^   Tr   r   r   r   c              3   ,   #    U  H
  nS U;   v   M     g7fr   rb   r   s     rQ   rf   ;QwenImageLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>  r   ri   r   r   c              3   B   #    U  H  oR                  S 5      v   M     g7f)z.alphaN)r  r   s     rQ   rf   r3    s     HZzz(33ZrR  c              3   B   #    U  H  oR                  S 5      v   M     g7fr  r   r   s     rQ   rf   r3    s     K
1LL66
rR  )rp   r   r   r   r   r   r%   )r   rW   r   r   r   r   r   r   r   r   r   r   r^   r   r   r   rm   r   r   r   r   has_alphas_in_sdhas_lora_unetr   s                           rQ   ru   (QwenImageLoraLoaderMixin.lora_state_dict  s   p JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	jj5 **%6=%zz*@%H""OL#7iP
02W#+-)!% 

H !$#Jz#J J  {HNN8$+5+;+;+=W+=41aUVAV$!Q$+=JWHZHHK
KK}FzRJ(<z8$
 CM
 Xs   F.FNFrX   rY   c           
         [         (       d  [        S5      eUR                  S[        5      nU(       a  [	        SS5      (       a  [        S5      e[        U[        5      (       a  UR                  5       nSUS'   U R                  " U40 UD6u  pg[        S UR                  5        5       5      nU(       d  [        S	5      eU R                  U[        U S
5      (       d  [        X R                  5      OU R                  UUU UUS9  g)rL  r[   r\   r+  r,  r]   Tr^   c              3   ,   #    U  H
  nS U;   v   M     g7fr`   rb   rc   s     rQ   rf   =QwenImageLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>S  rh   ri   rj   r.   r/  NrO  r2  s	            rQ   r   *QwenImageLoraLoaderMixin.load_lora_weights&  rQ  rS   c           
          U(       a  [        SS5      (       a  [        S5      e[        R                  SU R                   S35        UR                  USUUUUUS9  g)ad  
This will load the LoRA layers specified in `state_dict` into `transformer`.

Parameters:
    state_dict (`dict`):
        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
        encoder lora layers.
    transformer (`QwenImageTransformer2DModel`):
        The Transformer model to load the LoRA layers into.
    adapter_name (`str`, *optional*):
        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.
    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*):
        See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
    metadata (`dict`):
        Optional LoRA adapter metadata. When supplied, the `LoraConfig` arguments of `peft` won't be derived
        from the state dict.
r+  r,  r]   r   r   Nr5  r6  r7  s           rQ   r0  3QwenImageLoraLoaderMixin.load_lora_into_transformera  rT  rS   r   r;  r   r   r   r   r=  c           
          0 n0 n	U(       d  [        S5      eUR                  U R                  X R                  5      5        Ub$  U	R                  [	        XpR                  5      5        U R                  UUUUUUU	S9  grV  rW  rX  s
             rQ   r   *QwenImageLoraLoaderMixin.save_lora_weights  rZ  rS   r   r   ro   r   r   c                 0   > [         TU ]  " SUUUUS.UD6  gr   r   r   s         rQ   r   "QwenImageLoraLoaderMixin.fuse_lora  r   rS   c                 *   > [         TU ]  " SSU0UD6  gr^  r   r   s      rQ   r   $QwenImageLoraLoaderMixin.unfuse_lora  r`  rS   rb   r   r   ra  rb  r  s   @rQ   r0  r0    s    ,_'c/4S$sELL?P:Q5Q/Rc  cR '+	9
/4S$sELL?P:Q5Q/R9
 sm9
 	9
v  /
 /
 /
b 
 TX $"&#'<@5
c2;;./5
 "&c5%,,1N+O&O!P5
 	5

 5
  5
 !5
 ,4D>5
 5
t "/!-1-
I-
 -
 	-

  S	*-
 -
` 4A/ =d3i = =rS   r0  c                   (   ^  \ rS rSrU 4S jrSrU =r$ )LoraLoaderMixini  c                 D   > Sn[        SSU5        [        TU ]  " U0 UD6  g )NzLoraLoaderMixin is deprecated and this will be removed in a future version. Please use `StableDiffusionLoraLoaderMixin`, instead.rF  z1.0.0)r   r   __init__)r~   argsr   deprecation_messager?   s       rQ   rH  LoraLoaderMixin.__init__  s,     b#W.AB$)&)rS   rb   )r@   r   r   r   rH  r   r  r  s   @rQ   rF  rF    s    * *rS   rF  )Fr   typingr   r   r   r   r   rE   huggingface_hub.utilsr   utilsr
   r   r   r   r   r   r   r   r   r   r   	lora_baser   r   r   r   r   r   lora_conversion_utilsr   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   rq   
get_loggerr@   r   r   r   rC  r  rR   rU   r  r!  rE  rd  r  r'  r9  rL  re  rw  r  r  r  r
  r  r0  rF  rb   rS   rQ   <module>rR     s   
 8 8  6       " #( D'""D(++%''#C22*.' 
		H	%" 	  &2M%B ".ba=] a=Ht=} t=nP= P=fS=m S=l
GT- GTXl
: l
^P=} P=f
S=M S=l
U=m U=p
S=- S=l
U=- U=p
V=] V=r
\= \=~_= _=DS=m S=l
U=- U=p
W=} W=t
*4 *rS   