a
    Sic^                     @   sX   d Z ddlm  mZ ddlmZ ddlmZ ddl	m
Z
 e
dG dd dejZdS )	z Adamax optimizer implementation.    N)backend_config)optimizer_v2)keras_exportzkeras.optimizers.Adamaxc                       sZ   e Zd ZdZdZd fdd	Zd	d
 Z fddZdddZdddZ	 fddZ
  ZS )Adamaxa2
  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 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.

    Reference:
      - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980)
    TMbP??+?Hz>c                    s`   t  j|fi | | d|d| | d| j | d| | d| |pXt | _d S )Nlearning_ratelrdecaybeta_1beta_2)super__init__
_set_hyperget_initial_decayr   epsilon)selfr
   r   r   r   namekwargs	__class__ `/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/optimizers/optimizer_v2/adamax.pyr   Z   s    	zAdamax.__init__c                 C   s0   |D ]}|  |d q|D ]}|  |d qd S )Nmv)add_slot)r   var_listvarr   r   r   _create_slotsj   s    zAdamax._create_slotsc           	         s   t  ||| t| jd |}t| d|}t| d|}t||}|||f d }|||f t	| d|  t
| j|||d| |tjdtjdd d S )N   r   r   lr_tr   )dtype)neg_scaled_lrr   beta_1_tbeta_1_powerone_minus_beta_1_tbeta_2_tzero)r   _prepare_localtfcast
iterationsidentity
_get_hyperpowupdatedictconvert_to_tensorr   zerosint64)	r   
var_device	var_dtypeapply_state
local_stepr&   r)   r'   r#   r   r   r   r+   q   s"    zAdamax._prepare_localNc           	      C   s   |j |jj }}|pi ||fp,| ||}| |d}| |d}tjj|j	|j	|j	|d |d |d |d |d || j
d
S )	Nr   r   r'   r#   r&   r)   r   )
r    r   r   beta1_powerr   beta1beta2r   graduse_locking)devicer$   
base_dtyper   _fallback_apply_stateget_slotr,   raw_opsResourceApplyAdaMaxhandle_use_locking)	r   r>   r    r9   r7   r8   coefficientsr   r   r   r   r   _resource_apply_dense   s(    
zAdamax._resource_apply_densec                 C   sz  |j |jj }}|pi ||fp,| ||}| |d}tj|||d d}	|	|d  ||d   }
t|
g | 	|||
}W d    n1 s0    Y  | |d}tj|||d d}t
||d  t|}t|g | 	|||}W d    n1 s0    Y  |d |
||d	    }t|g | |||}W d    n1 s`0    Y  tj|||g S )
Nr   r*   )axisr&   r(   r   r)   r%   r   )r@   r$   rA   r   rB   rC   r,   gathercontrol_dependencies_resource_scatter_updatemaximumabs_resource_scatter_addgroup)r   r>   r    indicesr9   r7   r8   rH   r   m_slice	m_t_slicem_tr   v_slice	v_t_slicev_t	var_slice
var_updater   r   r   _resource_apply_sparse   s2    


,..zAdamax._resource_apply_sparsec                    s:   t   }|| d| j| d| d| jd |S )Nr
   r   r   )r
   r   r   r   r   )r   
get_configr2   _serialize_hyperparameterr   r   )r   configr   r   r   r\      s    
zAdamax.get_config)r   r   r   r	   r   )N)N)__name__
__module____qualname____doc___HAS_AGGREGATE_GRADr   r!   r+   rI   r[   r\   __classcell__r   r   r   r   r      s   <     

r   )rb   tensorflow.compat.v2compatv2r,   kerasr   keras.optimizers.optimizer_v2r    tensorflow.python.util.tf_exportr   OptimizerV2r   r   r   r   r   <module>   s   