ó
    >:jð  ã                   óL  • S SK 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  S\R                  S\4S	 jrS\R                  S
\4S jr\R&                  " 5        SS\R                  S\S\/ S4   S\\   4S jj5       rS\R                  S\S\/ S4   4S jrg)é    N)ÚCallable)ÚAnyÚOptional)ÚConv1D)Ú
LoraConfig)Ú	LoraModelÚmodelÚconfigc              #   óÐ   #   • U R                  5        HN  u  p#[        R                  " X5      (       d  M"  [        U[        R
                  [        45      (       d  MI  X#4v •  MP     g7f)z™
Iterate over LoRA-GA target name and modules of a model. A module is a target if its name is in
`config.target_modules` and is `nn.Linear` or `Conv1D`.
N)Únamed_modulesr   Ú_check_target_module_existsÚ
isinstanceÚnnÚLinearr   )r	   r
   ÚnameÚmodules       ÚT/home/mande/repo/quber/.venv/lib/python3.13/site-packages/peft/tuners/lora/loraga.pyÚget_target_modulesr      sN   é € ð
 ×+Ñ+Ö-‰ˆÜ×0Ò0°×>Ó>Ä:ÈfÔWY×W`ÑW`ÔbhÐVi×CjÓCjØ�,Ôò .ùs   ‚/A&µ#A&Á
A&Úreturnc                 ó”   • [        U S5      (       a  U R                  n [        [        U R	                  5       5      5      R
                  $ )Nr   )Úhasattrr   ÚnextÚiterÚ
parametersÚdevice)r	   s    r   Úget_model_devicer   (   s7   € Üˆu�h×ÑØ—‘ˆÜ”�U×%Ñ%Ó'Ó(Ó)×0Ñ0Ð0ó    Úlora_configÚ
train_stepÚ
cache_filec                 ór  • UR                   c  [        S5      eUR                  cV  [        R                  " U 5      n[        R
                  R                  US   5      nUc  [        S5      e[        U5      Ul        [        X5       H%  u  pg[        US5      (       d  M  [        SU S35      e   Ub†  [        R                  R                  U5      (       ab  [        R                  R                  U5      S:”  a?  [        R                  " U[!        U 5      S	9n[        X5       H  u  pgX† S
3   Ul        M     g[%        XU5        Ubp  0 n[        X5       H  u  pgUR"                  X† S
3'   M     [        R&                  " [        R                  R)                  U5      SS9  [        R*                  " Xƒ5        gg)a/  
Build necessary LoRA-GA fields for a model by estimating gradients.

For each linear layer, gradients will be estimated by running the provided train_step callback. These gradients are
then attached to the modules and used during initialization.

Args:
    model (`nn.Module`):
        Model to preprocess.
    lora_config (`LoraConfig`):
        Lora configuration of the model. `lora_config.lora_ga_config` should be set.
    train_step (`Callable[[], None]`):
        Callback to run gradient estimation. Typically you should run model forward and backward passes in this
        callback. The gradients will be accumulated across all calls within this callback.
    cache_file (`Optional[str]`):
        Optional path to cache file for saving/loading gradients. If provided and the file exists, gradients will
        be loaded from cache. Otherwise, gradients will be estimated and saved to this path.

Upon completion, the following fields are set for each target module:
    _peft_loraga_grad (`torch.Tensor`):
        Accumulated gradient for the weight matrix.
NzƒIf you want to use LoRA-GA, please initialize the LoraConfig with init_lora_weights='lora_ga' and lora_ga_config=LoraGAConfig(...).Ú
model_typez0Please specify `target_modules` in `peft_config`Úquant_statezDLoRA-GA does not support quantized models. Found quantized module: 'zB'. LoRA-GA requires full-precision gradients during preprocessing.r   )Úmap_locationz._peft_loraga_gradT)Úexist_ok)Úlora_ga_configÚ
ValueErrorÚtarget_modulesr   Úget_model_configÚtarget_module_mappingÚgetÚsetr   r   ÚosÚpathÚexistsÚgetsizeÚtorchÚloadr   Ú_peft_loraga_gradÚestimate_gradientsÚmakedirsÚdirnameÚsave)	r	   r   r   r    Úmodel_configr(   r   r   Úcaches	            r   Úpreprocess_loragar:   .   s˜  € ð: ×!Ñ!Ñ)ÜðPó
ð 	
ð ×!Ñ!Ñ)Ü ×1Ò1°%Ó8ˆÜ"×8Ñ8×<Ñ<¸\È,Ñ=WÓXˆØÑ!ÜÐOÓPÐPÜ%(¨Ó%8ˆÔ"ô +¨5Ö>‰ˆÜ�6˜=×)Ó)ÜØVÐW[ÐV\ð ]Rð Róð ñ ?ð Ñ¤"§'¡'§.¡.°×"<Ñ"<ÄÇÁÇÁÐQ[ÓA\Ð_`ÓA`Ü—
’
˜:Ô4DÀUÓ4KÑLˆÜ.¨uÖB‰LˆDØ',¨vÐ5GÐ-HÑ'IˆFÖ$ò Cô 	˜5¨zÔ:ð Ñ!Ø$&ˆEÜ 2°5Ö F‘�Ø5;×5MÑ5M�˜Ð0Ð1Ó2ñ !Gô �KŠKœŸ™Ÿ™¨
Ó3¸dÒCÜ�JŠJ�uÕ)ð "r   c                 ó�  • U R                   nU R                  5         [        [        X5      5      nU(       d  [	        S5      eU H  u  pVSUl        M     0 nU R                  5        H  u  pXUR                  Xu'   SUl        M     U H  u  pVSUR                  l        M     / n	S n
U H'  u  pVUR                  U
5      nU	R                  U5        M)     [        R                  " 5          U" 5         SSS5        U	 H  nUR                  5         M     U R                  5        H  u  pXXW;   d  M  Xu   Ul        M     U H^  u  pVUR
                  S:”  a6  UR                  R                  R                  5       UR
                  -  Ul        SUR                  l        U?M`     U(       d  U R#                  5         gg! , (       d  f       NÍ= f)zÜ
Estimate gradients for LoRA-GA initialization.

This function enables gradient computation ONLY on target module weights and runs the train_step callback. This is
more memory-efficient than enabling gradients globally.
z¿No supported layers found for LoRA-GA initialization. LoRA-GA only supports nn.Linear and Conv1D layers. Please ensure your model contains at least one of these layer types in target_modules.r   FTc                 ó.   • U =R                   S-  sl         g )Né   )Ú_peft_loraga_grad_count)r   Ú
grad_inputÚgrad_outputs      r   Úbackward_hookÚ)estimate_gradients.<locals>.backward_hook¢   s   € Ø×&Ò&¨!Ñ+Ö&r   N)ÚtrainingÚtrainÚlistr   r'   r>   Únamed_parametersÚrequires_gradÚweightÚregister_full_backward_hookÚappendr1   Úenable_gradÚremoveÚgradÚdetachr3   Úeval)r	   r   r   Úwas_trainingÚtarget_module_listr   r   Úoriginal_requires_gradÚparamÚhooksrA   Úhooks               r   r4   r4   v   s   € ð —>‘>€LØ	‡K�K„Mô Ô0°ÓDÓEÐö Üðeó
ð 	
ó +‰ˆØ)*ˆÖ&ñ +ð
  ÐØ×-Ñ-Ö/‰ˆØ',×':Ñ':ÐÑ$Ø#ˆÖñ 0ó
 +‰ˆØ&*ˆ�‰Ö#ñ +ð €Eò,ó +‰ˆØ×1Ñ1°-Ó@ˆØ�‰�TÖñ +ô
 
×	Ò	Õ	ÙŒ÷ 
ó ˆØ�‰Žñ ð ×-Ñ-Ö/‰ˆØÕ)Ø"8Ñ">ˆEÖñ 0ó
 +‰ˆØ×)Ñ)¨AÓ-Ø'-§}¡}×'9Ñ'9×'@Ñ'@Ó'BÀV×EcÑEcÑ'cˆFÔ$Ø!ˆ�‰ÔØÒ*ñ	 +ö Ø�
‰
�ð ÷) 
Õ	ús   Ã(F7Æ7
G)N)r-   Úcollections.abcr   Útypingr   r   r1   Útorch.nnr   Útransformers.pytorch_utilsr   Úpeft.tuners.lora.configr   Úpeft.tuners.lora.modelr   ÚModuler   Ústrr   Úno_gradr:   r4   © r   r   Ú<module>r`      sØ   ðó$ 
Ý $ß  ã Ý Ý -å .Ý ,ð˜bŸi™ið °ô ð1˜BŸI™Ið 1¨#ô 1ð ‡‚ƒð
 !%ñ	D*Ø�9‰9ðD*àðD*ð ˜˜T˜Ñ"ðD*ð ˜‘ô	D*ó ðD*ðNIØ�9‰9ðIàðIð ˜˜T˜Ñ"õIr   