
    bi>&                         d dl 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 dd	lmZ dd
lmZ deddfdZdeddfdZddededdfdZdedefdZed        Zedde
j2                  defd       Zy)    N)contextmanager)deepcopy)update_wrapper)
MethodType)nn   )
PeftConfig	PeftModel)	LoraLayer)BaseTunerLayermodelreturnc                 n   t        j                  | j                        }t        |j                        dk(  r~d|j                  v rod|j                  v r`t        | j                  j                        }t        |t        | j                               j                  d       t        ||       | _        yyyy)a  
    Updates the forward signature of the PeftModel to include parents class signature
        model (`PeftModel`): Peft model to update the forward signature

    Example:

    ```python
    >>> from transformers import WhisperForConditionalGeneration
    >>> from peft import get_peft_model, LoraConfig, update_forward_signature

    >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
    >>> peft_config = LoraConfig(r=8, lora_alpha=32, lora_dropout=0.1, target_modules=["q_proj", "v_proj"])

    >>> peft_model = get_peft_model(model, peft_config)
    >>> update_forward_signature(peft_model)
    ```
       argskwargs__doc____name____annotations__assignedN)inspect	signatureforwardlen
parametersr   __func__r   typeget_base_modelr   )r   current_signaturer   s      G/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/peft/helpers.pyupdate_forward_signaturer#      s    (  ))%--8(()Q.'222)4445==112T%..0199Dn	
 #7E2 5 3 	/    c                    t        | d      syt        j                  | j                        }t	        |j
                        dk(  rd|j
                  v rd|j
                  v s&t	        |j
                        dk(  rod|j
                  v r`t        | j                  j                        }t        |t        | j                               j                  d       t        ||       | _        yyy)	ab  
    Updates the generate signature of a PeftModel with overriding generate to include parents class signature
        model (`PeftModel`): Peft model to update the generate signature

    Example:

    ```python
    >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
    >>> from peft import get_peft_model, LoraConfig, TaskType, update_generate_signature

    >>> model_name_or_path = "bigscience/mt0-large"
    >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
    >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)

    >>> peft_config = LoraConfig(
    ...     task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
    ... )
    >>> peft_model = get_peft_model(model, peft_config)
    >>> update_generate_signature(peft_model)
    >>> help(peft_model.generate)
    ```
    generateNr   r   r   r   r   r   )hasattrr   r   r&   r   r   r   r   r   r   r    r   )r   r!   r&   s      r"   update_generate_signaturer(   =   s    . 5*%))%..9(()Q.'222)444
**
+q
0XARA]A]5]ENN334%%'(11?	

 $He4 6^
0r$   methodc                     |dk(  rt        |        y|dk(  rt        |        y|dk(  rt        |        t        |        yt        d| d      )a  
    Updates the signature of a PeftModel include parents class signature for forward or generate method
        model (`PeftModel`): Peft model to update generate or forward signature method (`str`): method to update
        signature choose one of "forward", "generate", "all"

    Example:
    ```python
    >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
    >>> from peft import get_peft_model, LoraConfig, TaskType, update_signature

    >>> model_name_or_path = "bigscience/mt0-large"
    >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
    >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)

    >>> peft_config = LoraConfig(
    ...     task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
    ... )
    >>> peft_model = get_peft_model(model, peft_config)
    >>> update_signature(peft_model)
    >>> help(peft_model.generate)
    ```
    r   r&   allzmethod zE is not supported please choose one of ['forward', 'generate', 'all']N)r#   r(   
ValueError)r   r)   s     r"   update_signaturer-   e   sP    .  '	:	!%(	5 '!%(76(*opqqr$   model_name_or_pathc                 Z    d}	 t        j                  |        |S # t        $ r d}Y |S w xY w)z
    Check if the model is a PEFT model.

    Args:
        model_name_or_path (`str`):
            Model id to check, can be local or on the Hugging Face Hub.

    Returns:
        `bool`: True if the model is a PEFT model, False otherwise.
    TF)r	   from_pretrained	Exception)r.   is_peft_models     r"   check_if_peft_modelr3      sA     M""#56
 	  	s    **c              #     K   t        |t        t        f      st        dt	        |             i }| j                         D ]f  }t        |t              s|j                  j                         ||<   |j                  j                         D ci c]  \  }}|||z   c}}|_        h |st        d      	 d |j                         D ]  \  }}||_         yc c}}w # |j                         D ]  \  }}||_         w xY ww)a?  
    Context manager to temporarily rescale the scaling of the LoRA adapter in a model.

    The original scaling values are restored when the context manager exits. This context manager works with the
    transformers and diffusers models that have directly loaded LoRA adapters.

    For LoRA, applying this context manager with multiplier in [0, 1] is strictly equivalent to applying
    [wise-ft](https://huggingface.co/papers/2109.01903) (see [#1940](https://github.com/huggingface/peft/issues/1940)
    for details). It can improve the performances of the model if there is a distribution shiftbetween the training
    data used for fine-tuning, and the test data used during inference.

    Warning: It has been reported that when using Apple's MPS backend for PyTorch, it is necessary to add a short sleep
        time after exiting the context before the scales are fully restored.

    Args:
        model: The model containing `LoraLayer` modules whose scaling is to be adjusted.
        multiplier (float or int):
            The multiplier that rescales the `scaling` attribute. Must be of type float or int.

    Raises:
        ValueError: If the model does not contain any `LoraLayer`
            instances, indicating that the model does not support scaling.

    Example:

    ```python
    >>> model = ModelWithLoraLayer()
    >>> multiplier = 0.5
    >>> with rescale_adapter_scale(model, multiplier):
    ...     outputs = model(**inputs)  # Perform operations with the scaled model
    >>> outputs = model(**inputs)  # The original scaling values are restored here
    ```
    z1Argument multiplier should be of type float, got z6scaling is only supported for models with `LoraLayer`sN)
isinstancefloatint	TypeErrorr   modulesr   scalingcopyitemsr,   )r   
multiplieroriginal_scalingmodulekvr:   s          r"   rescale_adapter_scalerB      s    H j5#,/KDQ[L\K]^__ --/ Tfi('-~~':':'<V$<BNN<P<P<RSDAqaZ/SFNT QRR%  0557 	%OFG$FN	% T  0557 	%OFG$FN	%s0   AD:DC D9C# =&D#!DDactivec              #     K   |sd yi }| j                         D ],  \  }}t        |t              s|j                  ||<   d|_        . 	 d | j                         D ]%  \  }}t        |t              s||v s||   |_        ' y# | j                         D ]%  \  }}t        |t              s||v s||   |_        ' w xY ww)a:  
    Context manager disables input dtype casting to the dtype of the weight.

    Parameters:
        model (nn.Module):
            The model containing PEFT modules whose input dtype casting is to be adjusted.
        active (bool):
            Whether the context manager is active (default) or inactive.

    NF)named_modulesr5   r   cast_input_dtype_enabled)r   rC   original_valuesnamer?   s        r"   disable_input_dtype_castingrI      s       O++- 0f&.1 & ? ?*/'	0H!//1 	HLD&fn5&2A$2G/		HE//1 	HLD&fn5&2A$2G/		Hs*   A	CB	 +C<C	,C6CC)r+   )T)r   
contextlibr   r;   r   	functoolsr   typesr   torchr   
peft_modelr	   r
   tuners.lorar   tuners.tuners_utilsr   r#   r(   strr-   boolr3   rB   ModulerI    r$   r"   <module>rU      s     %  $   - " /3I 3$ 3B%5Y %54 %5PrI rs rt rDC D * 9% 9%x !Hryy !H$ !H !Hr$   