Ë
    S^(hrA  ã                   óÌ  — d Z ddlZddlmZmZmZ ddlZ	 ddlm	Z	 ddlmZ  eej                   j"                  d«      r!ej                   j"                  j$                  Znej                   j"                  Z G d„ d	ej&                  «      Z	 	 	 	 	 	 	 	 	 dd
edededededededee   dee   dededeee      fd„Z G d„ de	«      Z G d„ d«      Zy# e
ef$ r	 ddlm	Z	 Y ŒÆw xY w)z?Functions and classes related to optimization (weight updates).é    N)ÚCallableÚOptionalÚUnion)ÚAdamé   )ÚkerasÚlearning_rate_schedulec                   óP   ‡ — e Zd ZdZ	 	 d
dededededee   f
ˆ fd„Z	d„ Z
d	„ Zˆ xZS )ÚWarmUpaì  
    Applies a warmup schedule on a given learning rate decay schedule.

    Args:
        initial_learning_rate (`float`):
            The initial learning rate for the schedule after the warmup (so this will be the learning rate at the end
            of the warmup).
        decay_schedule_fn (`Callable`):
            The schedule function to apply after the warmup for the rest of training.
        warmup_steps (`int`):
            The number of steps for the warmup part of training.
        power (`float`, *optional*, defaults to 1.0):
            The power to use for the polynomial warmup (defaults is a linear warmup).
        name (`str`, *optional*):
            Optional name prefix for the returned tensors during the schedule.
    Úinitial_learning_rateÚdecay_schedule_fnÚwarmup_stepsÚpowerÚnamec                 óh   •— t         ‰| �  «        || _        || _        || _        || _        || _        y ©N)ÚsuperÚ__init__r   r   r   r   r   )Úselfr   r   r   r   r   Ú	__class__s         €úZ/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/optimization_tf.pyr   zWarmUp.__init__8   s6   ø€ ô 	‰ÑÔØ%:ˆÔ"Ø(ˆÔØˆŒ
Ø!2ˆÔØˆ�	ó    c                 óÜ  ‡ ‡‡— t        j                  ‰ j                  xs d«      5 }t        j                  ‰t         j                  «      }t        j                  ‰ j
                  t         j                  «      }||z  }‰ j                  t         j                  j                  |‰ j                  «      z  Št        j                  ||k  ˆfd„ˆ ˆfd„|¬«      cd d d «       S # 1 sw Y   y xY w)Nr   c                  ó   •— ‰ S r   © )Úwarmup_learning_rates   €r   ú<lambda>z!WarmUp.__call__.<locals>.<lambda>Q   s   ø€ Ð,€ r   c                  ó@   •— ‰ j                  ‰‰ j                  z
  «      S r   )r   r   )r   Ústeps   €€r   r   z!WarmUp.__call__.<locals>.<lambda>R   s   ø€ ˜×.Ñ.¨t°d×6GÑ6GÑ/GÓH€ r   ©r   )ÚtfÚ
name_scoper   ÚcastÚfloat32r   r   ÚmathÚpowr   Úcond)r   r   r   Úglobal_step_floatÚwarmup_steps_floatÚwarmup_percent_doner   s   ``    @r   Ú__call__zWarmUp.__call__G   s³   ú€ Ü�]‰]˜4Ÿ9™9Ò0¨Ó1ð 	°Tô !#§¡¨¬b¯j©jÓ 9ÐÜ!#§¡¨×):Ñ):¼B¿J¹JÓ!GÐØ"3Ð6HÑ"HÐØ#'×#=Ñ#=ÄÇÁÇÁÐL_Ðae×akÑakÓ@lÑ#lÐ Ü—7‘7Ø!Ð$6Ñ6Û,ÜHØô	÷	÷ 	ò 	ús   §B1C"Ã"C+c                 óv   — | j                   | j                  | j                  | j                  | j                  dœS )N©r   r   r   r   r   r-   ©r   s    r   Ú
get_configzWarmUp.get_configV   s5   € à%)×%?Ñ%?Ø!%×!7Ñ!7Ø ×-Ñ-Ø—Z‘ZØ—I‘Iñ
ð 	
r   )ç      ð?N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úfloatr   Úintr   Ústrr   r+   r/   Ú__classcell__©r   s   @r   r   r   &   sS   ø„ ñð, Ø"ñà$ðð $ðð ð	ð
 ðð �s‰mõòö
r   r   Úinit_lrÚnum_train_stepsÚnum_warmup_stepsÚmin_lr_ratioÚ
adam_beta1Ú
adam_beta2Úadam_epsilonÚadam_clipnormÚadam_global_clipnormÚweight_decay_rater   Úinclude_in_weight_decayc                 óð   — t         j                  | ||z
  | |z  |
¬«      }|rt        | ||¬«      }|	dkD  rt        ||	|||||g d¢|¬«	      }||fS t        j
                  j                  ||||||¬«      }||fS )a­  
    Creates an optimizer with a learning rate schedule using a warmup phase followed by a linear decay.

    Args:
        init_lr (`float`):
            The desired learning rate at the end of the warmup phase.
        num_train_steps (`int`):
            The total number of training steps.
        num_warmup_steps (`int`):
            The number of warmup steps.
        min_lr_ratio (`float`, *optional*, defaults to 0):
            The final learning rate at the end of the linear decay will be `init_lr * min_lr_ratio`.
        adam_beta1 (`float`, *optional*, defaults to 0.9):
            The beta1 to use in Adam.
        adam_beta2 (`float`, *optional*, defaults to 0.999):
            The beta2 to use in Adam.
        adam_epsilon (`float`, *optional*, defaults to 1e-8):
            The epsilon to use in Adam.
        adam_clipnorm (`float`, *optional*, defaults to `None`):
            If not `None`, clip the gradient norm for each weight tensor to this value.
        adam_global_clipnorm (`float`, *optional*, defaults to `None`)
            If not `None`, clip gradient norm to this value. When using this argument, the norm is computed over all
            weight tensors, as if they were concatenated into a single vector.
        weight_decay_rate (`float`, *optional*, defaults to 0):
            The weight decay to use.
        power (`float`, *optional*, defaults to 1.0):
            The power to use for PolynomialDecay.
        include_in_weight_decay (`List[str]`, *optional*):
            List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is
            applied to all parameters except bias and layer norm parameters.
    )r   Údecay_stepsÚend_learning_rater   )r   r   r   ç        )Ú	LayerNormÚ
layer_normÚbias)	Úlearning_raterC   Úbeta_1Úbeta_2ÚepsilonÚclipnormÚglobal_clipnormÚexclude_from_weight_decayrD   )rL   rM   rN   rO   rP   rQ   )Ú	schedulesÚPolynomialDecayr   ÚAdamWeightDecayr   Ú
optimizersr   )r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   r   rD   Úlr_scheduleÚ	optimizers                 r   Úcreate_optimizerrY   `   sÁ   € ô\ ×+Ñ+Ø%Ø#Ð&6Ñ6Ø! LÑ0Øð	 ,ó €Kñ ÜØ")Ø)Ø)ô
ˆð
 ˜3ÒÜ#Ø%Ø/ØØØ Ø"Ø0Ú&IØ$;ô

ˆ	ð, �kÐ!Ð!ô ×$Ñ$×)Ñ)Ø%ØØØ Ø"Ø0ð *ó 
ˆ	ð �kÐ!Ð!r   c                   óð   ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 ddeeej                  f   dededededede	e
e      d	e	e
e      d
efˆ fd„Zeˆ fd„«       Zˆ fd„Zd„ Zdˆ fd„	Zd„ Zdˆ fd„	Zdˆ fd„	Zˆ fd„Zd„ Zˆ xZS )rU   a]
  
    Adam enables L2 weight decay and clip_by_global_norm on gradients. Just adding the square of the weights to the
    loss function is *not* the correct way of using L2 regularization/weight decay with Adam, since that will interact
    with the m and v parameters in strange ways as shown in [Decoupled Weight Decay
    Regularization](https://arxiv.org/abs/1711.05101).

    Instead we want to decay the weights in a manner that doesn't interact with the m/v parameters. This is equivalent
    to adding the square of the weights to the loss with plain (non-momentum) SGD.

    Args:
        learning_rate (`Union[float, LearningRateSchedule]`, *optional*, defaults to 0.001):
            The learning rate to use or a schedule.
        beta_1 (`float`, *optional*, defaults to 0.9):
            The beta1 parameter in Adam, which is the exponential decay rate for the 1st momentum estimates.
        beta_2 (`float`, *optional*, defaults to 0.999):
            The beta2 parameter in Adam, which is the exponential decay rate for the 2nd momentum estimates.
        epsilon (`float`, *optional*, defaults to 1e-07):
            The epsilon parameter in Adam, which is a small constant for numerical stability.
        amsgrad (`bool`, *optional*, defaults to `False`):
            Whether to apply AMSGrad variant of this algorithm or not, see [On the Convergence of Adam and
            Beyond](https://arxiv.org/abs/1904.09237).
        weight_decay_rate (`float`, *optional*, defaults to 0.0):
            The weight decay to apply.
        include_in_weight_decay (`List[str]`, *optional*):
            List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is
            applied to all parameters by default (unless they are in `exclude_from_weight_decay`).
        exclude_from_weight_decay (`List[str]`, *optional*):
            List of the parameter names (or re patterns) to exclude from applying weight decay to. If a
            `include_in_weight_decay` is passed, the names in it will supersede this list.
        name (`str`, *optional*, defaults to `"AdamWeightDecay"`):
            Optional name for the operations created when applying gradients.
        kwargs (`Dict[str, Any]`, *optional*):
            Keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by
            norm; `clipvalue` is clip gradients by value, `decay` is included for backward compatibility to allow time
            inverse decay of learning rate. `lr` is included for backward compatibility, recommended to use
            `learning_rate` instead.
    rL   rM   rN   rO   ÚamsgradrC   rD   rR   r   c
                 óZ   •— t        ‰| �  ||||||	fi |
¤Ž || _        || _        || _        y r   )r   r   rC   Ú_include_in_weight_decayÚ_exclude_from_weight_decay)r   rL   rM   rN   rO   r[   rC   rD   rR   r   Úkwargsr   s              €r   r   zAdamWeightDecay.__init__Û   s:   ø€ ô 	‰Ñ˜¨°¸ÀÈ$ÑYÐRXÒYØ!2ˆÔØ(?ˆÔ%Ø*CˆÕ'r   c                 ó6   •— dt         i}t        ‰| �	  ||¬«      S )z?Creates an optimizer from its config with WarmUp custom object.r   )Úcustom_objects)r   r   Úfrom_config)ÚclsÚconfigra   r   s      €r   rb   zAdamWeightDecay.from_configí   s$   ø€ ð #¤FÐ+ˆÜ‰wÑ" 6¸.Ð"ÓIÐIr   c                 óz   •— t         ‰| �  |||«       t        j                  | j                  d¬«      |||f   d<   y )NÚadam_weight_decay_rater    rC   )r   Ú_prepare_localr!   ÚconstantrC   )r   Ú
var_deviceÚ	var_dtypeÚapply_stater   s       €r   rg   zAdamWeightDecay._prepare_localó   s?   ø€ Ü‰Ñ˜z¨9°kÔBÜDFÇKÁKØ×"Ñ"Ð)AôE
ˆ�Z Ð+Ñ,Ð-@ÒAr   c                 óö   — | j                  |j                  «      }|rI|j                  ||z  ||j                  |j                  j
                  f   d   z  | j                  ¬«      S t        j                  «       S )NrC   )Úuse_locking)	Ú_do_use_weight_decayr   Ú
assign_subÚdeviceÚdtypeÚ
base_dtypeÚ_use_lockingr!   Úno_op)r   ÚvarrL   rk   Údo_decays        r   Ú_decay_weights_opz!AdamWeightDecay._decay_weights_opù   sq   € Ø×,Ñ,¨S¯X©XÓ6ˆÙØ—>‘>Ø Ñ# k°3·:±:¸s¿y¹y×?SÑ?SÐ2TÑ&UÐViÑ&jÑjØ ×-Ñ-ð "ó ð ô �x‰x‹zÐr   c                 ód   •— t        t        |Ž «      \  }}t        ‰| �  t        ||«      fd|i|¤ŽS )Nr   )ÚlistÚzipr   Úapply_gradients)r   Úgrads_and_varsr   r_   ÚgradsÚtvarsr   s         €r   r{   zAdamWeightDecay.apply_gradients  s7   ø€ ÜœC Ð0Ó1‰ˆˆuÜ‰wÑ&¤s¨5°%Ó'8ÑN¸tÐNÀvÑNÐNr   c                 ó¢   — |€| j                   |   i fS |xs i }|j                  ||f«      }|€| j                  ||«      }||||f<   |d   d|ifS )z1Retrieves the learning rate with the given state.Úlr_trk   )Ú_decayed_lr_tÚgetÚ_fallback_apply_state)r   ri   rj   rk   Úcoefficientss        r   Ú_get_lrzAdamWeightDecay._get_lr  sw   € àÐØ×%Ñ% iÑ0°"Ð4Ð4à!Ò' RˆØ"—‘¨
°IÐ'>Ó?ˆØÐØ×5Ñ5°jÀ)ÓLˆLØ3?ˆK˜ YÐ/Ñ0à˜FÑ# m°[Ð%AÐAÐAr   c                 ó  •— | j                  |j                  |j                  j                  |«      \  }}| j	                  |||«      }t        j                  |g«      5  t        ‰| �   ||fi |¤Žcd d d «       S # 1 sw Y   y xY wr   )	r…   rp   rq   rr   rw   r!   Úcontrol_dependenciesr   Ú_resource_apply_dense)r   Úgradru   rk   r€   r_   Údecayr   s          €r   rˆ   z%AdamWeightDecay._resource_apply_dense  sx   ø€ Ø—|‘| C§J¡J°·	±	×0DÑ0DÀkÓR‰ˆˆfØ×&Ñ& s¨D°+Ó>ˆÜ×$Ñ$ e WÓ-ñ 	FÜ‘7Ñ0°°sÑE¸fÑE÷	F÷ 	Fò 	Fús   ÁA:Á:Bc                 ó  •— | j                  |j                  |j                  j                  |«      \  }}| j	                  |||«      }t        j                  |g«      5  t        ‰| �   |||fi |¤Žcd d d «       S # 1 sw Y   y xY wr   )	r…   rp   rq   rr   rw   r!   r‡   r   Ú_resource_apply_sparse)	r   r‰   ru   Úindicesrk   r€   r_   rŠ   r   s	           €r   rŒ   z&AdamWeightDecay._resource_apply_sparse  sz   ø€ Ø—|‘| C§J¡J°·	±	×0DÑ0DÀkÓR‰ˆˆfØ×&Ñ& s¨D°+Ó>ˆÜ×$Ñ$ e WÓ-ñ 	PÜ‘7Ñ1°$¸¸WÑOÈÑO÷	P÷ 	Pò 	Pús   ÁA;Á;Bc                 ó^   •— t         ‰| �  «       }|j                  d| j                  i«       |S )NrC   )r   r/   ÚupdaterC   )r   rd   r   s     €r   r/   zAdamWeightDecay.get_config  s-   ø€ Ü‘Ñ#Ó%ˆØ�‰Ð*¨D×,BÑ,BÐCÔDØˆr   c                 óø   — | j                   dk(  ry| j                  r)| j                  D ]  }t        j                  ||«      €Œ y | j                  r)| j                  D ]  }t        j                  ||«      €Œ y y)z0Whether to use L2 weight decay for `param_name`.r   FT)rC   r]   ÚreÚsearchr^   )r   Ú
param_nameÚrs      r   rn   z$AdamWeightDecay._do_use_weight_decay$  s~   € à×!Ñ! QÒ&Øà×(Ò(Ø×2Ñ2ò  �Ü—9‘9˜Q 
Ó+Ñ7Ùð ð ×*Ò*Ø×4Ñ4ò !�Ü—9‘9˜Q 
Ó+Ñ7Ù ð!ð r   )	gü©ñÒMbP?çÍÌÌÌÌÌì?ç+‡ÙÎ÷ï?gH¯¼šò×z>FrH   NNrU   r   )r1   r2   r3   r4   r   r5   rS   ÚLearningRateScheduleÚboolr   ry   r7   r   Úclassmethodrb   rg   rw   r{   r…   rˆ   rŒ   r/   rn   r8   r9   s   @r   rU   rU   ´   só   ø„ ñ$ðP GLØØØØØ#&Ø7;Ø9=Ø%ñDà˜U I×$BÑ$BÐBÑCðDð ðDð ð	Dð
 ðDð ðDð !ðDð "*¨$¨s©)Ñ!4ðDð $,¨D°©IÑ#6ðDð õDð$ óJó ðJô

òõOòBõFõPôö
r   rU   c                   óB   — e Zd ZdZd„ Zed„ «       Zed„ «       Zd„ Zd„ Z	y)ÚGradientAccumulatoraR  
    Gradient accumulation utility. When used with a distribution strategy, the accumulator should be called in a
    replica context. Gradients will be accumulated locally on each replica and without synchronization. Users should
    then call `.gradients`, scale the gradients if required, and pass the result to `apply_gradients`.
    c                 ó    — g | _         d| _        y)zInitializes the accumulator.N)Ú
_gradientsÚ_accum_stepsr.   s    r   r   zGradientAccumulator.__init__A  s   € àˆŒØ ˆÕr   c                 ó0  — | j                   €qt        j                  t        j                  dt        j                  ¬«      dt        j
                  j                  t        j                  j                  ¬«      | _         | j                   j                  «       S )zNumber of accumulated steps.r   )rq   F©Ú	trainableÚsynchronizationÚaggregation)
rž   r!   ÚVariablerh   Úint64ÚVariableSynchronizationÚON_READÚVariableAggregationÚONLY_FIRST_REPLICAÚvaluer.   s    r   r   zGradientAccumulator.stepF  sk   € ð ×ÑÐ$Ü "§¡Ü—‘˜A¤R§X¡XÔ.ØÜ "× :Ñ :× BÑ BÜ×2Ñ2×EÑEô	!ˆDÔð × Ñ ×&Ñ&Ó(Ð(r   c                 ó’   — | j                   st        d«      ‚| j                   D �cg c]  }|�|j                  «       n|‘Œ c}S c c}w )z1The accumulated gradients on the current replica.zBThe accumulator should be called first to initialize the gradients)r�   Ú
ValueErrorrª   ©r   Úgradients     r   Ú	gradientszGradientAccumulator.gradientsS  sB   € ð �ŠÜÐaÓbÐbØW[×WfÑWfÖgÈ8 HÐ$8�—‘Ô ¸hÑFÒgÐgùÒgs   ¦Ac                 óˆ  — | j                   s“| j                  }| j                   j                  |D �cg c]b  }|�\t        j                  t        j
                  |«      dt        j                  j                  t        j                  j                  ¬«      n|‘Œd c}«       t        |«      t        | j                   «      k7  r-t        dt        | j                   «      › dt        |«      › �«      ‚t        | j                   |«      D ]  \  }}|€Œ	|€Œ|j                  |«       Œ | j                  j                  d«       yc c}w )z/Accumulates `gradients` on the current replica.NFr    z	Expected z gradients, but got r   )r�   r   Úextendr!   r¤   Ú
zeros_liker¦   r§   r¨   r©   Úlenr¬   rz   Ú
assign_addrž   )r   r¯   Ú_r®   Úaccum_gradients        r   r+   zGradientAccumulator.__call__Z  s  € à�ŠØ—	‘	ˆAØ�O‰O×"Ñ"ð %.ö
ð !ð  Ð+ô —K‘KÜŸ™ hÓ/Ø"'Ü(*×(BÑ(B×(JÑ(JÜ$&×$:Ñ$:×$MÑ$Mõ	ð "ñ"ò
ôô ˆy‹>œS §¡Ó1Ò1Ü˜y¬¨T¯_©_Ó)=Ð(>Ð>RÔSVÐW`ÓSaÐRbÐcÓdÐdä(+¨D¯O©O¸YÓ(Gò 	4Ñ$ˆN˜HØÑ)¨hÑ.BØ×)Ñ)¨(Õ3ð	4ð 	×Ñ×$Ñ$ QÕ'ùò'
s   ²A'D?c                 óÄ   — | j                   sy| j                  j                  d«       | j                   D ])  }|€Œ|j                  t        j                  |«      «       Œ+ y)z8Resets the accumulated gradients on the current replica.Nr   )r�   rž   Úassignr!   r²   r­   s     r   ÚresetzGradientAccumulator.resett  sN   € à�ŠØØ×Ñ× Ñ  Ô#ØŸ™ò 	9ˆHØÑ#Ø—‘¤§¡¨hÓ 7Õ8ñ	9r   N)
r1   r2   r3   r4   r   Úpropertyr   r¯   r+   r¹   r   r   r   r›   r›   6  s@   „ ñò!ð
 ñ
)ó ð
)ð ñhó ðhò(ó49r   r›   )	rH   r•   r–   g:Œ0âŽyE>NNrH   r0   N)r4   r‘   Útypingr   r   r   Ú
tensorflowr!   Útf_keras.optimizers.legacyr   ÚImportErrorÚModuleNotFoundErrorÚ"tensorflow.keras.optimizers.legacyÚmodeling_tf_utilsr   ÚhasattrrV   rS   r	   r—   r   r5   r6   ry   r7   rY   rU   r›   r   r   r   ú<module>rÃ      sc  ðñ Fã 	ß ,Ñ ,ã ð8Ý/õ %ñ ˆ5×Ñ×%Ñ%Ð'?Ô@Ø× Ñ ×*Ñ*×AÑA�Ià× Ñ ×*Ñ*€Iô7
ˆY×+Ñ+ô 7
ð| ØØØØ%)Ø,0Ø"ØØ37ñQ"ØðQ"àðQ"ð ðQ"ð ð	Q"ð
 ðQ"ð ðQ"ð ðQ"ð ˜E‘?ðQ"ð # 5™/ðQ"ð ðQ"ð ðQ"ð & d¨3¡iÑ0óQ"ôh~�dô ~÷DE9ò E9øð{ 	Ð(Ð)ò 8ß7ð8ús   –C ÃC#Ã"C#