§
    [zniª{  ã                   ó  — d Z ddlZddlZddlmZ ddlmZmZmZm	Z	m
Z
 ddlZddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ  ej        e¦  «        Zd4d„Zd5dedefd„Zdefd„Zdedefd„Zd5dededefd„Z dededefd„Z!d5d„Z"dededede#fd„Z$	 d6dededede#def
d„Z%dedededefd„Z&	 d7dededededef
d„Z'dededede#d e#d!efd"„Z(	 d8d%„Z)dd&œdeded'efd(„Z*	 d9deded'edefd)„Z+ej,        e"ej-        e%ej.        e'ej/        e)ej0        eej1        e ej2        e+ej3        eiZ4	 	 d:d*e
e5ef         dedee         dee         fd+„Z6 G d,„ d-e¦  «        Z7 G d.„ d/e¦  «        Z8 G d0„ d1e¦  «        Z9d;d3„Z:dS )<z$PyTorch optimization for BERT model.é    N)Úpartial)ÚCallableÚIterableÚOptionalÚTupleÚUnion)Únn)Ú	Optimizer)ÚLambdaLRÚReduceLROnPlateaué   )ÚSchedulerType)Úlogging)Úrequire_versionc                 ó   — dS ©Nr   © )Ú_s    úy/var/www/html/cool-property-finder/image-detection-backend/venv/lib/python3.11/site-packages/transformers/optimization.pyÚ_get_constant_lambdar   #   s   € Øˆ1ó    éÿÿÿÿÚ	optimizerÚ
last_epochc                 ó0   — t          | t          |¬¦  «        S )a²  
    Create a schedule with a constant learning rate, using the learning rate set in optimizer.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        last_epoch (`int`, *optional*, defaults to -1):
            The index of the last epoch when resuming training.

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
    ©r   )r   r   )r   r   s     r   Úget_constant_scheduler   '   s   € õ �IÕ3À
ÐKÑKÔKÐKr   c                 ó    — t          | ¦  «        S )aL  
    Create a schedule with a constant learning rate that decreases when a metric has stopped improving.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.

    Return:
        `torch.optim.lr_scheduler.ReduceLROnPlateau` with the appropriate schedule.
    )r   )r   s    r   Úget_reduce_on_plateau_scheduler   8   s   € õ ˜YÑ'Ô'Ð'r   Úcurrent_stepÚnum_warmup_stepsc                ól   — | |k     r-t          | ¦  «        t          t          d|¦  «        ¦  «        z  S dS )Nç      ð?©ÚfloatÚmax)r    r!   s     r   Ú,_get_constant_schedule_with_warmup_lr_lambdar'   G   s9   € ØÐ&Ò&Ð&Ý�\Ñ"Ô"¥U­3¨sÐ4DÑ+EÔ+EÑ%FÔ%FÑFÐFØˆ3r   c                 óR   — t          t          |¬¦  «        }t          | ||¬¦  «        S )ad  
    Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate
    increases linearly between 0 and the initial lr set in the optimizer.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        num_warmup_steps (`int`):
            The number of steps for the warmup phase.
        last_epoch (`int`, *optional*, defaults to -1):
            The index of the last epoch when resuming training.

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
    ©r!   r   )r   r'   r   )r   r!   r   Ú	lr_lambdas       r   Ú!get_constant_schedule_with_warmupr+   M   s-   € õ" ÕDÐWgÐhÑhÔh€IÝ�I˜y°ZÐ@Ñ@Ô@Ð@r   Únum_training_stepsc                óê   — | |k     r-t          | ¦  «        t          t          d|¦  «        ¦  «        z  S t          dt          || z
  ¦  «        t          t          d||z
  ¦  «        ¦  «        z  ¦  «        S )Nr   ç        r$   )r    r!   r,   s      r   Ú*_get_linear_schedule_with_warmup_lr_lambdar/   b   sp   € ØÐ&Ò&Ð&Ý�\Ñ"Ô"¥U­3¨qÐ2BÑ+CÔ+CÑ%DÔ%DÑDÐDÝˆs•EÐ,¨|Ñ;Ñ<Ô<½uÅSÈÐL^ÐaqÑLqÑErÔErÑ?sÔ?sÑsÑtÔtÐtr   c                 óR   — t          t          ||¬¦  «        }t          | ||¦  «        S )aÝ  
    Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after
    a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        num_warmup_steps (`int`):
            The number of steps for the warmup phase.
        num_training_steps (`int`):
            The total number of training steps.
        last_epoch (`int`, *optional*, defaults to -1):
            The index of the last epoch when resuming training.

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
    ©r!   r,   )r   r/   r   )r   r!   r,   r   r*   s        r   Úget_linear_schedule_with_warmupr2   h   s5   € õ& Ý2Ø)Ø-ðñ ô €Iõ
 �I˜y¨*Ñ5Ô5Ð5r   Ú
num_cyclesc                ó^  — | |k     r-t          | ¦  «        t          t          d|¦  «        ¦  «        z  S t          | |z
  ¦  «        t          t          d||z
  ¦  «        ¦  «        z  }t          dddt          j        t          j        t          |¦  «        z  dz  |z  ¦  «        z   z  ¦  «        S )Nr   r.   ç      à?r#   g       @©r%   r&   ÚmathÚcosÚpi©r    r!   r,   r3   Úprogresss        r   Ú*_get_cosine_schedule_with_warmup_lr_lambdar<   ƒ   s¤   € ð Ð&Ò&Ð&Ý�\Ñ"Ô"¥U­3¨qÐ2BÑ+CÔ+CÑ%DÔ%DÑDÐDÝ�\Ð$4Ñ4Ñ5Ô5½½cÀ!ÐEWÐZjÑEjÑ>kÔ>kÑ8lÔ8lÑl€HÝˆs�C˜3¥¤­$¬'µE¸*Ñ4EÔ4EÑ*EÈÑ*KÈhÑ*VÑ!WÔ!WÑWÑXÑYÔYÐYr   r5   c                 óT   — t          t          |||¬¦  «        }t          | ||¦  «        S )aÝ  
    Create a schedule with a learning rate that decreases following the values of the cosine function between the
    initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the
    initial lr set in the optimizer.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        num_warmup_steps (`int`):
            The number of steps for the warmup phase.
        num_training_steps (`int`):
            The total number of training steps.
        num_cycles (`float`, *optional*, defaults to 0.5):
            The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0
            following a half-cosine).
        last_epoch (`int`, *optional*, defaults to -1):
            The index of the last epoch when resuming training.

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
    ©r!   r,   r3   )r   r<   r   ©r   r!   r,   r3   r   r*   s         r   Úget_cosine_schedule_with_warmupr@   Œ   s8   € õ2 Ý2Ø)Ø-Øð	ñ ô €Iõ �I˜y¨*Ñ5Ô5Ð5r   c                ón  — | |k     r-t          | ¦  «        t          t          d|¦  «        ¦  «        z  S t          | |z
  ¦  «        t          t          d||z
  ¦  «        ¦  «        z  }|dk    rdS t          dddt          j        t          j        t          |¦  «        |z  dz  z  ¦  «        z   z  ¦  «        S )Nr   r#   r.   r5   r6   r:   s        r   Ú=_get_cosine_with_hard_restarts_schedule_with_warmup_lr_lambdarB   ®   s³   € ð Ð&Ò&Ð&Ý�\Ñ"Ô"¥U­3¨qÐ2BÑ+CÔ+CÑ%DÔ%DÑDÐDÝ�\Ð$4Ñ4Ñ5Ô5½½cÀ!ÐEWÐZjÑEjÑ>kÔ>kÑ8lÔ8lÑl€HØ�3‚€ØˆsÝˆs�C˜3¥¤­$¬'µe¸JÑ6GÔ6GÈ(Ñ6RÐVYÑ5YÑ*ZÑ![Ô![Ñ[Ñ\Ñ]Ô]Ð]r   c                 óT   — t          t          |||¬¦  «        }t          | ||¦  «        S )aŽ  
    Create a schedule with a learning rate that decreases following the values of the cosine function between the
    initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases
    linearly between 0 and the initial lr set in the optimizer.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        num_warmup_steps (`int`):
            The number of steps for the warmup phase.
        num_training_steps (`int`):
            The total number of training steps.
        num_cycles (`int`, *optional*, defaults to 1):
            The number of hard restarts to use.
        last_epoch (`int`, *optional*, defaults to -1):
            The index of the last epoch when resuming training.

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
    r>   )r   rB   r   r?   s         r   Ú2get_cosine_with_hard_restarts_schedule_with_warmuprD   ¹   s8   € õ0 ÝEØ)Ø-Øð	ñ ô €Iõ �I˜y¨*Ñ5Ô5Ð5r   Úlr_endÚpowerÚlr_initc                óÈ   — | |k     r-t          | ¦  «        t          t          d|¦  «        ¦  «        z  S | |k    r||z  S ||z
  }||z
  }d| |z
  |z  z
  }|||z  z  |z   }	|	|z  S r   r$   )
r    r!   r,   rE   rF   rG   Úlr_rangeÚdecay_stepsÚpct_remainingÚdecays
             r   Ú4_get_polynomial_decay_schedule_with_warmup_lr_lambdarM   Ú   s•   € ð Ð&Ò&Ð&Ý�\Ñ"Ô"¥U­3¨qÐ2BÑ+CÔ+CÑ%DÔ%DÑDÐDØ	Ð*Ò	*Ð	*Ø˜ÑÐà˜VÑ#ˆØ(Ð+;Ñ;ˆØ˜\Ð,<Ñ<ÀÑKÑKˆØ˜=¨%Ñ/Ñ/°&Ñ8ˆØ�w‰Ðr   çH¯¼šò×z>r#   c                 óª   — | j         d         }||k    st          d|› d|› d�¦  «        ‚t          t          |||||¬¦  «        }t	          | ||¦  «        S )a�  
    Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the
    optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the
    initial lr set in the optimizer.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        num_warmup_steps (`int`):
            The number of steps for the warmup phase.
        num_training_steps (`int`):
            The total number of training steps.
        lr_end (`float`, *optional*, defaults to 1e-7):
            The end LR.
        power (`float`, *optional*, defaults to 1.0):
            Power factor.
        last_epoch (`int`, *optional*, defaults to -1):
            The index of the last epoch when resuming training.

    Note: *power* defaults to 1.0 as in the fairseq implementation, which in turn is based on the original BERT
    implementation at
    https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/optimization.py#L37

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.

    Úlrzlr_end (z&) must be be smaller than initial lr (ú))r!   r,   rE   rF   rG   )ÚdefaultsÚ
ValueErrorr   rM   r   )r   r!   r,   rE   rF   r   rG   r*   s           r   Ú)get_polynomial_decay_schedule_with_warmuprT   ï   sy   € ð> Ô  Ô&€GØ�fÒÐÝÐ\ FÐ\Ð\ÐRYÐ\Ð\Ð\Ñ]Ô]Ð]åÝ<Ø)Ø-ØØØðñ ô €Iõ �I˜y¨*Ñ5Ô5Ð5r   )Ú	timescalerU   c                ó°   — | |k     r-t          | ¦  «        t          t          d|¦  «        ¦  «        z  S ||z
  }dt          j        | |z   |z  ¦  «        z  }|S )Nr   r#   )r%   r&   r7   Úsqrt)r    r!   rU   ÚshiftrL   s        r   Ú$_get_inverse_sqrt_schedule_lr_lambdarY     sb   € ØÐ&Ò&Ð&Ý�\Ñ"Ô"¥U­3¨qÐ2BÑ+CÔ+CÑ%DÔ%DÑDÐDØÐ(Ñ(€EØ•$”)˜\¨EÑ1°YÑ>Ñ?Ô?Ñ?€EØ€Lr   c                 ó\   — |€|}t          t          ||¬¦  «        }t          | ||¬¦  «        S )aÚ  
    Create a schedule with an inverse square-root learning rate, from the initial lr set in the optimizer, after a
    warmup period which increases lr linearly from 0 to the initial lr set in the optimizer.

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        num_warmup_steps (`int`):
            The number of steps for the warmup phase.
        timescale (`int`, *optional*, defaults to `num_warmup_steps`):
            Time scale.
        last_epoch (`int`, *optional*, defaults to -1):
            The index of the last epoch when resuming training.

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
    N)r!   rU   r   )r   rY   r   )r   r!   rU   r   r*   s        r   Úget_inverse_sqrt_scheduler[   %  s;   € ð. ÐØ$ˆ	åÕ<ÐO_ÐktÐuÑuÔu€IÝ�I˜y°ZÐ@Ñ@Ô@Ð@r   Únamec                 óp  — t          | ¦  «        } t          |          }| t           j        k    s| t           j        k    r ||¦  «        S |€t	          | › d�¦  «        ‚| t           j        k    r |||¬¦  «        S | t           j        k    r |||¬¦  «        S |€t	          | › d�¦  «        ‚ ||||¬¦  «        S )a  
    Unified API to get any scheduler from its name.

    Args:
        name (`str` or `SchedulerType`):
            The name of the scheduler to use.
        optimizer (`torch.optim.Optimizer`):
            The optimizer that will be used during training.
        num_warmup_steps (`int`, *optional*):
            The number of warmup steps to do. This is not required by all schedulers (hence the argument being
            optional), the function will raise an error if it's unset and the scheduler type requires it.
        num_training_steps (`int``, *optional*):
            The number of training steps to do. This is not required by all schedulers (hence the argument being
            optional), the function will raise an error if it's unset and the scheduler type requires it.
    Nz; requires `num_warmup_steps`, please provide that argument.r)   z= requires `num_training_steps`, please provide that argument.r1   )r   ÚTYPE_TO_SCHEDULER_FUNCTIONÚCONSTANTÚREDUCE_ON_PLATEAUrS   ÚCONSTANT_WITH_WARMUPÚINVERSE_SQRT)r\   r   r!   r,   Úschedule_funcs        r   Úget_schedulerrd   O  så   € õ* ˜ÑÔ€DÝ.¨tÔ4€MØ�}Ô%Ò%Ð%¨µÔ1PÒ)PÐ)PØˆ}˜YÑ'Ô'Ð'ð ÐÝ˜DÐ]Ð]Ð]Ñ^Ô^Ð^à�}Ô1Ò1Ð1Øˆ}˜YÐ9IÐJÑJÔJÐJà�}Ô)Ò)Ð)Øˆ}˜YÐ9IÐJÑJÔJÐJð Ð!Ý˜DÐ_Ð_Ð_Ñ`Ô`Ð`àˆ=˜Ð5EÐZlÐmÑmÔmÐmr   c                   ó¶   ‡ — e Zd ZdZ	 	 	 	 	 	 ddeej        j                 d	ed
e	eef         dedede
de
fˆ fd„Z ej        ¦   «         ddefd„¦   «         Zˆ xZS )ÚAdamWa;  
    Implements Adam algorithm with weight decay fix as introduced in [Decoupled Weight Decay
    Regularization](https://arxiv.org/abs/1711.05101).

    Parameters:
        params (`Iterable[nn.parameter.Parameter]`):
            Iterable of parameters to optimize or dictionaries defining parameter groups.
        lr (`float`, *optional*, defaults to 0.001):
            The learning rate to use.
        betas (`Tuple[float,float]`, *optional*, defaults to `(0.9, 0.999)`):
            Adam's betas parameters (b1, b2).
        eps (`float`, *optional*, defaults to 1e-06):
            Adam's epsilon for numerical stability.
        weight_decay (`float`, *optional*, defaults to 0.0):
            Decoupled weight decay to apply.
        correct_bias (`bool`, *optional*, defaults to `True`):
            Whether or not to correct bias in Adam (for instance, in Bert TF repository they use `False`).
        no_deprecation_warning (`bool`, *optional*, defaults to `False`):
            A flag used to disable the deprecation warning (set to `True` to disable the warning).
    çü©ñÒMbP?©gÍÌÌÌÌÌì?g+‡ÙÎ÷ï?ç�íµ ÷Æ°>r.   TFÚparamsrP   ÚbetasÚepsÚweight_decayÚcorrect_biasÚno_deprecation_warningc                 óÎ  •— |st          j        dt          ¦  «         t          d¦  «         |dk     rt	          d|› d�¦  «        ‚d|d         cxk    rdk     sn t	          d|d         › d	�¦  «        ‚d|d
         cxk    rdk     sn t	          d|d
         › d	�¦  «        ‚d|k    st	          d|› d�¦  «        ‚|||||dœ}t          ¦   «                              ||¦  «         d S )NzÊThis implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warningútorch>=1.5.0r.   zInvalid learning rate: z - should be >= 0.0r   r#   zInvalid beta parameter: z - should be in [0.0, 1.0)r   zInvalid epsilon value: )rP   rk   rl   rm   rn   )ÚwarningsÚwarnÚFutureWarningr   rS   ÚsuperÚ__init__)
Úselfrj   rP   rk   rl   rm   rn   ro   rR   Ú	__class__s
            €r   rv   zAdamW.__init__�  s7  ø€ ð &ð 	ÝŒMðõ ñ	ô ð õ 	˜Ñ'Ô'Ð'Ø�Š8ˆ8ÝÐN°rÐNÐNÐNÑOÔOÐOØ�e˜A”hÐ$Ð$Ò$Ð$ Ò$Ð$Ð$Ð$ÝÐ\¸¸a¼Ð\Ð\Ð\Ñ]Ô]Ð]Ø�e˜A”hÐ$Ð$Ò$Ð$ Ò$Ð$Ð$Ð$ÝÐ\¸¸a¼Ð\Ð\Ð\Ñ]Ô]Ð]Ø�cŠzˆzÝÐO°sÐOÐOÐOÑPÔPÐPØ u°SÈ,ÐhtÐuÐuˆÝ‰Œ×Ò˜ Ñ*Ô*Ð*Ð*Ð*r   NÚclosurec                 óÎ  — d}|�
 |¦   «         }| j         D �]Í}|d         D �]À}|j        €Œ|j        }|j        rt          d¦  «        ‚| j        |         }t          |¦  «        dk    r3d|d<   t          j        |¦  «        |d<   t          j        |¦  «        |d<   |d         |d         }}|d         \  }	}
|dxx         d	z  cc<   |                     |	¦  «         	                    |d
|	z
  ¬¦  «         |                     |
¦  «         
                    ||d
|
z
  ¬¦  «         |                     ¦   «          	                    |d         ¦  «        }|d         }|d         r6d
|	|d         z  z
  }d
|
|d         z  z
  }|t          j        |¦  «        z  |z  }|                     ||| ¬¦  «         |d         dk    r'| 	                    ||d          |d         z  ¬¦  «         �ŒÂ�ŒÏ|S )z³
        Performs a single optimization step.

        Arguments:
            closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss.
        Nrj   zJAdam does not support sparse gradients, please consider SparseAdam insteadr   ÚstepÚexp_avgÚ
exp_avg_sqrk   r   r#   ©Úalpha)Úvaluerl   rP   rn   rm   r.   )Úparam_groupsÚgradÚ	is_sparseÚRuntimeErrorÚstateÚlenÚtorchÚ
zeros_likeÚmul_Úadd_Úaddcmul_rW   r7   Úaddcdiv_)rw   ry   ÚlossÚgroupÚpr‚   r…   r|   r}   Úbeta1Úbeta2ÚdenomÚ	step_sizeÚbias_correction1Úbias_correction2s                  r   r{   z
AdamW.step­  s&  € ð ˆØÐØ�7‘9”9ˆDàÔ&ð .	Lñ .	LˆEØ˜8”_ð -Lñ -L�Ø”6�>ØØ”v�Ø”>ð uÝ&Ð'sÑtÔtÐtàœ
 1œ�õ �u‘:”: ’?�?Ø$%�E˜&‘Må',Ô'7¸Ñ':Ô':�E˜)Ñ$å*/Ô*:¸1Ñ*=Ô*=�E˜,Ñ'à&+¨IÔ&6¸¸lÔ8K˜�Ø$ Wœ~‘��uà�f��” Ñ"��‘ð —’˜UÑ#Ô#×(Ò(¨°c¸E±kÐ(ÑCÔCÐCØ—’ Ñ&Ô&×/Ò/°°dÀ#ÈÁ+Ð/ÑNÔNÐNØ"ŸšÑ)Ô)×.Ò.¨u°U¬|Ñ<Ô<�à! $œK�	Ø˜Ô(ð [Ø'*¨U°e¸F´mÑ-CÑ'CÐ$Ø'*¨U°e¸F´mÑ-CÑ'CÐ$Ø )­D¬IÐ6FÑ,GÔ,GÑ GÐJZÑ Z�Ià—
’
˜7 E°)°�
Ñ<Ô<Ð<ð ˜Ô(¨3Ò.Ð.Ø—F’F˜1 e¨D¤k \°E¸.Ô4IÑ%I�FÑKÔKÐKùñ[-Lð^ ˆr   )rg   rh   ri   r.   TF©N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r	   Ú	parameterÚ	Parameterr%   r   Úboolrv   r‡   Úno_gradr   r{   Ú__classcell__©rx   s   @r   rf   rf   z  së   ø€ € € € € ðð ð0 Ø%1ØØ!Ø!Ø',ð+ð +à˜œÔ/Ô0ð+ð ð+ð �U˜E�\Ô"ð	+ð
 ð+ð ð+ð ð+ð !%ð+ð +ð +ð +ð +ð +ð: €U„]�_„_ð;ð ;˜Hð ;ð ;ð ;ñ „_ð;ð ;ð ;ð ;ð ;r   rf   c                   óÀ   ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 dˆ fd	„	Zed
„ ¦   «         Zed„ ¦   «         Zed„ ¦   «         Zed„ ¦   «         Z	 e
j        ¦   «         dd„¦   «         Zˆ xZS )Ú	Adafactora)  
    AdaFactor pytorch implementation can be used as a drop in replacement for Adam original fairseq code:
    https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py

    Paper: *Adafactor: Adaptive Learning Rates with Sublinear Memory Cost* https://arxiv.org/abs/1804.04235 Note that
    this optimizer internally adjusts the learning rate depending on the `scale_parameter`, `relative_step` and
    `warmup_init` options. To use a manual (external) learning rate schedule you should set `scale_parameter=False` and
    `relative_step=False`.

    Arguments:
        params (`Iterable[nn.parameter.Parameter]`):
            Iterable of parameters to optimize or dictionaries defining parameter groups.
        lr (`float`, *optional*):
            The external learning rate.
        eps (`Tuple[float, float]`, *optional*, defaults to `(1e-30, 0.001)`):
            Regularization constants for square gradient and parameter scale respectively
        clip_threshold (`float`, *optional*, defaults to 1.0):
            Threshold of root mean square of final gradient update
        decay_rate (`float`, *optional*, defaults to -0.8):
            Coefficient used to compute running averages of square
        beta1 (`float`, *optional*):
            Coefficient used for computing running averages of gradient
        weight_decay (`float`, *optional*, defaults to 0.0):
            Weight decay (L2 penalty)
        scale_parameter (`bool`, *optional*, defaults to `True`):
            If True, learning rate is scaled by root mean square
        relative_step (`bool`, *optional*, defaults to `True`):
            If True, time-dependent learning rate is computed instead of external learning rate
        warmup_init (`bool`, *optional*, defaults to `False`):
            Time-dependent learning rate computation depends on whether warm-up initialization is being used

    This implementation handles low-precision (FP16, bfloat) values, but we have not thoroughly tested.

    Recommended T5 finetuning settings (https://discuss.huggingface.co/t/t5-finetuning-tips/684/3):

        - Training without LR warmup or clip_threshold is not recommended.

           - use scheduled LR warm-up to fixed LR
           - use clip_threshold=1.0 (https://arxiv.org/abs/1804.04235)
        - Disable relative updates
        - Use scale_parameter=False
        - Additional optimizer operations like gradient clipping should not be used alongside Adafactor

    Example:

    ```python
    Adafactor(model.parameters(), scale_parameter=False, relative_step=False, warmup_init=False, lr=1e-3)
    ```

    Others reported the following combination to work well:

    ```python
    Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None)
    ```

    When using `lr=None` with [`Trainer`] you will most likely need to use [`~optimization.AdafactorSchedule`]
    scheduler as following:

    ```python
    from transformers.optimization import Adafactor, AdafactorSchedule

    optimizer = Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None)
    lr_scheduler = AdafactorSchedule(optimizer)
    trainer = Trainer(..., optimizers=(optimizer, lr_scheduler))
    ```

    Usage:

    ```python
    # replace AdamW with Adafactor
    optimizer = Adafactor(
        model.parameters(),
        lr=1e-3,
        eps=(1e-30, 1e-3),
        clip_threshold=1.0,
        decay_rate=-0.8,
        beta1=None,
        weight_decay=0.0,
        relative_step=False,
        scale_parameter=False,
        warmup_init=False,
    )
    ```N©g ÂëþKH´9rg   r#   çš™™™™™é¿r.   TFc           
      óÎ   •— t          d¦  «         |�|	rt          d¦  «        ‚|
r|	st          d¦  «        ‚||||||||	|
dœ	}t          ¦   «                              ||¦  «         d S )Nrq   z;Cannot combine manual `lr` and `relative_step=True` optionsz0`warmup_init=True` requires `relative_step=True`)	rP   rl   Úclip_thresholdÚ
decay_rater�   rm   Úscale_parameterÚrelative_stepÚwarmup_init)r   rS   ru   rv   )rw   rj   rP   rl   r¦   r§   r�   rm   r¨   r©   rª   rR   rx   s               €r   rv   zAdafactor.__init__A  s–   ø€ õ 	˜Ñ'Ô'Ð'Øˆ>˜mˆ>ÝÐZÑ[Ô[Ð[Øð 	Q˜}ð 	QÝÐOÑPÔPÐPð ØØ,Ø$ØØ(Ø.Ø*Ø&ð

ð 

ˆõ 	‰Œ×Ò˜ Ñ*Ô*Ð*Ð*Ð*r   c                 ó  — | d         }| d         r@| d         rd|d         z  nd}t          |dt          j        |d         ¦  «        z  ¦  «        }d}| d         r"t          | d	         d
         |d         ¦  «        }||z  S )NrP   r©   rª   ri   r{   g{®Gáz„?r#   r¨   rl   r   ÚRMS)Úminr7   rW   r&   )Úparam_groupÚparam_stateÚrel_step_szÚmin_stepÚparam_scales        r   Ú_get_lrzAdafactor._get_lra  s™   € à! $Ô'ˆØ�Ô'ð 	NØ5@ÀÔ5OÐY�t˜k¨&Ô1Ñ1Ð1ÐUYˆHÝ˜h¨­d¬i¸ÀFÔ8KÑ.LÔ.LÑ(LÑMÔMˆKØˆØÐ(Ô)ð 	IÝ˜k¨%Ô0°Ô3°[ÀÔ5GÑHÔHˆKØ˜[Ñ(Ð(r   c                 óD   — t          |¦  «        dk    }| d         d u}||fS )Né   r�   )r†   )r®   Úparam_shapeÚfactoredÚuse_first_moments       r   Ú_get_optionszAdafactor._get_optionsl  s0   € å�{Ñ#Ô# qÒ(ˆØ& wÔ/°tÐ;ÐØÐ)Ð)Ð)r   c                 ó\   — |                       d¦  «        |                      ¦   «         dz  z  S )Nrµ   r5   )ÚnormÚnumel)Útensors    r   Ú_rmszAdafactor._rmsr  s$   € à�{Š{˜1‰~Œ~ §¢¡¤°3Ñ!6Ñ7Ð7r   c                 óø   — | |                       dd¬¦  «        z                       ¦   «                              d¦  «        }|                     d¦  «                             ¦   «         }t	          j        ||¦  «        S )Nr   T)ÚdimÚkeepdiméþÿÿÿ)ÚmeanÚrsqrt_Ú	unsqueezeÚrsqrtr‡   Úmul)Úexp_avg_sq_rowÚexp_avg_sq_colÚr_factorÚc_factors       r   Ú_approx_sq_gradzAdafactor._approx_sq_gradv  sm   € ð # ^×%8Ò%8¸RÈÐ%8Ñ%NÔ%NÑN×VÒVÑXÔX×bÒbÐceÑfÔfˆØ!×+Ò+¨BÑ/Ô/×5Ò5Ñ7Ô7ˆÝŒy˜ 8Ñ,Ô,Ð,r   c                 ó’	  — d}|�
 |¦   «         }| j         D �]¯}|d         D �]¢}|j        €Œ|j        }|j        t          j        t          j        hv r|                     ¦   «         }|j        rt          d¦  «        ‚| j	        |         }|j
        }|                      ||¦  «        \  }}	t          |¦  «        dk    r­d|d<   |	rt          j        |¦  «        |d<   |rpt          j        |dd…         ¦  «                             |¦  «        |d<   t          j        |dd	…         |dd…         z   ¦  «                             |¦  «        |d
<   nt          j        |¦  «        |d<   d|d<   n}|	r|d                              |¦  «        |d<   |r=|d                              |¦  «        |d<   |d
                              |¦  «        |d
<   n|d                              |¦  «        |d<   |}
|j        t          j        t          j        hv r|
                     ¦   «         }
|dxx         dz  cc<   |                      |
¦  «        |d<   |                      ||¦  «        }dt%          j        |d         |d         ¦  «        z
  }|dz  |d         d         z   }|r¾|d         }|d
         }|                     |¦  «                             |                     d¬¦  «        d|z
  ¬¦  «         |                     |¦  «                             |                     d	¬¦  «        d|z
  ¬¦  «         |                      ||¦  «        }|                     |¦  «         n\|d         }|                     |¦  «                             |d|z
  ¬¦  «         |                     ¦   «                              |¦  «        }|                     |                      |¦  «        |d         z                       d¬¦  «        ¦  «         |                     |¦  «         |	rC|d         }|                     |d         ¦  «                             |d|d         z
  ¬¦  «         |}|d         dk    r!|
                     |
|d          |z  ¬¦  «         |
                     | ¦  «         |j        t          j        t          j        hv r|                     |
¦  «         �Œ¤�Œ±|S )z¾
        Performs a single optimization step

        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        Nrj   z,Adafactor does not support sparse gradients.r   r{   r|   r   rÈ   rÂ   rÉ   r}   r¬   r   r#   r§   rµ   rl   )rÀ   r~   r¦   )r­   r�   rm   )r�   r‚   Údtyper‡   Úfloat16Úbfloat16r%   rƒ   r„   r…   Úshaper¹   r†   rˆ   ÚzerosÚtor¾   r³   r7   Úpowr‰   rŠ   rÃ   rÌ   rÆ   Údiv_Úclamp_Úcopy_)rw   ry   r�   rŽ   r�   r‚   r…   Ú
grad_shaper·   r¸   Úp_data_fp32rP   Úbeta2tÚupdaterÈ   rÉ   r}   r|   s                     r   r{   zAdafactor.step~  sâ  € ð ˆØÐØ�7‘9”9ˆDàÔ&ð M	)ñ M	)ˆEØ˜8”_ð L)ñ L)�Ø”6�>ØØ”v�Ø”:¥%¤-µ´Ð!@Ð@Ð@ØŸ:š:™<œ<�DØ”>ð WÝ&Ð'UÑVÔVÐVàœ
 1œ�Ø!œZ�
à-1×->Ò->¸uÀjÑ-QÔ-QÑ*�Ð*å�u‘:”: ’?�?Ø$%�E˜&‘Mà'ð Bå+0Ô+;¸DÑ+AÔ+A˜˜iÑ(Øð EÝ27´+¸jÈÈ"È¼oÑ2NÔ2N×2QÒ2QÐRVÑ2WÔ2W˜Ð.Ñ/Ý27´+¸jÈÈ"È¼oÐPZÐ[]Ð[^Ð[^ÔP_Ñ>_Ñ2`Ô2`×2cÒ2cÐdhÑ2iÔ2i˜Ð.Ñ/Ð/å.3Ô.>¸tÑ.DÔ.D˜˜lÑ+à#$�E˜%‘L�Là'ð EØ+0°Ô+;×+>Ò+>¸tÑ+DÔ+D˜˜iÑ(Øð KØ27Ð8HÔ2I×2LÒ2LÈTÑ2RÔ2R˜Ð.Ñ/Ø27Ð8HÔ2I×2LÒ2LÈTÑ2RÔ2R˜Ð.Ñ/Ð/à.3°LÔ.A×.DÒ.DÀTÑ.JÔ.J˜˜lÑ+à�Ø”7�uœ}­e¬nÐ=Ð=Ð=Ø"-×"3Ò"3Ñ"5Ô"5�Kà�f��” Ñ"��‘Ø#Ÿyšy¨Ñ5Ô5��e‘Ø—\’\ %¨Ñ/Ô/�à�tœx¨¨f¬°u¸\Ô7JÑKÔKÑK�Ø ™' U¨5¤\°!¤_Ñ4�Øð ;Ø%*Ð+;Ô%<�NØ%*Ð+;Ô%<�Nà"×'Ò'¨Ñ/Ô/×4Ò4°V·[²[ÀR°[Ñ5HÔ5HÐQTÐW]ÑQ]Ð4Ñ_Ô_Ð_Ø"×'Ò'¨Ñ/Ô/×4Ò4°V·[²[ÀR°[Ñ5HÔ5HÐQTÐW]ÑQ]Ð4Ñ_Ô_Ð_ð "×1Ò1°.À.ÑQÔQ�FØ—K’K Ñ%Ô%Ð%Ð%à!& |Ô!4�Jà—O’O FÑ+Ô+×0Ò0°ÀÀfÁÐ0ÑNÔNÐNØ'×-Ò-Ñ/Ô/×4Ò4°TÑ:Ô:�Fà—’˜TŸYšY vÑ.Ô.°Ð7GÔ1HÑH×PÒPÐUXÐPÑYÔYÑZÔZÐZØ—’˜B‘”�à#ð %Ø# IÔ.�GØ—L’L  w¤Ñ0Ô0×5Ò5°fÀQÈÈwÌÑEWÐ5ÑYÔYÐYØ$�Fà˜Ô(¨AÒ-Ð-Ø×$Ò$ [¸%ÀÔ:OÐ9OÐRTÑ9TÐ$ÑVÔVÐVà× Ò  & Ñ)Ô)Ð)à”7�uœ}­e¬nÐ=Ð=Ð=Ø—G’G˜KÑ(Ô(Ð(ùñYL)ð\ ˆr   )	Nr£   r#   r¤   Nr.   TTFr–   )r—   r˜   r™   rš   rv   Ústaticmethodr³   r¹   r¾   rÌ   r‡   rž   r{   rŸ   r    s   @r   r¢   r¢   ì  s  ø€ € € € € ðRð Rðn ØØØØØØØØð+ð +ð +ð +ð +ð +ð@ ð)ð )ñ „\ð)ð ð*ð *ñ „\ð*ð
 ð8ð 8ñ „\ð8ð ð-ð -ñ „\ð-ð €U„]�_„_ð[ð [ð [ñ „_ð[ð [ð [ð [ð [r   r¢   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )ÚAdafactorSchedulea8  
    Since [`~optimization.Adafactor`] performs its own scheduling, if the training loop relies on a scheduler (e.g.,
    for logging), this class creates a proxy object that retrieves the current lr values from the optimizer.

    It returns `initial_lr` during startup and the actual `lr` during stepping.
    r.   c                 ó�   •‡— ˆfd„}|j         D ]}‰|d<   Œt          ¦   «                              ||¦  «         |j         D ]}|d= Œd S )Nc                 ó   •— ‰S r–   r   )r   Ú
initial_lrs    €r   r*   z-AdafactorSchedule.__init__.<locals>.lr_lambdaæ  s	   ø€ ØÐr   rá   )r�   ru   rv   )rw   r   rá   r*   rŽ   rx   s     `  €r   rv   zAdafactorSchedule.__init__å  s   øø€ ð	ð 	ð 	ð 	ð 	ð Ô+ð 	-ð 	-ˆEØ",ˆE�,ÑÐÝ‰Œ×Ò˜ IÑ.Ô.Ð.ØÔ+ð 	$ð 	$ˆEØ�lÐ#Ð#ð	$ð 	$r   c                 óp   ‡— | j         Šˆfd„‰j        D ¦   «         }t          |¦  «        dk    r| j        }|S )Nc                 ó�   •— g | ]B}|d          d         j         ®‰                     |‰j        |d          d                  ¦  «        ‘ŒCS )rj   r   )r‚   r³   r…   )Ú.0rŽ   Úopts     €r   ú
<listcomp>z,AdafactorSchedule.get_lr.<locals>.<listcomp>ñ  sS   ø€ ð 
ð 
ð 
àØ�XŒ˜qÔ!Ô&Ð2ð �KŠK˜˜sœy¨¨x¬¸Ô);Ô<Ñ=Ô=à2Ð2Ð2r   r   )r   r�   r†   Úbase_lrs)rw   Úlrsrå   s     @r   Úget_lrzAdafactorSchedule.get_lrï  sR   ø€ ØŒnˆð
ð 
ð 
ð 
àÔ)ð
ñ 
ô 
ˆõ
 ˆs‰8Œ8�qŠ=ˆ=Ø”-ˆCØˆ
r   ©r.   )r—   r˜   r™   rš   rv   ré   rŸ   r    s   @r   rÞ   rÞ   Ý  sV   ø€ € € € € ðð ð$ð $ð $ð $ð $ð $ð	ð 	ð 	ð 	ð 	ð 	ð 	r   rÞ   r.   c                 ó"   — t          | |¦  «        S )aX  
    Get a proxy schedule for [`~optimization.Adafactor`]

    Args:
        optimizer ([`~torch.optim.Optimizer`]):
            The optimizer for which to schedule the learning rate.
        initial_lr (`float`, *optional*, defaults to 0.0):
            Initial lr

    Return:
        [`~optimization.Adafactor`] proxy schedule object.


    )rÞ   )r   rá   s     r   Úget_adafactor_schedulerì   û  s   € õ ˜Y¨
Ñ3Ô3Ð3r   r–   )r   )r5   r   )r   r   )rN   r#   r   )Nr   )NNrê   );rš   r7   rr   Ú	functoolsr   Útypingr   r   r   r   r   r‡   r	   Útorch.optimr
   Útorch.optim.lr_schedulerr   r   Útrainer_utilsr   Úutilsr   Úutils.versionsr   Ú
get_loggerr—   Úloggerr   Úintr   r   r'   r+   r/   r2   r%   r<   r@   rB   rD   rM   rT   rY   r[   ÚLINEARÚCOSINEÚCOSINE_WITH_RESTARTSÚ
POLYNOMIALr_   ra   rb   r`   r^   Ústrrd   rf   r¢   rÞ   rì   r   r   r   ú<module>rü      sA  ðð +Ð *à €€€Ø €€€Ø Ð Ð Ð Ð Ð Ø =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =à €€€Ø Ð Ð Ð Ð Ð Ø !Ð !Ð !Ð !Ð !Ð !Ø @Ð @Ð @Ð @Ð @Ð @Ð @Ð @à (Ð (Ð (Ð (Ð (Ð (Ø Ð Ð Ð Ð Ð Ø +Ð +Ð +Ð +Ð +Ð +ð 
ˆÔ	˜HÑ	%Ô	%€ðð ð ð ðLð L Yð L¸Cð Lð Lð Lð Lð"(¨ið (ð (ð (ð (ð¸sð ÐY\ð ð ð ð ðAð A°ð AÈcð AÐ_bð Að Að Að Að*u¸Sð uÐWZð uÐpsð uð uð uð uð6ð 6ð 6ð 6ð6ZØðZØ,/ðZØEHðZØV[ðZð Zð Zð Zð vxð6ð 6Øð6Ø,/ð6ØEHð6ØV[ð6Øorð6ð 6ð 6ð 6ðD^Øð^Ø,/ð^ØEHð^ØVYð^ð ^ð ^ð ^ð rtð6ð 6Øð6Ø,/ð6ØEHð6ØVYð6Øknð6ð 6ð 6ð 6ðBØðð ðð ð	ð
 ðð ðð ðð ð ð ð, Y[ð+6ð +6ð +6ð +6ð\ hlð ð ð °sð ÐQTð Ðadð ð ð ð ð []ðAð AØðAØ,/ðAØ<?ðAØTWðAð Að Að Að> ÔÐ9ØÔÐ9ØÔ&Ð(ZØÔÐGØÔÐ1ØÔ&Ð(IØÔÐ 9ØÔ#Ð%Cð	Ð ð '+Ø(,ð	(nð (nØ
��]Ð"Ô
#ð(nàð(nð ˜s”mð(nð ! œð	(nð (nð (nð (nðVoð oð oð oð oˆIñ oô oð oðdnð nð nð nð n�	ñ nô nð nðbð ð ð ð ˜ñ ô ð ð<4ð 4ð 4ð 4ð 4ð 4r   