
    hh"                         d Z ddlmc mZ ddlmZ ddlmZ ddl	m
Z
  e        e
dddg 	       G d
 dej                                      Zej                   j                  dej                        e_         y)zAdamW optimizer implementation.    N)	optimizer)register_keras_serializable)keras_exportzkeras.optimizers.AdamWz#keras.optimizers.experimental.AdamWz+keras.dtensor.experimental.optimizers.AdamW)v1c                   Z     e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Z fdZd Z fdZ xZS )AdamWa  Optimizer that implements the AdamW algorithm.

    AdamW optimization is a stochastic gradient descent method that is based on
    adaptive estimation of first-order and second-order moments with an added
    method to decay weights per the techniques discussed in the paper,
    'Decoupled Weight Decay Regularization' by
    [Loshchilov, Hutter et al., 2019](https://arxiv.org/abs/1711.05101).

    According to
    [Kingma et al., 2014](http://arxiv.org/abs/1412.6980),
    the underying Adam method is "*computationally
    efficient, has little memory requirement, invariant to diagonal rescaling of
    gradients, and is well suited for problems that are large in terms of
    data/parameters*".

    Args:
        learning_rate: A `tf.Tensor`, floating point value, a schedule that is a
            `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable
            that takes no arguments and returns the actual value to use. The
            learning rate. Defaults to 0.001.
        beta_1: A float value or a constant float tensor, or a callable
            that takes no arguments and returns the actual value to use. The
            exponential decay rate for the 1st moment estimates.
            Defaults to 0.9.
        beta_2: A float value or a constant float tensor, or a callable
            that takes no arguments and returns the actual value to use. The
            exponential decay rate for the 2nd moment estimates.
            Defaults to 0.999.
        epsilon: A small constant for numerical stability. This epsilon is
            "epsilon hat" in the Kingma and Ba paper (in the formula just before
            Section 2.1), not the epsilon in Algorithm 1 of the paper.
            Defaults to 1e-7.
        amsgrad: Boolean. Whether to apply AMSGrad variant of this algorithm
            from the paper "On the Convergence of Adam and beyond".
            Defaults to `False`.
        {{base_optimizer_keyword_args}}

    Reference:
      - [Loshchilov et al., 2019](https://arxiv.org/abs/1711.05101)
      - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980) for `adam`
      - [Reddi et al., 2018](
          https://openreview.net/pdf?id=ryQu7f-RZ) for `amsgrad`.

    Notes:

    The sparse implementation of this algorithm (used when the gradient is an
    IndexedSlices object, typically because of `tf.gather` or an embedding
    lookup in the forward pass) does apply momentum to variable slices even if
    they were not used in the forward pass (meaning they have a gradient equal
    to zero). Momentum decay (beta1) is also applied to the entire momentum
    accumulator. This means that the sparse behavior is equivalent to the dense
    behavior (in contrast to some momentum implementations which ignore momentum
    unless a variable slice was actually used).
    c                     t        |   d||||	|
|||d| | j                  |      | _        || _        || _        || _        || _        || _        | j                  t        d      y )N)nameclipnorm	clipvalueglobal_clipnormuse_emaema_momentumema_overwrite_frequencyjit_compilezLMissing value of `weight_decay` which is required and must be a float value. )
super__init___build_learning_rate_learning_rateweight_decaybeta_1beta_2epsilonamsgrad
ValueError)selflearning_rater   r   r   r   r   r   r   r   r   r   r   r   r
   kwargs	__class__s                   [/var/www/html/dev/engine/venv/lib/python3.12/site-packages/tf_keras/src/optimizers/adamw.pyr   zAdamW.__init__Z   s    $ 	 
	
+%$;#
	
 
	
 #77F($*  %    c                    t         |   |       t        | d      r| j                  ryd| _        g | _        g | _        |D ]Z  }| j                  j                  | j                  |d             | j
                  j                  | j                  |d             \ | j                  r;g | _	        |D ].  }| j                  j                  | j                  |d             0 yy)a  Initialize optimizer variables.

        AdamW optimizer has 3 types of variables: momentums, velocities and
        velocity_hat (only set when amsgrad is applied),

        Args:
          var_list: list of model variables to build AdamW variables on.
        _builtNTm)model_variablevariable_namevvhat)
r   buildhasattrr$   
_momentums_velocitiesappendadd_variable_from_referencer   _velocity_hats)r   var_listvarr    s      r!   r*   zAdamW.build   s     	h4"t{{ 
	COO""00#&c 1 
 ##00#&c 1 
	 <<"$D ##**44'*& 5  r"   c                 V   t        j                  | j                  |j                        }t        j                  | j                  dz   |j                        }t        j
                  t        j                  | j                  |j                        |      }t        j
                  t        j                  | j                  |j                        |      }| j                  |      }| j                  | j                  |      }| j                  | j                  |      }	|t        j                  d|z
        z  d|z
  z  }
t        |t         j                        rp|j                  | d| j                  z
  z         |j!                  t        j                  |j"                  d| j                  z
  z  |j$                               |	j                  |	 d| j                  z
  z         |	j!                  t        j                  t        j&                  |j"                        d| j                  z
  z  |j$                               | j(                  rC| j*                  | j                  |      }|j-                  t        j.                  ||	             |}	|j1                  ||
z  t        j                  |	      | j2                  z   z         y|j                  ||z
  d| j                  z
  z         |	j                  t        j&                  |      |	z
  d| j                  z
  z         | j(                  rC| j*                  | j                  |      }|j-                  t        j.                  ||	             |}	|j1                  ||
z  t        j                  |	      | j2                  z   z         y)z=Update step given gradient and the associated model variable.   N)tfcastr   dtype
iterationspowr   r   _var_keyr,   _index_dictr-   sqrt
isinstanceIndexedSlices
assign_addscatter_addvaluesindicessquarer   r0   assignmaximum
assign_subr   )r   gradientvariablelr
local_stepbeta_1_powerbeta_2_powervar_keyr%   r(   alphav_hats               r!   update_stepzAdamW.update_step   s   WWT''8WWT__q0(..A
vvbggdkk8>>BJOvvbggdkk8>>BJO--)OOD,,W56T--g67RWWQ-..!l2BCh 0 01LL!q4;;/0MM  OOq4;;79I9I
 LL!q4;;/0MM  IIhoo.!dkk/B$$ ||++D,<,<W,EFRZZq12UrwwqzDLL/H IJ LL(Q,1t{{?;<LL"))H-1a$++oFG||++D,<,<W,EFRZZq12UrwwqzDLL/H IJr"   c           	          t         |          }|j                  | j                  | j                        | j
                  | j                  | j                  | j                  | j                  d       |S )N)r   r   r   r   r   r   )
r   
get_configupdate_serialize_hyperparameterr   r   r   r   r   r   )r   configr    s     r!   rR   zAdamW.get_config   sf    #%!%!?!?''" !% 1 1++++<<<<		
 r"   )gMbP?gMbp?g?g+?gHz>FNNNFgGz?NTr   )	__name__
__module____qualname____doc__r   r*   rP   rR   __classcell__)r    s   @r!   r   r      sR    5r  $(T!F)KV r"   r   z{{base_optimizer_keyword_args}})rY   tensorflow.compat.v2compatv2r5   tf_keras.src.optimizersr   'tf_keras.src.saving.object_registrationr    tensorflow.python.util.tf_exportr   	Optimizerr   replacebase_optimizer_keyword_argsr   r"   r!   <module>rd      s    & " ! - O : )1		I  D %%%y'L'Lr"   