
    oiG                    f   S SK Jr  S SKrS SKrS SKrS SKrS SKJr  S SKrS SK	r	S SKJ
r
Jr  S SKJr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JrJrJrJrJr  S	SK J!r!  S r"S r# SS jr$ S       SS jjr%        SS jr&   S     SS jjr'SS.S jr( S       SS jjr)g)    )annotationsN)Optional)file_existshf_hub_download)EntryNotFoundErrorLocalEntryNotFoundError)	load_file)http_user_agent)PEFT_TYPE_TO_PREFIX_MAPPING   )INCLUDE_LINEAR_LAYERS_SHORTHAND)EMBEDDING_LAYER_NAMESSAFETENSORS_WEIGHTS_NAMEWEIGHTS_NAMEAuxiliaryTrainingWrappercheck_file_exists_on_hf_hubinfer_devicematch_target_against_key)PeftTypec                    [        U S5      =(       aH    [        U R                  [        R                  R
                  [        R                  R                  45      $ )z.Check if the layer has an embedding base layer
base_layer)hasattr
isinstancer   torchnnLinear	Embedding)layers    R/home/james-whalen/.local/lib/python3.13/site-packages/peft/utils/save_and_load.pyhas_valid_embedding_base_layerr    ,   s;    5,'oJu7G7G%((//[`[c[c[m[mIn,oo    c                x    U R                  5        H&  u  p4U(       d  XA:X  d  U[        USS5      :X  d  M$  Us  $    g)z7Get the name of the embedding module for a given layer.r   N)named_modulesgetattr)modelr   is_embedding_in_target_modulesnamemodules        r   get_embedding_layer_namer)   1   s<    ++-.6?vQXY^`lnrQsGsK . r!   c           
       ^^!^"^# U(       a  [        U SU 5      n U R                  T   m!Uc  U R                  5       nT!R                  [        R
                  [        R                  4;   Ga  T!R                  nUS:X  a  U Vs0 s H  nSU;   d  M  XaU   _M     nnOtUS:X  a$  U Vs0 s H  nSU;   d  SU;   d  M  XaU   _M     nnOJUS:X  a>  0 nU H5  nSU;   d  M  X   Xv'   UR                  S5      S   S-   nX;   d  M/  X   Xx'   M7     O[        eUR                  5        VV	s0 s H  u  piSU;   a  TU;   d  SU;   d  M  Xi_M     nnn	T!R                  [        R                  :X  a`  T!R                  n
U
bQ  U
R                  5        VV	s0 s H  u  piUR                  S	T 3S
5      U	_M     n
nn	U
T!l        U R                  XT5      nT!R                  (       a7  ST S3m"U"4S jnUR                  5        VV	s0 s H  u  piU" U5      U	_M     nnn	GOT!R                  [        R                  :X  a  T!R                  nUS:X  a  U Vs0 s H  nSU;   d  M  XaU   _M     nnGOXUS:X  a%  U Vs0 s H  nSU;   d  SU;   d  M  XaU   _M     nnGO-US:X  a?  0 nU H5  nSU;   d  M  X   Xv'   UR                  S5      S   S-   nX;   d  M/  X   Xx'   M7     GO[        eT!R                  [        R                   :X  a@  U Vs0 s H1  ofR                  S	5      S   R#                  S5      (       d  M,  XaU   _M3     nnGOT!R$                  (       a  0 nT!R                  [        R&                  :X  a\  U R(                  T   R*                  US'   U R(                  T   R,                  US'   U R(                  T   R.                  R0                  nOFT!R2                  (       a$  U R(                  T   R.                  R0                  nOU R5                  T5      nXS'   GOT!R                  [        R6                  :X  a  [8        T!R                     nU Vs0 s H  omU;   d  M
  XaU   _M     nn[:        R<                  " 5       S:X  a  [>        R@                  " S5        U RC                  5        H|  u  p[E        US5      (       d  M  URF                  R                  5        HF  u  pi[:        R<                  " 5       S:X  a  U	RI                  [J        RL                  5      OU	X~ SU 3'   MH     M~     GOT!R                  [        RN                  :X  as  [8        T!R                     nU Vs0 s H  nUU;   d  M  XaU   _M     nnT!RP                  (       a0  ST 3U;  a  [S        S5      eUST-      UST-   '   UST-      UST-   '   GOT!R                  [        RT                  :X  a  U Vs0 s H  nSU;   d  M  XaU   _M     nnGOT!R                  [        RV                  :X  GaJ  0 nT!RX                  S:  a  [J        RZ                  nORT!RX                  S:  a  [J        R\                  nO1T!RX                  S:  a  [J        R^                  nO[J        R`                  nT!Rb                  (       a  U H  nS U;   d  M  X   Re                  T!Rd                  5      u  nnURg                  US!-   URI                  US"905        URg                  US#-   [J        Rh                  " USS$9SS2SS2SS24   Rk                  5       05        M     OU Vs0 s H  nS U;   d  M  XaU   _M     nnUS%T-      US%T-   '   OfT!R                  [m        [        5      ;   a1  [8        T!R                     nU Vs0 s H  nUU;   d  M  XaU   _M     nnO[S        S&T!R                   35      eU RC                  5        H  u  p[o        U[p        5      (       d  M  UR#                  S'5      (       a  URs                  S'5      nUR                  5        VV	s0 s H5  u  piUR#                  U S	35      (       d  M   URs                  U S	35      U	_M7     nnn	URg                  URu                  TU5      R                  5        VV	s0 s H  u  piU S	U 3U	_M     sn	n5        M     S(n[E        T!S)5      (       a  [o        T!Rv                  [x        5      (       a[  T!Rv                  [z        :w  aG  [E        U S*5      (       a  U R}                  5       OU n[        U!4S+ jURC                  5        5       5      nO*T!Rv                  (       a  [        U!4S, j[         5       5      nT!R                  [        R                  :H  =(       d    [        T!S-S5      SLnUS.:X  a(  U(       a!  U(       d  [>        R@                  " S/5        S0nGOUS.:X  Ga  [        [        U S1S5      S2S5      n[        T!S3S5      nS(nUbt  [        R                  R                  [        R                  R                  US45      5      nU=(       d    [        US45      nUc  [>        R@                  " S5U S635        S(nOUnU(       aZ  U(       aS  U(       aL  UU R                  R                  R                  U5      R                  :w  a  [>        R@                  " S75        S0nOS(nU(       a  [E        U S85      (       a  U R                  5       U R                  5       4 Hn  nU(       a  [        U5      (       d  M  [        U UU5      nU(       d  M2  URg                  UR                  5        VV	s0 s H  u  piUU;   d  M  Xi_M     sn	n5        Mp     OU(       a  [>        R@                  " S95        [        R                  " [        R                  " S	T 35      S:-   5      m#UU!U#4S; jn UR                  5        VV	s0 s H  u  piU " U5      U	_M     nnn	U$ s  snf s  snf s  sn	nf s  sn	nf s  sn	nf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  sn	nf s  sn	nf s  sn	nf s  sn	nf )<u  
Get the state dict of the given adapter of the PEFT model.

This only includes the PEFT parameters, not the parameters of the base model. Thus the returned `state_dict` is
generally small compared to the full model size. To retrieve the full `state_dict`, just call `model.state_dict()`.

Note that the adapter name is removed from the `state_dict`, as this is just an arbitrary name that can be changed
when loading the adapter. So e.g. if the adapter name is `'default'` and the original key is
`'model.q_proj.lora_A.default.weight'`, the returned key will be `'model.q_proj.lora_A.weight'`. Use this function
in conjunction with [`set_peft_model_state_dict`] to take care of the adapter name when loading weights.

Args:
    model ([`PeftModel`]): The Peft model. When using torch.nn.DistributedDataParallel, DeepSpeed or FSDP,
        the model should be the underlying model/unwrapped model (i.e. model.module).
    state_dict (`dict`, *optional*, defaults to `None`):
        The state dict of the model. If not provided, the state dict of the passed model will be used.
    adapter_name (`str`, *optional*, defaults to `"default"`):
        The name of the adapter whose state dict should be returned.
    unwrap_compiled (`bool`, *optional*, defaults to `False`):
        Whether to unwrap the model if torch.compile was used.
    save_embedding_layers (`Union[bool, str]`, , *optional*, defaults to `auto`):
        If `True`, save the embedding layers in addition to adapter weights. If `auto`, checks the common embedding
        layers `peft.utils.other.EMBEDDING_LAYER_NAMES` in config's `target_modules` when available. Based on it
        sets the boolean flag. This only works for 🤗 transformers models.

	_orig_modNnonelora_allbias	lora_onlyr   . lora_magnitude_vector..weightc                >   > U R                  T5      (       a  U S S n U $ )Niendswith)knew_dora_suffixs    r   renamed_dora_weights7get_peft_model_state_dict.<locals>.renamed_dora_weights   s"    ::o..#2Ar!   boft_	boft_only	adaption_prefix_task_colsprefix_task_rowsprompt_embeddingsWindowszWindows has issues saving integers into safetensors. Hence, we convert shira_indices to float32 before saving on Windows OS. The shira_indices will always be converted to integers when loading.shira_indices.shira_indices.zbase_model.vera_A.zModel was initialised to not save vera_A and vera_B but config now specifies to save projection! Set `config.save_projection` to `False`.zbase_model.vera_B.internal_xlora_classifier   i   l        vblora_logits_topk_indices)dtype_topk_weightsdimzbase_model.vblora_vector_bank.zUnknown PEFT type passed: _fsdp_wrapped_module.Ftarget_modulesget_base_modelc              3     >^#    U  H>  u  mn[        U4S  j[         5       5      (       d  M&  [        TR                  T5      v   M@     g7f)c              3  Z   >#    U  H   n[         R                  " S U S3T5      v   M"     g7f)z(.*\.)?$N)rematch).0er8   s     r   	<genexpr>6get_peft_model_state_dict.<locals>.<genexpr>.<genexpr>  s)     S=Rrxx71#Q33=Rs   (+N)anyr   r   rO   )rV   _r8   configs     @r   rX   ,get_peft_model_state_dict.<locals>.<genexpr>
  s?      (2DAqS=RSS C()>)>BB2s
   %A
A
c              3  @   >#    U  H  oTR                   ;   v   M     g 7f)N)rO   )rV   r8   r\   s     r   rX   r]     s     'bLaqV-B-B(BLas   trainable_token_indicesautozXSetting `save_embedding_layers` to `True` as embedding layers found in `target_modules`.Tr\   
vocab_sizebase_model_name_or_pathzconfig.jsonz Could not find a config file in z4 - will assume that the vocabulary was not modified.zdSetting `save_embedding_layers` to `True` as the embedding layer has been resized during finetuning.get_input_embeddingsuY   Could not identify embedding layer(s) because the model is not a 🤗 transformers model.rS   c                j  > SU ;  a  U $ U R                  ST 35      (       a  U R                  ST 35      $ U R                  S5      u  pnTR                  [        R
                  :X  a3  UR                  T S35      (       a  U S-   UR                  T S35      -   $ TR                  SU 5      n U  SU 3$ )Nr1   r[   r2   )	r7   removesuffix
rpartition	peft_typer   VBLORA
startswithremoveprefixsub)keyr[   suffixadapter_namer\   patterns      r   remove_adapter_name6get_peft_model_state_dict.<locals>.remove_adapter_nameK  s    c>J<<!L>*++##a~$677 ,/V5F5F,WXGY5Z5Z 9v22l^13EFFFkk"c"ax  r!   )Rr$   peft_config
state_dictrg   r   LORAADALORAr/   splitNotImplementedErroritemsrank_patternreplace!resize_state_dict_by_rank_patternuse_doraBOFTADAPTION_PROMPTri   is_prompt_learningMULTITASK_PROMPT_TUNINGprompt_encoderr@   rA   	embeddingweightinference_modeget_prompt_embedding_to_saveSHIRAr   platformsystemwarningswarnr#   r   rD   tor   float32VERAsave_projection
ValueErrorXLORArh   num_vectorsuint8int16int32int64save_only_topk_weightstopkupdatesoftmax
contiguouslistr   r   rj   adapter_state_dictrO   strr   rP   rZ   r   TRAINABLE_TOKENSospathexistsjoinr   r\   	__class__from_pretrainedra   rc   get_output_embeddingsr    r)   rT   compileescape)$r%   rs   rn   unwrap_compiledsave_embedding_layersr/   r8   	to_return	bias_namevry   r:   rB   shira_prefixr'   r(   vera_prefixindices_dtypelogitsindicesprefixmodule_state_dictembedding_is_targeted_modelusing_trainable_tokensra   model_idhas_base_configlocal_config_existsr   r   embedding_module_namerp   r\   r9   ro   s$     `                              @@@r   get_peft_model_state_dictr   9   s   : {E2|,F%%'
 HMM8+;+;<< {{6>3=N:aA)qM):INIU]3=]:aAQW[\Q\)qM):I]I[ Ia<#-=IL ! 0 3f <I ./9/D	,   &%&/oo&7s&7daW\l^_N_ekopepTQT&7	sx///!..L'Q]QcQcQefQe		Al^*<b A1 DQef&2#!CCL]ij	?? !7|nGLO
 AJ@QR@Q-a0!3@QIR			X]]	*{{6>3=N:aA)qM):INIU]3=]:aAQW[\Q\)qM):I]I[ Ia<#-=IL ! 0 3f <I ./9/D	,   &%			X55	5/9fz!WWS\"=M=X=XYd=e%Q1%z	f			"	"	x???,1,@,@,N,_,_I(),1,@,@,N,_,_I() % 4 4\ B L L S S$$$)$8$8$F$P$P$W$W!$)$F$F|$T!):%&			X^^	+263C3CD/9Oz!Q=N%Q1%z	O??	)MMt "//1LDv//"00668DA 08/@I/MU]]+ST oaS9: 9 2 
		X]]	*1&2B2BC/9Nz![A=M%Q1%z	N!! $L>2*D @  >HH\_kHk=lI*\9:=GH\_kHk=lI*\9:			X^^	+/9^z!=X\]=]%Q1%z	^				X__	,	$!KKM%'!KKM%'!KKM!KKM(("a'&0m&8&8&EOFG$$a/&97::M:;Z%[\$$a/&95==UW;XYZ\]_b`b_bYb;c;n;n;p%qr	   4>V:aTUAU)qM):IVEO,|;F
	2\AB 
		T(^	+,V-=-=>/9Iz!Vq[%Q1%z	I	5f6F6F5GHII ++-f677677 (()@A ;E:J:J:L!:L$!PQP\P\`d_eef]gPh-$qz*A-:L  ! .4.G.GVg.h.n.n.pq.pdaD61#!.pq .: "v'((f++S11v7L7LPo7o 07u>N/O/OU))+UZF$' ("002( %!
 ""$''bLa'b$b! 	H555uIbdh9iqu9u  &+@I_pq $	&	(WUHd;\4P
6#<dC   "$''..h1V"W(`,GR_,`F~6xj@tu #("( u||55EEhOZZZMMv %)!$)!0F!G!G002E4O4O4QRE ),J5,Q,Q(@Od(e%(($$z7G7G7I%h7ItqMbfgMgdad7I%hi S 
qr jjQ|n#56=>G!* 8A7HI7Htq$Q'*7HII{ O] t  g S
 O] g" P& O _( W J! r\ &i: Js    
o5	o5$o:8	o:!o?=o?"p4p
p	p'p;	p5+p$	p?	p 	p 
p%	p%
p*	p*'
p/5	p/
p4	p4p9>p9p?q qqc                   U(       d  U/ 4$ / nU R                  5       nUR                  5        H  u  pVXT;  a  M  XE   R                  S   S:X  a)  XE   R                  5       S-  UR                  5       :X  a  MJ  XE   R                  UR                  :w  d  Mh  UR	                  XVR                  XE   R                  45        M     U H	  u  n  nX	 M     X4$ )Nr>   r      )rs   rx   shapenumelappend)r%   peft_model_state_dictignore_mismatched_sizes
mismatchedrs   rl   tensorr[   s           r   _find_mismatched_keysr   d  s     #$b((J!!#J,224  O!!"%*1F1F1H11LPVP\P\P^1^ ?  FLL0sLL*/2G2GHI 5  	Q!&   !,,r!   c                L   0 nU R                  5        H  u  pEX$;   a  UR                  U5      u    pgSU;   aX  SR                  UR                  S5      SS 5      n[        R
                  " [        R                  " U5      S-   U SU 3U5      nOU SU 3nXSU'   M  XSU'   M     U$ )zbUtility function to remap the state_dict keys to fit the PEFT model by inserting the adapter name.r1   r   NrS   )rx   rf   r   rv   rT   rk   r   )	rs   rn   parameter_prefixr   rl   valr[   rm   suffix_to_replaces	            r   $_insert_adapter_name_into_state_dictr     s     $$&">>*:;LAqf}$'HHV\\#->qr-B$C! ffRYY'89D@\NRSTeSfBgilmQ|n-),#&),#& ' ! r!   c                  ^  U R                   U   nUnU R                  5        Hu  u  px[        U[        5      (       d  M  UR	                  U5      n	UR                  S5      (       a  UR                  S5      nU	 H  n
U SU
 3nU SX    3nX   Xl'   Xk	 M     Mw     UR                  (       d  UR                  [        R                  :X  a  UnGOUR                  [        R                  :X  a  UnGOUR                  [        ;   Ga  0 n[        UR                     nUR                  [        R                  :X  Ga`  UR                  (       GaN  U R                  U   R                   u  p[#        UR%                  5       5      nU GH  n
SU
;   d  M  Xj   R'                  [(        R*                  5      nU
R-                  SS5      nXjR-                  SS5         n[(        R.                  " USUR1                  SSS	9-
  /SS
9n[(        R2                  " U5      n[(        R4                  " / UR                   SS QUP5      R7                  [9        S5      5      R'                  UR:                  5      R=                  SUU5      nUUU'   Xj	 XjR-                  SS5      	 GM     [?        XbUS9nUR                  [        R@                  :X  a#  URB                  nUb  U RE                  UU5        GOUR                  [        RF                  :X  a  [H        RJ                  " 5       S:X  a  [L        RN                  " S5        U R                  5        Hg  u  px[Q        US5      (       d  M  U SU 3U;   d  M%  URS                  U SU 35      nUR'                  [(        RT                  5      URV                  U'   Mi     GO3UR                  [        RX                  :X  ax  URZ                  (       a  SU;  a  []        S5      eURZ                  (       d  SU;   a  [L        RN                  " S5        OURZ                  (       d  [L        RN                  " S5        OUR                  [        R^                  :X  a8  SU 3m U 4S jnURa                  5        V
Vs0 s H  u  n
nU" U
5      U_M     nn
nOGUR                  [        Rb                  :X  a"  [e        S U 5       5      (       a  []        S5      eO[f        e[i        XUS9u  nnU(       aM  U Rk                  USSS9nU Rm                  5        H'  n[Q        US5      (       d  M  URo                  U5        M)     OU Rk                  USS9nUR                  (       a,  U Rp                  U   Rr                  Rk                  SUS    0SS9  UR                  [        Rt                  :X  a  U Rp                  U   Rk                  USS9  U(       ag  S!Rw                  U VVVs/ s H  u  nnnS"U S#U S$U S%3PM     snnn5      nS&U Rx                  Rz                   S'U S3n[L        RN                  " U5        U$ s  snn
f s  snnnf )(a@  
Set the state dict of the PEFT model.

Given a PEFT `state_dict` (as returned by [`get_peft_model_state_dict`]), insert the weights into the model. The
model needs to have the PEFT adapters already in place (e.g. via [`inject_adapter_in_model`]).

Setting the adapter weights also takes care of re-inserting the adapter name. This name may be a different name
than the one originally used to train the adapter.

Args:
    model ([`PeftModel`]):
        The Peft model.
    peft_model_state_dict (`dict`):
        The state dict of the Peft model.
    adapter_name (`str`, *optional*, defaults to `"default"`):
        The name of the adapter whose state dict should be set.
    ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`):
        Whether to ignore mismatched in the state dict.
    low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
        This argument must be `True` if the `model` was loaded with adapter weights on the meta device, e.g. after
        calling `inject_adapter_in_model` with `low_cpu_mem_usage=True`. Otherwise, leave it as `False`.

rN   r1   rI   r2   rK   r   r>   T)keepdimrL   Nz-inf)rn   r   rC   zWindows has issues saving integers into safetensors. Hence, we had converted shira_indices to float32 before saving on Windows OS. The shira_indices will always be converted to integers when loading.rD   rE   zbase_model.vera_AzXSpecified to load vera_A and vera_B from state dictionary however they were not present!zSpecified to not load vera_A and vera_B from state dictionary however they are present in state dictionary! Consider using them to ensure checkpoint loading is correct on all platforms using `peft_config.save_projection = True`zSpecified to not load vera_A and vera_B from state dictionary. This means we will be relying on PRNG initialisation to restore these projections using `config.projection_prng_key`, which may not be accurate on all system configurations.r3   c                >   > U R                  T5      (       a  U S-   n U $ )Nr4   r6   )r8   old_dora_suffixs    r   r:   7set_peft_model_state_dict.<locals>.renamed_dora_weights  s     ::o..IAr!   c              3  ,   #    U  H
  nS U;   v   M     g7f)z.oft_r.N )rV   rl   s     r   rX   ,set_peft_model_state_dict.<locals>.<genexpr>$  s     E/D9#/Ds   zTrying to load old OFT checkpoint, which is no longer supported. Please install PEFT <= v0.15.2 to load it or train a new OFT adapter.)r   F)strictassign%_move_adapter_to_device_of_base_layer)r   r   rB   
z- z: found shape z in the checkpoint and z in the model instantiatedzSome weights of zy were not initialized from the model checkpoint and are being ignored because you passed `ignore_mismatched_sizes=True`: )>rr   r#   r   r   adapter_state_dict_load_mapri   rj   r   rg   r   r~   r   r   rh   r   vblora_vector_bankr   r   keysr   r   longrz   catsumlogzerosfill_floatdevicescatterr   ru   ry   resize_modules_by_rank_patternr   r   r   r   r   r   popintrD   r   r   r   rt   rx   OFTrZ   rw   r   load_state_dictmodulesr   r   r   r   r   r   __name__)!r%   r   rn   r   low_cpu_mem_usager\   rs   r'   r(   key_mapr8   
lookup_key	store_keyr   r   r[   state_dict_keysr   original_keytopk_weightstopk_logitsmatrixry   shira_indices_valuesr:   mismatched_keysload_resultrl   shape1shape2mismatched_warningmsgr   s!                                   @r   set_peft_model_state_dictr     s   < |,F&J
 ++-f677 88FG677 (()@A $vQqc]
#fAgj\2	(=(I
% *  .&   F$4$48P8P$P *			X^^	+ *			8	8 "6v7G7GHx.63P3P3P"55lCIINK":??#45O$ #a'"((4A#$99_b#AL#-ii.Y#ZL#(99lA@P@PQS]a@P@b<b-cik#lL"'))L"9K$L{'8'8"'=$L$LMuV}-K../ Q4	  06J|,""99_o#NO/ %2 !EDT!
 x///!..L'44\<P/ I-$
 !& 3 3 56?33|n=AVV/D/H/HD6Q`am`nIo/p, >R=T=TUZU^U^=_,,\: !6 .%%*=EZ*Z n  ++0CG\0\<
 ++E
 . !7|nEO
 MbLgLgLi$jLiDAq%9!%<a%?Li!$j!-E/DEEE  ]  "!-B>U.*? ++,A%X\+]mmoFvFGG<<\J & ++,A%+P  \*44DD,-@AB4 	E 	
 8;;;\*::;PY^:_!YY ,;+:'C SEx/FvhNhi+:
 u778 9XXjWkkln 	 	cU %k@s   X;#YT)weights_onlyc                2    [         R                  " USU 0UD6$ )z|Call torch.load and handle weights_only.

Defaults to weights_only=True to anticipate upcoming switch on the PyTorch side.

r   )r   load)r   argskwargss      r   
torch_loadr   P  s     ::tA,A&AAr!   c                .  ^ TR                  SS5      b#  [        R                  R                  U TS   5      OU nUc
  [	        5       nSU4S jjnST;  a  [        5       TS'   [        R                  R                  [        R                  R                  U[        5      5      (       a(  [        R                  R                  U[        5      nSnGO=[        R                  R                  [        R                  R                  U[        5      5      (       a'  [        R                  R                  U[        5      nSnO[        R                  R                  (       a*  U" SS9nTR                  SS5         [        X4SS0TD6nSnOTR                  S	S5      n	U	c  TR                  S
S5      n	U" SS9n[        U UTR                  SS5      TR                  SS5      U	S9n
U
nU
(       a  [        U [        40 TD6nO [        U [        40 TD6nU(       aN  [%        [&        R(                  S5      (       a%  U[&        R*                  " S5      :X  a  [-        USS9nO([-        XaS9nO[/        U[&        R*                  " U5      S9nU(       d  UnU$ 0 nUR1                  5        H  u  pUR3                  S5      (       a  SnO$UR3                  S5      (       a  SnO[#        S5      eUR5                  U5      nUR1                  5        H+  u  nn[6        R8                  " UUU5      u  nnUS:  d  M)  Un  O   U U 3nXU'   M     U$ ! [         a    U" SS9n[        X4SS0TD6nSn GNUf = f! [          a$    [#        SU  SU  S[         S[         SU  S35      ef = f)a  
A helper method to load the PEFT weights from the HuggingFace Hub or locally

Args:
    model_id (`str`):
        The local path to the adapter weights or the name of the adapter to load from the HuggingFace Hub.
    device (`str`):
        The device to load the weights onto.
    key_mapping (dict, *optional*, defaults to None)
        Extra mapping of PEFT `state_dict` keys applied before loading the `state_dict`. When this mapping is
        applied, the PEFT-specific `"base_model.model"` prefix is removed beforehand and the adapter name (e.g.
        `"default"`) is not inserted yet. Only pass this argument if you know what you're doing.
    hf_hub_download_kwargs (`dict`):
        Additional arguments to pass to the `hf_hub_download` method when loading from the HuggingFace Hub.
	subfolderNTc                   > U (       a  [         O[        nTR                  SS 5      b#  [        R                  R                  TS   U5      $ U$ )Nr  )r   r   getr   r   r   )use_safetensorsweights_namehf_hub_download_kwargss     r   get_hub_filename+load_peft_weights.<locals>.get_hub_filenamet  sK    3B/ &))+t<H GGLL/<lK	
 	
r!   
user_agentF)r  local_files_onlytokenuse_auth_tokenrevision	repo_type)repo_idfilenamer  r  r  zCan't find weights for z in z8 or in the Hugging Face Hub. Please check that the file z or z is present at r1   mpscpu)r   )map_locationzbase_model.model.zbase_model.zAn error occurred while trying to load a PEFT state_dict with key_mapping. This should not happen. Please open an issue on https://github.com/huggingface/peft/issues and report the error.r   )T)r  r   r   r   r   r
   r   r   r   huggingface_hub	constantsHF_HUB_OFFLINEr   r   r   r   r   r   r   r   backendsr   safe_load_filer   rx   ri   rj   rT   subn)r   r   key_mappingr  r   r  r  r  hub_filenamer  has_remote_safetensors_fileadapters_weightsremapped_adapters_weightsrl   r   r   ro   replacementkey_new	n_replacekey_with_prefixs      `                 r   load_peft_weightsr$  Y  s   ( "%%k48D 	X5kBC 	 ~
 11/>/@|,	ww~~bggll4)ABCC77<<&>?	T<8	9	977<<l3		"	"	1	1'=""#5t<	$&xoPToXnoH"O '**7D9=*../?FE'=&1!+//
DA,00dC'
# 6&&( )H*8\\E[\ 5>>5))ve9L/L-huE-hF%hU\\&=QR$4!4 %$- %'!(..0HC~~122,..& w 
 ""6*C(3(9(9(;$%'WWWk3%G"q=!C )< "(.O9<o6' 1* %$Q ' 	$ ,EBL&xoPToXnoH#O	$> &  -hZtH: F22>tD\C]]lmulvvwy s   5L? <M& ? M#"M#&.N)NdefaultFr`   )F)r%   ztorch.nn.Moduler   dict[str, torch.Tensor]r   boolreturnzRtuple[dict[str, torch.Tensor], list[tuple[str, tuple[int, ...], tuple[int, ...]]]])rs   r&  rn   r   r   r   r(  r&  )r%  FF)r   r'  r   r'  r(  None)NN)r   r   r   zOptional[str]r  zOptional[dict[str, str]]r(  dict)*
__future__r   r   r   rT   r   typingr   r  r   r   r   huggingface_hub.errorsr   r   safetensors.torchr	   r  transformers.utilsr
   peft.mappingr   r  r   otherr   r   r   r   r   r   r   
peft_typesr   r    r)   r   r   r   r   r   r$  r   r!   r   <module>r3     s   # 	  	     8 N 9 . 4 6   !p
 bhhX	 mr--3J-ei-W-8!'!7:!NQ!!0 $)#w "	w
 w 
wv $( B Z^{%{%({%>V{%	{%r!   