Ë
    S^(hYŽ  ã                   ó,  — d Z ddlZddlZddlmZ ddlmZmZ ddlZddl	m
Z
 ddlmZ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d;d„Zd<de
defd„Zde
fd„Zdedefd„Zd<de
dedefd„Zdededefd„Z d<d„Z!dededede"fd„Z#	 d=de
dedede"def
d„Z$dedededefd„Z%	 d>d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'	 d?d!„Z(dd"œdeded#ee   fd$„Z)	 d@de
ded#ee   defd%„Z*d&d'œdededede"d(e"f
d)„Z#	 	 	 	 dAde
dedede"ded*ee"   d(ee"   fd+„Z+deded,ed-ed.e,d/e,d0e"de"fd1„Z-	 	 	 	 	 	 	 dBde
ded-edee   d,ee   d.e,d/e,d0e"de"defd2„Z.ej^                  e!ej`                  e$ejb                  e&ejd                  e(ejf                  eejh                  eejj                  e*ejl                  eejn                  e+ejp                  e.i
Z9	 	 	 dCd3ee,ef   de
dee   dee   d4ee:   f
d5„Z; G d6„ d7e
«      Z< G d8„ d9e«      Z=dDd:„Z>y)Ez$PyTorch optimization for BERT model.é    N)Úpartial)ÚOptionalÚUnion)Ú	Optimizer)ÚLambdaLRÚReduceLROnPlateaué   )ÚLayerWiseDummyOptimizerÚLayerWiseDummyScheduler)ÚSchedulerType)Úlogging)Úrequire_versionc                  ó   — y©Nr	   © )Ú_s    úW/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/optimization.pyÚ_get_constant_lambdar   "   s   € Øó    Ú	optimizerÚ
last_epochc                 ó&   — 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ÐKr   c                 ó   — t        | fi |¤ŽS )a  
    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.
        kwargs (`dict`, *optional*):
            Extra parameters to be passed to the scheduler. See `torch.optim.lr_scheduler.ReduceLROnPlateau`
            for possible parameters.

    Return:
        `torch.optim.lr_scheduler.ReduceLROnPlateau` with the appropriate schedule.
    )r   )r   Úkwargss     r   Úget_reduce_on_plateau_scheduler   7   s   € ô ˜YÑ1¨&Ñ1Ð1r   Úcurrent_stepÚnum_warmup_stepsc                óP   — | |k  r!t        | «      t        t        d|«      «      z  S y)Nç      ð?©ÚfloatÚmax)r   r   s     r   Ú,_get_constant_schedule_with_warmup_lr_lambdar%   I   s+   € ØÐ&Ò&Ü�\Ó"¤U¬3¨sÐ4DÓ+EÓ%FÑFÐFØr   c                 ó@   — 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)   O   s!   € ô" ÔDÐWgÔ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-   d   sX   € ØÐ&Ò&Ü�\Ó"¤U¬3¨qÐ2BÓ+CÓ%DÑDÐDÜˆs”EÐ,¨|Ñ;Ó<¼uÄSÈÐL^ÐaqÑLqÓErÓ?sÑsÓtÐtr   c                 ó@   — 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_warmupr0   j   s(   € ô& Ü2Ø)Ø-ô€Iô
 �I˜y¨*Ó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!   ç       @©r#   r$   ÚmathÚcosÚpi©r   r   r*   r1   Úprogresss        r   Ú*_get_cosine_schedule_with_warmup_lr_lambdar;   …   sŠ   € ð Ð&Ò&Ü�\Ó"¤U¬3¨qÐ2BÓ+CÓ%DÑDÐDÜ�\Ð$4Ñ4Ó5¼¼cÀ!ÐEWÐZjÑEjÓ>kÓ8lÑl€HÜˆs�C˜3¤§¡¬$¯'©'´E¸*Ó4EÑ*EÈÑ*KÈhÑ*VÓ!WÑWÑXÓYÐYr   c                 óB   — 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*   r1   )r   r;   r   ©r   r   r*   r1   r   r(   s         r   Úget_cosine_schedule_with_warmupr?   Ž   s+   € ô2 Ü2Ø)Ø-Øô	€Iô �I˜y¨*Ó5Ð5r   c                ó2  — | |k  r!t        | «      t        t        d|«      «      z  S t        | |z
  «      t        t        d||z
  «      «      z  }|dk\  ryt        dddt        j                  t        j                  t        |«      |z  dz  z  «      z   z  «      S )Nr	   r!   r,   r3   r5   r9   s        r   Ú=_get_cosine_with_hard_restarts_schedule_with_warmup_lr_lambdarA   °   s•   € ð Ð&Ò&Ü�\Ó"¤U¬3¨qÐ2BÓ+CÓ%DÑDÐDÜ�\Ð$4Ñ4Ó5¼¼cÀ!ÐEWÐZjÑEjÓ>kÓ8lÑl€HØ�3‚ØÜˆs�C˜3¤§¡¬$¯'©'´e¸JÓ6GÈ(Ñ6RÐVYÑ5YÑ*ZÓ![Ñ[Ñ\Ó]Ð]r   c                 óB   — 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   rA   r   r>   s         r   Ú2get_cosine_with_hard_restarts_schedule_with_warmuprC   »   s+   € ô0 ÜEØ)Ø-Øô	€Iô �I˜y¨*Ó5Ð5r   Úlr_endÚpowerÚlr_initc                ó¬   — | |k  r!t        | «      t        t        d|«      «      z  S | |kD  r||z  S ||z
  }||z
  }d| |z
  |z  z
  }|||z  z  |z   }	|	|z  S r   r"   )
r   r   r*   rD   rE   rF   Úlr_rangeÚdecay_stepsÚpct_remainingÚdecays
             r   Ú4_get_polynomial_decay_schedule_with_warmup_lr_lambdarL   Ü   s†   € ð Ð&Ò&Ü�\Ó"¤U¬3¨qÐ2BÓ+CÓ%DÑDÐDØ	Ð*Ò	*Ø˜ÑÐà˜VÑ#ˆØ(Ð+;Ñ;ˆØ˜\Ð,<Ñ<ÀÑKÑKˆØ˜=¨%Ñ/Ñ/°&Ñ8ˆØ�w‰Ðr   c                 ó’   — | j                   d   }||kD  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 smaller than initial lr (ú))r   r*   rD   rE   rF   )ÚdefaultsÚ
ValueErrorr   rL   r   )r   r   r*   rD   rE   r   rF   r(   s           r   Ú)get_polynomial_decay_schedule_with_warmuprR   ñ   se   € ð> × Ñ  Ñ&€GØ�fÒÜ˜8 F 8Ð+NÈwÈiÐWXÐYÓZÐZäÜ<Ø)Ø-ØØØô€Iô �I˜y¨*Ó5Ð5r   )Ú	timescalerS   c                ó˜   — | |k  r!t        | «      t        t        d|«      «      z  S ||z
  }dt        j                  | |z   |z  «      z  }|S )Nr	   r!   )r#   r$   r6   Úsqrt)r   r   rS   ÚshiftrK   s        r   Ú$_get_inverse_sqrt_schedule_lr_lambdarW     sU   € ØÐ&Ò&Ü�\Ó"¤U¬3¨qÐ2BÓ+CÓ%DÑDÐDØÐ(Ñ(€EØ”$—)‘)˜\¨EÑ1°YÑ>Ó?Ñ?€EØ€Lr   c                 óR   — |€|xs d}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.
    i'  )r   rS   r   )r   rW   r   )r   r   rS   r   r(   s        r   Úget_inverse_sqrt_schedulerY   '  s4   € ð. ÐØ$Ò.¨ˆ	äÔ<ÐO_ÐktÔu€IÜ�I˜y°ZÔ@Ð@r   r,   )Úmin_lr_raterZ   c                ó@  — | |k  r!t        | «      t        t        d|«      «      z  S t        | |z
  «      t        t        d||z
  «      «      z  }ddt        j                  t        j                  t        |«      z  dz  |z  «      z   z  }|d|z
  z  |z   }t        d|«      S )Nr	   r3   r!   r4   r   r5   )r   r   r*   r1   rZ   r:   Úfactors          r   r;   r;   E  s¡   € ð Ð&Ò&Ü�\Ó"¤U¬3¨qÐ2BÓ+CÓ%DÑDÐDÜ�\Ð$4Ñ4Ó5¼¼cÀ!ÐEWÐZjÑEjÓ>kÓ8lÑl€HØ�Cœ$Ÿ(™(¤4§7¡7¬U°:Ó->Ñ#>ÀÑ#DÀxÑ#OÓPÑPÑQ€FØ�q˜;‘Ñ'¨+Ñ5€FÜˆq�&‹>Ðr   Úmin_lrc                 ó¦   — |�|�t        d«      ‚|�|| j                  d   z  }n|€t        d«      ‚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 min_lr, 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.
        min_lr (`float`, *optional*):
            The minimum learning rate to reach after the cosine schedule.
        min_lr_rate (`float`, *optional*):
            The minimum learning rate as a ratio of the initial learning rate. If set, `min_lr` should not be set.

    Return:
        `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
    z/Only one of min_lr or min_lr_rate should be setrN   zLOne of min_lr or min_lr_rate should be set through the `lr_scheduler_kwargs`)r   r*   r1   rZ   )rQ   rP   r   r;   r   )r   r   r*   r1   r   r]   rZ   r(   s           r   Ú+get_cosine_with_min_lr_schedule_with_warmupr_   P  ss   € ðF Ð˜kÐ5ÜÐJÓKÐKØ	Ð	Ø˜y×1Ñ1°$Ñ7Ñ7‰Ø	Ð	ÜÐgÓhÐhäÜ2Ø)Ø-ØØô€Iô �I˜y¨*Ó5Ð5r   Únum_stable_stepsÚnum_decay_stepsÚwarmup_typeÚ
decay_typeÚmin_lr_ratioc                óª  — | |k  r’t        | «      t        t        d|«      «      z  }|dk(  r|}	nR|dk(  r-ddt        j                  t        j                  |z  «      z
  z  }	n |dk(  rdt        j
                  d|z
  «      z
  }		d|z
  z  |z   }	t        d|	«      S | ||z   k  ry| ||z   |z   k  r§t        | |z
  |z
  «      t        t        d|«      «      z  }|dk(  rd|z
  }	n^|dk(  r<ddt        j                  t        j                  t        |«      z  dz  |z  «      z   z  }	n|dk(  rdt        j
                  |«      z
  }		d|z
  z  |z   }	t        d|	«      S |S )	Nr	   ÚlinearÚcosiner3   r!   ú1-sqrtr,   r4   )r#   r$   r6   r7   r8   rU   )
r   r   r`   ra   rb   rc   rd   r1   r:   r\   s
             r   Ú_get_wsd_scheduler_lambdari   „  sz  € ð Ð&Ò&Ü˜Ó&¬¬s°1Ð6FÓ/GÓ)HÑHˆØ˜(Ò"Ø‰FØ˜HÒ$Ø˜C¤$§(¡(¬4¯7©7°XÑ+=Ó">Ñ>Ñ?‰FØ˜HÒ$Øœ4Ÿ9™9 S¨8¡^Ó4Ñ4ˆFØ˜3 Ñ-Ñ.°Ñ=ˆÜ�3˜ÓÐàÐ&Ð)9Ñ9Ò9ØàÐ&Ð)9Ñ9¸OÑKÒKÜ˜Ð(8Ñ8Ð;KÑKÓLÌuÔUXÐYZÐ\kÓUlÓOmÑmˆØ˜Ò!Ø˜8‘^‰FØ˜8Ò#Ø˜C¤$§(¡(¬4¯7©7´U¸:Ó5FÑ+FÈÑ+LÈxÑ+WÓ"XÑXÑY‰FØ˜8Ò#Øœ4Ÿ9™9 XÓ.Ñ.ˆFØ˜3 Ñ-Ñ.°Ñ=ˆÜ�3˜ÓÐØÐr   c
           
      óú   — |€|€t        d«      ‚|�|�t        j                  d«       |dvrt        d|› d�«      ‚|dvrt        d|› d�«      ‚|€||z
  |z
  }t        t        |||||||¬«      }
t        | |
|	«      S )aÿ  
    Create a schedule with a learning rate that has three stages:
    1. warmup: increase from min_lr_ratio times the initial learning rate to the initial learning rate following a warmup_type.
    2. stable: constant learning rate.
    3. decay: decrease from the initial learning rate to min_lr_ratio times the initial learning rate following a decay_type.

    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_decay_steps (`int`):
            The number of steps for the decay phase.
        num_training_steps (`int`, *optional*):
            The total number of training steps. This is the sum of the warmup, stable and decay steps. If `num_stable_steps` is not provided, the stable phase will be `num_training_steps - num_warmup_steps - num_decay_steps`.
        num_stable_steps (`int`, *optional*):
            The number of steps for the stable phase. Please ensure that `num_warmup_steps + num_stable_steps + num_decay_steps` equals `num_training_steps`, otherwise the other steps will default to the minimum learning rate.
        warmup_type (`str`, *optional*, defaults to "linear"):
            The type of warmup to use. Can be 'linear', 'cosine' or '1-sqrt'.
        decay_type (`str`, *optional*, defaults to "cosine"):
            The type of decay to use. Can be 'linear', 'cosine' or '1-sqrt'.
        min_lr_ratio (`float`, *optional*, defaults to 0):
            The minimum learning rate as a ratio of the initial learning rate.
        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.
    z@Either num_training_steps or num_stable_steps must be specified.zZBoth num_training_steps and num_stable_steps are specified. num_stable_steps will be used.)rf   rg   rh   zUnknown warmup type: z), expected 'linear', 'cosine' or '1-sqrt'zUnknown decay type: )r   r`   ra   rb   rc   rd   r1   )rQ   ÚwarningsÚwarnr   ri   r   )r   r   ra   r*   r`   rb   rc   rd   r1   r   r(   s              r   Úget_wsd_schedulerm   ª  s¾   € ðZ Ð!Ð&6Ð&>ÜÐ[Ó\Ð\àÐ%Ð*:Ð*FÜ�‰ÐrÔsàÐ8Ñ8ÜÐ0°°Ð=fÐgÓhÐhàÐ7Ñ7ÜÐ/°
¨|Ð;dÐeÓfÐfàÐØ-Ð0@Ñ@À?ÑRÐäÜ!Ø)Ø)Ø'ØØØ!Øô	€Iô �I˜y¨*Ó5Ð5r   ÚnameÚscheduler_specific_kwargsc                 óä  ‡	— t        | «      } t        |    }|�št        |t        «      rŠ|j                  }i Š	|j                  «       D ]  }t        | ||   ||¬«      ‰	|<   Œ ˆ	fd„}|j                  «       D ]   }|j                  sŒ|j                  |«       Œ" t        ||j                  d   ¬«      S | t         j                  k(  r ||«      S |€i }| t         j                  k(  r	 ||fi |¤ŽS |€t        | › d�«      ‚| t         j                  k(  r
 |||¬«      S | t         j                  k(  r
 |||¬«      S | t         j                   k(  r ||f||dœ|¤ŽS |€t        | › d�«      ‚ ||f||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.
        scheduler_specific_kwargs (`dict`, *optional*):
            Extra parameters for schedulers such as cosine with restarts. Mismatched scheduler types and scheduler
            parameters will cause the scheduler function to raise a TypeError.
    )r   r   r*   c                 ó,   •— ‰|    j                  «        y ©N)Ústep)ÚparamÚscheduler_dicts    €r   Úscheduler_hookz%get_scheduler.<locals>.scheduler_hook+  s   ø€ ð ˜5Ñ!×&Ñ&Õ(r   rN   )Úoptimizer_dictrN   z; requires `num_warmup_steps`, please provide that argument.r'   r/   z= requires `num_training_steps`, please provide that argument.)r   ÚTYPE_TO_SCHEDULER_FUNCTIONÚ
isinstancer
   rw   ÚkeysÚget_schedulerÚrequires_gradÚ"register_post_accumulate_grad_hookr   rP   ÚCONSTANTÚREDUCE_ON_PLATEAUrQ   ÚCONSTANT_WITH_WARMUPÚINVERSE_SQRTÚWARMUP_STABLE_DECAY)
rn   r   r   r*   ro   Úschedule_funcrw   rt   rv   ru   s
            @r   r{   r{     sÒ  ø€ ô2 ˜Ó€DÜ.¨tÑ4€Mð Ð¤¨IÔ7NÔ!OØ"×1Ñ1ˆØˆà#×(Ñ(Ó*ò 	ˆEÜ$1ØØ(¨Ñ/Ø!1Ø#5ô	%ˆN˜5Ò!ð	ô	)ð
 $×(Ñ(Ó*ò 	IˆEØ×"Ó"Ø×8Ñ8¸ÕHð	Iô '°nÈ×I[ÑI[Ð\`ÑIaÔbÐbàŒ}×%Ñ%Ò%Ù˜YÓ'Ð'à Ð(Ø$&Ð!àŒ}×.Ñ.Ò.Ù˜YÑDÐ*CÑDÐDð ÐÜ˜D˜6Ð!\Ð]Ó^Ð^àŒ}×1Ñ1Ò1Ù˜YÐ9IÔJÐJàŒ}×)Ñ)Ò)Ù˜YÐ9IÔJÐJð Œ}×0Ñ0Ò0ÙØð
à-Ø1ñ
ð (ñ	
ð 	
ð Ð!Ü˜D˜6Ð!^Ð_Ó`Ð`áØðà)Ø-ñð $ñ	ð r   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,
    )
    ```c           
      ó�   •— t        d«       |�|	rt        d«      ‚|
r|	st        d«      ‚||||||||	|
dœ	}t        ‰| �  ||«       y )Nztorch>=1.5.0z;Cannot combine manual `lr` and `relative_step=True` optionsz0`warmup_init=True` requires `relative_step=True`)	rN   ÚepsÚclip_thresholdÚ
decay_rateÚbeta1Úweight_decayÚscale_parameterÚrelative_stepÚwarmup_init)r   rQ   ÚsuperÚ__init__)ÚselfÚparamsrN   r‡   rˆ   r‰   rŠ   r‹   rŒ   r�   rŽ   rP   Ú	__class__s               €r   r�   zAdafactor.__init__³  sf   ø€ ô 	˜Ô'Øˆ>™mÜÐZÓ[Ð[Ù™}ÜÐOÓPÐPð ØØ,Ø$ØØ(Ø.Ø*Ø&ñ

ˆô 	‰Ñ˜ Õ*r   c                 óÀ   — | d   }| d   r4| d   rd|d   z  nd}t        |dt        j                  |d   «      z  «      }d}| d   rt        | d	   d
   |d   «      }||z  S )NrN   r�   rŽ   g�íµ ÷Æ°>rs   g{®Gáz„?r!   rŒ   r‡   r	   ÚRMS)Úminr6   rU   r$   )Úparam_groupÚparam_stateÚrel_step_szÚmin_stepÚparam_scales        r   Ú_get_lrzAdafactor._get_lrÓ  s€   € à! $Ñ'ˆØ�Ò'Ø5@ÀÒ5O�t˜k¨&Ñ1Ò1ÐUYˆHÜ˜h¨¬d¯i©i¸ÀFÑ8KÓ.LÑ(LÓMˆKØˆØÐ(Ò)Ü˜k¨%Ñ0°Ñ3°[ÀÑ5GÓHˆKØ˜[Ñ(Ð(r   c                 ó4   — t        |«      dk\  }| d   d u}||fS )Né   rŠ   )Úlen)r—   Úparam_shapeÚfactoredÚuse_first_moments       r   Ú_get_optionszAdafactor._get_optionsÞ  s-   € ä�{Ó# qÑ(ˆØ& wÑ/°tÐ;ÐØÐ)Ð)Ð)r   c                 óL   — | j                  d«      | j                  «       dz  z  S )Nrž   r3   )ÚnormÚnumel)Útensors    r   Ú_rmszAdafactor._rmsä  s    € à�{‰{˜1‹~ §¡£°3Ñ!6Ñ7Ð7r   c                 óÒ   — | | j                  dd¬«      z  j                  «       j                  d«      }|j                  d«      j                  «       }t	        j
                  ||«      S )NéÿÿÿÿT)ÚdimÚkeepdiméþÿÿÿ)ÚmeanÚrsqrt_Ú	unsqueezeÚrsqrtÚtorchÚmul)Úexp_avg_sq_rowÚexp_avg_sq_colÚr_factorÚc_factors       r   Ú_approx_sq_gradzAdafactor._approx_sq_gradè  s]   € ð # ^×%8Ñ%8¸RÈÐ%8Ó%NÑN×VÑVÓX×bÑbÐceÓfˆØ!×+Ñ+¨BÓ/×5Ñ5Ó7ˆÜ�y‰y˜ 8Ó,Ð,r   c                 ó‚  — d}|� |«       }| j                   D �]#  }|d   D �]  }|j                  €Œ|j                  }|j                  t        j                  t        j
                  hv r|j                  «       }|j                  rt        d«      ‚| j                  |   }|j                  }| j                  ||«      \  }}	t        |«      dk(  ršd|d<   |	rt        j                  |«      |d<   |r[t        j                  |dd «      j                  |«      |d<   t        j                  |dd	 |dd z   «      j                  |«      |d
<   nt        j                  |«      |d<   d|d<   na|	r|d   j                  |«      |d<   |r/|d   j                  |«      |d<   |d
   j                  |«      |d
<   n|d   j                  |«      |d<   |}
|j                  t        j                  t        j
                  hv r|
j                  «       }
|dxx   dz  cc<   | j!                  |
«      |d<   | j#                  ||«      }dt%        j&                  |d   |d   «      z
  }|dz  |d   d   z   }|r˜|d   }|d
   }|j)                  |«      j+                  |j-                  d¬«      d|z
  ¬«       |j)                  |«      j+                  |j-                  d	¬«      d|z
  ¬«       | j/                  ||«      }|j)                  |«       nI|d   }|j)                  |«      j+                  |d|z
  ¬«       |j1                  «       j)                  |«      }|j3                  | j!                  |«      |d   z  j5                  d¬«      «       |j)                  |«       |	r2|d   }|j)                  |d   «      j+                  |d|d   z
  ¬«       |}|d   dk7  r|
j+                  |
|d    |z  ¬«       |
j+                  | «       |j                  t        j                  t        j
                  hv s�Œ|j7                  |
«       �Œ �Œ& |S )z¾
        Performs a single optimization step

        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        Nr’   z,Adafactor does not support sparse gradients.r   rs   Úexp_avgrª   r´   r­   rµ   Ú
exp_avg_sqr•   r	   r!   r‰   rž   r‡   )r«   )Úalpharˆ   )r–   rŠ   r‹   )Úparam_groupsÚgradÚdtyper²   Úfloat16Úbfloat16r#   Ú	is_sparseÚRuntimeErrorÚstateÚshaper£   rŸ   Ú
zeros_likeÚzerosÚtor¨   rœ   r6   ÚpowÚmul_Úadd_r®   r¸   r±   Údiv_Úclamp_Úcopy_)r‘   ÚclosureÚlossÚgroupÚpr¾   rÄ   Ú
grad_shaper¡   r¢   Úp_data_fp32rN   Úbeta2tÚupdater´   rµ   r»   rº   s                     r   rs   zAdafactor.stepð  s#  € ð ˆØÐÙ“9ˆDà×&Ñ&ó M	)ˆEØ˜8‘_ó L)�Ø—6‘6�>ØØ—v‘v�Ø—:‘:¤%§-¡-´·±Ð!@Ñ@ØŸ:™:›<�DØ—>’>Ü&Ð'UÓVÐVàŸ
™
 1™�Ø!ŸZ™Z�
à-1×->Ñ->¸uÀjÓ-QÑ*�Ð*ä�u“: ’?Ø$%�E˜&‘Má'ä+0×+;Ñ+;¸DÓ+A˜˜iÑ(ÙÜ27·+±+¸jÈÈ"¸oÓ2N×2QÑ2QÐRVÓ2W˜Ð.Ñ/Ü27·+±+¸jÈÈ"¸oÐPZÐ[]Ð[^ÐP_Ñ>_Ó2`×2cÑ2cÐdhÓ2i˜Ð.Ò/ä.3×.>Ñ.>¸tÓ.D˜˜lÑ+à#$�E˜%’Lá'Ø+0°Ñ+;×+>Ñ+>¸tÓ+D˜˜iÑ(ÙØ27Ð8HÑ2I×2LÑ2LÈTÓ2R˜Ð.Ñ/Ø27Ð8HÑ2I×2LÑ2LÈTÓ2R˜Ð.Ò/à.3°LÑ.A×.DÑ.DÀTÓ.J˜˜lÑ+à�Ø—7‘7œuŸ}™}¬e¯n©nÐ=Ñ=Ø"-×"3Ñ"3Ó"5�Kà�f“ Ñ"“Ø#Ÿy™y¨Ó5��e‘Ø—\‘\ %¨Ó/�àœtŸx™x¨¨f©°u¸\Ñ7JÓKÑK�Ø ™' U¨5¡\°!¡_Ñ4�ÙØ%*Ð+;Ñ%<�NØ%*Ð+;Ñ%<�Nà"×'Ñ'¨Ó/×4Ñ4°V·[±[ÀR°[Ó5HÐQTÐW]ÑQ]Ð4Ô_Ø"×'Ñ'¨Ó/×4Ñ4°V·[±[ÀR°[Ó5HÐQTÐW]ÑQ]Ð4Ô_ð "×1Ñ1°.À.ÓQ�FØ—K‘K Õ%à!& |Ñ!4�Jà—O‘O FÓ+×0Ñ0°ÀÀfÁÐ0ÔNØ'×-Ñ-Ó/×4Ñ4°TÓ:�Fà—‘˜TŸY™Y vÓ.°Ð7GÑ1HÑH×PÑPÐUXÐPÓYÔZØ—‘˜B”á#Ø# IÑ.�GØ—L‘L  w¡Ó0×5Ñ5°fÀQÈÈwÉÑEWÐ5ÔYØ$�Fà˜Ñ(¨AÒ-Ø×$Ñ$ [¸%ÀÑ:OÐ9OÐRTÑ9TÐ$ÔVà× Ñ  & Ô)à—7‘7œuŸ}™}¬e¯n©nÐ=Ó=Ø—G‘G˜KÖ(òYL)ðM	)ð^ ˆr   )	N)g ÂëþKH´9gü©ñÒMbP?r!   gš™™™™™é¿Nr,   TTFrr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r�   Ústaticmethodrœ   r£   r¨   r¸   r²   Úno_gradrs   Ú__classcell__©r“   s   @r   r…   r…   ^  s›   ø„ ñRðn ØØØØØØØØõ+ð@ ñ)ó ð)ð ñ*ó ð*ð
 ñ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.
    c                 ó†   •‡— ˆfd„}|j                   D ]  }‰|d<   Œ	 t        ‰| �	  ||«       |j                   D ]  }|d= Œ y )Nc                 ó   •— ‰S rr   r   )r   Ú
initial_lrs    €r   r(   z-AdafactorSchedule.__init__.<locals>.lr_lambdaX  s	   ø€ ØÐr   rã   )r½   r�   r�   )r‘   r   rã   r(   rÑ   r“   s     `  €r   r�   zAdafactorSchedule.__init__W  sU   ù€ ô	ð ×+Ñ+ò 	-ˆEØ",ˆE�,Òð	-ä‰Ñ˜ IÔ.Ø×+Ñ+ò 	$ˆEØ�lÑ#ñ	$r   c           	      óø   — | j                   }|j                  D �cg c]9  }|d   d   j                  �%|j                  ||j                  |d   d      «      ‘Œ; }}t        |«      dk(  r| j                  }|S c c}w )Nr’   r   )r   r½   r¾   rœ   rÄ   rŸ   Úbase_lrs)r‘   ÚoptrÑ   Úlrss       r   Úget_lrzAdafactorSchedule.get_lra  s‚   € Ø�n‰nˆð ×)Ñ)ö
àØ�X‰˜qÑ!×&Ñ&Ð2ð �K‰K˜˜sŸy™y¨¨x©¸Ñ);Ñ<Õ=ð
ˆð 
ô
 ˆs‹8�qŠ=Ø—-‘-ˆCØˆ
ùò
s   ›>A7©r,   )r×   rØ   rÙ   rÚ   r�   rè   rÝ   rÞ   s   @r   rà   rà   O  s   ø„ ñõ$ö	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ë   m  s   € ô ˜Y¨
Ó3Ð3r   rr   )rª   )r3   rª   )r	   rª   )gH¯¼šò×z>r!   rª   )Nrª   )r3   rª   NN)NNrf   rg   r   r3   rª   )NNNré   )?rÚ   r6   rk   Ú	functoolsr   Útypingr   r   r²   Útorch.optimr   Útorch.optim.lr_schedulerr   r   Útrainer_pt_utilsr
   r   Útrainer_utilsr   Úutilsr   Úutils.versionsr   Ú
get_loggerr×   Úloggerr   Úintr   r   r%   r)   r-   r0   r#   r;   r?   rA   rC   rL   rR   rW   rY   r_   Ústrri   rm   ÚLINEARÚCOSINEÚCOSINE_WITH_RESTARTSÚ
POLYNOMIALr~   r€   r�   r   ÚCOSINE_WITH_MIN_LRr‚   rx   Údictr{   r…   rà   rë   r   r   r   ú<module>rþ      s™  ðñ +ã Û Ý ß "ã Ý !ß @ç NÝ (Ý Ý +ð 
ˆ×	Ñ	˜HÓ	%€óñL Yð L¸Có Lð"2¨ió 2ð$¸sð ÐY\ó ñA°ð AÈcð AÐ_bó Að*u¸Sð uÐWZð uÐpsó uó6ð6ZØðZØ,/ðZØEHðZØV[óZð vxñ6Øð6Ø,/ð6ØEHð6ØV[ð6Øoró6ðD^Øð^Ø,/ð^ØEHð^ØVYó^ð rtñ6Øð6Ø,/ð6ØEHð6ØVYð6Øknó6ðBØðð ðð ð	ð
 ðð ðð óð, Y[ó+6ð\ rvò °sð ÐQTð ÐaiÐjmÑanó ð egñAØðAØ,/ðAØ<DÀS¹MðAØ^aóAð> svòØðØ,/ðØEHðØV[ðØjoóð ØØ"Ø#'ñ16Øð16àð16ð ð16ð ð	16ð
 ð16ð �U‰Oð16ð ˜%‘ó16ðh#Øð#ð ð#ð ð	#ð
 ð#ð ð#ð ð#ð ð#ð ó#ðT )-Ø&*ØØØØØñF6ØðF6àðF6ð ðF6ð ! ™ð	F6ð
 ˜s‘mðF6ð ðF6ð ðF6ð ðF6ð ðF6ð óF6ðT ×ÑÐ9Ø×ÑÐ9Ø×&Ñ&Ð(ZØ×ÑÐGØ×ÑÐ1Ø×&Ñ&Ð(IØ×ÑÐ 9Ø×#Ñ#Ð%CØ×$Ñ$Ð&QØ×%Ñ%Ð'7ðÐ ð" '+Ø(,Ø04ñZØ
��]Ð"Ñ
#ðZàðZð ˜s‘mðZð ! ™ð	Zð
  (¨™~óZôzn�	ô nôb˜ô ô<4r   