ó
    >:j6F  ã                   ó  • S SK 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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  S
\R$                  S\S\4S jr\R,                  " 5        SS\S\\-  S\S\\R$                  \R$                  \4   4S jj5       r   SS\R4                  R6                  S\\-  S\S\S\\\\\R$                  4   4   4
S jjr   SS\\R>                  -  S\R4                  R6                  S\\-  S\S\SS4S jjr g)é    N)Ú	save_file)Útqdm)ÚConv1D)ÚBaseTunerLayer)ÚSAFETENSORS_WEIGHTS_NAME)ÚModulesToSaveWrapperé   )Ú
LoraConfigÚSÚ	thresholdÚreturnc                 óØ   • U R                  5       S:w  a  [        S5      eU S-  n[        R                  " USS9nUS   nX-  n[        R                  " X55      R                  5       nUS-   $ )Nr	   zInput vector must be 1d.é   r   )Údiméÿÿÿÿ)r   Ú
ValueErrorÚtorchÚcumsumÚsearchsortedÚitem)r   r   ÚenergyÚcsÚtotalÚcutoffÚks          ÚX/home/mande/repo/quber/.venv/lib/python3.13/site-packages/peft/tuners/lora/conversion.pyÚ_find_cutoff_indexr       sg   € à‡u�uƒw�!ƒ|ÜÐ3Ó4Ð4à�‰T€FÜ	�Š�f !Ñ	$€BØˆr‰F€EàÑ€Fä×Ò˜2Ó&×+Ñ+Ó-€Aàˆq‰5€Ló    ÚmoduleÚrankÚadapter_namec                 ó¢  • U R                  U5      nUR                  nUR                  5       n[        R                  R                  USS9u  pVn[        U[        5      (       a  UnO	[        XaS9nX…R                  S   :”  a  [        SU SUR                  S    S35      eUSS2SU24   USU -  n	USU n
U
R                  U5      U	R                  U5      pš[        U R                  5       [        5      (       a5  U	R                  R                  5       U
R                  R                  5       U4$ U
R                  5       U	R                  5       U4$ )	zgConvert a single BaseTunerLayer's adapter weight to a LoRA weight, return A, B, and the effective rank.F)Úfull_matrices)r   r	   zThe chosen rank z" is larger than the weight shape (z), please choose a lower rank.N)Úget_delta_weightÚdtypeÚfloatr   ÚlinalgÚsvdÚ
isinstanceÚintr   Úshaper   ÚtoÚget_base_layerr   ÚTÚ
contiguous)r   r    r!   Údelta_weightÚ
orig_dtypeÚUr   ÚVÚeffective_rankÚlora_BÚlora_As              r   Ú_convert_module_to_lorar7   0   sO  € ð
 ×*Ñ*¨<Ó8€Lð ×#Ñ#€JØ×%Ñ%Ó'€LÜ�l‰l×Ñ˜|¸5ÐÐA�G€Aˆ!Ü�$œ×ÑØ‰ô ,¨AÑ>ˆàŸ™ ™
Ó"ÜØ˜~Ð.Ð.PÐQR×QXÑQXÐYZÑQ[ÐP\ð ]ð ó
ð 	
ð
 Šq�/�>�/Ð!Ñ" Q ¨Ð%7Ñ7€FØˆ�Ð€FØ—Y‘Y˜zÓ*¨F¯I©I°jÓ,AˆFä�&×'Ñ'Ó)¬6×2Ñ2à�x‰x×"Ñ"Ó$ f§h¡h×&9Ñ&9Ó&;¸^ÐKÐKØ×ÑÓ × 1Ñ 1Ó 3°^ÐCÐCr   ÚmodelÚprogressbarc           	      ój	  • SSK Jn  [        U[        5      (       a  SUs=:  a  S::  d  O  [	        SU S35      eUS:X  a  [	        S5      e/ nSnSnU R                  5        HM  n	US-  n[        U	[        5      (       d  M  U	R                  U5      (       a  US-  nM<  UR                  U	5        MO     U V	s1 s H  n	[        [        U	5      5      iM     n
n	U
(       a  [        SSR                  U
5       S35      eUS:X  a  [        S	5      e[        U S
0 5      R                  U5      nUb0  UR                  UR                   :X  a  ["        R$                  " S5        [        US[        USS5      5      nUS:w  a  [	        SU S35      eSn0 0 ['        5       S.nUb¢  U R(                  U   n[*        R*                  " UR,                  5      US'   UR.                  US'   [1        US5      (       a  UR2                  US'   UR4                  US'   [        U[6        5      (       a  [9        S%XS.UD6nO4[9        S%SSS.UD6nO%[9        S%[        U[6        5      (       a  UOS/ S.UD6nUb  [:        R<                  " [>        40 UD6nO[>        n0 n[A        U RC                  5       U(       + SUS9 GH   u  nn	[        U	[        5      (       d  M  [1        U	S5      (       d  [        S[        U	5       S35      eU" X‘US9u  nnnUS:X  a,  URD                  RG                  URI                  U5      5        M„  UU:w  d  [        UR,                  [J        5      (       a=  UURL                  URI                  U5      '   UURN                  URI                  U5      '   O*UR,                  RG                  URI                  U5      5        UUU S 3'   UUU S!3'   GM#     U(       d  [	        S"5      eUbÊ  [        US#S5      (       a¸  [*        R*                  " URP                  5      Ul(        U RC                  5        H  u  nn	[        U	[R        5      (       d  M  U	RP                  RU                  5        HD  u  nnURW                  S$5      u  n  nURY                  S5      u    nnURZ                  UU SU 3'   MF     M�     UU4$ s  sn	f )&a˜  
Convert a non-LoRA model with PEFT layers to a LoRA checkpoint.

This is only supported for some specific PEFT methods that allow an equivalent conversion. Essentially, this comes
down to PEFT methods that work by updating the base weight with a delta weight. Also, right now, only linear layers
are supported.

The LoRA adapter will try to approximate the initial adapter as close as possible. The higher the rank, the better
the approximation. It is expected that the approximation will never reach the full performance of the original
adapter, and that the parameter efficiency of the LoRA adapter will be less than that of the original adapter (i.e.
for a similar performance, it will require more parameters). The conversion can still be useful in many situations:

- In PEFT, LoRA supports more features than most other methods, e.g. mixed adapter batches. Thus the converted
  adapter can be used with those features.
- Some downstream packages support LoRA adapters, but not other PEFT methods, e.g. Diffusers. The conversion allows
  to use a non-LoRA adapter with those packages.

The LoRA scaling factor is already baked into the LoRA weights, thus the scaling will always be one (i.e. rank and
alpha are chosen to be identical).

Note: This function does not support sharded models (yet).

Args:
    model:
        The model to be converted. Should be a model that has PEFT layers that support conversion.
    rank (`int` or `float`):
        The desired rank for the returned LoRA adapter. A higher rank results in a LoRA adapter that more
        accurately mirrors the original adapter. It will, however, also require more memory, compute, and disk
        space. Therefore, choose a value that represents the best trade off for your use case and validate the
        final adapter. If a float is passed, it is interpreted as an explained variance / energy threshold: we pick
        the smallest rank k such that the top k singular values account for at least that fraction of the total
        squared singular values. This effectively results in lower ranks being assigned if a few singular can
        capture the adaptation of this layer. A lower float means the rank is lower and vice versa. Be aware that
        dynamic ranks can lead to very unequal ranks per layer, which means that some layers may require a
        disproportionally high amount of memory for activations. Choosing a fixed (int) rank is better to achieve
        predictable memory requirement.
    adapter_name (`str`, *optional*):
        The name of the adapter to be converted. Can only convert a single adapter at a time. Defaults to
        `"default"`.
    progressbar (`bool`):
        whether to show a progressbar indicating the progress of the conversion (it can take a few minutes for big
        models).
    compile_kwargs (`dict`, *optional*):
        If provided, compile the function to convert individual modules to LoRA with the given kwargs being passed
        to `torch.compile`. This can potentially speed up the conversion on large models.

Returns:
    lora_config (`LoraConfig`)
        The `LoraConfig` that corresponds to the converted LoRA adapter.
    state_dict (`dict[str, torch.Tensor]`)
        The `state_dict` containing the LoRA weights.

Raises
    TypeError:
        If the provided model does not have any layers that can be converted to LoRA, a `TypeError` is raised.
    ValueError:
        If an invalid rank was chosen (too high or too low).
r   )ÚPeftTyper	   zYIf rank is a float, it is interpreted as a threshold. It must be between 0 and 1 but got Ú.zBPassing a rank of 0 doesn't make sense, please pass a valid value.z@Some module types on this model do not support LoRA conversion: z, z9Could not detect any layer that supports LoRA conversion.Úpeft_configNzfConverting a PEFT adapter to LoRA that is already a LoRA adapter. There is typically no need for that.ÚbiasÚ	lora_biasÚnonezThe adapter's config sets bias=z", this is not supported right now.zbase_model.model.)Úrank_patternÚalpha_patternÚexclude_modulesÚtarget_modulesÚbase_model_name_or_pathÚlayers_patternÚlayers_to_transform)ÚrÚ
lora_alpha)rH   rD   zConverting to LoRA)ÚdisableÚdescr   r$   zModule of type zŒ does not have a get_delta_weight method, which is required for conversion. Please open an issue: https://github.com/huggingface/peft/issues)r    r!   z.lora_A.weightz.lora_B.weightz†Did not convert a single layer, this means that something went wrong. Please open an issue: https://github.com/huggingface/peft/issuesÚmodules_to_savez.modules_to_save.© ).Úpeftr;   r)   r&   r   Úmodulesr   Úsupports_lora_conversionÚappendÚreprÚtypeÚ	TypeErrorÚjoinÚgetattrÚgetÚ	peft_typeÚLORAÚwarningsÚwarnÚsetr=   ÚcopyrD   rE   ÚhasattrrF   rG   r*   r
   r   Úcompiler7   r   Únamed_modulesrC   ÚaddÚremoveprefixÚstrrA   rB   rL   r   Únamed_parametersÚ	partitionÚ
rpartitionÚdata)r8   r    r!   r9   Úcompile_kwargsr;   Úmodules_not_supporting_loraÚnum_modules_with_supportÚnum_modules_totalr   Úunsupportedr=   Úconfig_biasÚpeft_prefixÚconfig_kwargsÚlora_configÚconvert_module_to_loraÚ
state_dictÚnamer6   r5   r4   Úmodule_nameÚ
param_nameÚparamÚprefixÚ_Úsuffixs                               r   Úconvert_to_lorarz   Q   sÜ  € õB ô �$œ×Ñ¨¨D­°A­ÜØgÐhlÐgmÐmnÐoó
ð 	
ð 
�‹ÜÐ]Ó^Ð^ð #%ÐØ ÐØÐØ—-‘-–/ˆØ˜QÑÐÜ˜&¤.×1Ñ1Ùà×*Ñ*¨<×8Ñ8Ø$¨Ñ)Ò$à'×.Ñ.¨vÖ6ñ "ñ 5PÓPÒ4O¨&”4œ˜V›Ö%Ñ4O€KÐPÞÜÐZÐ[_×[dÑ[dÐepÓ[qÐZrÐrsÐtÓuÐuà 1Ó$ÜÐSÓTÐTä˜% °Ó3×7Ñ7¸ÓE€KØÑ k×&;Ñ&;¸x¿}¹}Ó&LÜ�ŠØtô	
ô ˜+ v¬w°{ÀKÐQWÓ/XÓY€KØ�fÓäÐ:¸;¸-ÐGiÐjÓkÐkð &€KàØÜ›5ñ€Mð Ñà×'Ñ'¨Ñ5ˆÜ*.¯)ª)°K×4NÑ4NÓ*OˆÐ&Ñ'Ø3>×3VÑ3VˆÐ/Ñ0Ü�;Ð 0×1Ñ1à.9×.HÑ.HˆMÐ*Ñ+Ø3>×3RÑ3RˆMÐ/Ñ0Ü�dœC× Ñ ä$ÐN tÑNÀÑN‰Kô %ÐH q°QÑH¸-ÑH‰Kô !ð 
Ü  ¤s×+Ñ+‰d°Øñ
ð ñ
ˆð Ñ!Ü!&§¢Ô/FÑ!YÈ.Ñ!YÑä!8Ðð €JÜØ×ÑÓ¨;¤Ð=QÐYjõ‰ˆˆfô ˜&¤.×1Ñ1ÙÜ�vÐ1×2Ñ2ô Ø!¤$ v£, ð 0_ð _óð ñ
 *@ÀÐ`lÑ)mÑ&ˆ�˜Ø˜QÓð ×'Ñ'×+Ñ+¨D×,=Ñ,=¸kÓ,JÔKÙð ˜dÓ"¤z°+×2LÑ2LÌc×'RÑ'Rð HVˆK×$Ñ$ T×%6Ñ%6°{Ó%CÑDØHVˆK×%Ñ% d×&7Ñ&7¸Ó&DÒEð ×&Ñ&×*Ñ*¨4×+<Ñ+<¸[Ó+IÔJð /5ˆ
�d�V˜>Ð*Ñ+Ø.4ˆ
�d�V˜>Ð*Ô+ñEöH äð9ó
ð 	
ð 	Ñ¤W¨[Ð:KÈT×%RÑ%Rä&*§i¢i°×0KÑ0KÓ&LˆÔ#à#(×#6Ñ#6Ö#8ÑˆK˜Ü˜&Ô"6×7Ó7Ø)/×)?Ñ)?×)PÑ)PÖ)RÑ%�J à#.×#8Ñ#8Ð9LÓ#M‘L�F˜A˜qà#-×#8Ñ#8¸Ó#=‘L�A�q˜&Ø7<·z±z�J & ¨¨6¨(Ð3Ó4ó *Sñ $9ð ˜
Ð"Ð"ùòu Qs   Â6R0Úpathc                 óø   • [         R                  " U 5      n U R                  5       (       d  [        R                  " U 5        [        XX4US9u  pg[        Xp[        -  5        UR                  [        U 5      5        g)aÚ  
Convert a non-LoRA model with PEFT layers to a LoRA, then save the checkpoint file and PEFT config.

This is only supported for some specific PEFT methods that allow an equivalent conversion. Essentially, this comes
down to PEFT methods that work by updating the base weight with a delta weight. Also, right now, only linear layers
are supported.

The LoRA adapter will try to approximate the initial adapter as close as possible. The higher the rank, the better
the approximation. It is expected that the approximation will never reach the full performance of the original
adapter, and that the parameter efficiency of the LoRA adapter will be less than that of the original adapter (i.e.
for a similar performance, it will require more parameters). The conversion can still be useful in many situations:

- In PEFT, LoRA supports more features than most other methods, e.g. mixed adapter batches. Thus the converted
  adapter can be used with those features.
- Some downstream packages support LoRA adapters, but not other PEFT methods, e.g. Diffusers. The conversion allows
  to use a non-LoRA adapter with those packages.

The LoRA scaling factor is already baked into the LoRA weights, thus the scaling will always be one (i.e. rank and
alpha are chosen to be identical).

You can load the converted LoRA weight like this:

```py
>>> lora_path = ...
>>> save_as_lora(lora_path, model, rank=...)
>>> base_model = AutoModel.from_pretrained(...)
>>> lora_model = PeftModel.from_pretrained(base_model, lora_path)
```

Note: This function does not support sharded models (yet).

Args:
    model:
        The model to be converted. Should be a model that has PEFT layers that support conversion.
    rank (`int` or `float`):
        The desired rank for the returned LoRA adapter. A higher rank results in a LoRA adapter that more
        accurately mirrors the original adapter. It will, however, also require more memory, compute, and disk
        space. Therefore, choose a value that represents the best trade off for your use case and validate the
        final adapter. If a float is passed, it is interpreted as an explained variance / energy threshold: we pick
        the smallest rank k such that the top k singular values account for at least that fraction of the total
        squared singular values. This effectively results in lower ranks being assigned if a few singular can
        capture the adaptation of this layer. A lower float means the rank is lower and vice versa. Be aware that
        dynamic ranks can lead to very unequal ranks per layer, which means that some layers may require a
        disproportionally high amount of memory for activations. Choosing a fixed (int) rank is better to achieve
        predictable memory requirement.
    adapter_name (`str`, *optional*):
        The name of the adapter to be converted. Can only convert a single adapter at a time. Defaults to
        `"default"`.
    progressbar (`bool`):
        whether to show a progressbar indicating the progress of the conversion (it can take a few minutes for big
        models).
    compile_kwargs (`dict`, *optional*):
        If provided, compile the function to convert individual modules to LoRA with the given kwargs being passed
        to `torch.compile`. This can potentially speed up the conversion on large models.

Raises
    TypeError:
        If the provided model does not have any layers that can be converted to LoRA, a `TypeError` is raised.
    ValueError:
        If an invalid rank was chosen (too high or too low).
)r    r!   r9   rh   N)
ÚpathlibÚPathÚexistsÚosÚmakedirsrz   r   r   Úsave_pretrainedrc   )r{   r8   r    r!   r9   rh   rp   rr   s           r   Úsave_as_lorarƒ   *  sa   € ôJ �<Š<˜Ó€DØ�;‰;�=‰=Ü
�Š�DÔä-Ø |Ð]kñÑ€Kô ˆjÔ!9Ñ9Ô:Ø×Ñ¤ D£	Õ*r   )Údefault)r„   FN)!r]   r€   r}   rZ   r   Úsafetensors.torchr   r   Útransformers.pytorch_utilsr   Úpeft.tuners.tuners_utilsr   Ú
peft.utilsr   Úpeft.utils.otherr   Úconfigr
   ÚTensorr&   r*   r   Úno_gradrc   Útupler7   ÚnnÚModuleÚboolÚdictrz   ÚPathLikerƒ   rM   r   r   Ú<module>r“      sr  ðó Û 	Û Û ã Ý 'Ý Ý -å 3Ý /Ý 1å ð˜%Ÿ,™,ð °5ð ¸Sô ð  ‡‚ƒàCLñDØðDØ"%¨¡+ðDØ=@ðDà
ˆ5�<‰<˜Ÿ™ sÐ*Ñ+ôDó ðDðF "ØØñV#Ø�8‰8�?‰?ðV#à
�‰+ðV#ð ðV#ð ð	V#ð ˆ:�t˜C §¡Ð-Ñ.Ð.Ñ/õV#ðz "ØØñM+Ø
�—‘Ñ
ðM+à�8‰8�?‰?ðM+ð �‰+ðM+ð ð	M+ð
 ðM+ð 
öM+r   