
    oiP                        S SK Jr  S SKrS SKJr  S SKJrJrJr  S SK	r	S SK
Jr  S SK	Jr  S SKJr  S SKJr  S	S
KJr  S	SKJr  S	SKJr  S	SKJrJr  SS jrSS jr " S S\\	R                  R8                  5      rg)    )annotationsN)contextmanager)AnyOptionalUnion)remove_hook_from_submodules)nn)PushToHubMixin)DUMMY_MODEL_CONFIG   )
PeftConfig)	PeftModel)
MixedModel)_set_adapter_set_trainablec                J   [        U SS5      (       d  U $ [        U SS5      (       d}  [        U SS5      (       dj  [        U SS5      (       dW  [        U S5      (       a  U R                  5         g
[        U S5      (       a#  S	 nU R                  5       R	                  U5        g
g
g
g
g
)z<
Prepares the model for gradient checkpointing if necessary
is_gradient_checkpointingTis_loaded_in_8bitFis_loaded_in_4bitis_quantizedenable_input_require_gradsget_input_embeddingsc                &    UR                  S5        g )NT)requires_grad_)moduleinputoutputs      J/home/james-whalen/.local/lib/python3.13/site-packages/peft/mixed_model.pymake_inputs_require_gradK_prepare_model_for_gradient_checkpointing.<locals>.make_inputs_require_grad3   s    %%d+    N)getattrhasattrr   r   register_forward_hook)modelr   s     r   )_prepare_model_for_gradient_checkpointingr&   "   s    
 55t<< 	*E225-u555.%005677,,.U233, &&(>>?WX 4	 1 6 	3r!   c                z    SSK Jn  U R                  U;  a%  [        SU R                  R                   SU 35      eg )Nr   )COMPATIBLE_TUNER_TYPESzThe provided `peft_type` 'zE' is not compatible with the `PeftMixedModel`. Compatible types are: )tuners.mixedr(   	peft_type
ValueErrorvalue)peft_configr(   s     r   _check_config_compatibler.   9   sK    4$::()>)>)D)D(E F%%;$<>
 	
 ;r!   c                    ^  \ rS rSrSrSSU 4S jjjr\SS j5       r\SS j5       r\S S j5       r	S r
S rS!U 4S	 jjrS"S
 jrS"S jr\S 5       rS#S$S jjrS%S jrS#S&S jjrS'S jrS"S jrS"S jrS rS r\S(S j5       rS)S jrS*S jrS+S jr  S,       S-S jjr\   S.           S/S jj5       rSr U =r!$ )0PeftMixedModelC   a  
PeftMixedModel for loading mixing different types of adapters for inference.

This class does not support loading/saving, and it shouldn't usually be initialized directly. Instead, use
`get_peft_model` with the argument `mixed=True`.

> [!TIP] > Read the [Mixed adapter types](https://huggingface.co/docs/peft/en/developer_guides/mixed_models) guide
to learn > more about using different adapter types.

Example:

```py
>>> base_model = ...  # load the base model, e.g. from transformers
>>> peft_model = PeftMixedModel.from_pretrained(base_model, path_to_adapter1, "adapter1").eval()
>>> peft_model.load_adapter(path_to_adapter2, "adapter2")
>>> peft_model.set_adapter(["adapter1", "adapter2"])  # activate both adapters
>>> peft_model(data)  # forward pass using both adapters
```

Args:
    model (`torch.nn.Module`):
        The model to be tuned.
    config (`PeftConfig`):
        The config of the model to be tuned. The adapter type must be compatible.
    adapter_name (`str`, `optional`, defaults to `"default"`):
        The name of the first adapter.
    low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
        Create empty adapter weights on meta device. Useful to speed up the loading process.
c                  > [         TU ]  5         [        U5        [        U5        S U l        [        XU0U5      U l        U R                  X#5        [        US[        5      U l
        [        U R                  S5      (       aB  [        U R                  R                  S5      (       a  SU R                  R                  l        g g g )Nconfigpretraining_tpr   )super__init__r.   r&   modules_to_saver   
base_modelset_modules_to_saver"   r   r3   r#   r4   )selfr%   r-   adapter_name	__class__s       r   r6   PeftMixedModel.__init__b   s     -1%8#$U;,GV  ;eX/AB
 4??H--'$//:P:PRb2c2c45DOO""1 3d-r!   c                .    U R                   R                  $ N)r8   r-   r:   s    r   r-   PeftMixedModel.peft_configr   s    ***r!   c                .    U R                   R                  $ r?   )r8   active_adapterr@   s    r   rC   PeftMixedModel.active_adapterv   s    ---r!   c                .    U R                   R                  $ r?   )r8   active_adaptersr@   s    r   rF   PeftMixedModel.active_adaptersz   s    ...r!   c                   SnSnU R                  5        Hr  u  p4UR                  5       nUS:X  a  [        US5      (       a  UR                  nUR                  R
                  S:X  a  US-  nX%-  nUR                  (       d  Mn  X-  nMt     X4$ )zW
Returns the number of trainable parameters and number of all parameters in the model.
r   ds_numel
Params4bit   )named_parametersnumelr#   rI   r<   __name__requires_grad)r:   trainable_params	all_param_param
num_paramss         r   get_nb_trainable_parameters*PeftMixedModel.get_nb_trainable_parameters~   s    
 	--/HAJQ75*#=#="^^

 ''<7'!^
#I""" .  0   **r!   c           	     b    U R                  5       u  p[        SUS SUS SSU-  U-  S 35        g)a  
Prints the number of trainable parameters in the model.

Note: print_trainable_parameters() uses get_nb_trainable_parameters() which is different from
num_parameters(only_trainable=True) from huggingface/transformers. get_nb_trainable_parameters() returns
(trainable parameters, all parameters) of the Peft Model which includes modified backbone transformer model.
For techniques like LoRA, the backbone transformer model is modified in place with LoRA modules. However, for
prompt tuning, the backbone transformer model is unmodified. num_parameters(only_trainable=True) returns number
of trainable parameters of the backbone transformer model which can be different.
ztrainable params: z,dz || all params: z || trainable%: d   z.4fN)rU   print)r:   rP   rQ   s      r   print_trainable_parameters)PeftMixedModel.print_trainable_parameters   sS     '+&F&F&H# !1" 5 6$R. )!11I=cBD	
r!   c                ~   >  [         TU ]  U5      $ ! [         a     US:X  a  e [        U R                  U5      s $ f = f)z1Forward missing attributes to the wrapped module.r8   )r5   __getattr__AttributeErrorr"   r8   )r:   namer<   s     r   r]   PeftMixedModel.__getattr__   sC    	27&t,, 	2|#4??D11	2s    '<<c                &    U R                   " U0 UD6$ )z
Forward pass of the model.
)r8   r:   argskwargss      r   forwardPeftMixedModel.forward   s     ///r!   c                :    U R                   R                  " U0 UD6$ )z
Generate output.
)r8   generaterb   s      r   rh   PeftMixedModel.generate   s     ''888r!   c              #     #     U R                   R                  5         Sv   U R                   R                  5         g! U R                   R                  5         f = f7f)z
Disables the adapter module.
N)r8   disable_adapter_layersenable_adapter_layersr@   s    r   disable_adapterPeftMixedModel.disable_adapter   s=     
	4OO224OO113DOO113s   A= AAAc                    [        U5         X R                  U'   U R                  R                  XUS9  U R                  X!5        g! [         a    XR                  ;   a  U R                  U	 e f = f)a^  
Add an adapter to the model based on the passed configuration.

This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`].

The name for the new adapter should be unique.

The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active
adapter.

Args:
    adapter_name (`str`):
        The name of the adapter to be added.
    peft_config ([`PeftConfig`]):
        The configuration of the adapter to be added.
    low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
        Create empty adapter weights on meta device. Useful to speed up the process when loading saved
        adapters.

        > [!TIP] > Don't use `low_cpu_mem_usage=True` when creating a new PEFT adapter for training (training
        is untested > and discouraged for PeftMixedModel in general).
)low_cpu_mem_usageN)r.   r-   r8   inject_adapter	Exceptionr9   )r:   r;   r-   rp   s       r   add_adapterPeftMixedModel.add_adapter   su    . 	!-	-8\*OO**4Qb*c 	  ;  	///$$\2	s   (A (A/c           	         [        USS 5      =nc  g U R                  c  [        U5      U l        OU R                  R                  U5        [	        U U[        USS 5      UR
                  S9  g )Nr7   )module_namesinference_mode)r"   r7   setupdater   rw   )r:   r-   r;   r7   s       r   r9   "PeftMixedModel.set_modules_to_save   sk    &{4EtLLOU'#&#7D   ''8 .?F&55		
r!   c           	     \   [        U[        5      (       a  U/n[        U5      [        U R                  R	                  5       5      -
  nU(       a;  [        S[        U5       S[        U R                  R	                  5       5       35      eU R                  R                  XS9  [        XUS9  g)a2  
Sets the active adapter(s) for the model.

Note that the order in which the adapters are applied during the forward pass may not be the same as the order
in which they are passed to this function. Instead, the order during the forward pass is determined by the
order in which the adapters were loaded into the model. The active adapters only determine which adapters are
active during the forward pass, but not the order in which they are applied.

Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless
inference_mode is True.

Args:
    adapter_name (str, list[str]):
        The name(s) of the adapter(s) to set as active
    inference_mode (bool, optional):
         Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False.
Adapter(s)   not found, available adapters: )rw   N)

isinstancestrrx   r-   keysr+   sortedr8   set_adapterr   )r:   r;   rw   
mismatcheds       r   r   PeftMixedModel.set_adapter   s    $ lC(((>L&T-=-=-B-B-D)EE
fZ011QRXY]YiYiYnYnYpRqQrs  	##L#PTGr!   c           	     L   [        U[        5      (       a  U/n[        U5      [        U R                  R	                  5       5      -
  nU(       a;  [        S[        U5       S[        U R                  R	                  5       5       35      eU R                  R                  U5        g )Nr|   r}   )	r~   r   rx   r-   r   r+   r   r8   delete_adapter)r:   r;   r   s      r   r   PeftMixedModel.delete_adapter  s    lC(((>L&T-=-=-B-B-D)EE
fZ011QRXY]YiYiYnYnYpRqQrs  	&&|4r!   c                :    U R                   R                  " U0 UD6$ )a9  
This method merges the adapter 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`.
)r8   merge_and_unloadrb   s      r   r   PeftMixedModel.merge_and_unload'  s     //@@@r!   c                :    U R                   R                  " U0 UD6$ )zx
Gets back the base model by removing all the adapter modules without merging. This gives back the original base
model.
)r8   unloadrb   s      r   r   PeftMixedModel.unload8  s    
 %%t6v66r!   c                H    [        SU R                  R                   S35      e)Nz&get_layer_status is not supported for .	TypeErrorr<   rN   r@   s    r   get_layer_statusPeftMixedModel.get_layer_status?  #    @AXAX@YYZ[\\r!   c                H    [        SU R                  R                   S35      e)Nz&get_model_status is not supported for r   r   r@   s    r   get_model_statusPeftMixedModel.get_model_statusB  r   r!   c                .    [         R                  " U5      $ r?   )r   _split_kwargs)clsrd   s     r   r   PeftMixedModel._split_kwargsE  s    &&v..r!   c                ,    [         R                  " XUS9$ )N)is_trainable)r   _check_new_adapter_config)r:   r-   r   s      r   r   (PeftMixedModel._check_new_adapter_configI  s    224S_``r!   c                r    [         R                  " XU/UQ70 UD6nU R                  U R                  5        U$ )a  
Load a trained adapter into the model.

The name for the new adapter should be unique.

The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active
adapter.

Args:
    adapter_name (`str`):
        The name of the adapter to be added.
    peft_config ([`PeftConfig`]):
        The configuration of the adapter to be added.
    is_trainable (`bool`, *optional*, defaults to `False`):
        Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be
        used for inference.
    torch_device (`str`, *optional*, defaults to None):
        The device to load the adapter on. If `None`, the device will be inferred.
    autocast_adapter_dtype (`bool`, *optional*, defaults to `True`):
        Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter
        weights using float16 and bfloat16 to float32, as this is typically required for stable training, and
        only affect select PEFT tuners.
    ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`):
        Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`.
    low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
        Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the
        process.
    kwargs: (`optional`):
        Additional arguments to modify the way the adapter is loaded, e.g. the token for Hugging Face Hub.
)r   load_adapterr   rF   )r:   model_idr;   rc   rd   r   s         r   r   PeftMixedModel.load_adapterL  s:    @ ''VtVvV--.r!   c                H    [        SU R                  R                   S35      e)Nz)Model card creation is not supported for  (yet).NotImplementedErrorr<   rN   )r:   
output_dirs     r   create_or_update_model_card*PeftMixedModel.create_or_update_model_cardq  s#    !$MdnnNeNeMffm"noor!   c                H    [        SU R                  R                   S35      e)NzSaving is not supported for r   r   )r:   save_directorysafe_serializationselected_adaptersrd   s        r   save_pretrainedPeftMixedModel.save_pretrainedt  s%     "$@AXAX@YY`"abbr!   c                P   SSK JnJn  Uc  UR                  SS5      UR                  SS5      UR                  SS5      UR                  SS5      S.n	UR                  S	S5      =n
(       a  XS	'   U[        R
                  " U40 U	D6   R                  " U40 UD6nO:[        U[        5      (       a  U(       + Ul        O[        S
UR                   35      eUR                  U;  a  [        SUR                   S35      e[        USS5      bL  [        [        UR                  R!                  5       5      R#                  SS15      5      S:  a  [%        U5        UR&                  (       a  U(       a  [        S5      eU(       + Ul        U " XU5      nUR(                  " X#4SU0UD6  U$ )a  
Instantiate a PEFT mixed model from a pretrained model and loaded PEFT weights.

Note that the passed `model` may be modified inplace.

Args:
    model (`nn.Module`):
        The model to be adapted.
    model_id (`str` or `os.PathLike`):
        The name of the PEFT configuration to use. Can be either:
            - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face
              Hub.
            - A path to a directory containing a PEFT configuration file saved using the `save_pretrained`
              method (`./my_peft_config_directory/`).
    adapter_name (`str`, *optional*, defaults to `"default"`):
        The name of the adapter to be loaded. This is useful for loading multiple adapters.
    is_trainable (`bool`, *optional*, defaults to `False`):
        Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and use for
        inference
    config ([`~peft.PeftConfig`], *optional*):
        The configuration object to use instead of an automatically loaded configuration. This configuration
        object is mutually exclusive with `model_id` and `kwargs`. This is useful when configuration is already
        loaded before calling `from_pretrained`.
    low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
        Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the
        process.
    kwargs: (`optional`):
        Additional keyword arguments passed along to the specific PEFT configuration class.
r   )PEFT_TYPE_TO_CONFIG_MAPPING PEFT_TYPE_TO_MIXED_MODEL_MAPPINGN	subfolderrevision	cache_dirtoken)r   r   r   r   use_auth_tokenz+The input config must be a PeftConfig, got zAdapter of type z# is not supported for mixed models.hf_device_mapcpudiskr   zRCannot set a prompt learning adapter to trainable when loading pretrained adapter.r   )mappingr   r   getr   _get_peft_typefrom_pretrainedr~   rw   r+   r<   r*   r"   lenrx   r   valuesintersectionr   is_prompt_learningr   )r   r%   r   r;   r   r3   rd   r   r   	hf_kwargsr   s              r   r   PeftMixedModel.from_pretrained}  s   P 	[ >#ZZT:"JJz48#ZZT:GT2	I "(,<d!CC~C.<*+01J1J81aW`1abrr"F 
++(4$4F!J6K[K[J\]^^ #CC/0@0@/AAdeffE?D1=3##**,-::E6?KD
D (.$$qrr(4$4F! E<08WWPVWr!   )r8   r3   r7   )default)r%   	nn.Moduler-   r   r;   r   returnNone)r   zdict[str, PeftConfig])r   r   )r   z	list[str])r_   r   )rc   r   rd   r   )F)r;   r   r-   r   rp   boolr   r   )r-   r   r;   r   r   r   )r;   Union[str, list[str]]rw   r   r   r   )r;   r   r   r   )rd   zdict[str, Any])r-   r   r   r   r   r   )r   r   r;   r   rc   r   rd   r   )r   r   )FN)r   r   r   r   r   zOptional[list[str]]rd   r   )r   FN)r%   r   r   zstr | os.PathLiker;   r   r   r   r3   zOptional[PeftConfig]rd   r   )"rN   
__module____qualname____firstlineno____doc__r6   propertyr-   rC   rF   rU   rZ   r]   re   rh   r   rm   rs   r9   r   r   r   r   r   r   classmethodr   r   r   r   r   r   __static_attributes____classcell__)r<   s   @r   r0   r0   C   sg   <6 6  + + . . / /+2
(209 4 4!<F
H<
5A"7]] / /a#Jp $)15	cc !c /	c
 c 
 &"'+NN $N 	N
 N %N N Nr!   r0   )r%   r   r   r   )r-   r   r   r   )
__future__r   os
contextlibr   typingr   r   r   torchaccelerate.hooksr   r	   transformers.utilsr
   peft.utils.constantsr   r3   r   
peft_modelr   tunersr   utilsr   r   r&   r.   Moduler0    r!   r   <module>r      sT    # 	 % ' '  8  - 3  !  /Y.
I^UXX__ Ir!   