o
    1Aiz                     @  sL  d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ d dl	m
Z
 d dlmZmZmZ d dlZd dlmZ d dl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mZ e e!Z"e
dd Z#G dd dej$eZ%G dd deZ&d3ddZ'd4d5ddZ(d6d$d%Z)d7d8d*d+Z*d9d:d-d.Z+d;d1d2Z,dS )<    )annotationsN)ABCabstractmethod)contextmanager)AnyOptionalUnion)AlignDevicesHook)named_module_tensorsoffload_state_dict)nn)PreTrainedModel)Conv1D)INCLUDE_LINEAR_LAYERS_SHORTHAND)
PeftConfig)ModulesToSaveWrapper_get_submodulesc                 c  sL   g }|   D ]#\}}|dv rqt|dr*t|jtr*|jjr*|j| || qd}t| drat| jdrat| jjtra| jjjrat	
d| jjj v rW| jjjjj}| jj| j d}dV  |D ]}|j|t	g  qf|rdd	 t| jD | jj_t	
d| jjj v rt|| jjj | jj| jt	g  dS dS )
a  
    A utility for modifying a module containing one or more tuners and a base layer, any of which are offloaded to the
    CPU or disk. Moves a module's sub-modules to the execution device before some action is performed, after that the
    base layer state dictionary is re-assigned (if that layer was offloaded to the disk) and finally the parameters are
    offloaded.

    If the module has no offloaded sub-modules, this function does nothing.

    Args:
        layer ('torch.nn.Module'):
            layer with tuners to be merged
    ) 
base_layer_hf_hookFr   metaTNc                 S  s   i | ]
\}}|| d qS )cpu)to).0nameparam r   D/data/cameron/vidgen/svd_motion_lora/Motion-LoRA/LoRA/tuner_utils.py
<dictcomp>R   s    z onload_layer.<locals>.<dictcomp>)named_moduleshasattr
isinstancer   r	   offloadpre_forwardappendr   torchdeviceoriginal_devicesvaluesweights_mapdatasetsave_folderpost_forwardtensorr
   r   )layeroffloaded_modulesr   modulebase_layer_offloadoffload_folderr   r   r   onload_layer(   s@   


r3   c                      s   e Zd ZdZd7 fdd	Zed8ddZd9ddZed:ddZ	d;ddZ
ed<ddZed=d#d$Zed>d%d&Zd?d(d)Zd*d+ Zd@d,d-ZdAdBd1d2Zd3d4 ZdCd5d6Z  ZS )D	BaseTunera  
    A base tuner model that provides the common methods and attributes for all tuners that are injectable into a
    torch.nn.Module

    For adding a new Tuner class, one needs to overwrite the following methods:

    - **_prepare_adapter_config**:
        A private method to eventually prepare the adapter config, for example in case the field `target_modules` is
        missing.
    - **_create_and_replace**:
        A private method to create and replace the target module with the adapter module.
    - **_check_target_module_exists**:
        A private helper method to check if the passed module's key name matches any of the target modules in the
        adapter_config.

    The easiest is to check what is done in the `peft.tuners.lora.LoraModel` class.

    Attributes:
        model (`torch.nn.Module`):
            The model to which the adapter tuner layers will be attached.
        forward (`Callable`):
            The forward method of the model.
        peft_config (`Union[`PeftConfig`, dict[str, PeftConfig]]`):
            The adapter configuration object, it should be a dictionary of `str` to `PeftConfig` objects. One can also
            pass a PeftConfig object and a new adapter will be created with the default name `adapter` or create a new
            dictionary with a key `adapter_name` and a value of that peft config.
        config (`dict[str, Any]`):
            The model configuration object, it should be a dictionary of `str` to `Any` objects.
        targeted_module_names (`list[str]`):
            The list of module names that were actually adapted. Can be useful to inspect if you want to quickly
            double-check that the `config.target_modules` where specified correctly.
    peft_config(Union[PeftConfig, dict[str, PeftConfig]]adapter_namestrreturnNonec                   s   t    || _g | _t| dst|tr||in|| _nt	d t|tr-|| j|< n| j
| || _| | j| | j| j_d S )Nr5   zAlready found a `peft_config` attribute in the model. This will lead to having multiple adapters in the model. Make sure to know what you are doing!)super__init__modeltargeted_module_namesr    r!   r   r5   loggerinfoupdateactive_adapterinject_adapter)selfr=   r5   r7   	__class__r   r   r<   ~   s   


zBaseTuner.__init__	list[str]c                 C     t | jtr
| jgS | jS Nr!   rB   r8   rD   r   r   r   active_adapters      zBaseTuner.active_adaptersargsr   kwargsc                 O  s   | j j|i |S rI   )r=   forward)rD   rN   rO   r   r   r   rP      s   zBaseTuner.forwardr   model_configdictc                 C     dS )a  
        A private method to eventually prepare the adapter config. For transformers based models, if
        `peft_config.target_modules` is None, we can automatically infer the target modules from the
        `TRANSFORMERS_MODELS_TO_XXX_TARGET_MODULES_MAPPING`. This method can be further refactored in the future to
        automatically infer it for all tuner models.

        Check out `peft.tuner.lora.LoraModel._prepare_adapter_config` for an example.

        Args:
            peft_config (`PeftConfig`):
                The adapter config.
            model_config (`dict`):
                The transformers model config, that config should contain the `model_type` key.
        Nr   )rD   r5   rQ   r   r   r   _prepare_adapter_config   s   z!BaseTuner._prepare_adapter_configr=   	nn.Modulec                 C  rS   )a_  
        A private method to modify the model structure before adapter is applied.

        See `peft.tuner.lora.LoraModel._prepare_model` for an example.

        Args:
            peft_config (`PeftConfig`):
                The prepared adapter config.
            model (`nn.Module`):
                The model that is going to be adapted.
        Nr   )rD   r5   r=   r   r   r   _prepare_model      zBaseTuner._prepare_modelkeyboolc                 C  rS   )aq  
        A helper private method to check if the passed module's key name matches any of the target modules in the
        `peft_config.target_modules` list. If it does, return `True`, else return `False`.

        Args:
            peft_config (`PeftConfig`):
                The adapter config.
            key (`str`):
                The module's key name.
        Nr   )r5   rX   r   r   r   _check_target_module_exists   rW   z%BaseTuner._check_target_module_existstargettarget_nameparentcurrent_keyc                 C  rS   )a  
        Inplace replacement of the target module with the adapter layer. This method needs to be overridden by all the
        tuner classes.

        Check `peft.tuners.lora.LoraModel._create_and_replace` for an example.

        Args:
            peft_config (`PeftConfig`):
                The adapter config.
            adapter_name (`str`):
                The adapter name.
            target (`nn.Module`):
                The target module.
            target_name (`str`):
                The target module's name.
            parent (`nn.Module`):
                The parent module.
            current_key (`str`):
                The key of the current target being adapted.
        Nr   )rD   r5   r7   r[   r\   r]   r^   r   r   r   _create_and_replace   s   zBaseTuner._create_and_replacec                 C  rS   )a)  
        A helper method to mark only the adapter layers as trainable (i.e. module.requires_grad = False) This needs to
        be overridden for all tuner classes to match the correct key names.

        Check `peft.tuners.lora.LoraModel._mark_only_adapters_as_trainable` for an example.
        Nr   )rD   r=   r   r   r    _mark_only_adapters_as_trainable   s   z*BaseTuner._mark_only_adapters_as_trainableconfigc                 C  rS   )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.

        Nr   )rD   ra   r   r   r   _check_new_adapter_config   s   z#BaseTuner._check_new_adapter_configc                 C  rS   )zHelper method to check whether the adapter can be merged.

        Raise a ValueError if it is not possible to merge the adapter with the given configuration.
        Nr   rK   r   r   r   _check_merge_allowed  s   zBaseTuner._check_merge_allowedc              	     s  | j | }| | t|dddu}d}t|dddi}t|dr%| }| ||}| || d}dd	 | D }t||}|D ]S |rtt	 fd
d|j
D rtt| \}	}
}t|
tslt|
|}t|	|| n|
| d}qC| | s{qC| j  d}t| \}	}
}| j|||
||	 d qC|std|j d| | | j | jr| D ]\}}||v rd|_q|rt|dst|j
|_
dS |j
t|j
 dS dS )a  
        Creates adapter layers and replaces the target modules with the adapter layers. This method is called under the
        hood by `peft.mapping.get_peft_model` if a non-prompt tuning adapter class is passed.

        The corresponding PEFT config is directly retrieved from the `peft_config` attribute of the BaseTuner class.

        Args:
            model (`nn.Module`):
                The model to be tuned.
            adapter_name (`str`):
                The adapter name.
        modules_to_saveNFra   
model_typecustomto_dictc                 S  s   g | ]
\}}d |v r|qS )temporal_transformer_blockr   r   rX   _r   r   r   
<listcomp>+      z,BaseTuner.inject_adapter.<locals>.<listcomp>c                 3  s    | ]	}  | V  qd S rI   endswith)r   module_to_saverX   r   r   	<genexpr>1      
z+BaseTuner.inject_adapter.<locals>.<genexpr>T)r^   zTarget modules zL not found in the base model. Please check the target modules and try again.)r5   rb   getattrr    rg   rT   rV   r    _maybe_include_all_linear_layersanyrd   r   r!   r   setattrrA   rZ   r>   r$   r_   
ValueErrortarget_modulesr`   inference_modenamed_parametersrequires_gradset)rD   r=   r7   r5   _check_for_modules_to_save_has_modules_to_saverQ   is_target_modules_in_base_modelkey_listr]   r[   r\   
new_modulenpr   rp   r   rC     sX   








zBaseTuner.inject_adapterNadapter_namesOptional[list[str]]c              	   C  sZ   |    | j D ]!}t|tr*t| |j|d W d   n1 s%w   Y  q	dS )a  
        This method merges the adapter layers into the base model.

        Merging adapters can lead to a speed up of the forward pass. A copy of the adapter weights is still kept in
        memory, which is required to unmerge the adapters. In order to merge the adapter weights without keeping them
        in memory, please call `merge_and_unload`.

        Args:
            safe_merge (`bool`, *optional*):
                If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs
                before merging the weights. This is useful if you want to check if the merge operation will produce
                NaNs. Defaults to `False`.
            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   N)rc   r=   modulesr!   BaseTunerLayerr3   merge)rD   r   r0   r   r   r   merge_adapter[  s   

zBaseTuner.merge_adapterc              	   C  sN   | j  D ]}t|tr$t| |  W d   n1 sw   Y  qdS )zU
        This method unmerges all merged adapter layers from the base model.
        N)r=   r   r!   r   r3   unmerge)rD   r0   r   r   r   unmerge_adapterr  s   


zBaseTuner.unmerge_adapterc                   s@   |p j }t fdd|D }|rt|dkrtdd S d S )Nc                 3  s    | ]	} j | jV  qd S rI   )r5   rd   )r   adapterrK   r   r   rq   }  rr   z.BaseTuner._unloading_checks.<locals>.<genexpr>   z?Cannot unload multiple adapters that specify `modules_to_save`.)rL   ru   lenrw   )rD   r   adapters_to_consideris_modules_to_save_availabler   rK   r   _unloading_checks{  s   
zBaseTuner._unloading_checks)r5   r6   r7   r8   r9   r:   r9   rG   )rN   r   rO   r   )r5   r   rQ   rR   r9   r   )r5   r   r=   rU   )r5   r   rX   r8   r9   rY   )r5   r   r7   r8   r[   rU   r\   r8   r]   rU   r^   r8   r9   r:   )r=   rU   )ra   r   r9   r:   )r=   rU   r7   r8   rI   )r   r   r9   r:   )r   r   )__name__
__module____qualname____doc__r<   propertyrL   rP   r   rT   rV   rZ   r_   r`   rb   rc   rC   r   r   r   __classcell__r   r   rE   r   r4   \   s*    !


		
P	r4   c                   @  s   e Zd ZU dZdZdZded< dZded< dZded	< d
Z	ded< g Z
ded< d3ddZed4ddZed4ddZd5d6ddZd7ddZed8d d!Zed8d"d#Zed9d%d&Zed'd( Zd:d*d+Zd;d,d-Zd<d.d/Zd=d1d2ZdS )>r   aK  
    A tuner layer mixin that provides the common methods and attributes for all tuners.

    Args:
        is_pluggable (`bool`, *optional*):
            Whether the adapter layer can be plugged to any pytorch module
        active_adapters (Union[List[`str`], `str`], *optional*):
            The name of the active adapter.
    Nr   z
tuple[str]adapter_layer_namesother_param_namesFrY   _disable_adaptersdefaultstr | list[str]_active_adapterrG   merged_adaptersr9   rU   c                 C  s"   | }t |dr|j}t |ds|S )z
        (Recursively) get the base_layer.

        This is necessary for the case that the tuner layer wraps another tuner layer.

        r   )r    r   rD   r   r   r   r   get_base_layer  s
   

zBaseTunerLayer.get_base_layertorch.Tensorc                 C  s&   |   }t|dr|j}|S |j}|S )Nqweight)r   r    r   weight)rD   r   r   r   r   r   r     s   
zBaseTunerLayer.weightc                 C  s   |   }|jS rI   )r   biasr   r   r   r   r     s   zBaseTunerLayer.bias
safe_merger   r   r:   c                 C     t rI   NotImplementedError)rD   r   r   r   r   r   r        zBaseTunerLayer.mergec                 C  r   rI   r   rK   r   r   r   r     r   zBaseTunerLayer.unmergec                 C  s
   t | jS rI   )rY   r   rK   r   r   r   merged  s   
zBaseTunerLayer.mergedc                 C     | j S rI   )r   rK   r   r   r   disable_adapters     zBaseTunerLayer.disable_adaptersr8   c                 C  r   rI   )r   rK   r   r   r   rB     r   zBaseTunerLayer.active_adapterc                 C  rH   rI   rJ   rK   r   r   r   rL     rM   zBaseTunerLayer.active_adaptersenabledc                 C  sD   |r|  | j d| _dS | jD ]}t| |}|d qd| _dS )zToggle the enabling and disabling of adapters

        Takes care of setting the requires_grad flag for the adapter weights.

        Args:
            enabled (bool): True to enable adapters, False to disable adapters
        FTN)set_adapterrL   r   r   rs   requires_grad_)rD   r   
layer_namer.   r   r   r   enable_adapters  s   



zBaseTunerLayer.enable_adaptersc                 C  s`   t |tr|g}| jD ]}t| |}| D ]\}}||v r$|d q|d q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.
        TFN)r!   r8   r   rs   itemsr   r   )rD   r   r   module_dictrX   r.   r   r   r   r     s   



zBaseTunerLayer.set_adapterc                 C  sB   t  }| j| j D ]}t| |}t|dr||  q	t|S )z3Return a sorted list of all available adapter nameskeys)r|   r   r   rs   r    rA   r   sorted)rD   r   r   attrr   r   r   _all_available_adapter_names  s   

z+BaseTunerLayer._all_available_adapter_namesr7   c                 C  s   | j | j D ]}|t| |v rt| ||= q|| jv rV| jdd }|| |r0| | dS |  }|s=| g  dS |d }td| d| d | |d  dS dS )a  
        Delete an adapter from the layer

        This should be called on all adapter layers, or else we will get an inconsistent state.

        This method will also set a new active adapter if the deleted adapter was an active adapter. It is important
        that the new adapter is chosen in a deterministic way, so that the same adapter is chosen on all layers.

        Args:
            adapter_name (`str`): The name of the adapter to delete

        Nr   zAdapter z< was active which is now deleted. Setting active adapter to .)	r   r   rs   rL   remover   r   warningswarn)rD   r7   r   rL   remaining_adaptersnew_active_adapterr   r   r   delete_adapter  s(   

zBaseTunerLayer.delete_adapter)r9   rU   )r9   r   )FN)r   rY   r   r   r9   r:   )r9   r:   )r9   rY   )r9   r8   )r   rY   r9   r:   )r   r   r9   r:   r   )r7   r8   r9   r:   )r   r   r   r   rB   r   __annotations__r   r   r   r   r   r   r   r   r   r   r   r   rL   r   r   r   r   r   r   r   r   r     s6   
 






r   rX   r8   r9   bool | re.Match[str] | Nonec                   s.  t | jtrt| j }|S  | jv rd}|S t fdd| jD }t| dd}t| dd}|duo@t |tr?t|dknd}|r|rd}|du sQt|dkrXt	d }nt |tr`|gn|}|D ]}t	d	| d
 }|durv nqd|du rd}|S t
|d}t |t
r||k}|S ||v }|S )a  A helper method to check if the passed module's key name matches any of the target modules in the adapter_config.

    Args:
        config (`LoraConfig` | `LycorisConfig`): A config to match target modules from
        key (`str`): A key to search any matches in config

    Returns:
        `bool` | `re.Match[str]` | `None`: True of match object if key matches any target modules from config, False or
        None if no match found
    Tc                 3  s     | ]}  d | V  qdS )r   Nrm   )r   
target_keyrp   r   r   rq   N  s    z-check_target_module_exists.<locals>.<genexpr>layers_to_transformNlayers_patternr   z.*\.[^.]*\.(\d+)\.z.*\.z	\.(\d+)\.Fr   )r!   rx   r8   re	fullmatchru   rs   listr   matchintgroup)ra   rX   target_module_foundlayer_indexesr   is_using_layer_indexeslayer_indexpatternr   rp   r   check_target_module_exists=  s>   #
 
r   r   tunerr7   rR   c                 C  s`   | j | }dd | j D }g g d}|D ]}| ||r&|d | q|d | q|S )zw
    A helper function to inspect the set of matched and unmatched modules for a PEFT model and the given adapter.
    c                 S  s   g | ]\}}|qS r   r   ri   r   r   r   rk   t  s    z+inspect_matched_modules.<locals>.<listcomp>)matched	unmatchedr   r   )r5   r=   r   rZ   r$   )r   r7   ra   r   r   rX   r   r   r   inspect_matched_moduleso  s   

r   r5   r   r=   rU   c                   s   t | jtr| j tks| S t |tstdtdtjj	t
f}t }| D ]\}}t ||r?|ddd }|| q)|   durZ fdd| D d	 }||h8 }|| _| S )
z
    Helper function to update `target_modules` to all linear/Conv1D layers if provided as 'all-linear'. Adapted from
    the QLoRA repository: https://github.com/artidoro/qlora/blob/main/qlora.py
    z:Only instances of PreTrainedModel support `target_modules=`r   r   Nc                   s   g | ]
\}}| u r|qS r   r   )r   r   r0   
output_embr   r   rk     rl   z4_maybe_include_all_linear_layers.<locals>.<listcomp>r   )r!   rx   r8   lowerr   r   rw   r%   r   Linearr   r|   r   rsplitaddget_output_embeddings)r5   r=   linear_classeslinear_module_namesr   r0   nameslast_module_namer   r   r   rt   ~  s*   





rt   r0   r   r   rG   c                   sl   |du r| j }| jr4t| j  fdd|D }|r/tdd| j dd| d |S td |S )	z
    Helper function to check which adapters should be merged.

    Only return those adapters that are not already merged. Give a warning if some or all of the adapters are already
    merged.

    Nc                   s   g | ]}| vr|qS r   r   )r   r   r   r   r   rk     s    z+check_adapters_to_merge.<locals>.<listcomp>z'Already following adapters were merged ,z#. You are now additionally merging r   z/All adapters are already merged, nothing to do.)rL   r   r|   r   r   r   join)r0   r   r   r   r   check_adapters_to_merge  s   

r   Fc                 C  s>   t | }ddd}|r|  D ]\}}|||| q|S )zClone a module in a pytorch model.

    Clones a module of a model, optionally sharing all the parameters between the original and the clone. Simplifies
    reusing a module when manipulating the architecture of a model.
    srcrU   dstc                 S  s&   | j ddD ]
\}}||| qd S )NF)recurse)rz   register_parameter)r   r   r   r   r   r   r   _share_weights  s   z$clone_module.<locals>._share_weightsN)r   rU   r   rU   )copydeepcopyr   get_submodule)r0   share_weightscloner   r   	submoduler   r   r   clone_module  s   

r   	layer_maplist[tuple[int, int]]c           
      C  s^  t | dr| j} t | dst | dr| j} d}d}t | dr$d}| j}nt | dr6t | jdr6d}| jj}n
t | dr@d	}| j}|rHt|tj	sLt
d
g }|D ],\}}t||D ]"}t|}|t|| dd |d  D ]
}	t |	drz||	_qpqYqPt	|}|dkr|| _n|dkr|| j_n|d	kr|| _nt
dt | jdrt|| j_dS dS )a~  Replicate layers in a transfomer model with weight sharing.

    This function looks for a module list attribute at model[(.model)*].layers and replicates the layers in the module
    list according to the layer map. For example the map `[[0, 4], [2, 5]]` will take the set of layers `[0, 1, 2, 3,
    4]` and replace them with a module list containing `[0, 1, 2, 3, 2, 3, 4]`.
    r=   bertNlayersllamaencoderr.   hfalconzlCould not locate the layers attribute in the model. Expected Llama, Bert or Falcon compatible architectures.T)r   r   	layer_idxz@Unexpected model type, need to handle post-processing of layers.num_hidden_layers)r    r=   r   r   r   r.   r   r!   r   
ModuleListrw   ranger   r$   r   r   r   ra   r   )
r=   r   re   r   
new_layersstartendicurrent_idxr   r   r   r   replicate_layers  sT   








r  )rX   r8   r9   r   )r   )r   r4   r7   r8   r9   rR   )r5   r   r=   rU   r9   r   rI   )r0   r   r   r   r9   rG   )F)r0   rU   )r=   rU   r   r   )-
__future__r   r   loggingr   r   abcr   r   
contextlibr   typingr   r   r   r%   Zaccelerate.hooksr	   accelerate.utilsr
   r   r   transformersr   Ztransformers.pytorch_utilsr   
peft.utilsr   peft.configr   r   r   	getLoggerr   r?   r3   Moduler4   r   r   r   rt   r   r   r  r   r   r   r   <module>   s>   

3  * 
:2
$