a
    Sic)T                     @   sj   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G d	d
 d
ejZdS )zAdam optimizer implementation.    N)backend_config)optimizer_v2)keras_exportzkeras.optimizers.Adamc                       sf   e Zd ZdZdZd fdd		Zd
d Z fddZ fddZdddZ	dddZ
 fddZ  ZS )Adama  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.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).
    TMbP??+?Hz>Fc                    sf   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amsgradselfr
   r   r   r   r   namekwargs	__class__ ^/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/optimizers/optimizer_v2/adam.pyr   h   s    
zAdam.__init__c                 C   sL   |D ]}|  |d q|D ]}|  |d q| jrH|D ]}|  |d q6d S Nmvvhatadd_slotr   r   var_listvarr   r   r   _create_slotsz   s    zAdam._create_slotsc           
         s   t  ||| t| jd |}t| d|}t| d|}t||}t||}|||f d td| d|   }	|||f 	t
|	t| j|||d| ||d| d d S 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_stepr,   r/   r-   r0   r   r   r   r   r3      s*    zAdam._prepare_localc                    sN   | j }tt|d d }t|d| d kr>|d t| }t | d S Nr*         weightsintlenr   set_weightsr   rG   paramsnum_varsr   r   r   rJ      s
    zAdam.set_weightsNc           
      C   s   |j |jj }}|pi ||fp,| ||}| |d}| |d}| jstjj	|j
|j
|j
|d |d |d |d |d |d || jd	S | |d
}	tjj|j
|j
|j
|	j
|d |d |d |d |d |d || jdS d S )Nr    r!   r-   r0   r+   r,   r/   r   )r'   r    r!   beta1_powerbeta2_powerr   beta1beta2r   graduse_lockingr"   )r'   r    r!   r"   rN   rO   r   rP   rQ   r   rR   rS   )devicedtype
base_dtyper   _fallback_apply_stateget_slotr   r4   raw_opsResourceApplyAdamhandle_use_lockingResourceApplyAdamWithAmsgrad)
r   rR   r'   rA   r?   r@   coefficientsr    r!   r"   r   r   r   _resource_apply_dense   sJ    
zAdam._resource_apply_densec                 C   s  |j |jj }}|pi ||fp,| ||}| |d}||d  }	tjjj	|||d  | j
d}
t|
g | |||	}
W d    n1 s0    Y  | |d}|| |d  }tjjj	|||d  | j
d}t|g | |||}W d    n1 s
0    Y  | js`t|}tjjj||d |
 ||d	   | j
d}tj||
|g S | |d
}t||}t|g& tjjj	||| j
d}W d    n1 s0    Y  t|}tjjj||d |
 ||d	   | j
d}tj||
||g S d S )Nr    r.   r,   )rS   r!   r1   r/   r   r   r"   )rT   rU   rV   r   rW   rX   r4   compatv1assignr\   control_dependencies_resource_scatter_addr   r:   
assign_subgroupmaximum)r   rR   r'   indicesrA   r?   r@   r^   r    m_scaled_g_valuesm_tr!   v_scaled_g_valuesv_tv_sqrt
var_updatev_hatv_hat_t
v_hat_sqrtr   r   r   _resource_apply_sparse   sZ    
,.
&

zAdam._resource_apply_sparsec              	      s>   t   }|| d| j| d| d| j| jd |S Nr
   r   r   )r
   r   r   r   r   r   r   
get_configr;   _serialize_hyperparameterr   r   r   r   configr   r   r   ru      s    
zAdam.get_config)r   r   r   r	   Fr   )N)N)__name__
__module____qualname____doc___HAS_AGGREGATE_GRADr   r(   r3   rJ   r_   rr   ru   __classcell__r   r   r   r   r      s   J      

(
1r   c                       s~   e Zd ZdZdZd fd	d
	Zdd Z fddZ fddZe	j
dddddZe	j
dddddZ fddZ  ZS )NonFusedAdama   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.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
    Tr   r   r   r	   Fr   c                    sf   t  j|fi | | d|d| | d| j | d| | d| |pXt | _|| _dS )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   r   r   r   r   \  s    *zNonFusedAdam.__init__c                 C   sL   |D ]}|  |d q|D ]}|  |d q| jrH|D ]}|  |d q6d S r   r#   r%   r   r   r   r(     s    zNonFusedAdam._create_slotsc           
         s   t  ||| t| jd |}t| d|}t| d|}t||}t||}|||f d td| d|   }	|||f 	t
|	t| j|||d| ||d| d d S r)   r2   r>   r   r   r   r3     s*    zNonFusedAdam._prepare_localc                    sN   | j }tt|d d }t|d| d kr>|d t| }t | d S rC   rF   rK   r   r   r   rJ     s
    zNonFusedAdam.set_weights)jit_compileNc                 C   s   |j |jj }}|pi ||fp,| ||}| |d}| |d}|d td|d   d|d   }	||| d|d    |t	|| d|d    | j
r| |d	}
|
t|
| |
}|||	 t||d
    d S )Nr    r!   r+   r*   r0   r-   r,   r/   r"   r   )rT   rU   rV   r   rW   rX   r4   r:   
assign_addsquarer   rb   rg   re   )r   rR   r'   rA   r?   r@   r^   r    r!   alphar"   r   r   r   r_     s*    

 z"NonFusedAdam._resource_apply_densec                 C   s  |j |jj }}|pi ||fp,| ||}| |d}||d  }	|||d   |t	|	| | |d}
|| |d  }|
|
|d   |
t	|| | j
s||d | t|
|d    nB| |d	}|t||
 ||d | t||d    d S )
Nr    r.   r,   r!   r1   r/   r   r   r"   )rT   rU   rV   r   rW   rX   rb   scatter_addr4   IndexedSlicesr   re   r:   rg   )r   rR   r'   rh   rA   r?   r@   r^   r    ri   r!   rk   ro   r   r   r   rr     s6    
z#NonFusedAdam._resource_apply_sparsec              	      s>   t   }|| d| j| d| d| j| jd |S rs   rt   rw   r   r   r   ru     s    
zNonFusedAdam.get_config)r   r   r   r	   Fr   )N)N)ry   rz   r{   r|   r}   r   r(   r3   rJ   r4   functionr_   rr   ru   r~   r   r   r   r   r     s"   H      2


r   )r|   tensorflow.compat.v2r`   v2r4   kerasr   keras.optimizers.optimizer_v2r    tensorflow.python.util.tf_exportr   OptimizerV2r   r   r   r   r   r   <module>   s    w