
    6biV                         S r SSKJs  Jr  SSKJr  SSKJr  SSK	J
r
  \
" SSS/S9 " S	 S
\R                  5      5       r " S S\R                  5      rg)zAdam optimizer implementation.    N)backend_config)optimizer_v2)keras_exportzkeras.optimizers.legacy.Adamzkeras.optimizers.Adam)v1c                   ~   ^  \ rS rSrSrSr      SU 4S jjrS rU 4S jrU 4S jr	SS jr
SS	 jrU 4S
 jrSrU =r$ )Adam   a  Optimizer that implements the Adam algorithm.

Adam optimization is a stochastic gradient descent method that is based on
adaptive estimation of first-order and second-order moments.

According to
[Kingma et al., 2014](http://arxiv.org/abs/1412.6980),
the 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 `Tensor`, floating point value, or 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`.
  name: Optional name for the operations created when applying gradients.
    Defaults to `"Adam"`.
  **kwargs: keyword arguments. Allowed arguments are `clipvalue`,
    `clipnorm`, `global_clipnorm`.
    If `clipvalue` (float) is set, the gradient of each weight
    is clipped to be no higher than this value.
    If `clipnorm` (float) is set, the gradient of each weight
    is individually clipped so that its norm is no higher than this value.
    If `global_clipnorm` (float) is set the gradient of all weights is
    clipped so that their global norm is no higher than this value.

Usage:

>>> opt = tf.keras.optimizers.legacy.Adam(learning_rate=0.1)
>>> var1 = tf.Variable(10.0)
>>> loss = lambda: (var1 ** 2)/2.0       # d(loss)/d(var1) == var1
>>> step_count = opt.minimize(loss, [var1]).numpy()
>>> # The first step is `-learning_rate*sign(grad)`
>>> var1.numpy()
9.9

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

Notes:

The default value of 1e-7 for epsilon might not be a good default in
general. For example, when training an Inception network on ImageNet a
current good choice is 1.0 or 0.1. Note that since Adam uses the
formulation just before Section 2.1 of the Kingma and Ba paper rather than
the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon
hat" in the paper.

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).
Tc                 >  > [         TU ]  " U40 UD6  U R                  SUR                  SU5      5        U R                  SU R                  5        U R                  SU5        U R                  SU5        U=(       d    [
        R                  " 5       U l        XPl        g )Nlearning_ratelrdecaybeta_1beta_2super__init__
_set_hyperget_initial_decayr   epsilonamsgrad	selfr   r   r   r   r   namekwargs	__class__s	           ]/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/optimizers/legacy/adam.pyr   Adam.__init__l   sz     	((D-)HI!4!45&)&):."8"8":    c                     U H  nU R                  US5        M     U H  nU R                  US5        M     U R                  (       a  U H  nU R                  US5        M     g g Nmvvhatadd_slotr   r   var_listvars      r   _create_slotsAdam._create_slots~   X     CMM#s# CMM#s# <<c6*   r   c                 @  > [         T
U ]  XU5        [        R                  " U R                  S-   U5      n[        R
                  " U R                  SU5      5      n[        R
                  " U R                  SU5      5      n[        R                  " XT5      n[        R                  " Xd5      nX1U4   S   [        R                  " SU-
  5      SU-
  -  -  n	X1U4   R                  [        U	[        R                  " U R                  U5      UUSU-
  UUSU-
  S95        g N   r   r   lr_t)r   r   beta_1_tbeta_1_powerone_minus_beta_1_tbeta_2_tbeta_2_powerone_minus_beta_2_tr   _prepare_localtfcast
iterationsidentity
_get_hyperpowsqrtupdatedictconvert_to_tensorr   r   
var_device	var_dtypeapply_state
local_stepr1   r4   r2   r5   r   r   s             r   r8   Adam._prepare_local       zkBWWT__q0)<
;;txCD;;txCDvvh3vvh3i01&9GGA$%\)9:
 	+,33,,T\\9E!)#$x<!)#$x<		
r   c                    > U R                   n[        [        U5      S-
  S-  5      n[        U5      SU-  S-   :X  a  US [        U5       n[        TU ]  U5        g Nr/         weightsintlenr   set_weightsr   rO   paramsnum_varsr   s       r   rR   Adam.set_weights   W     Fa1,-w<1x<!++mF,GG$r   c                    UR                   UR                  R                  pTU=(       d    0 R                  XE45      =(       d    U R	                  XE5      nU R                  US5      nU R                  US5      nU R                  (       da  [        R                  R                  UR                  UR                  UR                  US   US   US   US   US   US   UU R                  S	9$ U R                  US
5      n	[        R                  R                  UR                  UR                  UR                  U	R                  US   US   US   US   US   US   UU R                  S9$ )Nr"   r#   r2   r5   r0   r1   r4   r   )r)   r"   r#   beta1_powerbeta2_powerr   beta1beta2r   graduse_lockingr$   )r)   r"   r#   r$   rY   rZ   r   r[   r\   r   r]   r^   )devicedtype
base_dtyper   _fallback_apply_stateget_slotr   r9   raw_opsResourceApplyAdamhandle_use_lockingResourceApplyAdamWithAmsgrad)
r   r]   r)   rF   rD   rE   coefficientsr"   r#   r$   s
             r   _resource_apply_denseAdam._resource_apply_dense   sd    #

CII,@,@I#)r..#
 ?''
> 	 MM#s#MM#s#||:://JJ(((((8(8'":.":.$Y/ -- 0   ==f-D::::JJ(((([[(8(8'":.":.$Y/ -- ;  r   c                    UR                   UR                  R                  peU=(       d    0 R                  XV45      =(       d    U R	                  XV5      nU R                  US5      nXS   -  n	[        R                  R                  R                  XUS   -  U R                  S9n
[        R                  " U
/5         U R                  XU	5      n
S S S 5        U R                  US5      nX-  US   -  n[        R                  R                  R                  XUS   -  U R                  S9n[        R                  " U/5         U R                  XU5      nS S S 5        U R                  (       dl  [        R                  " U5      n[        R                  R                  R                  UUS   U
-  XS	   -   -  U R                  S9n[        R                   " XU/6 $ U R                  US
5      n[        R"                  " UU5      n[        R                  " U/5         [        R                  R                  R                  UUU R                  S9nS S S 5        [        R                  " U5      n[        R                  R                  R                  UUS   U
-  UUS	   -   -  U R                  S9n[        R                   " XUU/6 $ ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       N= f)Nr"   r3   r1   )r^   r#   r6   r4   r   r   r$   )r_   r`   ra   r   rb   rc   r9   compatr   assignrg   control_dependencies_resource_scatter_addr   r?   
assign_subgroupmaximum)r   r]   r)   indicesrF   rD   rE   ri   r"   m_scaled_g_valuesm_tr#   v_scaled_g_valuesv_tv_sqrt
var_updatev_hatv_hat_t
v_hat_sqrts                      r   _resource_apply_sparseAdam._resource_apply_sparse   s    #

CII,@,@I#)r..#
 ?''
> 	
 MM#s# 0D#EEiill!!<
++9J9J " 
 $$cU+,,Q9JKC , MM#s#![L9M,NNiill!!<
++9J9J " 
 $$cU+,,Q9JKC , ||WWS\F00T"S(F)5L,LM -- 1 J
 88js344MM#v.Ejj,G(('3)),,--70A0A .  4 )J00T"Y 779 !-- 1 J 88jsG<==G ,+ ,+ 43s$   =KK4K)
K
K&)
K7c           	         > [         TU ]  5       nUR                  U R                  S5      U R                  U R                  S5      U R                  S5      U R
                  U R                  S.5        U$ Nr   r   r   )r   r   r   r   r   r   r   
get_configr@   _serialize_hyperparameterr   r   r   r   configr   s     r   r   Adam.get_config  n    #%!%!?!?#" ,,88B88B<<<<		
 r   r   r   gMbP?g?g+?gHz>Fr   N)__name__
__module____qualname____firstlineno____doc___HAS_AGGREGATE_GRADr   r*   r8   rR   rj   r~   r   __static_attributes____classcell__r   s   @r   r   r      sP    
IV  $	+
0%&P/>b r   r   c                      ^  \ rS rSrSrSr      SU 4S jjrS rU 4S jrU 4S jr	\
R                  " SS9S	 5       rSS
 jr\
R                  " SS9S 5       rSS jrU 4S jrSrU =r$ )NonFusedAdami  aK  Optimizer that implements the Adam algorithm without fused kernels.

Adam optimization is a stochastic gradient descent method that is based on
adaptive estimation of first-order and second-order moments.
According to the paper
[Adam: A Method for Stochastic Optimization. Kingma et al.,
2014](http://arxiv.org/abs/1412.6980), the 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*".

For AMSGrad see [On The Convergence Of Adam And Beyond.
Reddi et al., 5-8](https://openreview.net/pdf?id=ryQu7f-RZ).

**If amsgrad = False**:

initialize $m_0$ as 1st moment vector
initialize $v_0$ as 2nd moment vector

The update rule for $\theta$ with gradient $g$ uses an optimization
described at the end of section 2 of the paper:

$$lr_t = \mathrm{learning\_rate} *
  \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$
$$m_t = \beta_1 * m_{t-1} + (1 - \beta_1) * g$$
$$v_t = \beta_2 * v_{t-1} + (1 - \beta_2) * g^2$$
$$\theta_t = \theta_{t-1} - lr_t * m_t / (\sqrt{v_t} + \epsilon)$$

**If amsgrad = True**:

initialize $m_0$ as 1st moment vector
initialize $v_0$ as 2nd moment vector
initialize $\hat{v}_0$ as 2nd moment vector

The update rule for $\theta$ with gradient $g$ uses an optimization
described at the end of section 2 of the paper:

$$lr_t = \mathrm{learning\_rate} *
  \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$

$$m_t = \beta_1 * m_{t-1} + (1 - \beta_1) * g$$
$$v_t = \beta_2 * v_{t-1} + (1 - \beta_2) * g^2$$
$$\hat{v}_t = \max(\hat{v}_{t-1}, v_t)$$
$$\theta_t = \theta_{t-1} - lr_t * m_t / (\sqrt{\hat{v}_t} + \epsilon)$$

The default value of 1e-7 for epsilon might not be a good default in
general. For example, when training an Inception network on ImageNet a
current good choice is 1.0 or 0.1. Note that since Adam uses the
formulation just before Section 2.1 of the Kingma and Ba paper rather than
the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon
hat" in the paper.

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).

Usage:

>>> opt = tf.keras.optimizers.legacy.Adam(learning_rate=0.1)
>>> var1 = tf.Variable(10.0)
>>> loss = lambda: (var1 ** 2)/2.0       # d(loss)/d(var1) == var1
>>> step_count = opt.minimize(loss, [var1]).numpy()
>>> # The first step is `-learning_rate*sign(grad)`
>>> var1.numpy()
9.9
Tc                 >  > [         TU ]  " U40 UD6  U R                  SUR                  SU5      5        U R                  SU R                  5        U R                  SU5        U R                  SU5        U=(       d    [
        R                  " 5       U l        XPl        g)a*  Construct a new Adam optimizer.

Args:
  learning_rate: A `Tensor`, floating point value, or 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`.
  name: Optional name for the operations created when applying
    gradients.  Defaults to "Adam".
  **kwargs: 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.
r   r   r   r   r   Nr   r   s	           r   r   NonFusedAdam.__init__`  s{    T 	((D-)HI!4!45&)&):."8"8":r   c                     U H  nU R                  US5        M     U H  nU R                  US5        M     U R                  (       a  U H  nU R                  US5        M     g g r!   r%   r'   s      r   r*   NonFusedAdam._create_slots  r,   r   c                 @  > [         T
U ]  XU5        [        R                  " U R                  S-   U5      n[        R
                  " U R                  SU5      5      n[        R
                  " U R                  SU5      5      n[        R                  " XT5      n[        R                  " Xd5      nX1U4   S   [        R                  " SU-
  5      SU-
  -  -  n	X1U4   R                  [        U	[        R                  " U R                  U5      UUSU-
  UUSU-
  S95        g r.   r7   rC   s             r   r8   NonFusedAdam._prepare_local  rI   r   c                    > U R                   n[        [        U5      S-
  S-  5      n[        U5      SU-  S-   :X  a  US [        U5       n[        TU ]  U5        g rK   rN   rS   s       r   rR   NonFusedAdam.set_weights  rW   r   )jit_compilec                    UR                   UR                  R                  pTU=(       d    0 R                  XE45      =(       d    U R	                  XE5      nU R                  US5      nU R                  US5      nUS   [        R                  " SUS   -
  5      -  SUS   -
  -  n	UR                  X-
  SUS   -
  -  5        UR                  [        R                  " U5      U-
  SUS   -
  -  5        U R                  (       a9  U R                  US	5      n
U
R                  [        R                  " X5      5        U
nUR                  Xy-  [        R                  " U5      US
   -   -  5        g )Nr"   r#   r0   r/   r5   r2   r1   r4   r$   r   )r_   r`   ra   r   rb   rc   r9   r?   
assign_addsquarer   rn   rs   rq   )r   r]   r)   rF   rD   rE   ri   r"   r#   alphar$   s              r   _resource_apply_dense_impl'NonFusedAdam._resource_apply_dense_impl  sC    #

CII,@,@I#)r..#
 ?''
> 	 MM#s#MM#s#  gga,~6678<//1 	
 	
dh1|J'?#?@A	biio)a,z2J.JKL<<==f-DKK

4+,A	bggaj<	3J&JKLr   c                     U R                  XU5        [        R                  " 5       (       d9  [        R                  R                  R                  5       R                  5       S   $ g N)r   r9   executing_eagerlyrm   r   get_default_graphget_operations)r   r]   r)   rF   s       r   rj   "NonFusedAdam._resource_apply_dense  sK    '';?##%%99<<113BBDRHH &r   c                 d   UR                   UR                  R                  peU=(       d    0 R                  XV45      =(       d    U R	                  XV5      nU R                  US5      nXS   -  n	UR                  XS   -  5        UR                  [        R                  " X5      5        U R                  US5      n
X-  US   -  nU
R                  XS   -  5        U
R                  [        R                  " X5      5        U R                  (       d5  UR                  US   U-  [        R                  " U
5      US   -   -  5        g U R                  US	5      nUR                  [        R                  " X5      5        UR                  US   U-  [        R                  " U5      US   -   -  5        g )
Nr"   r3   r1   r#   r6   r4   r   r   r$   )r_   r`   ra   r   rb   rc   rn   scatter_addr9   IndexedSlicesr   rq   r?   rs   )r   r]   r)   rt   rF   rD   rE   ri   r"   ru   r#   rw   r{   s                r   _resource_apply_sparse_impl(NonFusedAdam._resource_apply_sparse_impl  sz    #

CII,@,@I#)r..#
 ?''
> 	
 MM#s# 0D#EE	*--.	b&&'8BC MM#s#![L9M,NN	*--.	b&&'8BC||NNT"Q&"''!*|I7N*NO MM#v.ELLE-.NNT"775>L$;;=r   c                     U R                  XX45        [        R                  " 5       (       d9  [        R                  R                  R                  5       R                  5       S   $ g r   )r   r9   r   rm   r   r   r   )r   r]   r)   rt   rF   s        r   r~   #NonFusedAdam._resource_apply_sparse  sK    ((GI##%%99<<113BBDRHH &r   c           	         > [         TU ]  5       nUR                  U R                  S5      U R                  U R                  S5      U R                  S5      U R
                  U R                  S.5        U$ r   r   r   s     r   r   NonFusedAdam.get_config   r   r   r   r   r   )r   r   r   r   r   r   r   r*   r8   rR   r9   functionr   rj   r   r~   r   r   r   r   s   @r   r   r     s    FP  0d	+
0% [[T"M #M,I
 [[T" #>I
 r   r   )r   tensorflow.compat.v2rm   v2r9   tf_keras.srcr   tf_keras.src.optimizers.legacyr    tensorflow.python.util.tf_exportr   OptimizerV2r   r    r   r   <module>r      se    % ! ! ' 7 : "!?@t<## t	tny<++ yr   