o
    pi>                     @   s   d dl Z d dlmZ d dlmZmZmZmZ ddlm	Z	m
Z
mZmZmZmZmZ ddlmZ eedd	 d
d	 dZG dd dZdS )    N)partial)DictListOptionalUnion   )MIN_PEFT_VERSIONUSE_PEFT_BACKENDcheck_peft_versiondelete_adapter_layersis_peft_availableset_adapter_layers!set_weights_and_activate_adapters   )_maybe_expand_lora_scalesc                 C      |S N 	model_clsweightsr   r   T/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/diffusers/loaders/peft.py<lambda>"       r   c                 C   r   r   r   r   r   r   r   r   #   r   )UNet2DConditionModelUNetMotionModelSD3Transformer2DModelFluxTransformer2DModelc                   @   s  e Zd ZdZdZ	d&deee ef deee	e
ee	 ee
 ed f  fddZd'd	ed
dfddZd	eeee f d
dfddZd(ddZd(ddZd
ee fddZd)ddZd&ddZdd Zdd Zdd Zd d! Zd"d# Zdeee ef fd$d%ZdS )*PeftAdapterMixina  
    A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
    more details about adapters and injecting them in a base model, check out the PEFT
    [documentation](https://huggingface.co/docs/peft/index).

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

    - Attach new adapters in the model.
    - Attach multiple adapters and iteratively activate/deactivate them.
    - Activate/deactivate all adapters from the model.
    - Get a list of the active adapters.
    FNadapter_namesr   c                 C   s   t stdt|tr|gn|}t|ts|gt| }t|t|kr3tdt| dt| ddd |D }t| jj }|| |}t	| || dS )a  
        Set the currently active adapters for use in the UNet.

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

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
        pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
        ```
        z.PEFT backend is required for `set_adapters()`.zLength of adapter names z- is not equal to the length of their weights .c                 S   s   g | ]
}|d ur
|ndqS )N      ?r   ).0wr   r   r   
<listcomp>g   s    z1PeftAdapterMixin.set_adapters.<locals>.<listcomp>N)
r	   
ValueError
isinstancestrlistlen_SET_ADAPTER_SCALE_FN_MAPPING	__class____name__r   )selfr   r   scale_expansion_fnr   r   r   set_adapters7   s   

zPeftAdapterMixin.set_adaptersdefaultadapter_namereturnc                 C   s   t td t stdddlm}m} | jsd| _n|| jv r(t	d| dt
||s7t	dt| d	d
|_||| | | | d
S )a  
        Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
        to the adapter to follow the convention of the PEFT library.

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

        Args:
            adapter_config (`[~peft.PeftConfig]`):
                The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
                methods.
            adapter_name (`str`, *optional*, defaults to `"default"`):
                The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
        min_versionTPEFT is not available. Please install PEFT to use this function: `pip install peft`.r   )
PeftConfiginject_adapter_in_modelTzAdapter with name z- already exists. Please use a different name.z8adapter_config should be an instance of PeftConfig. Got z	 instead.N)r
   r   r   ImportErrorpeftr6   r7   _hf_peft_config_loadedpeft_configr%   r&   typebase_model_name_or_pathset_adapter)r-   adapter_configr1   r6   r7   r   r   r   add_adaptero   s   


zPeftAdapterMixin.add_adapterc                 C   s   t td | jstdt|tr|g}t|t| j }t|dkr5tdd	| dt
| j  ddlm} d}|  D ](\}}t||rit|d	rU|| nt|d	sdt|d
krdtd||_d}qA|sptddS )a  
        Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.

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

        Args:
            adapter_name (Union[str, List[str]])):
                The list of adapters to set or the adapter name in the case of a single adapter.
        r3   0No adapter loaded. Please load an adapter first.r   z)Following adapter(s) could not be found: z, zV. Make sure you are passing the correct adapter name(s). current loaded adapters are: BaseTunerLayerFr>   r   zYou are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT. `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`TzhDid not succeeded in setting the adapter. Please make sure you are using a model that supports adapters.N)r
   r   r:   r%   r&   r'   setr;   r)   joinr(   keyspeft.tuners.tuners_utilsrC   named_moduleshasattrr>   active_adapter)r-   r1   missingrC   _adapters_has_been_set_moduler   r   r   r>      s<   



zPeftAdapterMixin.set_adapterc                 C   b   t td | jstdddlm} |  D ]\}}t||r.t|dr+|j	dd qd|_
qd	S )
a  
        Disable all adapters attached to the model and fallback to inference with the base model only.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        r3   rA   r   rB   enable_adaptersFenabledTNr
   r   r:   r%   rG   rC   rH   r&   rI   rP   disable_adaptersr-   rC   rM   rN   r   r   r   rT      s   


z!PeftAdapterMixin.disable_adaptersc                 C   rO   )
aK  
        Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the list of
        adapters to enable.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        r3   rA   r   rB   rP   TrQ   FNrS   rU   r   r   r   rP      s   


z PeftAdapterMixin.enable_adaptersc                 C   s\   t td t std| jstdddlm} |  D ]\}}t	||r+|j
  S qdS )z
        Gets the current list of active adapters of the model.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        r3   r5   rA   r   rB   N)r
   r   r   r8   r:   r%   rG   rC   rH   r&   rJ   rU   r   r   r   active_adapters   s   


z PeftAdapterMixin.active_adaptersr!   c                 C   s0   t std|| _|| _| t| j|d d S )Nz+PEFT backend is required for `fuse_lora()`.)r   )r	   r%   
lora_scale_safe_fusingapplyr   _fuse_lora_apply)r-   rW   safe_fusingr   r   r   r   	fuse_lora  s
   zPeftAdapterMixin.fuse_lorac                 C   s   ddl m} d| ji}t||rC| jdkr|| j tt|j	j
}d|v r-||d< nd|vr9|d ur9td|j	di | d S d S )Nr   rB   
safe_merger!   r   zThe `adapter_names` argument is not supported with your PEFT version. Please upgrade to the latest version of PEFT. `pip install -U peft`r   )rG   rC   rX   r&   rW   scale_layerr(   inspect	signaturemerge
parametersr%   )r-   rN   r   rC   merge_kwargssupported_merge_kwargsr   r   r   rZ     s   



z!PeftAdapterMixin._fuse_lora_applyc                 C   s   t std| | j d S )Nz-PEFT backend is required for `unfuse_lora()`.)r	   r%   rY   _unfuse_lora_applyr-   r   r   r   unfuse_lora&  s   zPeftAdapterMixin.unfuse_lorac                 C   s&   ddl m} t||r|  d S d S )Nr   rB   )rG   rC   r&   unmerge)r-   rN   rC   r   r   r   re   +  s   
z#PeftAdapterMixin._unfuse_lora_applyc                 C   s6   t stdddlm} ||  t| dr| `d S d S )Nz-PEFT backend is required for `unload_lora()`.r   )recurse_remove_peft_layersr;   )r	   r%   utilsri   rI   r;   )r-   ri   r   r   r   unload_lora1  s   
zPeftAdapterMixin.unload_lorac                 C      t stdt| dd dS )a,  
        Disables the active LoRA layers of the underlying model.

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.disable_lora()
        ```
        )PEFT backend is required for this method.FrQ   Nr	   r%   r   rf   r   r   r   disable_lora;     zPeftAdapterMixin.disable_lorac                 C   rl   )a*  
        Enables the active LoRA layers of the underlying model.

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.enable_lora()
        ```
        rm   TrQ   Nrn   rf   r   r   r   enable_loraR  rp   zPeftAdapterMixin.enable_lorac                 C   sL   t stdt|tr|g}|D ]}t| | t| dr#| j|d qdS )a  
        Delete an adapter's LoRA layers from the underlying model.

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

        Example:

        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
        )
        pipeline.delete_adapters("cinematic")
        ```
        rm   r;   N)r	   r%   r&   r'   r   rI   r;   pop)r-   r   r1   r   r   r   delete_adaptersi  s   


z PeftAdapterMixin.delete_adaptersr   )r0   )r2   N)r!   FN)r,   
__module____qualname____doc__r:   r   r   r'   r   floatr   r/   r@   r>   rT   rP   rV   r\   rZ   rg   re   rk   ro   rq   rs   r   r   r   r   r   '   s,     
8&
1



r   )r_   	functoolsr   typingr   r   r   r   rj   r   r	   r
   r   r   r   r   unet_loader_utilsr   r*   r   r   r   r   r   <module>   s   $	