B
    ӻd                 @   s   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 edG dd dejZdS )z Adamax optimizer implementation.    )dtypes)ops)backend_config)optimizer_v2)	array_ops)control_flow_ops)math_ops)gen_training_ops)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 )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)
  TMbP??+?Hz>c                s`   t t| j|f| | d|d| | d| j | d| | d| |pXt | _d S )Nlearning_ratelrdecaybeta_1beta_2)superr   __init__Z
_set_hyperget_initial_decayr   epsilon)selfr   r   r   r   namekwargs)	__class__ ]/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/optimizer_v2/adamax.pyr   Y   s    zAdamax.__init__c             C   s8   x|D ]}|  |d qW x|D ]}|  |d q W d S )Nmv)Zadd_slot)r   Zvar_listvarr   r   r   _create_slotsg   s    

zAdamax._create_slotsc       	         s   t 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   r   _prepare_localr   castZ
iterationsr   identityZ
_get_hyperpowupdatedictr   Z"convert_to_tensor_v2_with_dispatchr   Zzerosr   Zint64)	r   
var_device	var_dtypeapply_stateZ
local_stepr(   r+   r)   r%   )r   r   r   r-   n   s     zAdamax._prepare_localNc       	      C   s   |j |jj }}|pi ||fp,| ||}| |d}| |d}tj|j|j|j|d |d |d |d |d || j	d
S )	Nr    r!   r)   r%   r(   r+   r   )
r"   r    r!   Zbeta1_powerr   Zbeta1Zbeta2r   gradZuse_locking)
devicer&   
base_dtyper   _fallback_apply_stateget_slotr	   ZResourceApplyAdaMaxhandleZ_use_locking)	r   r6   r"   r5   r3   r4   coefficientsr    r!   r   r   r   _resource_apply_dense   s     zAdamax._resource_apply_densec          	   C   s:  |j |jj }}|pi ||fp,| ||}| |d}tj|||d d}	|	|d  ||d   }
t	|
g | 
|||
}W d Q R X | |d}tj|||d d}t||d  t|}t	|g | 
|||}W d Q R X |d |
||d	    }t	|g | |||}W d Q R X tj|||g S )
Nr    r,   )Zaxisr(   r*   r!   r+   r'   r   )r7   r&   r8   r   r9   r:   r   gatherr   Zcontrol_dependenciesZ_resource_scatter_updater   maximumabsZ_resource_scatter_addr   group)r   r6   r"   indicesr5   r3   r4   r<   r    Zm_sliceZ	m_t_sliceZm_tr!   Zv_sliceZ	v_t_sliceZv_tZ	var_sliceZ
var_updater   r   r   _resource_apply_sparse   s(    
zAdamax._resource_apply_sparsec                s>   t t|  }|| d| j| d| d| jd |S )Nr   r   r   )r   r   r   r   r   )r   r   
get_configr1   Z_serialize_hyperparameterr   r   )r   config)r   r   r   rD      s    zAdamax.get_config)r   r   r   r   r   )N)N)__name__
__module____qualname____doc__Z_HAS_AGGREGATE_GRADr   r#   r-   r=   rC   rD   __classcell__r   r   )r   r   r      s   8    	

r   N)rI   Ztensorflow.python.frameworkr   r   Ztensorflow.python.kerasr   Z$tensorflow.python.keras.optimizer_v2r   Ztensorflow.python.opsr   r   r   Ztensorflow.python.trainingr	   Z tensorflow.python.util.tf_exportr
   ZOptimizerV2r   r   r   r   r   <module>   s   