
    qi1              	          U d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZ ddlmZmZmZ ddlmZmZmZmZmZmZ ddlmZmZmZmZmZmZmZmZm Z  ddl!m"Z" dd	l#m$Z$  e       rd dl%Z% e       rd d
l&m'Z' d dl(m)Z)m*Z* dZ+ e jX                  e-      Z.erddl/m0Z0 d Z1 G d de      Z2 G d de      Z3 G d de      Z4	 d/de5eez     dz  de6de5eez     fdZ7dddddddddddZ8e9e6e9e6e6f   f   e:d<   dd d!hidd"d#hidZ;e9e6e9e6e<e6   f   f   e:d$<   d% Z= G d& d'      Z>d(e"fd)Z?d*e6fd+Z@d,e%j                  j                  d-e5e	   dz  fd.ZCy)0    N)replace)TYPE_CHECKINGAnyLiteralOptional   )_MODEL_TO_CONVERSION_PATTERN!get_checkpoint_conversion_mappingget_model_conversion_mapping)ConcatenateConversionOpsMergeModulelist	TransposeWeightConverterWeightRenaming)	CONFIG_NAMEcached_filecheck_peft_versionextract_commit_hashfind_adapter_config_fileis_accelerate_availableis_peft_availableis_torch_availablelogging)DownloadKwargs)log_state_dict_report)dispatch_model)get_balanced_memoryinfer_auto_device_mapz0.18.0)LoadStateDictConfigc                      g }t        t        | d               D ]3  }|j                  t        j                  | d   |   | d   |                5 t        j
                  |d      }|S )Nr      dim)rangelenappendtorch
block_diagstack)tensorslora_b_block_diagiouts       P/opt/pipecat/venv/lib/python3.12/site-packages/transformers/integrations/peft.py_block_diag_3dr0   C   sg    3wqz?# Q  !1!1'!*Q-A!OPQ
++'Q
/CJ    c                       e Zd ZdZej
                  deeeej                     f   dee   dee   dedeeeej                     f   f
d       Z
edefd       Zy	)
PeftConcatenatea]  Convert per-expert LoRA weights to merged weights.

    When the base weights are fused, e.g. W01 = [W0, W1], the LoRA weights also need to be fused. To achieve this
    correctly, concatenate the LoRA A weights along the r (rank) dimension. This doesn't require a new Operation. But
    for LoRA B, the weights need to be merged in a block diagonal fashion to achieve the correct result.

    To illustrate:

    Before
    W0' = W0 + A0 @ B0
    W1' = W1 + A1 @ B1

    After
    W01' = W01 + A01 @ B01_bd
        where
        A01 = [A0, A1]
        B01_bd = [[B0,  0],
                  [0,  B1]]

    This class is responsible for merging LoRA B in this block-diagonal fashion. Assuming that we fuse N weights, it
    should look like this:

    1. LoRA B is 2-dim
    Normal LoRA weight of shape (out_feat, rank), the output shape should be (N * out_feat, N * rank).

    2. LoRA B is 3-dim
    MoE LoRA weight of shape (experts, out_feat, rank), the output shape should be (experts, N * out_feat, N * rank).

    After this, the experts x rank dimension are flattened, as PEFT expects 2d tensors for LoRA.
    
input_dictsource_patternstarget_patternsfull_layer_namereturnc                    |j                         D cg c]  }|j                          }}t        |      dhdhfvrt        dt        |             t        |      dhk(  r$|t	        j
                  |j                          i}|S t        |j                          }	t	        j                  |	d      }	|	j                  dd      }	|	j                  }	||	i}|S c c}w )Nr      zXTo convert this LoRA adapter, the LoRA weights all need to have either 2 or 3 dims, got r   r   r"   r   r"   )
valuesr$   set
ValueErrorr(   r)   r0   permuteflattenT)
selfr4   r5   r6   r7   kwargsvdimsoutput_dictr.   s
             r/   convertzPeftConcatenate.convertk   s     ",!2!2!45A55t9aS1#J&jknosktjuv  t9*E,<,<j>O>O>Q,RSK  !*"3"3"56C--Y/C++a#C%%C*C0K 6s   Cc                     t        d      )Nz9Reversing PEFT LoRA MoE conversions is not supported yet.NotImplementedErrorrB   s    r/   
reverse_opzPeftConcatenate.reverse_op   s    !"]^^r1   N)__name__
__module____qualname____doc__r(   no_graddictstrlistTensorrG   propertyr   rL    r1   r/   r3   r3   K   s    > ]]d5<<001 c c	
  
c4%%	& 0 _M _ _r1   r3   c                       e Zd ZdZdeeedf   z  fdZej                  de	e
eej                     f   dee
   dee
   de	e
eej                     f   fd	       Zedefd
       Zd Zy)FlattenDimsz8
    Flatten the tensors along the given dimensions
    rE   .c                 8    t        |t              r|f}|| _        y N)
isinstanceintrE   rB   rE   s     r/   __init__zFlattenDims.__init__   s    dC 7D	r1   r4   r5   r6   r8   c                     |j                         D ci c]  \  }}| |j                  | j                   ! }}}|S c c}}w r[   )itemsr@   rE   	rB   r4   r5   r6   configrC   krD   rF   s	            r/   rG   zFlattenDims.convert   E     =G<L<L<NODAqq)!))TYY//OO P   $=c                     t        d      )Nz.Reversing flatteing operatio is not supported.rI   rK   s    r/   rL   zFlattenDims.reverse_op   s    !"RSSr1   c                 N    | j                   j                   d| j                   dS Nz(dims=)	__class__rM   rE   rK   s    r/   __repr__zFlattenDims.__repr__   $    ..))*&1==r1   N)rM   rN   rO   rP   r]   tupler_   r(   rQ   rR   rS   rT   rU   rG   rV   r   rL   rm   rW   r1   r/   rY   rY      s    S5c?2 
 ]]	d5<<001	 c	 c		 
c4%%	&	 	 TM T T>r1   rY   c                       e Zd ZdZdeedf   fdZej                  de	e
eej                     f   dee
   dee
   de	e
eej                     f   fd	       Zedefd
       Zd Zy)PermuteDimsz8
    Permute the tensors along the given dimensions
    rE   .c                     || _         y r[   rE   r^   s     r/   r_   zPermuteDims.__init__   s	    	r1   r4   r5   r6   r8   c                     |j                         D ci c]  \  }}| |j                  | j                   ! }}}|S c c}}w r[   )ra   r?   rE   rb   s	            r/   rG   zPermuteDims.convert   re   rf   c                     t        d      )Nz2Reversing flatteing operatio is not supported yet.rI   rK   s    r/   rL   zPermuteDims.reverse_op   s    !"VWWr1   c                 N    | j                   j                   d| j                   dS ri   rk   rK   s    r/   rm   zPermuteDims.__repr__   rn   r1   N)rM   rN   rO   rP   ro   r]   r_   r(   rQ   rR   rS   rT   rU   rG   rV   r   rL   rm   rW   r1   r/   rq   rq      s    U38_  ]]	d5<<001	 c	 c		 
c4%%	&	 	 XM X X>r1   rq   weight_conversionsadapter_namer8   c           	         | sg S t        dd      g}t               }ddlm} t	        |dd       }||v r|j                  ||          n|j                  |j                                t        |      D ]:  }t        j                  |      }|j                  t        d| dd| 	             < | D ]P  }	t        |	t               r|j                  |	       &t        |	j                        d
k(  rw|	j                  d   j                  d      rXdD ]P  }
g }|	j                   D ]  }t        |t"              rX|
dk(  r&|j                  t%        |j&                               >|j                  |       |j                  t)        d             kt        |t*              s||j                  |        g }t-        |	j.                        D ].  }|j1                  dd
      d   }|j                  | d|
 d       0 |	j                  d   }|j3                  dd      }| d|
 d| dg}|	j5                  |||	j6                  |	j8                  |      }|j                  |       S t        |	j                        d
k(  s|	j                  d   j                  d      sdD ][  }
g }|	j                   D ]  }t        |t*              s|j                  |       |
dk(  r|j                  t)        d             F|j                  t;        d             |j                  t)        d             |j                  t=        dd
              g }t-        |	j.                        D ].  }|j1                  dd
      d   }|j                  | d|
 d       0 |	j                  d   }|j3                  dd      }| d|
 d| dg}|	j5                  |||	j6                  |	j8                  |      }|j                  |       ^ S |S )Nzbase_model.model.model.zmodel.r   )PEFT_TYPE_TO_PREFIX_MAPPING	peft_type(z[^\.]*)z\1.)r5   r6   r"   gate_up_proj)lora_Alora_Br   r#   )r   r"   rs   .z.*
base_layerz.weight)r5   r6   distributed_operationquantization_operation
operations	down_projr~   r;   )dim0dim1z
.down_proj )r   r=   peft.mappingrz   getattraddupdater<   sortedreescaper'   r\   r&   r6   endswithr   r   r3   r$   rY   r   rT   r5   rsplitr   rl   r   r   rq   r   )rw   rx   peft_confignew_weight_conversionsprefixesrz   r{   prefixescaped_prefixorig_conversionlorapeft_weight_operationsopnew_source_patternspatnew_target_patternsnew_conversions                    r/   _build_peft_weight_mappingr      s   
 	 --FQRuH8[$7I//0;<3::<=" 
6*%%#$^$4G <#&|n 5	

 . R>o~6"))/:../149X9XYZ9[9d9des9t, $>)+&)44 :B!"k28+299/bff:UV299"=299+6:RS#B8.55b9: ')# ? ?@ BC**S!,Q/C'..#avR/@A	B &55a8kk.,?*-avQ|nG'L&M# "1!:!:$7$7*9*O*O+:+Q+Q5 "; " '--n=I$>L 001Q6?;Z;Z[\;];f;fgr;s, #>)+&)44 UB!"o6.55b98+299+6:RS299+9:UV299+6:RS299)QR:STU ')# ? ?@ BC**S!,Q/C'..#avR/@A	B &55a8kk,3*-avQ|nG'L&M# "1!:!:$7$7*9*O*O+:+Q+Q5 "; " '--n=G#>_R>h "!r1   zgate.weightr}   r   )gatew1w3w2)r   	gate_projup_projr   )mixtral	qwen2_moe_MOE_TARGET_MODULE_MAPPINGr   r   r   r   _MOE_FUSED_TARGETSc                 F   ddl m} ddl}t        | j                  dd      }t        |      t|j                  j                  j                  j                  j                   |      fd       }||j                  j                  j                  j                  _
        yy)zPEFT currently assumes that expert layers are of shape
        (expert, in, out)
    but with Mixtral in transformers v5 this is not true anymore.
    This will be addressed in PEFT >0.19 until then we need to handle
    it here for now.
    r   )wrapsN
model_typec                     t        | d      s9| j                  dv r+| j                  }| j                  | _        || _        d| _         | g|i |S )N_swapped_in_out)r   r}   T)hasattrparameter_namein_featuresout_featuresr   )layerargsrC   tmp_in_featuresupdate_layers       r/   new_update_layerz7patch_moe_parameter_targeting.<locals>.new_update_layer^  sZ    5"349M9MQn9n"'"3"3$)$6$6!%4"(,%7777r1   )	functoolsr   peftr   rc   r
   tunersr   r   ParamWrapperr   )modelr   r   r   r   r   r   s         @r/   patch_moe_parameter_targetingr   O  s      |T:J(4@{{''--::GG	|		8 
	8 <L++8 Ar1   c                      e Zd ZU dZdZdZedz  ed<   	 	 	 	 	 	 	 	 	 	 d&dedz  dedz  deee	f   dz  d	eed
f   dz  de
de
de
ed   z  de
deee	f   dz  ded   ddfdZ	 d'deded   ddfdZd(dedz  ddfdZdee   ez  ddfdZd)dZd)dZdee   fdZd*dedz  dedz  defdZ	 	 	 d+ded edz  d!edz  d"edz  ddf
d#Zd$ee   ez  ddfd%Zy),PeftAdapterMixinu'  
    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-prompt learning methods (LoRA, IA³, etc.). 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 (>= 0.18.0), 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_prepare_peft_hotswap_kwargsautopeft_model_idrx   r   adapter_state_dictztorch.Tensorlow_cpu_mem_usageis_trainablehotswaplocal_files_onlyadapter_kwargsload_configr    r8   c                 Z   ! ddl m  ddlm}m} |rd|d<   |
|
j
                  ni }|j                  |       |j                  dd        |d&i |}
|xs |
j                  }|d	k(  r8t        | d
d      }t        | j                  xr || j                  v       }|xr |}|r\| j                  r|| j                  vrt        d      t         fd| j                  j                         D              rt        d      ||nd}|	xs i }	ddl m}m} | j                  r|s|| j                  v rt        d| d      |r%| j                  r|| j                  vrt        d      |||t        d      |` |
j$                  j                  d&i |	 t'        |fi |
j$                  }|t        d| d       |j(                  |fi |
j$                  }t+        |       }t-        || |      }t/        |d      r| |_        t3        |||      }t5        | |       |s
 ||| |       | j                  sd| _        ||ddg}|
j6                  du r|j9                          dx}}d}|D ]>  }	  ||dd|j;                  d      r|
j6                  nddd||
j$                        \  }} n ||xs t=        d      g i }}t?        |
|||      }
| jA                  | |||
       \  }}|h!|@t        |d!d      3!jC                  |jD                  jF                  jI                                d"tJ        d#t        f!fd$}|jL                  D ch c]  } ||      s| c}|_&        tO        | |
j                  |
jP                  |tR        %       y# t<        $ r}|}Y d}~6d}~ww xY wc c}w )'u  
        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 to be installed 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 name "default".
            load_config (`LoadStateDictConfig`, *optional*):
                A load configuration to reuse when pulling adapter weights, typically from `from_pretrained`.
            kwargs (`dict[str, Any]`, *optional*):
                Additional `LoadStateDictConfig` fields passed as keyword arguments.
            peft_config (`dict[str, Any]`, *optional*):
                The configuration of the adapter to add, supported adapters are all non-prompt learning configs (LoRA,
                IA³, etc). 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.
            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.
            hotswap : (`"auto"` or `bool`, *optional*, defaults to `"auto"`)
                Whether to substitute an existing (LoRA) adapter with the newly loaded adapter in-place. This means
                that, instead of loading an additional adapter, this will take the existing adapter weights and replace
                them with the weights of the new adapter. This can be faster and more memory efficient. However, the
                main advantage of hotswapping is that when the model is compiled with torch.compile, loading the new
                adapter does not require recompilation of the model. When using hotswapping, the passed `adapter_name`
                should be the name of an already loaded adapter.

                If the new adapter and the old adapter have different ranks and/or LoRA alphas (i.e. scaling), you need
                to call an additional method before loading the adapter:

                ```py
                model = AutoModel.from_pretrained(...)
                max_rank = ...  # the highest rank among all LoRAs that you want to load
                # call *before* compiling and loading the LoRA adapter
                model.enable_peft_hotswap(target_rank=max_rank)
                model.load_adapter(file_name_1, adapter_name="default")
                # optionally compile the model now
                model = torch.compile(model, ...)
                output_1 = model(...)
                # now you can hotswap the 2nd adapter, use the same name as for the 1st
                # hotswap is activated by default since enable_peft_hotswap was called
                model.load_adapter(file_name_2, adapter_name="default")
                output_2 = model(...)
                ```

                By default, hotswap is disabled and requires passing `hotswap=True`. If you called
                `enable_peft_hotswap` first, it is enabled. You can still manually disable it in that case by passing
                `hotswap=False`.

                Note that hotswapping comes with a couple of limitations documented here:
                https://huggingface.co/docs/peft/main/en/package_reference/hotswap
            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.
        r   PeftTyper   )r    _get_resolved_checkpoint_filesTr   Npretrained_model_name_or_pathr   _hotswap_enabledFz\To hotswap an adapter, there must already be an existing adapter with the same adapter name.c              3   P   K   | ]  }|j                   j                  k7    y wr[   )r{   LORA).0confr   s     r/   	<genexpr>z0PeftAdapterMixin.load_adapter.<locals>.<genexpr>  s     Yt4>>X]]2Ys   #&zMHotswapping is currently only supported for LoRA, please set `hotswap=False`.default
PeftConfiginject_adapter_in_model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.z adapter model file not found in zB. Make sure you are passing the correct path to the adapter model.)r   conversionsinference_mode)r   )r   r   zadapter_model.safetensorszadapter_model.binz.safetensors)r   variant	gguf_fileuse_safetensors
user_agentis_remote_codetransformers_explicit_filenamedownload_kwargsz@Could not download either a .bin or a .safetensors adapter file.)r   sharded_metadataweight_mapping)r   
state_dictcheckpoint_filesr   r{   keyr8   c                 .     t         fdD              S )Nc              3   &   K   | ]  }|v  
 y wr[   rW   )r   markerr   s     r/   r   zHPeftAdapterMixin.load_adapter.<locals>.is_adapter_key.<locals>.<genexpr>K  s     Gv}Gs   )any)r   adapter_key_markerss   `r/   is_adapter_keyz5PeftAdapterMixin.load_adapter.<locals>.is_adapter_keyJ  s    G3FGGGr1   )r   r   ignore_mismatched_sizesloading_infologgerrW   )*r   r   modeling_utilsr    r   __dict__r   
setdefaultr   r   bool_hf_peft_config_loadedr   r>   r   r<   r   r   r   r   from_pretrainedr   $convert_peft_config_for_transformersr   r   r   r   r   reverser   OSErrorr   _load_pretrained_modelr   r{   valuelowerrS   missing_keysr   r   r   )"rB   r   rx   r   r   r   r   r   r   r   r   rC   r    r   base_load_confighotswap_enablednot_first_adapterr   r   adapter_config_filerw   peft_weight_conversionsadapter_filenamesr   r   
last_erroradapter_filenameerrorr   _r   rd   r   r   s"                                   @@r/   load_adapterzPeftAdapterMixin.load_adapter  sD   Z 	"X)-F%&3>3J;//PR'##$CTJ)=,<=%R)R)Rf%d,>FO $T%@%@%glVZVfVfFf h%;*;G//\IYIY5Y r  Yt?O?O?V?V?XYY !pqq'3'?|Y'-2<&&ldN^N^>^1,?lmnnt::TXTdTd@dn   &8&@[EXz  .K''..@@":#--#
 #* 6}o F% % 
 5*44--K
 :$?:;d`rs; 01-9)9K&"<=OQ]kv"w%DkJ#K|D***.D'%!<>Q R**e3!))+266/J$5 ' '9W6C $"&;K;T;TUc;dK77jo#'',7G(3(C(C:6$&6 '$  ' oG,n$oo13R.*7-2	
 55)-#	 6 
a  ,n"w{K'N'Z##K$9$9$?$?$E$E$GH	H 	H 	H 1=0I0I$_1^\]M^Q$_!*5*S*S$/$G$G%	
=  '!&J'8 %`s$   .:NN(N(	N%N  N%target_rankcheck_compiled)r  warnignorec                     t        | di       r?|dk(  rt        d      |dk(  rt        j                  d       n|dk7  rt	        d| d      d	| _        ||d
| _        y)a  Enables the possibility to hotswap PEFT adapters with different ranks, or, if the model is compiled, without
        triggering recompilation.

        Right now, hotswapping is only supported for LoRA.

        Calling this method is only required when hotswapping adapters and if the model is compiled or if the ranks of
        the loaded adapters differ. If the ranks are all identical and the model is not compiled, hotswapping works
        without calling this method first.

        Args:
            target_rank (`int`, *optional*, defaults to `128`):
                The highest rank among all the adapters that will be loaded.
            check_compiled (`str`, *optional*, defaults to `"error"`):
                How to handle the case when the model is already compiled, which should generally be avoided. The
                options are:
                  - "error" (default): raise an error
                  - "warn": issue a warning
                  - "ignore": do nothing
        r   r  z<Call `enable_peft_hotswap` before loading the first adapter.r  zhIt is recommended to call `enable_peft_hotswap` before loading the first adapter to avoid recompilation.r  zCcheck_compiles should be one of 'error', 'warn', or 'ignore', got 'z
' instead.T)r
  r  N)r   RuntimeErrorr   warningr>   r   r   )rB   r
  r  s      r/   enable_peft_hotswapz$PeftAdapterMixin.enable_peft_hotswapW  sy    , 4+("#abb6)~  8+ YZhYiist  !%<G[i,j)r1   c                 b   t        t               ddlm}m} |xs d}| j
                  sd| _        n|| j                  v rt        d| d      t        ||      st        dt        |       d	      | j                  j                  d
d      |_         ||| |       | j                  |       y)u  
        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).

        Note that the newly added adapter is not automatically activated. To activate it, use `model.set_adapter`.

        Args:
            adapter_config (`~peft.PeftConfig`):
                The configuration of the adapter to add, supported adapters are non-prompt learning methods (LoRA,
                IA³, etc.).
            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.
        min_versionr   r   r   Tr   r   z8adapter_config should be an instance of PeftConfig. Got z	 instead.name_or_pathN)r   MIN_PEFT_VERSIONr   r   r   r   r   r>   r\   	TypeErrortyper   getbase_model_name_or_pathset_adapter)rB   adapter_configrx   r   r   s        r/   add_adapterzPeftAdapterMixin.add_adapter|  s    $ 	'78<#0y***.D'T---1,?lmnn.*5VW[\jWkVlluvww 261B1B>SW1X.lC&r1   c           	      |   t        t               | j                  st        d      t	        |t
              rpt        |      t        | j                        z
  }t        |      dkD  rt        ddj                  |       dt        | j                  j                                      || j                  vr2t        d| dt        | j                  j                                      dd	lm} dd
lm} d}| j                         D ]'  \  }}t	        |||f      s|j!                  |       d}) |st        d      y)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: , 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ModulesToSaveWrapperFTzhDid not succeeded in setting the adapter. Please make sure you are using a model that supports adapters.N)r   r  r   r>   r\   rT   r=   r   r&   joinkeyspeft.tuners.tuners_utilsr"  
peft.utilsr$  named_modulesr  )rB   rx   missingr"  r$  _adapters_has_been_setr  modules           r/   r  zPeftAdapterMixin.set_adapter  sZ    	'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!&++- 	.IAv&>3G"HI""<0)-&	.
 &z  &r1   c                     t        t               | j                  st        d      ddlm} ddlm} | j                         D ]&  \  }}t        |||f      s|j                  d       ( y)	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  r  r   r!  r#  FenabledN)r   r  r   r>   r'  r"  r(  r$  r)  r\   enable_adapters)rB   r"  r$  r  r,  s        r/   disable_adaptersz!PeftAdapterMixin.disable_adapters  se     	'78**OPP;3++- 	6IAv&>3G"HI&&u&5	6r1   c                     t        t               | j                  st        d      ddlm} | j                         D ]$  \  }}t        ||      s|j                  d       & y)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  r  r   r!  Tr.  N)	r   r  r   r>   r'  r"  r)  r\   r0  )rB   r"  r  r,  s       r/   r0  z PeftAdapterMixin.enable_adapters  s\     	'78**OPP;++- 	5IAv&.1&&t&4	5r1   c                     t        t               | j                  st        d      ddlm} | j                         D ]  \  }}t        ||      s|j                  } n t        t              r|g}|S )a3  
        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  r  r   r!  )
r   r  r   r>   r'  r"  r)  r\   active_adapterrS   )rB   r"  r  r,  active_adapterss        r/   r5  z PeftAdapterMixin.active_adapters  ss     	'78**OPP;++- 	IAv&.1"("7"7	 os+./Or1   r   c                     t        t               | j                  st        d      ddlm} || j                         d   } || ||      }|S )ax  
        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  r  r   )get_peft_model_state_dict)r   rx   )r   r  r   r>   r   r7  r5  )rB   rx   r   r7  r   s        r/   get_adapter_state_dictz'PeftAdapterMixin.get_adapter_state_dict  sT      	'78**OPP2//1!4L6t
amn!!r1   
device_map
max_memoryoffload_folderoffload_indexc                     i }dt        j                  t              j                  v r||d<   | j                  }|dk7  rt        | |||dk(        }t        |t              rt        | ||      }t        | f||d| y)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@  )r9  offload_dirN)	inspect	signaturer   
parameters_no_split_modulesr   r\   rS   r   )rB   r9  r:  r;  r<  dispatch_model_kwargsr@  s          r/   _dispatch_accelerate_modelz+PeftAdapterMixin._dispatch_accelerate_model,  s    < !# g//?JJJ5B!/2"&"8"8%,%(?$(88	J j#&.E\J 		
!&	
 $		
r1   adapter_namesc                    t        t               | j                  st        d      ddlm} t        |t              r|g}|D cg c]  }|| j                  vs| }}|rt        ddj                  |             |D cg c]6  }| j                  |   j                  j                  j                          d8 }}t        ||      D ]G  \  }} || ||       t        | d	d
      st        | d      s,| j                  j!                  |d       I t#        | j                        dk(  r
| `d
| _        yyc c}w c c}w )z
        Delete a PEFT adapter from the underlying model.

        Args:
            adapter_names (`Union[list[str], str]`):
                The name(s) of the adapter(s) to delete.
        r  r  r   )delete_adapterz@The following adapter(s) are not present and cannot be deleted: r   r  )rx   r   r   Fr   N)r   r  r   r>   peft.functionalrK  r\   rS   r   r%  r{   r   r   zipr   r   popr&   )rB   rI  rK  namemissing_adaptersrx   r   r   s           r/   rK  zPeftAdapterMixin.delete_adapterd  sI    	'78**OPP2mS)*OM .;[Td$JZJZ>ZD[[RSWS\S\]mSnRop  fssUat''5??EEKKMNaPss$'x$@ 	9 L&4l6Jt5u='$P]B^  $$\48		9 t A% */D' & \ ts   D8D8;D=)
NNNNFFr   FNN)   r  r[   )r8   N)NN)NNN)rM   rN   rO   rP   r   r   rR   __annotations__rS   r   r   r   r   r	  r]   r  r  rT   r  r1  r0  r5  r8  rH  rK  rW   r1   r/   r   r   j  s   $ #04 $+4 %)#'-1?C"'"*0!&047;U
TzU
 DjU
 #s(^d*	U

 !n!45<U
  U
 U
 'U
 U
 S#X-U
 34U
 
U
p \c#k#k6=>W6X#k	#kJ&'d
 &'d &'P'S	C 'D 'R6&5$c :"3: "RVY]R] "im "@ "&%)$(6
6
 $J6
 d
	6

 Tz6
 
6
p%0DIO %0 %0r1   r   r   c                    | 
t               sd | |fS |j                  d      }|j                  d      t        | t        |j                  d      t	        |j                  dd            |j                  d      t	        |j                  dd            ||j                  d      |j                  d	      ddd
      }t        |d       |d<   |j                  dd       }|j                  dd       }||j                         }dD ]  }||vs||v s||   ||<    d|v r|d   |d<   t	        |j                  dd            |d<   t	        |j                  dd            |d<   |xs ||d<   t        | fi |}|Pt        j                  j                  |      r1t        |dd      5 }	| }t        j                  |	      d   } d d d        || |fS # 1 sw Y   xY w)Ntokencommit_hash	cache_dirforce_downloadFproxiesr   revision	subfolder)
rV  rW  rX  r   rT  rY  rZ   _raise_exceptions_for_gated_repo%_raise_exceptions_for_missing_entries'_raise_exceptions_for_connection_errors_adapter_model_path)rV  rX  rZ  _commit_hashrzutf-8)encodingr  )r   r  r   r   r   r   rN  copyr   ospathisfileopenjsonload)
r   r   r   rT  resolved_config_filer^  token_from_adapter_kwargspeft_kwargsarg_namefs
             r/   maybe_load_adaptersrn    s&   
 %,4E4G2NBB(E=)1*)%))+6 3 34De LM#''	2!/"5"56H%"PQ$((4%))+6-22749 
 *==QSW)X&(,,-BDI . 2 27D A"$))+= 	BH+(o2M(7(AH%	B O+*9-*HK'(,_-@-@AQSX-Y(Z$%*./B/BCUW\/]*^&'$A(AG6)


 &277>>:M+N%sW= 	T"?,0IIaL9R,S)	T  =~MM		T 	Ts   'GGr   c           
         t        j                  |d       }|| S t        |   }t        j                  |i       }t	        | j
                  xs g       | _        t	        | j                  xs g       | _        t        | d      r| j                  i | _        | j
                  j                         }t	               }|D ci c]  }|t	                }}| j                  D ]  }	d }
d }|j                         D ]$  \  }}|	|k(  s|	j                  d|       s |}
|} n |
|j                  |	       R|j                  |
       |
|v sh|k|j                  |
t	                     j                  |        |j                         D ]  \  }}|j                  |t	                     }dt        |      cxk  rt        |      k  rOn nLdj                  t!        ||z
              }dj                  t!        |            }t#        d| d| d| d      t        |      t        |      k(  st        |      dkD  s| j$                  t        |      z  | j                  d	t'        j(                  |       <    || _        || _        | S c c}w )
Nrank_patternr   r   r   zCannot convert PEFT target(s) z without also targeting z because they are fused into r"   z.*\.)r	   r  r   r   r=   target_parameterstarget_modulesr   rp  rb  ra   r   r   r   r&   r%  r   r>   r`  r   r   )r   r   base_model_typetarget_module_mappingfused_targetsnew_target_parametersremaining_target_modulesnew_namematched_targetstargetmapped_new_namemapped_old_nameold_namerequired_old_targetspresent_targetsr*  presents                    r/   _convert_peft_config_moer    s   266z4HO6G&**?B?M$'(E(E(K$LK!!$[%?%?%E2!FK;/;3K3K3S#% '99>>@"uLY+ZHceO+ZO+Z,, T"7"="="? 	Hh("v8*~'F"*"*		 "$((0!!/2m+0K&&>BB?ST" +8*=*=*? 
p&&)--h>s?#?c*>&??ii';o'M NOGii 78G0	9QRYQZZw  yA  xB  BC  D  3';#<<EYAZ]^A^FQmmVYZnVoFoK$$RYYx-@,A%BC
p %:K!!9KE ,[s   =Jr   r   c                    ddl m} | j                  |j                  k7  r| S t	        |d      s| S t	        |j
                  d      s| S t        j                  |       } t        |j
                  dd       }t        |      t        | |      } | S )Nr   r   rc   r   )r   r   r{   r   r   rc   rb  deepcopyr   r
   r  )r   r   r   r   r   s        r/   r   r     s     -5(#5<<.--,K|T:J(4@.{JGr1   r[   )Drb  rC  rg  rc  r   dataclassesr   typingr   r   r   r   conversion_mappingr	   r
   r   core_model_loadingr   r   r   r   r   r   utilsr   r   r   r   r   r   r   r   r   	utils.hubr   utils.loading_reportr   r(   
accelerater   accelerate.utilsr   r   r  
get_loggerrM   r   r   r    r0   r3   rY   rq   rT   rS   r   r   rR   rR  r   r=   r   r   rn  r  nnModuler   rW   r1   r/   <module>r     s      	 	  8 8 
 
 
 
 ' 8 )K   
		H	%4;_k ;_|>- ><>- >: gkq"_~=>Eq"UXq"	/N
*+q"r 	 #! 	9 Dd38n!45   t- ;	":;6 Dd3C=112 L6_0 _0D3N#3ND1c 1hUXX__ [_`c[dgk[k r1   