ó
    >:jJ…  ã                   óD  • S SK r S SKJrJr  S SKJrJrJr  S SKJ	r	  S SK
J
r
Jr  S SKJr  S SKJr  S SKJrJr  S SKrS SKJr  S S	KJr  S S
KJr  S SKJrJr  S SKJr  S SKJ r   S SK!J"r"J#r#  SSK$J%r%  SSK&J'r'J(r(J)r)J*r*  \'\)\*4r+ " S S5      r, " S S\,5      r- " S S\,5      r.S\/S\/4S jr0S\Rb                  Rd                  S\Rf                  4S jr4S\\5\Rf                  4   4S jr6S\%4S  jr7S\Rp                  4S! jr9S" r:S\Rb                  Rd                  S#\S\\%   S$\S%\\   S&\\   S'\\\/\5\4   S4   S(\;S)\;S\/4S* jr<S\Rb                  Rd                  S+\/S,\54S- jr=\R|                  " 5       S\:\7\9S.S/S/4S\Rb                  Rd                  S#\S\\%   S%\\   S&\\   S'\\\/\5\4   S4   S,\5S(\;S)\;S\/4S0 jj5       r?\R|                  " 5       SS\:\7\9S.S/S/4S\Rb                  Rd                  S#\\   S+\\/   S%\\   S&\\   S'\\\/\5\4   S4   S,\5S(\;S)\;4S1 jj5       r@g)2é    N)ÚCounterÚdefaultdict)ÚCallableÚIterableÚMapping)Únullcontext)ÚcopyÚdeepcopy)Úpartial)Úcycle)ÚOptionalÚUnion)Útqdm)ÚConv1D)Ú_find_minimal_target_modulesÚcheck_target_module_exists)Ú#MIN_TARGET_MODULES_FOR_OPTIMIZATION)ÚIncrementalPCA)Ú_get_submodulesÚget_pattern_keyé   )Ú
LoraConfig)Ú	EmbeddingÚ	LoraLayerÚMultiheadAttentionÚ_ConvNdc                   óœ   • \ rS rSrSr  SS\S\\   S\4S jjr	\
S\R                  4S	 j5       r\R                  " 5       S
 5       rS rSrg)Ú_Hooké)   z<
A base class for hooks that prepares layer inputs for EVA.
NÚnameÚprepare_layer_inputs_fnÚgather_distributed_inputsc                 ó`   • Xl         X0l        Uc  U R                  U l        OX l        S U l        g ©N)r    r"   Ú _prepare_layer_inputs_fn_defaultÚ_prepare_layer_inputs_fnÚmodel_input)Úselfr    r!   r"   s       ÚQ/home/mande/repo/quber/.venv/lib/python3.13/site-packages/peft/tuners/lora/eva.pyÚ__init__Ú_Hook.__init__.   s1   € ð Œ	Ø)BÔ&Ø"Ñ*Ø,0×,QÑ,QˆDÕ)à,CÔ)ØˆÕó    Úreturnc                 ó   • [        U [        R                  5      (       a  O<[        U [        [        45      (       a  U S   n O[        S[        U 5       SU S35      eU R                  S:”  a!  U R                  SU R                  S5      5      n U $ )Nr   úunsupported input type ú& for prepare_layer_inputs_fn in layer ú1, please provide a custom prepare_layer_inputs_fné   éÿÿÿÿ)
Ú
isinstanceÚtorchÚTensorÚtupleÚlistÚ
ValueErrorÚtypeÚndimÚviewÚsize©Úlayer_inputr'   Ú
layer_names      r)   r%   Ú&_Hook._prepare_layer_inputs_fn_default<   s“   € ä�k¤5§<¡<×0Ñ0ØÜ˜¤e¬T ]×3Ñ3Ø% a™.‰KäØ)¬$¨{Ó*;Ð)<Ð<bÐcmÐbnð oBð Bóð ð
 ×Ñ˜aÓØ%×*Ñ*¨2¨{×/?Ñ/?ÀÓ/CÓDˆKØÐr,   c                 óN   • U R                  XR                  U R                  5      $ r$   )r&   r'   r    )r(   r?   s     r)   Úprepare_layer_inputsÚ_Hook.prepare_layer_inputsL   s   € à×,Ñ,¨[×:JÑ:JÈDÏIÉIÓVÐVr,   c                 ó$  • [         R                  " 5       (       Gai  U R                  (       GaW  [         R                  " 5       n[        R
                  " UR                  S   /UR                  S9n[        R                  " X#R                  UR                  S9n[         R                  " XC5        UR                  5       nUR                  [        U5      /UR                  SS  Q75      nXS UR                  S   & [        U5       Vs/ s H  n[        R                  " U5      PM     nn[         R                   " XuR#                  5       5        [%        Xt5       VV	s/ s H
  u  p‰US U	 PM     nnn	[        R&                  " USS9$ U$ s  snf s  sn	nf )Nr   )Údevice)ÚdtyperF   r   )Údim)ÚdistÚis_initializedr"   Úget_world_sizer5   ÚtensorÚshaperF   ÚemptyrG   Úall_gather_into_tensorÚtolistÚ	new_zerosÚmaxÚrangeÚ
zeros_likeÚ
all_gatherÚ
contiguousÚzipÚcat)
r(   r?   Ú
world_sizeÚ
local_sizeÚ	all_sizesÚpadded_inputÚ_Úgathered_inputsrL   r=   s
             r)   Úgather_layer_inputsÚ_Hook.gather_layer_inputsP   sV  € Ü×Ò× Ò  T×%C×%CÐ%CÜ×,Ò,Ó.ˆJô Ÿš {×'8Ñ'8¸Ñ';Ð&<À[×EWÑEWÑXˆJÜŸš J×6FÑ6FÈ{×OaÑOaÑbˆIÜ×'Ò'¨	Ô>Ø!×(Ñ(Ó*ˆIð '×0Ñ0´#°i³.Ð1YÀ;×CTÑCTÐUVÐUWÐCXÑ1YÓZˆLØ3>Ð/˜;×,Ñ,¨QÑ/Ð0ô HMÈZÔGXÓYÒGXÀ!œu×/Ò/°Ö=ÑGXˆOÐYÜ�OŠO˜O×-DÑ-DÓ-FÔGô BEÀ_ÔA`ÔaÒA`±°˜v e t›}ÑA`ˆOÑaô —9’9˜_°!Ñ4Ð4ØÐùò Zùó bs   Ä FÅF)r&   r"   r'   r    )NT)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__Ústrr   r   Úboolr*   Ústaticmethodr5   r6   r%   Úno_gradrC   r_   Ú__static_attributes__© r,   r)   r   r   )   sx   † ñð 7;Ø*.ñ	 àð ð "*¨(Ñ!3ð ð $(õ	 ð ðÐRW×R^ÑR^ó ó ðð ‡]‚]ƒ_ñWó ðWõr,   r   c                   ó„   ^ • \ rS rSrSrS\S\\\R                  4   4U 4S jjr
\R                  " 5       S 5       rSrU =r$ )ÚSVDHookéj   aþ  
A forward hook for calculating incremental SVD on layer inputs. The hook is designed to be registered to a PyTorch
module using the `register_forward_hook` method.

This hook performs a step of incremental Singular Value Decomposition (SVD) on the inputs of a specified layer
during the forward pass of a neural network. The hook also tracks convergence of the computed components using
cosine similarity between the current and previous components.

Args:
    name (str): Name of the layer to which this hook is attached.
    n_components (int): Number of principal components to compute.
    sim_thresh (Union[float, torch.Tensor]): Similarity threshold for convergence.
    prepare_layer_inputs_fn (Optional[Callable]): Function to prepare layer inputs for SVD.
Ún_componentsÚ
sim_threshc                 óð  >• [         TU ]  " S0 UD6  Xl        X l        [	        U[
        R                  5      (       ay  [        UR                  5      S:”  a`  UR                  S5      U:H  =(       d    UR                  S5      S:H  n[        UR                  5      S:H  nU(       a  U(       d  [        S5      e[        USSSS9U l        S U l        [
        R                  " U4[
        R                  S9U l        g )	Nr   r   z`if sim_thresh is a tensor with more than 0 dimensions it must have shape (n_components,) or (1,)Té*   )ro   r	   ÚlowrankÚlowrank_seed)rG   rk   )Úsuperr*   ro   rp   r4   r5   r6   ÚlenrM   r=   r9   r   Úsvdr'   Úzerosrg   Ú	converged)r(   ro   rp   Úbase_class_kwargsÚcheck1Úcheck2Ú	__class__s         €r)   r*   ÚSVDHook.__init__z   sÑ   ø€ ô 	‰ÒÑ-Ð,Ò-Ø(ÔØ$ŒÜ�j¤%§,¡,×/Ñ/´C¸
×8HÑ8HÓ4IÈAÓ4MØ—_‘_ QÓ'¨<Ñ7×R¸:¿?¹?È1Ó;MÐQRÑ;RˆFÜ˜×)Ñ)Ó*¨aÑ/ˆFÞžvÜ Øvóð ô "Ø%ØØØñ	
ˆŒð  ˆÔÜŸš l _¼E¿J¹JÑGˆ�r,   c                 ó  • S n[        U R                  S5      (       a2  U R                  R                  R                  5       R	                  5       nU R                  U5      nU R                  U5      nUR                  S5      U R                  :  a'  [        SU R                   SU R                   S35        g U R                  R                  UR                  [        R                  5      5        Uc  g U R                  R                  n[        UR                   5      S:X  a$  UR#                  SS5      nUR#                  SS5      n[        R$                  R&                  R)                  Xd5      nXpR*                  :¬  U l        g )NÚcomponents_r   zskipping SVD for z because there are less than z	 examplesr   r3   )Úhasattrrw   r€   ÚcloneÚdetachrC   r_   r=   ro   Úprintr    Úpartial_fitÚtor5   Úfloat32rv   rM   ÚreshapeÚnnÚ
functionalÚcosine_similarityrp   ry   )r(   ÚmodelÚinputÚoutputÚprevious_componentsÚstatesÚ
componentsÚsims           r)   Ú__call__ÚSVDHook.__call__“   s0  € à"ÐÜ�4—8‘8˜]×+Ñ+Ø"&§(¡(×"6Ñ"6×"<Ñ"<Ó">×"EÑ"EÓ"GÐØ×*Ñ*¨5Ó1ˆØ×)Ñ)¨&Ó1ˆà�;‰;�q‹>˜D×-Ñ-Ó-ÜÐ% d§i¡i [Ð0MÈd×N_ÑN_ÐM`Ð`iÐjÔkØØ�‰×Ñ˜VŸY™Y¤u§}¡}Ó5Ô6àÑ&ØØ—X‘X×)Ñ)ˆ
Üˆz×ÑÓ  AÓ%Ø#×+Ñ+¨A¨rÓ2ˆJØ"5×"=Ñ"=¸aÀÓ"DÐä�h‰h×!Ñ!×3Ñ3°JÓTˆØ§¡Ñ/ˆ�r,   )ry   r'   ro   rp   rw   )ra   rb   rc   rd   re   Úintr   Úfloatr5   r6   r*   ri   r“   rj   Ú__classcell__©r}   s   @r)   rm   rm   j   sJ   ø† ñðHàðHð ˜% §¡Ð-Ñ.÷Hð2 ‡]‚]ƒ_ñ0ó ö0r,   rm   c                   ój   ^ • \ rS rSrSrU 4S jr\S 5       r\R                  " 5       S 5       r
SrU =r$ )ÚHashHooké­   aÿ  
A forward hook for hashing layer inputs. The hook is designed to be registered to a PyTorch module using the
`register_forward_hook` method.

This hook hashes the inputs of a specified layer during the forward pass of a neural network and stores the hash
values for later analysis or comparison.

Args:
    name (str): Name of the layer to which this hook is attached. hashed_inputs (list): List of hashed inputs.
    prepare_layer_inputs_fn (Optional[Callable]): Function to prepare layer inputs for hashing.
c                 ó4   >• [         TU ]  " S0 UD6  / U l        g ©Nrk   )ru   r*   Úhashed_inputs)r(   rz   r}   s     €r)   r*   ÚHashHook.__init__º   s   ø€ Ü‰ÒÑ-Ð,Ò-ØˆÕr,   c                 ód   • [        [        U R                  S5      R                  5       5      5      $ )Nr3   )Úhashr7   r<   rP   )rL   s    r)   Úhash_fnÚHashHook.hash_fn¾   s#   € ä”E˜&Ÿ+™+ b›/×0Ñ0Ó2Ó3Ó4Ð4r,   c                 ó¸   • U R                  U5      nU R                  U5      nU R                  R                  U R	                  UR                  5       5      5        g r$   )rC   r_   rž   Úappendr¢   Úcpu)r(   rŒ   r�   rŽ   Úxs        r)   r“   ÚHashHook.__call__Â   sE   € à×%Ñ% eÓ,ˆØ×$Ñ$ QÓ'ˆØ×Ñ×!Ñ! $§,¡,¨q¯u©u«wÓ"7Õ8r,   )rž   )ra   rb   rc   rd   re   r*   rh   r¢   r5   ri   r“   rj   r—   r˜   s   @r)   rš   rš   ­   s;   ø† ñ
õ ð ñ5ó ð5ð ‡]‚]ƒ_ñ9ó ö9r,   rš   Ú
dictionaryr-   c                 óð   • [        [        5      nU R                  5        H  u  p#X   R                  U5        M     UR                  5        VVs0 s H  u  p#[	        U5      S:”  d  M  X#_M     snn$ s  snnf )a&  
Find keys in a dictionary that have the same value.

This function takes a dictionary and returns a new dictionary containing keys that have the same value. The keys in
the output dictionary are the values from the input dictionary, and the values are lists of keys that share the
same value.
r   )r   r8   Úitemsr¥   rv   )r©   Ú
value_dictÚkÚvs       r)   Úfind_equal_valuesr¯   É   sf   € ô œTÓ"€JØ× Ñ Ö"‰ˆØ‰×Ñ˜QÖñ #à'×-Ñ-Ô/Ô>Ò/‘T�Q´3°q³6¸A±:‹DˆAŠDÑ/Ò>Ð>ùÓ>s   ÁA2Á(A2rŒ   c                 ó  • [        U R                  5        Vs1 s H*  oR                  R                  S:w  d  M  UR                  iM,     sn5      n[	        U5      S:”  a  [
        R                  " SU 35        gUS   $ s  snf )zY
Get the device of the model's parameters. Useful if some parameters are on meta device.
Úmetar   z8Could not determine device, model has multiple devices: Nr   )r8   Ú
parametersrF   r:   rv   ÚwarningsÚwarn)rŒ   ÚpÚdevicess      r)   Úget_device_with_meta_paramsr·   ×   sp   € ô  e×&6Ñ&6Ô&8ÓTÒ&8 ¿H¹H¿M¹MÈVÑ<S“H�A—H”HÑ&8ÑTÓU€GÜ
ˆ7ƒ|�aÓÜ�ŠÐPÐQXÐPYÐZÔ[ØØ�1‰:Ðùò	 Us
   ˜A>¹A>rF   c                 ó²  ^• [        U S5      (       a  U R                  T5      $ [        U [        5      (       a?  [	        U 5      " U R                  5        VVs0 s H  u  p#U[        UT5      _M     snn5      $ [        U [        [        45      (       a  [	        U 5      " U4S jU  5       5      $ [        R                  " S[	        U 5       S35        U $ s  snnf )zC
Move the inputs to the specified device. Adapted from hf.Trainer.
r†   c              3   ó<   >#   • U  H  n[        UT5      v •  M     g 7fr$   )Úmove_inputs_to_device)Ú.0r®   rF   s     €r)   Ú	<genexpr>Ú(move_inputs_to_device.<locals>.<genexpr>ë   s   øé € ÐMÂfÀÔ1°!°V×<Ð<Âfùs   ƒzinput of type z) could not be moved to the correct device)r�   r†   r4   r   r:   r«   rº   r7   r8   r³   r´   )ÚinputsrF   r­   r®   s    `  r)   rº   rº   â   s¬   ø€ ô ˆv�t×ÑØ�y‰y˜Ó Ð Ü�&œ'×"Ñ"Ü�FŒ|ÈVÏ\É\Ì^Ô\Ê^ÁTÀQ˜QÔ 5°a¸Ó @Ò@É^Ò\Ó]Ð]Ü	�FœU¤D˜M×	*Ñ	*Ü�FŒ|ÔMÁfÓMÓMÐMä�Š˜¤t¨F£| nÐ4]Ð^Ô_Øˆùó ]s   ÁC
Úpeft_configc                 óˆ  • [        U [        5      (       d  [        S5      eU R                  S[        R
                  " U S   5      5      R                  5       nUR                  R                  (       aA  [        U S5      (       a0  [        R                  " X S   UR                  R                  :g  5      nUR                  5       $ )z·
Get the indices of the items that should be used for SVD.

Attributes:
    model_input (dict): The model inputs.
    peft_config (LoraConfig): The configuration for the LoRA layers.
zRWhen using `prepare_model_inputs_fn_language_modeling` inputs must be a dictionaryÚattention_maskÚ	input_idsÚlabels)r4   Údictr9   Úgetr5   Ú	ones_likerg   Ú
eva_configÚuse_label_maskr�   Úlogical_andÚlabel_mask_valueÚnonzero)r'   r¿   Úmasks      r)   Ú)prepare_model_inputs_fn_language_modelingrÍ   ñ   s’   € ô �k¤4×(Ñ(ÜÐmÓnÐnØ�?‰?Ð+¬U¯_ª_¸[ÈÑ=UÓ-VÓW×\Ñ\Ó^€DØ×Ñ×,×,´¸Àh×1OÑ1OÜ× Ò  °8Ñ'<À×@VÑ@V×@gÑ@gÑ'gÓhˆØ�<‰<‹>Ðr,   c                 óò   • [        U [        R                  5      (       a  O<[        U [        [        45      (       a  U S   n O[        S[        U 5       SU S35      eXR                  R                  5          $ )a¦  
if not all items in the input should be used for SVD, this function can be used to get the indices of the items
that should be used.

Attributes:
    layer_input (torch.Tensor): The layer inputs.
    model_input (torch.Tensor):
        The model inputs or if `prepare_model_inputs_fn` is not None the output of this function.
    layer_name (str): The name of the layer.

Returns:
    torch.Tensor: The input to the SVD.
r   r/   r0   r1   )	r4   r5   r6   r7   r8   r9   r:   ÚTÚunbindr>   s      r)   Ú)prepare_layer_inputs_fn_language_modelingrÑ     sx   € ô �+œuŸ|™|×,Ñ,ØÜ	�K¤%¬ ×	/Ñ	/Ø! !‘n‰äØ%¤d¨;Ó&7Ð%8Ð8^Ð_iÐ^jð k>ð >ó
ð 	
ð
 —}‘}×+Ñ+Ó-Ñ.Ð.r,   c                 ó   • U " S0 UD6$ r�   rk   )rŒ   r¾   s     r)   Úforward_fn_dictrÓ     s   € Ù‰?�6‰?Ðr,   Ú
dataloaderÚtarget_module_check_fnÚ
forward_fnÚprepare_model_inputs_fnr!   r"   Úshow_progress_barc	           
      óº  ^0• S n	[        U5      S:X  a  [        S5      e[        R                  " 5       (       a  U(       a  [        R
                  " S5        Sn
UR                  R                  nXº:”  a9  [        S U R                  5        5       5      nXÂR                  -  n[        X½5      nU R                  n[        U 5      nU R                  5         [        [!        U5      5      nUb  [#        UU5      nUb
  U" UU5      nO[%        U5      n0 n0 m0SnU R'                  5        HÈ  u  nnU" UU5      (       d  M  [)        U[*        5      (       a  UR-                  US 5      nOUn[/        UUUS9nUUl        UR3                  U5      nUU4UU'   UR4                  R7                  [9        UR4                  R;                  5       U5      UR                  5      n[=        UU-  5      T0U'   UU-  nMÊ     [)        U[*        5      (       a+  [        U5      S:”  a  [        SUR;                  5        35      eU" U U5        UR?                  5        VVs0 s H  u  nnUUS   R@                  S   _M     nnn[C        [E        U5      RG                  5       5      nU VVs0 s H  nUS	S    H	  nUUS   _M     M     n nnU H&  n![        U04S
 jU! 5       5      n"U! H  n#U"T0U#'   M
     M(     [C        UR;                  5       5       H†  nUR-                  U5      u  nnURI                  5         UU ;   a  M/  [K        T0U   UR                  RL                  UURN                  US9nU RQ                  U5      nUR3                  U5      nUU4UU'   Mˆ     0 [S        [U        UR;                  5       UR;                  5       5      5      EU En$U(       aS  [        R                  " 5       (       a  [        RV                  " 5       S:X  a   [Y        [!        [[        U5      5      SSS9n%Sn&O[!        [[        U5      5      n%Sn&UR;                  5        Vs0 s H  nUS_M     n'nT0R]                  5       n(U% GH»  nUb  [#        UU5      nUb
  U" UU5      nO[%        U5      n[C        UR;                  5       5       H¨  nUU   u  nn[^        R`                  " URb                  S U(U    5      n)U'U   (       d'  U)(       a   U(       a  URI                  5         S nSU'U'   Mb  U'U   (       a.  U)(       d'  U RQ                  U5      nUR3                  U5      nSU'U'   UUl        UU4UU'   Mª     U&(       ag  [C        U'RG                  5       5      U RG                  5        Vs/ s H  nU'U   PM
     sn-   n*U%Re                  [g        U*5       S[        U*5       S35        [a        U'RG                  5       5      (       a    OBU" U U5        [a        S URG                  5        5       5      (       d  GM¯  U	" UU$U UT05      n(GM¾     U R'                  5        V#V+Vs1 s HA  u  n#n+U+Rh                  RG                  5         H  n[)        U[j        5      (       d  M  U#iM     MC     n,n+n#n[        U,5      S:”  a  [        SU, S35      e0 n-U(R?                  5        H¾  u  nn.UU$U      S   n[^        R`                  " URb                  S U. 5      (       d  [        SU SU. S35      eURl                  Rn                  S U. n/UR                  Rp                  (       a:  U/URl                  Rr                  S U. Ru                  5       Rw                  SS	5      -  n/U/U-U'   MÀ     U Ry                  U5        Ub5  U-R?                  5        VVs0 s H  u  nnUUR{                  U5      _M     n-nnU-$ s  snnf s  snnf s  snf s  snf s  snn+n#f s  snnf )Nc           
      óx  • U R                  5        VVs0 s H#  u  pVXVS   R                  R                  S XE    _M%     nnn[        UR                  5        VVV	s/ s H  u  pXXx     H  o•U	4PM     M     sn	nn6 u  p«[        R
                  " U5      R                  SS9n[        US U  Vs/ s H  oÚU   PM	     sn5      nUR                  5        Vs0 s H  oUUR                  US5      _M     nnUR                  5        H  u  p_Xå   Xï   nnUU:¼  a  M  UUsXï'   Xå'   M      U$ s  snnf s  sn	nnf s  snf s  snf )Nr   T)Ú
descending)
r«   rw   Úexplained_variance_ratio_rW   r5   ÚstackÚargsortr   ÚkeysrÅ   )ÚhooksÚlayer_hook_mapÚequal_inputs_mapÚrank_budgetÚmax_componentsr­   ÚhÚexp_varsr    Úcrß   ÚvaluesÚidxÚiÚcountsÚk_hookÚrankÚ	rank_hooks                     r)   Ú_get_rank_distributionÚ3_get_eva_state_dict.<locals>._get_rank_distribution.  s8  € Ø[`×[fÑ[fÔ[hÔiÒ[hÑSWÐST�A˜‘t—x‘x×9Ñ9Ð:M¸NÑ<MÐNÒNÑ[hˆÑiÜ°>×3GÑ3GÔ3IÕbÒ3I©¨ÐS[ÕSaÈa ›VÑSa™VÑ3IÓbÐc‰ˆÜ�kŠk˜&Ó!×)Ñ)°TÐ)Ð:ˆÜ¨3¨|°Ñ+<Ó=Ò+< a˜qœ'Ñ+<Ñ=Ó>ˆØ/=×/BÑ/BÔ/DÓEÒ/D¨!�V—Z‘Z  1Ó%Ò%Ñ/DˆÐEØ)×/Ñ/Ö1‰IˆAà$™i¨©�)ˆDØ˜DÓ ÙØ(,¨iÐ%ˆF‰N˜F›Iñ 2ð ˆùó jùÜbùâ=ùÚEs   ”*D%ÁD+Â,D2ÃD7r   zdataloader is emptyzÐtorch.distributed is initialized and `gather_distributed_inputs` is True, therefore EVA initialization will gather tensors from all ranks. Ensure the model does not receive the same inputs on different ranks.iè  c              3   óL   #   • U  H  n[        UR                  5      v •  M     g 7fr$   )rR   rM   )r»   rµ   s     r)   r¼   Ú&_get_eva_state_dict.<locals>.<genexpr>L  s   é € Ð?Ò,> q”c˜!Ÿ'™'—l�lÒ,>ùs   ‚"$)r    r!   r"   zaprepare_layer_inputs_fn is a mapping but the following module names were not found in the model: r   c              3   ó.   >#   • U  H
  nTU   v •  M     g 7fr$   rk   )r»   Únrä   s     €r)   r¼   rò     s   øé € Ð9²5¨a˜ qÖ)²5ùs   ƒ)ro   rp   r    r!   r"   F)ÚpositionÚleaveTÚ/z layers have convergedc              3   óT   #   • U  H  n[        US    R                  S5      v •  M      g7f)r   r€   N)r�   rw   )r»   rå   s     r)   r¼   rò   Å  s"   é € ÐLº^¸”7˜1˜Q™4Ÿ8™8 ]×3Ð3º^ùs   ‚&(z?Found active hooks added by EVA that weren't properly removed: zH. Please report this issue at https://github.com/huggingface/peft/issueszLayer z) has not converged but was assigned rank r3   )>rv   r9   rI   rJ   r³   r´   rÇ   ÚrhorR   r²   ÚrÚminÚtrainingr·   ÚevalÚnextÚiterrº   r
   Únamed_modulesr4   r   Úpoprš   r'   Úregister_forward_hookÚrank_patternrÅ   r   rß   Úroundr«   rž   r8   r¯   rè   Úremoverm   Útaur&   Úget_submodulerÄ   rW   Úget_rankr   r   r	   r5   Úallry   Úset_descriptionÚsumÚ_forward_hooksr   rw   r€   ÚwhitenÚsingular_values_Úsqrtrˆ   Útrainr†   )1rŒ   rÔ   r¿   rÕ   rÖ   r×   r!   r"   rØ   rï   Úrho_thresholdrù   Úmax_dimÚrho_ceilrü   rF   r¾   Úmodel_inputs_for_hooksrà   rã   r    ÚmoduleÚfnÚhookÚhandleÚ
layer_rankr­   rå   Ú	hash_dictÚequal_inputsr®   Úvvrâ   ÚnamesÚ	max_valuerô   rá   ÚpbarÚuse_tqdmÚconvergence_dictÚ	rank_distry   Úlayer_convergedÚmÚremaining_hooksÚeva_state_dictrí   Úurä   s1                                                   @r)   Ú_get_eva_state_dictr(  !  s}  ø€ òô ˆ:ƒ˜!ÓÜÐ.Ó/Ð/ô ×Ò×ÑÖ!:Ü�ŠðTô	
ð €MØ
×
 Ñ
 ×
$Ñ
$€CØ
ÓÜÑ?¨E×,<Ñ,<Ô,>Ó?Ó?ˆØŸm™mÑ+ˆÜ�#Ó ˆà�~‰~€HÜ(¨Ó/€FØ	‡J�J„Lô ”$�zÓ"Ó#€FØÑÜ& v¨vÓ6ˆØÑ*Ù!8¸ÀÓ!MÑä!)¨&Ó!1Ðà€EØ€NØ€KØ×+Ñ+Ö-‰ˆˆfÙ% d¨F×3Ñ3ÙÜÐ-¬w×7Ñ7Ø(×,Ñ,¨T°4Ó8‰Bà(ˆBÜ˜T¸2ÐYrÑsˆØ1ˆÔØ×-Ñ-¨dÓ3ˆØ˜V�nˆˆd‰Ø ×-Ñ-×1Ñ1Ü˜K×4Ñ4×9Ñ9Ó;¸TÓBÀKÇMÁMó
ˆ
ô  % Z°#Ñ%5Ó6ˆ�tÑØ�zÑ!Šñ .ô  Ð)¬7×3Ñ3¼Ð<SÓ8TÐWXÓ8XÜØoØ&×+Ñ+Ó-Ð.ð0ó
ð 	
ñ ˆu�fÔØ6;·k±k´mÔD²m©d¨a°��A�a‘D×&Ñ& qÑ)Ò)±m€IÑDô Ô)¨)Ó4×;Ñ;Ó=Ó>€LÙ*6ÔGª, QÀÀ1À2Ä¸2˜˜A˜a™DšÁ™©,ÐÑGãˆÜÔ9±5Ó9Ó9ˆ	ÛˆAØ )ˆN˜1Óó ñ ô �U—Z‘Z“\Ö"ˆØ—y‘y “‰ˆˆfØ�‰ŒØÐ#Ó#ÙÜØ'¨Ñ-Ø"×-Ñ-×1Ñ1ØØ$(×$AÑ$AØ&?ñ
ˆð ×$Ñ$ TÓ*ˆØ×-Ñ-¨dÓ3ˆØ˜V�nˆˆd‹ñ #ð SœœS §¡£¨u¯z©z«|Ó<Ó=ÐRÐAQÐR€Nö ¤$×"5Ò"5×"7Ñ"7¼4¿=º=»?ÈaÓ;OÜ”Dœ˜zÓ*Ó+°a¸uÑEˆØ‰ä”E˜*Ó%Ó&ˆØˆØ*/¯*©*¬,Ó7ª, Q˜˜5š©,ÐÐ7Ø×#Ñ#Ó%€IÜˆØÑÜ*¨6°6Ó:ˆFØ"Ñ.Ù%<¸VÀ[Ó%QÑ"ä%-¨fÓ%5Ð"ä˜Ÿ™›Ö&ˆDØ  ™;‰LˆD�&äŸ	š	 $§.¡.Ð1B°9¸T±?Ð"CÓDˆIà$ T×*¶	¾fØ—‘”Ø�Ø)-Ð  Ñ&Ùà! $×'¶	Ø×,Ñ,¨TÓ2�Ø×5Ñ5°dÓ;�Ø).Ð  Ñ&Ø5ˆDÔØ ˜.ˆE�$‹Kñ! 'ö$ Ü"Ð#3×#:Ñ#:Ó#<Ó=Ø-=×-DÑ-DÔ-FóAÚ-F¨Ð  Ô#Ñ-FñAñ ˆOð × Ñ ¤C¨Ó$8Ð#9¸¼3¸Ó;OÐ:PÐPfÐ!gÔhäÐ×&Ñ&Ó(×)Ñ)Ùá�5˜&Ô!ô ÑL¸U¿\¹\¼^ÓL×LÑLÚá*¨5°.ÐBRÐT_ÐaoÓp‹	ñU ðZ &+×%8Ñ%8Ô%:ÕvÒ%:™T˜Q ÀA×DTÑDT×D[ÑD[×D]¸qÔakÐlmÔot×au—qÑD]‘qÑ%:€OÒvÜ
ˆ?Ó˜aÓÜØMÈoÐM^ð _Uð Uó
ð 	
ð
 €NØ—o‘oÖ'‰
ˆˆdØ�^ DÑ)Ñ*¨1Ñ-ˆÜ�yŠy˜Ÿ™¨¨Ð.×/Ñ/ÜØ˜˜ÐGÈÀvð NYð Yóð ð �H‰H× Ñ   $Ð'ˆØ×!Ñ!×(×(Ø�—‘×*Ñ*¨5¨DÐ1×6Ñ6Ó8×@Ñ@ÀÀQÓGÑGˆAØ ˆ�tÓñ (ð 
‡K�K�Ôð ÑØ6D×6JÑ6JÔ6LÔMÒ6L©d¨a°˜!˜QŸT™T &›\š/Ñ6LˆÑMàÐùó] Eùó Hùò@ 8ùò:Aùô$ wùó2 Ns*   É ^:Ê_ Ð<_Õ>_Ø1:_Ù/
_Þ_r&  Úadapter_namec                 óÐ  • [        U R                  U   5      n/ n/ n/ n0 n0 nU R                  5        GH,  u  pšU	R                  SS5      n[	        U
[
        5      (       d  UR                  U5        M@  UR                  R                  [        UR                  R                  5       U	5      UR                  5      nUR                  R                  [        UR                  R                  5       U	5      UR                  5      nX‘;   Ga  UR                  U	5      nUR                  S5      nUS:X  a-  [!        X	5      u  nnn[#        UUU
R%                  5       5        GM+  Xü:w  a"  UR&                  R(                  (       a  XßU-  -  nXü:w  d1  U
R*                  U   R,                  R.                  R0                  S:X  a  SUl        U
R5                  X/XÓS9  U
R*                  U   R,                  R7                  U5        UR                  U5        O*SUl        U
R5                  X,XÓS9  UR                  U5        UnXóR                  :w  a  X÷U'   XÓR                  :w  d  GM(  XØU'   GM/     XT-   n[9        U5      [:        :¼  a  [=        XV5      nXPR                  U   l        XpR                  U   l        X€R                  U   l        U(       a!  [@        RB                  " SU S	[D         35        g g )
Nzbase_model.model.Ú r   r±   Úeva)r)  rú   Ú
lora_alphaÚconfigTzuthe following layers were initialized with init_lora_weights=True because they were not found in the eva state_dict: z@
currently the following lora modules are not supported by EVA: )#r	   r¿   r   Úreplacer4   r   r¥   r  rÅ   r   rß   rú   Úalpha_patternr-  r  r=   r   ÚsetattrÚget_base_layerrÇ   Úadjust_scaling_factorsÚlora_AÚweightrF   r:   Úinit_lora_weightsÚupdate_layerÚcopy_rv   r   r   Útarget_modulesr³   r´   ÚUNSUPPORTED_LORA_MODULES)rŒ   r&  r)  r¿   Úmissing_eva_initsÚnew_target_modulesÚother_module_namesr  r0  r    r  Úname_in_base_modelrú   ÚalphaÚwÚnew_rankÚparentr]   Útarget_names                      r)   Ú_load_eva_state_dictrD  é  s·  € ô
 �u×(Ñ(¨Ñ6Ó7€KØÐØÐØÐØ€LØ€MØ×+Ñ+×-‰ˆØ!Ÿ\™\Ð*=¸rÓBÐÜ˜&¤)×,Ñ,Ø×%Ñ%Ð&8Ô9Ùà×$Ñ$×(Ñ(¬¸×9QÑ9Q×9VÑ9VÓ9XÐZ^Ó)_Ðal×anÑanÓoˆØ×)Ñ)×-Ñ-Ü˜K×5Ñ5×:Ñ:Ó<¸dÓCÀ[×E[ÑE[ó
ˆð Ô!Ø×"Ñ" 4Ó(ˆAØ—v‘v˜a“yˆHØ˜1‹}Ü)8¸Ó)EÑ&�˜˜;Ü˜ ¨V×-BÑ-BÓ-DÔEÚØ“Ø×)Ñ)×@×@Ø¨™\Ñ)�EØ‹} §¡¨lÑ ;× BÑ B× IÑ I× NÑ NÐRXÓ XØ05�Ô-Ø×#Ñ#°ÐV[Ð#ÑpØ�M‰M˜,Ñ'×.Ñ.×4Ñ4°QÔ7Ø×%Ñ%Ð&8Õ9à,0ˆKÔ)Ø×Ñ¨\È5ÐÑeØ×$Ñ$Ð%7Ô8ØˆHà—}‘}Ó$Ø/7Ð+Ñ,Ø×*Ñ*Ö*Ø05Ð,Ô-ñE .ðJ ,Ñ?ÐÜ
ÐÓÔ"EÓEÜ9Ð:LÓaÐØ5G×Ñ�lÑ#Ô2ð 4@×Ñ�lÑ#Ô0ð 5B×Ñ�lÑ#Ô1æÜ�Šð5Ø5FÐ4Gð H@Ü@XÐ?Yð[õ	
ð r,   ÚdefaultTc	                 óH  • S n	S n
[        U S5      nU(       a  Uc  U R                  U   nOUc  [        S5      eU(       a  U R                  5       n[	        U	[
        S9nO[        5       n[	        X¢S9nU   [        U UUUUUUUUS9	nSSS5        U$ ! , (       d  f       W$ = f)	a9  
Compute the SVD for each layer in the model.

This function computes the Singular Value Decomposition (SVD) for each layer in the model. It uses the incremental
PCA method to compute the SVD components. The function also checks for convergence of the computed components using
cosine similarity. The rank distribution for each layer is determined based on the explained variance ratio.

Args:
    model (torch.nn.Module): The model to compute the SVD for. Does not need to be a PeftModel.
    dataloader (Iterable): The dataloader to use for the forward pass.
    peft_config (Optional[LoraConfig]):
        The configuration for the LoRA layers. Only required if `model` is not a PeftModel.
    forward_fn (Callable):
        The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default
        behavior is `return model(**inputs)`
    prepare_model_inputs_fn (Optional[Callable]):
        This function receives the model inputs and the peft_config and passes the output to
        `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original
        model inputs. For example for language modeling the attention mask is used to determine which indices are
        padding tokens and should not be used for SVD. Any function defined here expects two arguments:
        `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used
        by default.
    prepare_layer_inputs_fn (Union[Callable, Dict[str, Callable], None]):
        This function receives the layer inputs, the model inputs (potentially modified by
        `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for
        that particular layer. Any custom function defined here expects three arguments: `layer_input`,
        `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in
        peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this
        case model_inputs is the mask used to determine which indices should be used for SVD (created by
        `prepare_model_inputs_fn_language_modeling`).
    adapter_name (str): The name of the adapter to compute the SVD for.
    gather_distributed_inputs (bool):
        Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the
        layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this
        argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting.
    show_progress_bar (bool): Whether to show a progress bar. Default is True.

Returns:
    eva_state_dict (dict): The state dictionary containing the SVD components for each layer.
c                 óH   • [        US5      =(       a    [        X5      (       + $ )z?check if a module is an adapter module via base_layer attributeÚ
base_layer)r�   r4   )r    r  Úunsupported_lora_moduless      r)   Ú!target_module_check_fn_peft_modelÚ=get_eva_state_dict.<locals>.target_module_check_fn_peft_modela  s   € ä�v˜|Ó,×a´ZÀÓ5aÔ1aÐar,   c                 óœ   • SnUR                   b  [        X 5      n[        U[        R                  R
                  [        45      =(       a    U$ )z9check if a module is an adapter module via target_modulesT)r9  r   r4   r5   r‰   ÚLinearr   )r    r  r¿   Úis_target_modules       r)   Útarget_module_check_fn_defaultÚ:get_eva_state_dict.<locals>.target_module_check_fn_defaulte  s?   € àÐØ×%Ñ%Ñ1Ü9¸+ÓLÐä˜&¤5§8¡8§?¡?´FÐ";Ó<×QÐAQÐQr,   r¿   Nz3peft_config is required if model is not a PeftModel)rI  )r¿   )	rŒ   rÔ   r¿   rÕ   rÖ   r×   r!   r"   rØ   )r�   r¿   r9   Údisable_adapterr   r:  r   r(  )rŒ   rÔ   r¿   rÖ   r×   r!   r)  r"   rØ   rJ  rO  Úis_peft_modelÚctxrÕ   r&  s                  r)   Úget_eva_state_dictrT  ,  sÇ   € òjbòRô ˜E =Ó1€Mö ˜Ñ,Ø×'Ñ'¨Ñ5‰Ø	Ñ	ÜÐNÓOÐOö Ø×#Ñ#Ó%ˆÜ!(Ø-ÔH`ñ"
Ñô ‹mˆÜ!(Ð)GÑ!aÐâ	Ü,ØØ!Ø#Ø#9Ø!Ø$;Ø$;Ø&?Ø/ñ

ˆ÷ 
ð Ð÷ 
Œð Ðús   Á6BÂ
B!c	                 ó.  • [        U S5      (       d  [        S5      e[        U R                  5      S:”  a  [        S5      eU R                  U   R
                  S:w  a  [        S5      eUc  Uc  [        S5      e[        U UUUUUUUS	9n[        XU5        g)
aë
  
Initialize the weights of the LoRA layers using the EVA method.

This function initializes the weights of the LoRA layers using the EVA method. It computes the SVD for each adapter
layer and updates the weights accordingly.

Args:
    model (PeftModel): The peft model to compute the SVD for.
    dataloader (Optional[Iterable]):
        The dataloader to use for the forward pass. If None, eva_state_dict needs to be provided.
    eva_state_dict (Optional[dict]):
        The state_dict to load into the model. If None, a dataloader needs to be provided and the state_dict will
        be computed using `get_eva_state_dict`.
    forward_fn (Callable):
        The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default
        behavior is `return model(**inputs)`
    prepare_model_inputs_fn (Optional[Callable]):
        This function receives the model inputs and the peft_config and passes the output to
        `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original
        model inputs. For example for language modeling the attention mask is used to determine which indices are
        padding tokens and should not be used for SVD. Any function defined here expects two arguments:
        `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used
        by default.
    prepare_layer_inputs_fn (Union[Callable, Dict[str, Callable], None]):
        This function receives the layer inputs, the model inputs (potentially modified by
        `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for
        that particular layer. Any custom function defined here expects three arguments: `layer_input`,
        `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in
        peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this
        case model_inputs is the mask used to determine which indices should be used for SVD (created by
        `prepare_model_inputs_fn_language_modeling`).
    adapter_name (str): The name of the adapter to initialize the weights for.
    gather_distributed_inputs (bool):
        Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the
        layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this
        argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting.
    show_progress_bar (bool): Whether to show a progress bar. Default is True.

Returns:
    model (torch.nn.Module): The model with the initialized LoRA weights.
r¿   zmodel must be a PeftModelr   zO`initialize_lora_eva_weights` currently only works with a single active adapterr,  zM`initialize_lora_eva_weights` can only be used with `init_lora_weights='eva'`Nz8dataloader is required if eva_state_dict is not provided)rŒ   rÔ   rÖ   r×   r!   r)  r"   rØ   )r�   r9   rv   Úactive_adaptersr¿   r6  rT  rD  )	rŒ   rÔ   r&  rÖ   r×   r!   r)  r"   rØ   s	            r)   Úinitialize_lora_eva_weightsrW  Ž  s®   € ôj �5˜-×(Ñ(ÜÐ4Ó5Ð5ô ˆ5× Ñ Ó! AÓ%ÜÐjÓkÐkð ×Ñ˜Ñ&×8Ñ8¸EÓAÜÐhÓiÐið ÑØÑÜÐWÓXÐXÜ+ØØ!Ø!Ø$;Ø$;Ø%Ø&?Ø/ñ	
ˆô ˜°Õ=r,   )Ar³   Úcollectionsr   r   Úcollections.abcr   r   r   Ú
contextlibr   r	   r
   Ú	functoolsr   Ú	itertoolsr   Útypingr   r   r5   Útorch.distributedÚdistributedrI   r   Útransformers.pytorch_utilsr   Úpeft.tuners.tuners_utilsr   r   Úpeft.utils.constantsr   Úpeft.utils.incremental_pcar   Úpeft.utils.otherr   r   r.  r   Úlayerr   r   r   r   r:  r   rm   rš   rÄ   r¯   r‰   ÚModulerF   r·   rf   rº   rÍ   r6   rÑ   rÓ   rg   r(  rD  ri   rT  rW  rk   r,   r)   Ú<module>rg     s?  ðó ß ,ß 7Ñ 7Ý "ß Ý Ý ß "ã Ý  Ý Ý -ç ]Ý DÝ 5ß =å ß DÓ Dð &Ð'9¸7ÐCÐ ÷>ñ >ôB>0ˆeô >0ôF9ˆuô 9ð8? $ð ?¨4ô ?ð u§x¡x§¡ð ¸5¿<¹<ô ð¨%°°U·\±\Ð0AÑ*Bô ðÈ
ô ð /ÐW\×WcÑWcô /ò8ðEØ�8‰8�?‰?ðEàðEð ˜*Ñ%ðEð %ð	Eð
 ˜Ñ"ðEð & hÑ/ðEð # 8¨T°#°x°-Ñ-@À$Ð#FÑGðEð  $ðEð ðEð 
ôEðP@
Ø�8‰8�?‰?ð@
àð@
ð ô@
ðF ‡‚ƒð )-Ø%4Ø2[ØJsØ!Ø&*Ø"ñ^Ø�8‰8�?‰?ð^àð^ð ˜*Ñ%ð^ð ˜Ñ"ð	^ð
 & hÑ/ð^ð # 8¨T°#°x°-Ñ-@À$Ð#FÑGð^ð ð^ð  $ð^ð ð^ð 
ô^ó ð^ðB ‡‚ƒð &*Ø%)Ø%4Ø2[ØJsØ!Ø&*Ø"ñO>Ø�8‰8�?‰?ðO>à˜Ñ"ðO>ð ˜T‘NðO>ð ˜Ñ"ð	O>ð
 & hÑ/ðO>ð # 8¨T°#°x°-Ñ-@À$Ð#FÑGðO>ð ðO>ð  $ðO>ð ôO>ó ñO>r,   