o
    pi%                    @   s   d dl Z d dlmZmZmZmZmZ d dlZd dlm	Z	 ddl
mZmZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZmZ e rOdd	lmZmZ eeZ d
Z!dZ"dZ#dZ$dZ%G dd deZ&G dd deZ'G dd deZ(G dd deZ)G dd de&Z*G dd de&Z+dS )    N)CallableDictListOptionalUnion)validate_hf_hub_args   )USE_PEFT_BACKENDconvert_state_dict_to_diffusersconvert_state_dict_to_peftconvert_unet_state_dict_to_peft	deprecateget_adapter_nameget_peft_kwargsis_peft_versionis_transformers_availableloggingscale_lora_layers   )LoraBaseMixin)(_convert_non_diffusers_lora_to_diffusers"_maybe_map_sgm_blocks_to_diffusers)text_encoder_attn_modulestext_encoder_mlp_modulestext_encoderunettransformerzpytorch_lora_weights.binz pytorch_lora_weights.safetensorsc                       sN  e Zd ZdZddgZeZeZ	d"de	e
ee
ejf f fddZeede	e
ee
ejf f fdd	Zed#d
dZe				d$ddZe						d%de	e
ejf dee
e	ejjejf f dee
ejjf dede
dedefddZddgdddfdee
 dededeee
  f fddZddgfdee
 f fd d!Z  Z S )&StableDiffusionLoraLoaderMixinz
    Load LoRA layers into Stable Diffusion [`UNet2DConditionModel`] and
    [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
    r   r   N%pretrained_model_name_or_path_or_dictc                 K   s   t stdt|tr| }| j|fi |\}}tdd | D }|s+td| j||t	| ds:t
| | jn| j|| d | j||t	| dsPt
| | jn| j| j|| d d	S )
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_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`].
            kwargs (`dict`, *optional*):
                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.
        )PEFT backend is required for this method.c                 s        | ]}d |v pd|v V  qdS lora
dora_scaleN .0keyr$   r$   ]/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/diffusers/loaders/lora_pipeline.py	<genexpr>a       zCStableDiffusionLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>Invalid LoRA checkpoint.r   network_alphasr   adapter_name	_pipeliner   )r-   r   
lora_scaler.   r/   N)r	   
ValueError
isinstancedictcopylora_state_dictallkeysload_lora_into_unethasattrgetattr	unet_namer   load_lora_into_text_encodertext_encoder_namer   r0   )selfr   r.   kwargs
state_dictr-   is_correct_formatr$   r$   r(   load_lora_weights<   s2   

z0StableDiffusionLoraLoaderMixin.load_lora_weightsc                 K      | dd}| dd}| dd}| dd}| dd}| dd}| d	d}	| d
d}
| dd}| dd}d}|du rFd}d}ddd}| j||
||||||||	||d}d}tdd | D rx|durrt||}t|\}}||fS ) 
  
        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.
        	cache_dirNforce_downloadFproxieslocal_files_onlytokenrevision	subfolderweight_nameunet_configuse_safetensorsTattn_procs_weightspytorch	file_type	frameworkr   rL   rN   rH   rE   rF   rG   rI   rJ   rK   
user_agentallow_picklec                 s   8    | ]}| d p| dp| dp| dV  qdS lora_te_
lora_unet_	lora_te1_	lora_te2_N
startswithr&   kr$   r$   r(   r)          

zAStableDiffusionLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>pop_fetch_state_dictr6   r7   r   r   clsr   r?   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rV   rU   r@   r-   r$   r$   r(   r5   w   sN   7

z.StableDiffusionLoraLoaderMixin.lora_state_dictc                    `   t stdt| }t fdd|D }|s.td j d |j||||d dS dS )  
        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.
        r   c                 3       | ]	}|  jV  qd S Nr^   r=   r%   rf   r$   r(   r)          zEStableDiffusionLoraLoaderMixin.load_lora_into_unet.<locals>.<genexpr>Loading .r-   r.   r/   N	r	   r1   listr7   r6   loggerinfor;   load_attn_procsrf   r@   r-   r   r.   r/   r7   only_text_encoderr$   rl   r(   r8      s   
z2StableDiffusionLoraLoaderMixin.load_lora_into_unet      ?c                    D  t stdddlm} t| }	du rjntfdd|	D rfdd|	D fd	d
| D }
t	|
dkrt
d d i }t|
}
t|
}
t|D ]\}}dD ]}| d| d}||
vroq`|
| jd ||< q`qZt|D ]\}}dD ]}| d| d}||
vrq|
| jd ||< qq~|durfdd| D   fdd
| D }t|||
dd}d|v r|d rtddrtdn
tddr|d |di |}|du rt|}|\}}|j||
|d t||d |j|j|jd |r|  dS |r |  dS dS dS dS )?  
        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]`):
                See `LoRALinearLayer` for more details.
            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.
        r   r   
LoraConfigNc                 3       | ]} j |v V  qd S rj   r=   r%   rl   r$   r(   r)   3      zMStableDiffusionLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<genexpr>c                    ,   g | ]}|  r|d d  kr|qS ro   r   r^   splitr_   prefixr$   r(   
<listcomp>5     , zNStableDiffusionLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<listcomp>c                    ,   i | ]\}}|v r|   d d|qS ro    replacer&   r`   vr   text_encoder_keysr$   r(   
<dictcomp>6      &zNStableDiffusionLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<dictcomp>rn   ro   out_projq_projk_projv_proj.lora_B.weightr   fc1fc2c                    ,   g | ]}|  r|d d  kr|qS r   r   r_   r   r$   r(   r   Q      
c                    ,   i | ]\}}| v r|  d d|qS r   r   r   
alpha_keysr   r$   r(   r   T  r   Fis_unetuse_dora<0.9.0eYou need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`.r.   adapter_state_dictpeft_configweightdevicedtyper$   r	   r1   peftr|   rr   r7   r=   anyitemslenrs   rt   r
   r   r   shaper   r   r   rc   r   _optionally_disable_offloadingload_adapterr   tor   r   enable_model_cpu_offloadenable_sequential_cpu_offloadrf   r@   r-   r   r   r0   r.   r/   r|   r7   text_encoder_lora_state_dictrankname_modulerank_keylora_config_kwargslora_configis_model_cpu_offloadis_sequential_cpu_offloadr$   r   rf   r   r   r(   r<     s   



@z:StableDiffusionLoraLoaderMixin.load_lora_into_text_encoderTsave_directoryunet_lora_layerstext_encoder_lora_layersis_main_processrL   save_functionsafe_serializationc           	      C   ^   i }|s
|s
t d|r|| || j |r"|| || j | j||||||d dS )  
        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`.
        zPYou must pass at least one of `unet_lora_layers` and `text_encoder_lora_layers`.r@   r   r   rL   r   r   N)r1   updatepack_weightsr;   r=   write_lora_layers)	rf   r   r   r   r   rL   r   r   r@   r$   r$   r(   save_lora_weights~     !
z0StableDiffusionLoraLoaderMixin.save_lora_weightsF
componentsr0   safe_fusingadapter_namesc                       t  j||||d dS a  
        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   r0   r   r   Nsuper	fuse_lorar>   r   r0   r   r   r?   	__class__r$   r(   r        '
z(StableDiffusionLoraLoaderMixin.fuse_lorac                       t  j|d dS 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_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   Nr   unfuse_lorar>   r   r?   r   r$   r(   r        z*StableDiffusionLoraLoaderMixin.unfuse_lorarj   NNNrx   NNNNTNNT)!__name__
__module____qualname____doc___lora_loadable_modules	UNET_NAMEr;   TEXT_ENCODER_NAMEr=   r   strr   torchTensorrB   classmethodr   r5   r8   r<   osPathLikennModuleboolr   r   r   floatr   r   r   __classcell__r$   r$   r   r(   r   2   st    
;l"u7
&+r   c                       s|  e Zd ZdZg dZeZeZ	d#de	e
ee
ejf f dee
 fddZeede	e
ee
ejf f fdd	Zed$d
dZe				d%ddZe							d&de	e
ejf dee
e	ejjejf f dee
e	ejjejf f dee
e	ejjejf f dede
dedefddZg ddddfdee
 dededeee
  f fdd Zg dfdee
 f fd!d"Z  Z S )' StableDiffusionXLLoraLoaderMixinaC  
    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_2Nr   r.   c           	   	   K   s   t stdt|tr| }| j|fd| jji|\}}tdd |	 D }|s/td| j
||| j|| d dd | D }t|d	krW| j||| jd
| j|| d dd | D }t|d	krv| j||| jd| j|| d dS dS )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_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.
            kwargs (`dict`, *optional*):
                See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
        r   rM   c                 s   r    r!   r$   r%   r$   r$   r(   r)   .  r*   zEStableDiffusionXLLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>r+   r,   c                 S      i | ]\}}d |v r||qS ztext_encoder.r$   r   r$   r$   r(   r   5      zFStableDiffusionXLLoraLoaderMixin.load_lora_weights.<locals>.<dictcomp>r   r   r-   r   r   r0   r.   r/   c                 S   r   ztext_encoder_2.r$   r   r$   r$   r(   r   A  r   r   N)r	   r1   r2   r3   r4   r5   r   configr6   r7   r8   r   r   r<   r   r0   r   )	r>   r   r.   r?   r@   r-   rA   text_encoder_state_dicttext_encoder_2_state_dictr$   r$   r(   rB     sP   



z2StableDiffusionXLLoraLoaderMixin.load_lora_weightsc                 K   rC   )rD   rE   NrF   FrG   rH   rI   rJ   rK   rL   rM   rN   TrO   rP   rQ   rT   c                 s   rW   rX   r]   r_   r$   r$   r(   r)     ra   zCStableDiffusionXLLoraLoaderMixin.lora_state_dict.<locals>.<genexpr>rb   re   r$   r$   r(   r5   M  sN   8

z0StableDiffusionXLLoraLoaderMixin.lora_state_dictc                    rg   )rh   r   c                 3   ri   rj   rk   r%   rl   r$   r(   r)     rm   zGStableDiffusionXLLoraLoaderMixin.load_lora_into_unet.<locals>.<genexpr>rn   ro   rp   Nrq   rv   r$   rl   r(   r8     s   
z4StableDiffusionXLLoraLoaderMixin.load_lora_into_unetrx   c                    ry   )rz   r   r   r{   Nc                 3   r}   rj   r~   r%   rl   r$   r(   r)     r   zOStableDiffusionXLLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<genexpr>c                    r   r   r   r_   r   r$   r(   r     r   zPStableDiffusionXLLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<listcomp>c                    r   r   r   r   r   r$   r(   r     r   zPStableDiffusionXLLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<dictcomp>rn   ro   r   r   r   r   c                    r   r   r   r_   r   r$   r(   r   *  r   c                    r   r   r   r   r   r$   r(   r   -  r   Fr   r   r   r   r   r   r   r   r$   r   r   r$   r   r(   r<         



@z<StableDiffusionXLLoraLoaderMixin.load_lora_into_text_encoderTr   r   r   text_encoder_2_lora_layersr   rL   r   r   c	           
      C   st   i }	|s|s|st d|r|	| |d |r"|	| |d |r-|	| |d | j|	|||||d dS )u6  
        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`.
        zmYou must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`.r   r   r   r   N)r1   r   r   r   )
rf   r   r   r   r  r   rL   r   r   r@   r$   r$   r(   r   W  s&   %
z2StableDiffusionXLLoraLoaderMixin.save_lora_weightsFr   r0   r   r   c                    r   r   r   r   r   r$   r(   r     r   z*StableDiffusionXLLoraLoaderMixin.fuse_lorac                    r   r   r   r   r   r$   r(   r     r   z,StableDiffusionXLLoraLoaderMixin.unfuse_lorarj   r   r   NNNTNNT)!r   r   r   r   r   r   r;   r   r=   r   r   r   r   r   r   rB   r   r   r5   r8   r<   r   r   r   r   r   r   r   r   r   r   r   r   r$   r$   r   r(   r     s~    
Nl"u	?
&+r   c                       sj  e Zd ZdZg dZeZeZe	e
deeeeejf f fddZ	d"deeeeejf f fddZe	d#d	d
Ze					d$ddZe								d%deeejf deeejjf deeeejjejf f deeeejjejf f dedededefddZg ddddfdee dededeee  f fddZg dfdee f fd d!Z  Z S )&SD3LoraLoaderMixina_  
    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   r   c                 K      | dd}| dd}| dd}| dd}| dd}| dd}| d	d}	| d
d}
| dd}d}|du r@d}d}ddd}| j||
||||||||	||d}|S a	  
        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.

        rE   NrF   FrG   rH   rI   rJ   rK   rL   rN   TrO   rP   rQ   rT   rc   rd   rf   r   r?   rE   rF   rG   rH   rI   rJ   rK   rL   rN   rV   rU   r@   r$   r$   r(   r5     s>   6z"SD3LoraLoaderMixin.lora_state_dictNc              	   K   s   t stdt|tr| }| j|fi |}tdd | D }|s)td| j|t	| ds7t
| | jn| j|| d dd | D }t|d	kr[| j|d
| jd| j|| d dd | D }t|d	krz| j|d
| jd| j|| d d
S d
S )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`].
            kwargs (`dict`, *optional*):
                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.
        r   c                 s   r    r!   r$   r%   r$   r$   r(   r)   _  r*   z7SD3LoraLoaderMixin.load_lora_weights.<locals>.<genexpr>r+   r   r   r.   r/   c                 S   r   r   r$   r   r$   r$   r(   r   j  r   z8SD3LoraLoaderMixin.load_lora_weights.<locals>.<dictcomp>r   Nr   r  c                 S   r   r  r$   r   r$   r$   r(   r   v  r   r   )r	   r1   r2   r3   r4   r5   r6   r7   load_lora_into_transformerr9   r:   transformer_namer   r   r   r<   r   r0   r   )r>   r   r.   r?   r@   rA   r  r  r$   r$   r(   rB   =  sJ   


z$SD3LoraLoaderMixin.load_lora_weightsc                      ddl m}m}m} t| } fdd|D  fdd| D }t| dkrtt	| }	d|	vr=t
|}|t|di v rMtd	| d
i }
| D ]\}}d|v rb|jd |
|< qSt|
d|d}d|v r|d r{tddr{td|d |di |}|du rt|} |\}}||||d ||||}|durt|dd}|rtd| d |r|  dS |r|  dS dS dS )  
        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.
        r   r|   inject_adapter_in_modelset_peft_model_state_dictc                       g | ]
}|  jr|qS r$   r^   r  r_   rl   r$   r(   r         zASD3LoraLoaderMixin.load_lora_into_transformer.<locals>.<listcomp>c                    .   i | ]\}}|v r|  j d d|qS r   r   r  r   rf   transformer_keysr$   r(   r         (zASD3LoraLoaderMixin.load_lora_into_transformer.<locals>.<dictcomp>lora_Ar   Adapter name F already in use in the transformer - please select a new adapter name.lora_Br   Nnetwork_alpha_dictpeft_state_dictr   r   r   r   r.   unexpected_keysXLoading adapter weights from state_dict led to unexpected keys not found in the model:  . r$   r   r|   r  r  rr   r7   r   r   nextiterr   r:   r1   r   r   r   rc   r   r   rs   warningr   r   rf   r@   r   r.   r/   r|   r  r  r7   	first_keyr   r'   valr   r   r   r   incompatible_keysr&  r$   r  r(   r    s\   

1z-SD3LoraLoaderMixin.load_lora_into_transformerrx   c                    ry   )rz   r   r   r{   Nc                 3   r}   rj   r~   r%   rl   r$   r(   r)     r   zASD3LoraLoaderMixin.load_lora_into_text_encoder.<locals>.<genexpr>c                    r   r   r   r_   r   r$   r(   r     r   zBSD3LoraLoaderMixin.load_lora_into_text_encoder.<locals>.<listcomp>c                    r   r   r   r   r   r$   r(   r     r   zBSD3LoraLoaderMixin.load_lora_into_text_encoder.<locals>.<dictcomp>rn   ro   r   r   r   r   c                    r   r   r   r_   r   r$   r(   r     r   c                    r   r   r   r   r   r$   r(   r     r   Fr   r   r   r   r   r   r   r   r$   r   r   r$   r   r(   r<     r  z.SD3LoraLoaderMixin.load_lora_into_text_encoderTr   transformer_lora_layersr   r  r   rL   r   r   c	           
      C   sv   i }	|s|s|st d|r|	| || j |r#|	| |d |r.|	| |d | j|	|||||d dS )uD  
        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`.
        zrYou must pass at least one of `transformer_lora_layers`, `text_encoder_lora_layers`, `text_encoder_2_lora_layers`.r   r   r   N)r1   r   r   r  r   )
rf   r   r1  r   r  r   rL   r   r   r@   r$   r$   r(   r   G  s&   %
z$SD3LoraLoaderMixin.save_lora_weightsFr   r0   r   r   c                    r   r   r   r   r   r$   r(   r     r   zSD3LoraLoaderMixin.fuse_lorac                    r   r   r   r   r   r$   r(   r     r   zSD3LoraLoaderMixin.unfuse_lorarj   r   r   r  !r   r   r   r   r   TRANSFORMER_NAMEr  r   r=   r   r   r   r   r   r   r   r5   rB   r  r<   r   r   r   r   r   r   r   r   r   r   r   r   r   r$   r$   r   r(   r	    sz    Z
EMu	@
&+r	  c                       sN  e Zd ZdZddgZeZeZe	e
deeeeejf f fddZ	d"deeeeejf f fdd	Ze	d#d
dZe					d$ddZe							d%deeejf deeeejjejf f deeejjf dedededefddZddgdddfdee dededeee  f fddZddgfdee f fd d!Z  Z S )&FluxLoraLoaderMixinz
    Load LoRA layers into [`FluxTransformer2DModel`],
    [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).

    Specific to [`StableDiffusion3Pipeline`].
    r   r   r   c                 K   r
  r  r  r  r$   r$   r(   r5     s>   7z#FluxLoraLoaderMixin.lora_state_dictNc              	   K   s   t stdt|tr| }| j|fi |}tdd | D }|s)td| j|t	| ds7t
| | jn| j|| d dd | D }t|d	kr]| j|d
| jd| j|| d d
S d
S )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`].
            kwargs (`dict`, *optional*):
                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.
        r   c                 s   r    r!   r$   r%   r$   r$   r(   r)   P  r*   z8FluxLoraLoaderMixin.load_lora_weights.<locals>.<genexpr>r+   r   r  c                 S   r   r   r$   r   r$   r$   r(   r   [  r   z9FluxLoraLoaderMixin.load_lora_weights.<locals>.<dictcomp>r   Nr   r  )r	   r1   r2   r3   r4   r5   r6   r7   r  r9   r:   r  r   r   r   r<   r   r0   )r>   r   r.   r?   r@   rA   r  r$   r$   r(   rB   .  s4   

z%FluxLoraLoaderMixin.load_lora_weightsc                    r  )r  r   r  c                    r  r$   r  r_   rl   r$   r(   r   |  r  zBFluxLoraLoaderMixin.load_lora_into_transformer.<locals>.<listcomp>c                    r  r   r  r   r  r$   r(   r   }  r  zBFluxLoraLoaderMixin.load_lora_into_transformer.<locals>.<dictcomp>r  r   r  r   r!  r   Nr"  r   r   r   r   r%  r&  r'  r(  r$   r)  r-  r$   r  r(   r  g  s\   

1z.FluxLoraLoaderMixin.load_lora_into_transformerrx   c                    ry   )rz   r   r   r{   Nc                 3   r}   rj   r~   r%   rl   r$   r(   r)     r   zBFluxLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<genexpr>c                    r   r   r   r_   r   r$   r(   r     r   zCFluxLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<listcomp>c                    r   r   r   r   r   r$   r(   r     r   zCFluxLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<dictcomp>rn   ro   r   r   r   r   c                    r   r   r   r_   r   r$   r(   r      r   c                    r   r   r   r   r   r$   r(   r     r   Fr   r   r   r   r   r   r   r   r$   r   r   r$   r   r(   r<     r  z/FluxLoraLoaderMixin.load_lora_into_text_encoderTr   r1  r   r   rL   r   r   c           	      C   r   )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`.
        zWYou must pass at least one of `transformer_lora_layers` and `text_encoder_lora_layers`.r   Nr1   r   r   r  r=   r   )	rf   r   r1  r   r   rL   r   r   r@   r$   r$   r(   r   -  s   "
z%FluxLoraLoaderMixin.save_lora_weightsFr   r0   r   r   c                    r   r   r   r   r   r$   r(   r   e  r   zFluxLoraLoaderMixin.fuse_lorac                    r   )al  
        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   Nr   r   r   r$   r(   r     s   zFluxLoraLoaderMixin.unfuse_lorarj   r   r   r   r2  r$   r$   r   r(   r4    st    Z
9Mu8
&+r4  c                   @   s   e Zd ZddgZeZeZedddZ	e				dddZ
e								dd
eeejf deeejjf deeejjf dedededefddZdS )AmusedLoraLoaderMixinr   r   Nc                    s  t stdddlm}m}m} t| }	fdd|	D fdd| D }|durFfd	d| D   fd
d| D }t	| dkr|t
|di v r^td| di }
| D ]\}}d|v rs|jd |
|< qdt|
||}d|v r|d rtddrtd|d |di |}|du rt|}|\}}||||d ||||}|durt
|dd}|rtd| d |r|  dS |r|  dS dS dS )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.
            network_alphas (`Dict[str, float]`):
                See `LoRALinearLayer` for more details.
            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.
        r   r   r  c                    r  r$   r  r_   rl   r$   r(   r     r  zDAmusedLoraLoaderMixin.load_lora_into_transformer.<locals>.<listcomp>c                    r  r   r  r   r  r$   r(   r     r  zDAmusedLoraLoaderMixin.load_lora_into_transformer.<locals>.<dictcomp>Nc                    r  r$   r  r_   rl   r$   r(   r     r  c                    s.   i | ]\}}| v r| j d d|qS r   r  r   )r   rf   r$   r(   r     r  r   r  r   r!  r   r   r   r   r   r%  r&  r'  r(  r$   )r	   r1   r   r|   r  r  rr   r7   r   r   r:   r   r   r   rc   r   r   rs   r,  r   r   )rf   r@   r-   r   r.   r/   r|   r  r  r7   r   r'   r/  r   r   r   r   r0  r&  r$   )r   rf   r  r(   r    sd   

,z0AmusedLoraLoaderMixin.load_lora_into_transformerrx   c                    ry   )rz   r   r   r{   Nc                 3   r}   rj   r~   r%   rl   r$   r(   r)   (  r   zDAmusedLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<genexpr>c                    r   r   r   r_   r   r$   r(   r   *  r   zEAmusedLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<listcomp>c                    r   r   r   r   r   r$   r(   r   +  r   zEAmusedLoraLoaderMixin.load_lora_into_text_encoder.<locals>.<dictcomp>rn   ro   r   r   r   r   c                    r   r   r   r_   r   r$   r(   r   F  r   c                    r   r   r   r   r   r$   r(   r   I  r   Fr   r   r   r   r   r   r   r   r$   r   r   r$   r   r(   r<     r  z1AmusedLoraLoaderMixin.load_lora_into_text_encoderTr   r   r1  r   rL   r   r   c           	      C   s^   i }|s
|s
t d|r|| || j |r"|| || j | j||||||d dS )r   zVYou must pass at least one of `transformer_lora_layers` or `text_encoder_lora_layers`.r   Nr5  )	rf   r   r   r1  r   rL   r   r   r@   r$   r$   r(   r   s  r   z'AmusedLoraLoaderMixin.save_lora_weightsr   r   r   )r   r   r   r   r3  r  r   r=   r   r  r<   r   r   r   r   r   r   r   r   r   r   r   r$   r$   r$   r(   r6    sD    Sur6  c                       s   e Zd Z fddZ  ZS )LoraLoaderMixinc                    s&   d}t dd| t j|i | d S )NzLoraLoaderMixin is deprecated and this will be removed in a future version. Please use `StableDiffusionLoraLoaderMixin`, instead.r7  z1.0.0)r   r   __init__)r>   argsr?   deprecation_messager   r$   r(   r8    s   zLoraLoaderMixin.__init__)r   r   r   r8  r   r$   r$   r   r(   r7    s    r7  ),r   typingr   r   r   r   r   r   huggingface_hub.utilsr   utilsr	   r
   r   r   r   r   r   r   r   r   r   	lora_baser   lora_conversion_utilsr   r   models.lorar   r   
get_loggerr   rs   r   r   r3  LORA_WEIGHT_NAMELORA_WEIGHT_NAME_SAFEr   r   r	  r4  r6  r7  r$   r$   r$   r(   <module>   sF   4
   E   d   t   `  	