
    BVh                         d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddl	mZ dd	l	mZ dd
l	mZ  G d dej                        Zy)z Adamax optimizer implementation.    )dtypes)ops)tensor_conversion)backend_config)optimizer_v2)	array_ops)control_flow_ops)gen_training_ops)math_opsc                   \     e Zd ZdZdZ	 	 	 	 	 d	 fd	Zd Z fdZd
dZd
dZ	 fdZ
 xZS )Adamaxa  Optimizer that implements the Adamax algorithm.

  It is a variant of Adam based on the infinity norm.
  Default parameters follow those provided in the paper.
  Adamax is sometimes superior to adam, specially in models with embeddings.

  Initialization:

  ```python
  m = 0  # Initialize initial 1st moment vector
  v = 0  # Initialize the exponentially weighted infinity norm
  t = 0  # Initialize timestep
  ```

  The update rule for parameter `w` with gradient `g` is
  described at the end of section 7.1 of the paper:

  ```python
  t += 1
  m = beta1 * m + (1 - beta) * g
  v = max(beta2 * v, abs(g))
  current_lr = learning_rate / (1 - beta1 ** t)
  w = w - current_lr * m / (v + epsilon)
  ```

  Similarly to `Adam`, the epsilon is added for numerical stability
  (especially to get rid of division by zero when `v_t == 0`).

  In contrast to `Adam`, 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) only updates
  variable slices and corresponding `m_t`, `v_t` terms when that part of
  the variable was used in the forward pass. This means that the sparse
  behavior is contrast to the dense behavior (similar to some momentum
  implementations which ignore momentum unless a variable slice was actually
  used).

  Args:
    learning_rate: A `Tensor`, floating point value, or a schedule that is a
      `tf.keras.optimizers.schedules.LearningRateSchedule`. The learning rate.
    beta_1: A float value or a constant float tensor. The exponential decay
      rate for the 1st moment estimates.
    beta_2: A float value or a constant float tensor. The exponential decay
      rate for the exponentially weighted infinity norm.
    epsilon: A small constant for numerical stability.
    name: Optional name for the operations created when applying gradients.
      Defaults to `"Adamax"`.
    **kwargs: Keyword arguments. Allowed to be one of
      `"clipnorm"` or `"clipvalue"`.
      `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips
      gradients by value.

  Reference:
    - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980)
  Tc                 ,   t        t        | 
  |fi | | j                  d|j	                  d|             | j                  d| j
                         | j                  d|       | j                  d|       |xs t        j                         | _        y )Nlearning_ratelrdecaybeta_1beta_2)superr   __init__
_set_hyperget_initial_decayr   epsilon)selfr   r   r   r   namekwargs	__class__s          [/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/optimizer_v2/adamax.pyr   zAdamax.__init__X   sw     
&$ 00OOOVZZm%DEOOGT001OOHf%OOHf%6n446DL    c                 h    |D ]  }| j                  |d        |D ]  }| j                  |d        y )Nmv)add_slot)r   var_listvars      r   _create_slotszAdamax._create_slotsf   s<     
mmC 
mmCr   c                 ,   t         t        |   |||       t        j                  | j
                  dz   |      }t        j                  | j                  d|            }t        j                  | j                  d|            }t        j                  ||      }|||f   d   }|||f   j                  t        | d|z
  z  t        j                  | j                  |      ||d|z
  |t        j                  dt         j"                                     y )N   r   r   lr_t )dtype)neg_scaled_lrr   beta_1_tbeta_1_powerone_minus_beta_1_tbeta_2_tzero)r   r   _prepare_localr   cast
iterationsr   identity
_get_hyperpowupdatedictr   "convert_to_tensor_v2_with_dispatchr   zerosr   int64)
r   
var_device	var_dtypeapply_state
local_stepr-   r0   r.   r)   r   s
            r   r2   zAdamax._prepare_localm   s    	&$&z9kJt2I>J!!$//(I"FGH!!$//(I"FGH<<*5L
I./7DY'(//%1|#34%HHi % 8|6<<8
	
r   c                    |j                   |j                  j                  }}|xs i j                  ||f      xs | j	                  ||      }| j                  |d      }| j                  |d      }t        j                  |j                  |j                  |j                  |d   |d   |d   |d   |d   || j                  
      S )	Nr!   r"   r.   r)   r-   r0   r   )
r%   r!   r"   beta1_powerr   beta1beta2r   graduse_locking)
devicer+   
base_dtyper   _fallback_apply_stateget_slotr
   ResourceApplyAdaMaxhandle_use_locking)	r   rE   r%   r?   r=   r>   coefficientsr!   r"   s	            r   _resource_apply_densezAdamax._resource_apply_dense   s    JJ		(<(<	J &B++Z,CD I11*iH  	c3Ac3A//JJ
((
(( 0:&:&Y'%%
' 
'r   c                    |j                   |j                  j                  }}|xs i j                  ||f      xs | j	                  ||      }| j                  |d      }t        j                  |||d         }	|	|d   z  ||d   z  z   }
t        j                  |
g      5  | j                  |||
      }d d d        | j                  |d      }t        j                  |||d         }t        j                  ||d   z  t        j                  |            }t        j                  |g      5  | j                  |||      }d d d        |d   |
||d	   z   z  z  }t        j                  |g      5  | j                  |||      }d d d        t        j                   g S # 1 sw Y   xY w# 1 sw Y   mxY w# 1 sw Y   6xY w)
Nr!   r1   )axisr-   r/   r"   r0   r,   r   )rG   r+   rH   r   rI   rJ   r   gatherr   control_dependencies_resource_scatter_updater   maximumabs_resource_scatter_addr	   group)r   rE   r%   indicesr?   r=   r>   rN   r!   m_slice	m_t_slicem_tr"   v_slice	v_t_slicev_t	var_slice
var_updates                     r   _resource_apply_sparsezAdamax._resource_apply_sparse   s   JJ		(<(<	J &B++Z,CD I11*iH  	c3Aq'V0DEG<
33%9::;I		!	!9+	. A))!Wi@cA 	c3Aq'V0DEG  <
+C!C!)d!35I		!	!9+	. A))!Wi@cA _-Yi!889;I		!	!9+	. G--c7IFjG!!JS#9::A AA A
G Gs$   "F$0F03F<$F-0F9<Gc                     t         t        |          }|j                  | j	                  d      | j
                  | j	                  d      | j	                  d      | j                  d       |S )Nr   r   r   )r   r   r   r   r   )r   r   
get_configr8   _serialize_hyperparameterr   r   )r   configr   s     r   rd   zAdamax.get_config   sd    64+-F
MM77H$$00:00:<<  Mr   )gMbP?g?g+?gHz>r   )N)__name__
__module____qualname____doc___HAS_AGGREGATE_GRADr   r&   r2   rO   rb   rd   __classcell__)r   s   @r   r   r      sE    6p  #7.'&;6	 	r   r   N)rj   tensorflow.python.frameworkr   r   r   tensorflow.python.kerasr   $tensorflow.python.keras.optimizer_v2r   tensorflow.python.opsr   r	   r
   r   OptimizerV2r   r*   r   r   <module>rr      s;    ' / + 9 2 = + 2 2 *^\%% ^r   