
    eThl                         S SK r S SKrS SKrS SKJrJrJrJrJr  S SK	J
r
  SSKJrJrJrJrJrJr  \" 5       (       a  S SKr\" 5       (       a  S SKJr  S SKJrJr  Sr\R2                  " \5      r " S	 S
5      rg)    N)AnyDictListOptionalUnion)version   )check_peft_versionfind_adapter_config_fileis_accelerate_availableis_peft_availableis_torch_availablelogging)dispatch_model)get_balanced_memoryinfer_auto_device_mapz0.5.0c                      \ rS rSrSrSr             S!S\\   S\\   S\\   S\\   S	\\   S
\\   S\\   S\\   S\\	\\
4      S\\	\S4      S\S\S\\	\\
4      SS4S jjrS"S\\   SS4S jjrS\\\   \4   SS4S jrS#S jrS#S jrS\\   4S jrS\4S jrS$S\\   S\\   S\4S jjr   S%S	\S
\\   S\\   S\\   SS4
S jjrS\\\   \4   SS4S jrS rg)&PeftAdapterMixin.   a  
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 on a transformer-based model, check out the documentation of PEFT
library: https://huggingface.co/docs/peft/index

Currently supported PEFT methods are all non-prefix tuning methods. Below is the list of supported PEFT methods
that anyone can load, train and run with this mixin class:
- Low Rank Adapters (LoRA): https://huggingface.co/docs/peft/conceptual_guides/lora
- IA3: https://huggingface.co/docs/peft/conceptual_guides/ia3
- AdaLora: https://arxiv.org/abs/2303.10512

Other PEFT models such as prompt tuning, prompt learning are out of scope as these adapters are not "injectable"
into a torch module. For using these methods, please refer to the usage guide of PEFT library.

With this mixin, if the correct PEFT version is installed, it is possible to:

- Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model
- Attach new adapters in the model and train them with Trainer or by your own.
- Attach multiple adapters and iteratively activate / deactivate them
- Activate / deactivate all adapters from the model.
- Get the `state_dict` of the active adapter.
FNpeft_model_idadapter_namerevisiontoken
device_map
max_memoryoffload_folderoffload_indexpeft_configadapter_state_dictztorch.Tensorlow_cpu_mem_usageis_trainableadapter_kwargsreturnc                    [        [        S9  0 nU(       aa  Sn[        R                  " [        R
                  R                  S5      5      [        R                  " U5      :  a  XS'   O[        SU S35      eUb  UOSnUc  0 nS	S
KJnJ	nJ
n  S	SKJn  U R                  (       a  X R                  ;   a  [        SU S35      eUc  U
c  U	c  [        S5      eSU;  aD  [        U S5      (       d  U R                   O%[#        U R$                  R'                  5       5      S	   nOUR)                  S5      n[+        U[,        R                   5      (       a  [/        U5      nUb  SU;  a  X=S'   O&Ub#  SU;   a  X=S   :w  a  [0        R3                  S5        SU;   a  UR)                  S5      nU	cA  [5        U4SU0UD6nUc  [        SU S35      eUR6                  " U4SU0UD6n	U(       + U	l        U" XU40 UD6  U R                  (       d  SU l        Ub  U" U4UUS.UD6n
0 nSnU
R;                  5        H2  u  nnUR=                  U5      (       a  U[?        U5      S nOUnUUU'   M4     U" U UU40 UD6nUb  SnUb  UOSn[        US5      (       a;  [?        UR@                  5      S	:  a"  SU SSRC                  UR@                  5       S3n[E        US S5      nU(       aC  U Vs/ s H  nS!U;   d  M  UU;   d  M  UPM     n nU (       a  USU S"SRC                  U 5       3-  nU(       a  [0        RG                  U5        U	R8                  (       a  U RI                  5         [E        U SS5      bo  [?        [K        U R$                  R'                  5       5      RM                  S#S$15      5      S	:  a-  [?        U R                  5      S%:X  a  U RO                  UUUUS&9  ggggs  snf )'aj  
Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we
invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft

Requires peft as a backend to load the adapter weights.

Args:
    peft_model_id (`str`, *optional*):
        The identifier of the model to look for on the Hub, or a local path to the saved adapter config file
        and adapter weights.
    adapter_name (`str`, *optional*):
        The adapter name to use. If not set, will use the default adapter.
    revision (`str`, *optional*, defaults to `"main"`):
        The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
        git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
        identifier allowed by git.

        <Tip>

        To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.

        </Tip>

    token (`str`, `optional`):
        Whether to use authentication token to load the remote folder. Useful to load private repositories
        that are on HuggingFace Hub. You might need to call `huggingface-cli login` and paste your tokens to
        cache it.
    device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
        A map that specifies where each submodule should go. It doesn't need to be refined to each
        parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
        same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
        like `1`) on which the model will be allocated, the device map will map the entire model to this
        device. Passing `device_map = 0` means put the whole model on GPU 0.

        To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
        more information about each option see [designing a device
        map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
    max_memory (`Dict`, *optional*):
        A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
        GPU and the available CPU RAM if unset.
    offload_folder (`str` or `os.PathLike`, `optional`):
        If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
    offload_index (`int`, `optional`):
        `offload_index` argument to be passed to `accelerate.dispatch_model` method.
    peft_config (`Dict[str, Any]`, *optional*):
        The configuration of the adapter to add, supported adapters are non-prefix tuning and adaption prompts
        methods. This argument is used in case users directly pass PEFT state dicts
    adapter_state_dict (`Dict[str, torch.Tensor]`, *optional*):
        The state dict of the adapter to load. This argument is used in case users directly pass PEFT state
        dicts
    low_cpu_mem_usage (`bool`, *optional*, defaults to `False`):
        Reduce memory usage while loading the PEFT adapter. This should also speed up the loading process.
        Requires PEFT version 0.13.0 or higher.
    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.
    adapter_kwargs (`Dict[str, Any]`, *optional*):
        Additional keyword arguments passed along to the `from_pretrained` method of the adapter config and
        `find_adapter_config_file` method.
min_versionz0.13.0peftr    zcThe version of PEFT you are using does not support `low_cpu_mem_usage` yet, please install PEFT >= .Ndefaultr   )
PeftConfiginject_adapter_in_modelload_peft_weights)set_peft_model_state_dictAdapter with name - already exists. Please use a different name.zhYou should either pass a `peft_model_id` or a `peft_config` and `adapter_state_dict` to load an adapter.devicehf_device_mapr   zYou passed a `revision` argument both in `adapter_kwargs` and as a standalone argument. The one in `adapter_kwargs` will be used.r   z adapter model file not found in zB. Make sure you are passing the correct path to the adapter model.T)r   r0   zbase_model.model. 
state_dictunexpected_keyszLoading adapter weights from z0 led to unexpected keys not found in the model: , z. missing_keyslora_z# led to missing keys in the model: cpudisk   )r   r   r   r   )(r
   MIN_PEFT_VERSIONr   parse	importlibmetadata
ValueErrorr'   r*   r+   r,   
peft.utilsr-   _hf_peft_config_loadedr   hasattrr0   listr1   valuespop
isinstancetorchstrloggererrorr   from_pretrainedinference_modeitems
startswithlenr4   joingetattrwarningevalsetintersection_dispatch_accelerate_model)!selfr   r   r   r   r   r   r   r   r   r   r    r!   r"   peft_load_kwargsmin_version_lcmur*   r+   r,   r-   r0   adapter_config_fileprocessed_adapter_state_dictprefixkeyvaluenew_keyincompatible_keyserr_msgorigin_namer6   klora_missing_keyss!                                    V/var/www/auris/envauris/lib/python3.13/site-packages/transformers/integrations/peft.pyload_adapterPeftAdapterMixin.load_adapterH   sR   X 	'78 '}}Y//77?@GMMRbDcc8I!45 ..>-?qB 
 (4'?|Y!NOO8&&<;K;K+K1,?lmnn &8&@[EXz  >)(/o(F(FT[[DQUQcQcQjQjQlLmnoLpF#''1F fell++[F Jn$D)1:&!jN&BxblSmGmLL< n$"&&w/E":## !# #* 6}o F% % 
 %44 !K
 .:)9K& 	 <TCST***.D'$!2=!oV\!o`n!o (*$$,224JC~~f%%c&km,49(1 5 6.
@P
 (G+8+D-,K(*;<<EVEfEfAgjkAk3K=@pyy!2!B!BCDBH  ##4ndKL0<$c11QQ]abQbQ!$c$7}Dg99%678:G
 w'%%IIK T?D1=S++2245BBE6?STWXXD$$%*++%%-+	 ,  + Y > %ds   !
O/O7Oc                 x   [        [        S9  SSKJnJn  U=(       d    SnU R
                  (       d  SU l        OX R                  ;   a  [        SU S35      e[        X5      (       d  [        S[        U5       S	35      eU R                  R                  S
S5      Ul        U" XU5        U R                  U5        g)a  
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
official documentation: https://huggingface.co/docs/peft

Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default
name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the
default adapter name).

Args:
    adapter_config (`~peft.PeftConfig`):
        The configuration of the adapter to add, supported adapters are non-prefix tuning and adaption prompts
        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.
r%   r   )r*   r+   r)   Tr.   r/   z8adapter_config should be an instance of PeftConfig. Got z	 instead.name_or_pathN)r
   r;   r'   r*   r+   rA   r   r?   rF   	TypeErrortype__dict__getbase_model_name_or_pathset_adapter)rW   adapter_configr   r*   r+   s        re   add_adapterPeftAdapterMixin.add_adapter  s      	'78<#0y***.D'---1,?lmnn.55VW[\jWkVlluvww 261B1B>SW1X.lC&    c           	         [        [        S9  U R                  (       d  [        S5      e[	        U[
        5      (       ar  [        U5      [        U R                  5      -
  n[        U5      S:  aA  [        SSR                  U5       S[        U R                  R                  5       5       35      eOAXR                  ;  a2  [        SU S[        U R                  R                  5       5       35      eSS	KJn  SS
KJn  SnU R                  5        HD  u  pg[	        XsU45      (       d  M  [!        US5      (       a  UR#                  U5        OXl        SnMF     U(       d  [        S5      eg)a  
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
official documentation: https://huggingface.co/docs/peft

Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters.

Args:
    adapter_name (`Union[List[str], str]`):
        The name of the adapter to set. Can be also a list of strings to set multiple adapters.
r%   0No adapter loaded. Please load an adapter first.r   z)Following adapter(s) could not be found: r5   zV. Make sure you are passing the correct adapter name(s). current loaded adapters are: r.   z7 not found. Please pass the correct adapter name among BaseTunerLayerModulesToSaveWrapperFro   TzhDid not succeeded in setting the adapter. Please make sure you are using a model that supports adapters.N)r
   r;   rA   r?   rF   rC   rT   r   rO   rP   keyspeft.tuners.tuners_utilsrw   r@   ry   named_modulesrB   ro   active_adapter)rW   r   missingrw   ry   _adapters_has_been_set_modules           re   ro   PeftAdapterMixin.set_adapter@  sm    	'78**OPPd++,'#d.>.>*??G7|a ?		'@R?S T559$:J:J:O:O:Q5R4SU   
 !1!11$\N2ijnosoo  pE  pE  pG  kH  jI  J  	<3!&++-IA&3G"HII6=11&&|4,8))-& . &z  &rs   c                    [        [        S9  U R                  (       d  [        S5      eSSKJn  SSKJn  U R                  5        HB  u  p4[        XAU45      (       d  M  [        US5      (       a  UR                  SS9  M;  S	Ul        MD     g
)a  
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
official documentation: https://huggingface.co/docs/peft

Disable all adapters that are attached to the model. This leads to inferring with the base model only.
r%   ru   r   rv   rx   enable_adaptersFenabledTN)r
   r;   rA   r?   r{   rw   r@   ry   r|   rF   rB   r   disable_adapters)rW   rw   ry   r   r   s        re   r   !PeftAdapterMixin.disable_adaptersm  su     	'78**OPP;3++-IA&3G"HII6#455**5*9.2F+ .rs   c                 
   [        [        S9  U R                  (       d  [        S5      eSSKJn  U R                  5        H@  u  p#[        X15      (       d  M  [        US5      (       a  UR                  SS9  M9  SUl
        MB     g	)
z
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
official documentation: https://huggingface.co/docs/peft

Enable adapters that are attached to the model.
r%   ru   r   rv   r   Tr   FN)r
   r;   rA   r?   r{   rw   r|   rF   rB   r   r   )rW   rw   r   r   s       re   r    PeftAdapterMixin.enable_adapters  sl     	'78**OPP;++-IA&116#455**4*8.3F+ .rs   c                 6   [        [        S9  [        5       (       d  [        S5      eU R                  (       d  [        S5      eSSKJn  U R                  5        H#  u  p#[        X15      (       d  M  UR                  n  O   [        W[        5      (       a  U/nU$ )a  
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
official documentation: https://huggingface.co/docs/peft

Gets the current active adapters of the model. In case of multi-adapter inference (combining multiple adapters
for inference) returns the list of all active adapters so that users can deal with them accordingly.

For previous PEFT versions (that does not support multi-adapter inference), `module.active_adapter` will return
a single string.
r%   zTPEFT is not available. Please install PEFT to use this function: `pip install peft`.ru   r   rv   )r
   r;   r   ImportErrorrA   r?   r{   rw   r|   rF   r}   rH   )rW   rw   r   r   active_adapterss        re   r    PeftAdapterMixin.active_adapters  s     	'78 ""tuu**OPP;++-IA&11"("7"7 . os++./Ors   c                 ^    [         R                  " S[        5        U R                  5       S   $ )NzRThe `active_adapter` method is deprecated and will be removed in a future version.r   )warningswarnFutureWarningr   )rW   s    re   r}   PeftAdapterMixin.active_adapter  s*    `bo	
 ##%a((rs   r3   c                     [        [        S9  U R                  (       d  [        S5      eSSKJn  Uc  U R                  5       S   nU" XUS9nU$ )a  
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
official documentation: https://huggingface.co/docs/peft

Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter.
If no adapter_name is passed, the active adapter is used.

Args:
    adapter_name (`str`, *optional*):
        The name of the adapter to get the state dict from. If no name is passed, the active adapter is used.
    state_dict (nested dictionary of `torch.Tensor`, *optional*)
        The state dictionary of the model. Will default to `self.state_dict()`, but can be used if special
        precautions need to be taken when recovering the state dictionary of a model (like when using model
        parallelism).
r%   ru   r   )get_peft_model_state_dict)r3   r   )r
   r;   rA   r?   r'   r   r   )rW   r   r3   r   r   s        re   get_adapter_state_dict'PeftAdapterMixin.get_adapter_state_dict  sR      	'78**OPP2//1!4L6tamn!!rs   c                     0 nS[         R                  " [        5      R                  ;   a  XES'   U R                  nUS:w  a  [        U UUUS:H  S9n[        U[        5      (       a
  [        XUS9n[        U 4UUS.UD6  g)a  
Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with
accelerate (i.e. with `device_map=xxx`)

Args:
    device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
        A map that specifies where each submodule should go. It doesn't need to be refined to each
        parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
        same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
        like `1`) on which the model will be allocated, the device map will map the entire model to this
        device. Passing `device_map = 0` means put the whole model on GPU 0.

        To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
        more information about each option see [designing a device
        map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
    max_memory (`Dict`, *optional*):
        A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
        GPU and the available CPU RAM if unset.
    offload_folder (`str` or `os.PathLike`, *optional*):
        If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
    offload_index (`int`, *optional*):
        The offload_index argument to be passed to `accelerate.dispatch_model` method.
r   
sequentialbalanced_low_0)r   no_split_module_classeslow_zero)r   r   )r   offload_dirN)	inspect	signaturer   
parameters_no_split_modulesr   rF   rH   r   )rW   r   r   r   r   dispatch_model_kwargsr   s          re   rV   +PeftAdapterMixin._dispatch_accelerate_model  s    < !# g//?JJJ5B/2"&"8"8%,%(?$(88	J j#&&.E\J 		
!&	
 $		
rs   adapter_namesc                    [        [        S9  U R                  (       d  [        S5      eSSKJn  [        U[        5      (       a  U/nU Vs/ s H  o3U R                  ;  d  M  UPM     nnU(       a  [        SSR                  U5       35      eU H  nU R                  5        HB  n[        Xb5      (       d  M  [        US5      (       a  UR                  U5        M9  [        S5      e   [        U S	S
5      (       d  Mm  [        U S5      (       d  M  U R                  R                  US5        M     [        U R                  5      S:X  a
  U ?S
U l        ggs  snf )a2  
Delete an adapter's LoRA layers from the underlying model.

Args:
    adapter_names (`Union[List[str], str]`):
        The name(s) of the adapter(s) 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")
```
r%   ru   r   rv   z@The following adapter(s) are not present and cannot be deleted: r5   delete_adapterzdThe version of PEFT you are using is not compatible, please use a version that is greater than 0.6.1rA   Fr   N)r
   r;   rA   r?   r{   rw   rF   rH   r   rP   modulesrB   r   rQ   rE   rO   )rW   r   rw   namemissing_adaptersr   r   s          re   r   PeftAdapterMixin.delete_adapter  s<   0 	'78**OPP;mS))*OM .;[]T$JZJZ>ZD][RSWS\S\]mSnRop  *L,,.f55v'788--l;( C  ) t5u=='$P]B^B^  $$\48 *  t A% */D' &- \s   E#E)rA   )NNNNautoNNNNNFFN)N)r#   N)NN)NNN)__name__
__module____qualname____firstlineno____doc__rA   r   rH   intr   r   boolrf   rq   r   r   ro   r   r   r   r}   dictr   rV   r   __static_attributes__ rs   re   r   r   .   s   . # (,&*"&#$*$((,'+04BF"'"37Q}Q smQ 3-	Q
 }Q SMQ SMQ !Q  }Q d38n-Q %T#~*=%>?Q  Q Q !c3h0Q 
Qf#' #'QU #'J+d3in(= +$ +Z3.4,c @) )"8C= "U]^bUc "os "@ %)(,'+6
6
 SM6
 !	6

  }6
 
6
p;0E$s)S.,A ;0d ;0rs   r   )r=   r   r   typingr   r   r   r   r   	packagingr   utilsr
   r   r   r   r   r   rG   
accelerater   accelerate.utilsr   r   r;   
get_loggerr   rI   r   r   rs   re   <module>r      sf       3 3   )K   
		H	%c0 c0rs   