a
    Sic6+                     @   s~   d Z ddlZddlm  mZ ddlmZ ddlm	Z	 ddl
mZ e	 edg dG dd	 d	ejZej d
eje_ dS )zAdamW optimizer implementation.    N)	optimizer)generic_utils)keras_exportz#keras.optimizers.experimental.AdamW)v1c                       sT   e Zd ZdZd fdd	Z fddZdd Zdd Z fddZdddZ	  Z
S )AdamWa  Optimizer that implements the AdamW algorithm.

    AdamW optimization is a stochastic gradient descent method that is based on
    adaptive estimation of first-order and second-order moments with an added
    method to decay weights per the techniques discussed in the paper,
    'Decoupled Weight Decay Regularization' by
    [Loshchilov, Hutter et al., 2019](https://arxiv.org/abs/1711.05101).

    According to
    [Kingma et al., 2014](http://arxiv.org/abs/1412.6980),
    the underying Adam 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 `tf.Tensor`, floating point value, 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.
      weight_decay: A `tf.Tensor`, floating point value. The weight decay.
        Defaults to 0.004.
      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`.
      {{base_optimizer_keyword_args}}

    Reference:
      - [Loshchilov et al., 2019](https://arxiv.org/abs/1711.05101)
      - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980) for `adam`
      - [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).
    MbP?Mbp??+?Hz>FNGz?Tc                    sd   t  jf ||||	|
|||d| | || _|| _|| _|| _|| _|| _| jd u r`t	dd S )N)nameclipnorm	clipvalueglobal_clipnormuse_emaema_momentumema_overwrite_frequencyjit_compilezLMissing value of `weight_decay` which is required and must be a float value.)
super__init___build_learning_rate_learning_rateweight_decaybeta_1beta_2epsilonamsgrad
ValueError)selflearning_rater   r   r   r   r   r   r   r   r   r   r   r   r   kwargs	__class__ i/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/optimizers/optimizer_experimental/adamw.pyr   \   s,    	
zAdamW.__init__c                    s   t  | t| dr | jr dS d| _g | _g | _|D ]0}| j| j|dd | j| j|dd q6| jrg | _	|D ]}| j	| j|dd qxdS )a  Initialize optimizer variables.

        AdamW optimizer has 3 types of variables: momentums, velocities and
        velocity_hat (only set when amsgrad is applied),

        Args:
          var_list: list of model variables to build AdamW variables on.
        _builtNTm)model_variablevariable_namevvhat)
r   buildhasattrr&   
_momentums_velocitiesappendadd_variable_from_referencer   _velocity_hats)r   var_listvarr"   r$   r%   r,      s2    	zAdamW.buildc                 C   sJ   t | dg }t | dg }||v r$dS |D ]}t||jd ur( dS q(dS )N_exclude_from_weight_decay _exclude_from_weight_decay_namesFT)getattrresearchr   )r   variableexclude_from_weight_decayZexclude_from_weight_decay_namesr   r$   r$   r%   _use_weight_decay   s    zAdamW._use_weight_decayc                 C   s   d}d}t | j|j}t | jd |j}t t | j|j|}t t | j|j|}| |}| j	| j
|  }| j| j
|  }	|t d|  d|  }
| |rt | j|j}||| |  t|t jr|| d| j   |t |jd| j  |j |	|	 d| j   |	t t |jd| j  |j | jrz| j| j
|  }|t ||	 |}	|||
 t |	| j   n||| d| j   |	t ||	 d| j   | jr| j| j
|  }|t ||	 |}	|||
 t |	| j   dS )z=Update step given gradient and the associated model variable.N   )tfcastr    dtype
iterationspowr   r   _var_keyr.   _index_dictr/   sqrtr<   r   
assign_sub
isinstanceIndexedSlices
assign_addscatter_addvaluesindicessquarer   r2   assignmaximumr   )r   gradientr:   beta_1_powerbeta_2_powerlr
local_stepvar_keyr'   r*   alphawdv_hatr$   r$   r%   update_step   sN    

 zAdamW.update_stepc              	      s8   t   }|| | j| j| j| j| j| j	d |S )N)r    r   r   r   r   r   )
r   
get_configupdate_serialize_hyperparameterr   r   r   r   r   r   )r   configr"   r$   r%   rZ      s    
zAdamW.get_configc                 C   s0   t | dr| jrtd|pg | _|p(g | _dS )a  Exclude variables from weight decays.

        This method must be called before the optimizer's `build` method is
        called. You can set specific variables to exclude out, or set a list of
        strings as the anchor words, if any of which appear in a variable's
        name, then the variable is excluded.

        Args:
            var_list: A list of `tf.Variable`s to exclude from weight decay.
            var_names: A list of strings. If any string in `var_names` appear
                in the model variable's name, then this model variable is
                excluded from weight decay. For example, `var_names=['bias']`
                excludes all bias variables from weight decay.
        r&   zR`exclude_from_weight_decay()` can only be configued before the optimizer is built.N)r-   r&   r   r5   r6   )r   r3   	var_namesr$   r$   r%   r;      s    
zAdamW.exclude_from_weight_decay)r   r   r	   r
   r   FNNNFr   NTr   )NN)__name__
__module____qualname____doc__r   r,   r<   rY   rZ   r;   __classcell__r$   r$   r"   r%   r      s*   ?              *#2r   z{{base_optimizer_keyword_args}})rb   r8   tensorflow.compat.v2compatv2r>   'keras.optimizers.optimizer_experimentalr   keras.utilsr    tensorflow.python.util.tf_exportr   register_keras_serializable	Optimizerr   replacebase_optimizer_keyword_argsr$   r$   r$   r%   <module>   s   
 v