o
    8wiD                     @   s  d dl Z d dlmZ d dlmZ d dlmZ d dlZd dlmZ d dl	m	Z	 d dl
mZmZ d dlmZmZmZmZ d d	lmZmZmZmZ d
dlmZ d
dlmZ d
dlmZ d
dlmZ d
dlm Z  d
dl!m"Z" d
dl#m$Z$ d
dl%m&Z&m'Z' G dd deZ(dS )    N)asdict)Enum)Optional)nn)tqdm)is_bnb_4bit_availableis_bnb_available)	BaseTunerBaseTunerLayercheck_target_module_existsonload_layer)2TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPINGModulesToSaveWrapper_get_submodulesget_quantization_config   )dispatch_aqlm)dispatch_awq)	OFTConfig)dispatch_eetq)dispatch_gptq)dispatch_hqq)dispatch_inc)OFTLayerdispatch_defaultc                	       s\  e Zd ZU dZdZeed< d7deddf fdd	Zd
e	ddfddZ
edd Zdd Zdd ZdejddfddZedd Zdef fddZd7defddZd8dd Zd9d!d"Zd#d$ Zd%d& Z fd'd(Zed)d* Z				d:d+ed,ed-eee  fd.d/Zd0eddfd1d2Z	d;d+ed,ed-eee  dejjfd3d4Z dejjfd5d6Z!  Z"S )<OFTModelaE  
    Creates Orthogonal Finetuning model from a pretrained model. The method is described in
    https://huggingface.co/papers/2306.07280

    Args:
        model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached.
        config ([`OFTConfig`]): The configuration of the OFT model.
        adapter_name (`str`): The name of the adapter, defaults to `"default"`.
        low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
            Create empty adapter weights on meta device. Useful to speed up the loading process.

    Returns:
        `torch.nn.Module`: The OFT model.

    Example:
        ```py
        >>> from diffusers import StableDiffusionPipeline
        >>> from peft import OFTModel, OFTConfig

        >>> config_te = OFTConfig(
        ...     r=8,
        ...     target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
        ...     module_dropout=0.0,
        ...     init_weights=True,
        ... )
        >>> config_unet = OFTConfig(
        ...     r=8,
        ...     target_modules=[
        ...         "proj_in",
        ...         "proj_out",
        ...         "to_k",
        ...         "to_q",
        ...         "to_v",
        ...         "to_out.0",
        ...         "ff.net.0.proj",
        ...         "ff.net.2",
        ...     ],
        ...     module_dropout=0.0,
        ...     init_weights=True,
        ... )

        >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
        >>> model.text_encoder = OFTModel(model.text_encoder, config_te, "default")
        >>> model.unet = OFTModel(model.unet, config_unet, "default")
        ```

    **Attributes**:
        - **model** ([`~torch.nn.Module`]) -- The model to be adapted.
        - **peft_config** ([`OFTConfig`]): The configuration of the OFT model.
    oft_prefixFlow_cpu_mem_usagereturnNc                    s   t  j||||d d S )N)r   )super__init__)selfmodelconfigadapter_namer   	__class__ R/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/peft/tuners/oft/model.pyr!   f   s   zOFTModel.__init__r$   c                 C   s2   t | jdkr|jdkrt| jj ddS dS )z
        A helper method to check the config when a new adapter is being added.

        Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters.

        r   nonezf supports only 1 adapter with bias. When using multiple adapters, set bias to 'none' for all adapters.N)lenpeft_configbias
ValueErrorr'   __name__)r"   r$   r(   r(   r)   _check_new_adapter_configi   s
   	z"OFTModel._check_new_adapter_configc                 C   s
   t | |S N)r   )
oft_configkeyr(   r(   r)   _check_target_module_existsx   s   
z$OFTModel._check_target_module_existsc                 K   s$  |d u rt d|j|j|j|j|j|j|j|j|j	|j
t| jddt| jddd}g d}	|	D ]}
t| j|
d}|d urE|||
 d< q1t|tsxt| jd	rU| jjnd }| j|||fd
|i|}|| jvrn|d | |||| d S |j||j|j|j|j|j|j|j|j|j
d
 d S )NzCurrent Key shouldn't be `None`is_loaded_in_8bitFis_loaded_in_4bit)roft_block_sizemodule_dropoutcoftepsblock_shareuse_cayley_neumannnum_cayley_neumann_termsfan_in_fan_outinit_weightsloaded_in_8bitloaded_in_4bit)gptqaqlmawq)method_quantization_confighf_device_map
device_map)	r7   r8   r9   r:   r;   r<   r=   r>   r@   )r.   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   getattrr#   r   
isinstancer   hasattrrH   _create_new_moduleactive_adaptersrequires_grad__replace_moduleupdate_layer)r"   r2   r%   targettarget_nameparentcurrent_keyoptional_kwargskwargsquant_methodsquant_methodquantization_configrI   
new_moduler(   r(   r)   _create_and_replace|   sN   




zOFTModel._create_and_replacec                    s   t ||| t|dr|j}td | D ]M\}}| j|v s$d|v rdt|dr-|j}n$t|dr6|j}nt|dr?|j	}nt
|dd d urK|j}nt| }t fdd	| D sd||j qd S )
N
base_layermetaranknumqweightW_qweightin_proj_weightc                 3   s    | ]}|j  kV  qd S r1   )device).0pr^   r(   r)   	<genexpr>   s    z+OFTModel._replace_module.<locals>.<genexpr>)setattrrL   r]   torchrd   named_modulesr   r`   ra   rb   rJ   rc   next
parametersanyto)r"   rT   
child_namer[   childnamemodulerb   r(   rg   r)   rP      s&   




zOFTModel._replace_moduler#   c                 C   s   |  D ]\}}| j|vrd|_q| jD ]J}| j| j}|dkr!q|dkr6|  D ]\}}d|v r4d|_q)q|dkrW| D ]\}}t|trUt	|drU|jd urUd|j_q>qt
d| dd S )	NFr*   allr-   Toft_onlyzRequested bias: z, is not implemented.)named_parametersr   requires_gradrN   r,   r-   rk   rK   r   rL   NotImplementedError)r"   r#   nrf   active_adapterr-   rr   mr(   r(   r)    _mark_only_adapters_as_trainable   s,   

z)OFTModel._mark_only_adapters_as_trainablec           	   	   K   s   g }t  rddlm} || t rddlm} || |ttt	t
tttg d }|D ]}|||fd| i|}|d urA nq.|d u rNtd| d|S )Nr   )dispatch_bnb_8bit)dispatch_bnb_4bitr2   zTarget module zm is not supported. Currently, only the following modules are supported: `torch.nn.Linear`, `torch.nn.Conv2d`.)r   bnbr}   appendr   r~   extendr   r   r   r   r   r   r   r.   )	r2   r%   rR   rW   dispatchersr}   r~   r[   
dispatcherr(   r(   r)   rM      s8   


zOFTModel._create_new_modulerr   c                    s8   zt  |W S  ty   |dkr t| j| Y S w )z1Forward missing attributes to the wrapped module.r#   )r    __getattr__AttributeErrorrJ   r#   )r"   rr   r&   r(   r)   r     s   zOFTModel.__getattr__	inferencec                 C   sF   i }| j  D ]\}}dd t| D }|rd|d< q|||< |S )Nc                 S   s&   i | ]\}}|t |tr|jn|qS r(   )rK   r   value)re   kvr(   r(   r)   
<dictcomp>  s   & z4OFTModel.get_peft_config_as_dict.<locals>.<dictcomp>Tinference_mode)r,   itemsr   )r"   r   config_dictr3   r   r$   r(   r(   r)   get_peft_config_as_dict  s   z OFTModel.get_peft_config_as_dictTc                 C   s,   | j  D ]}t|ttfr|| qd S r1   )r#   modulesrK   r
   r   enable_adapters)r"   enabledrs   r(   r(   r)   _set_adapter_layers!  s
   
zOFTModel._set_adapter_layersc                 C   s   | j dd dS )zyEnable all adapters.

        Call this if you have previously disabled all adapters and want to re-enable them.
        Tr   N)r   r"   r(   r(   r)   enable_adapter_layers&  s   zOFTModel.enable_adapter_layersc                 C   sF   | j D ]}| j| j}|dkrd| d}t| q| jdd d S )Nr*   z>Careful, disabling adapter layers with bias configured to be 'zL' does not produce the same output as the base model would without adaption.Fr   )rN   r,   r-   warningswarnr   )r"   rz   valmsgr(   r(   r)   disable_adapter_layers-  s   


zOFTModel.disable_adapter_layersc                 C   sF   | j  D ]}t|tr|jrtd |  || q|| _	dS )a   Set the active adapter(s).

        Additionally, this function will set the specified adapters to trainable (i.e., requires_grad=True). If this is
        not desired, use the following code.

        ```py
        >>> for name, param in model_peft.named_parameters():
        ...     if ...:  # some check on name (ex. if 'lora' in name)
        ...         param.requires_grad = False
        ```

        Args:
            adapter_name (`str` or `list[str]`): Name of the adapter(s) to be activated.
        zJAdapter cannot be set when the model is merged. Unmerging the model first.N)
r#   r   rK   r   mergedr   r   unmergeset_adapterrz   )r"   r%   rs   r(   r(   r)   r   8  s   



zOFTModel.set_adapterc                    s<   t    t| jdddkrtd| jdrtddS )zVerify that the configuration supports merging.

        Currently gptq quantization and replicated layers do not support merging.
        quantization_methodNrC   z8Cannot merge OFT layers when the model is gptq quantizedlayer_replicationz=Cannot merge OFT layers when base model layers are replicated)r    _check_merge_allowedrJ   r#   r.   r,   getr   r&   r(   r)   r   O  s   
zOFTModel._check_merge_allowedc                 C   s4   | j d u r|d tvrtdtt|d  | _ | S )N
model_typez0Please specify `target_modules` in `peft_config`)target_modulesr   r.   set)r,   model_configr(   r(   r)   _prepare_adapter_configZ  s   

z OFTModel._prepare_adapter_configprogressbar
safe_mergeadapter_namesc              	      s  |r     fdd j D }d|rdnd d }t|| |dD ]Y}zt j|\}}	}
W n	 ty:   Y q$w t|	6 t|	drV|	j|||d	} 	||
||	 nt|	d
rn|rd|	j
||d  	||
|	 |	 W d    n1 sxw   Y  q$ jS )Nc                       g | ]\}} j |vr|qS r(   r   re   r3   _r   r(   r)   
<listcomp>n      z9OFTModel._unload_and_optionally_merge.<locals>.<listcomp>z
Unloading zand merging  r#   )disabledesc"unload_and_optionally_merge_module)merger   r   r]   )r   r   )r   r#   rk   r   r   r   r   rL   r   rP   r   get_base_layer)r"   r   r   r   r   key_listr   r3   rT   rR   rS   unloaded_moduler(   r   r)   _unload_and_optionally_merged  s0   


z%OFTModel._unload_and_optionally_merger%   c                    s   |t  j vrtd| d j|=  fdd j D }d}|D ] }t j|\}}}t|trE|	| |du rE|j
dd }q%|pIg  _ j||d dS )z
        Deletes an existing adapter.

        Args:
            adapter_name (str): Name of the adapter to be deleted.
        zAdapter z does not existc                    r   r(   r   r   r   r(   r)   r     r   z+OFTModel.delete_adapter.<locals>.<listcomp>N)new_active_adapters)listr,   keysr.   r#   rk   r   rK   r   delete_adapterrN   rz   _delete_auxiliary_adapter)r"   r%   r   new_adapterr3   r   rR   r(   r   r)   r     s   


zOFTModel.delete_adapterc                 C   s   | j |||dS )a  
        This method merges the OFT layers into the base model. This is needed if someone wants to use the base model as
        a standalone model.

        Args:
            progressbar (`bool`):
                whether to show a progressbar indicating the unload and merge process
            safe_merge (`bool`):
                whether to activate the safe merging check to check if there is any potential Nan in the adapter
                weights
            adapter_names (`List[str]`, *optional*):
                The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
                to `None`.

        )r   r   r   r   )r"   r   r   r   r(   r(   r)   merge_and_unload  s   zOFTModel.merge_and_unloadc                 C   s   | j ddS )z
        Gets back the base model by removing all the oft modules without merging. This gives back the original base
        model.
        F)r   r   r   r(   r(   r)   unload  s   zOFTModel.unload)F)T)r   N)TFFN)FFN)#r/   
__module____qualname____doc__r   str__annotations__boolr!   r   r0   staticmethodr4   r\   rP   r   Moduler|   rM   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   r   __classcell__r(   r(   r&   r)   r   0   sX   
 3
8
+	
	





r   ))r   dataclassesr   enumr   typingr   rj   r   r   peft.import_utilsr   r   peft.tuners.tuners_utilsr	   r
   r   r   
peft.utilsr   r   r   r   rD   r   rE   r   r$   r   eetqr   rC   r   hqqr   incr   layerr   r   r   r(   r(   r(   r)   <module>   s&   