o
    i e                     @   sH  d Z ddl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 ddlmZ edG dd	 d	Zed
G dd deZedG dd deZedG dd deZedG dd deZeddG dd deZeddG dd deZG dd deZG d d! d!eZed"d)d$d%Zed&d*d'd(ZdS )+z)Various learning rate schedule functions.    N)backend)serialization_lib)serialization)keras_exportz/keras.optimizers.schedules.LearningRateSchedulec                   @   s8   e Zd ZdZejdd Zejdd Zedd Z	dS )	LearningRateSchedulea  The learning rate schedule base class.

    You can use a learning rate schedule to modulate how the learning rate
    of your optimizer changes over time.

    Several built-in learning rate schedules are available, such as
    `tf.keras.optimizers.schedules.ExponentialDecay` or
    `tf.keras.optimizers.schedules.PiecewiseConstantDecay`:

    ```python
    lr_schedule = keras.optimizers.schedules.ExponentialDecay(
        initial_learning_rate=1e-2,
        decay_steps=10000,
        decay_rate=0.9)
    optimizer = keras.optimizers.SGD(learning_rate=lr_schedule)
    ```

    A `LearningRateSchedule` instance can be passed in as the `learning_rate`
    argument of any optimizer.

    To implement your own schedule object, you should implement the `__call__`
    method, which takes a `step` argument (scalar integer tensor, the
    current training step count).
    Like for any other Keras object, you can also optionally
    make your object serializable by implementing the `get_config`
    and `from_config` methods.

    Example:

    ```python
    class MyLRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):

      def __init__(self, initial_learning_rate):
        self.initial_learning_rate = initial_learning_rate

      def __call__(self, step):
         return self.initial_learning_rate / (step + 1)

    optimizer = tf.keras.optimizers.SGD(learning_rate=MyLRSchedule(0.1))
    ```
    c                 C      t d| jj d)NLearning rate schedule 'z'' must override `__call__(self, step)`.NotImplementedError	__class____name__selfstep r   d/var/www/myenv/lib/python3.10/site-packages/keras/src/optimizers/schedules/learning_rate_schedule.py__call__J      zLearningRateSchedule.__call__c                 C   r   )Nr   z;' must override `get_config()` in order to be serializable.r	   r   r   r   r   
get_configQ   r   zLearningRateSchedule.get_configc                 C   s   | di |S )zInstantiates a `LearningRateSchedule` from its config.

        Args:
            config: Output of `get_config()`.

        Returns:
            A `LearningRateSchedule` instance.
        Nr   r   )clsconfigr   r   r   from_configX   s   
z LearningRateSchedule.from_configN)
r   
__module____qualname____doc__abcabstractmethodr   r   classmethodr   r   r   r   r   r      s    *

r   z+keras.optimizers.schedules.ExponentialDecayc                       6   e Zd ZdZ		d
 fdd	Zdd Zdd	 Z  ZS )ExponentialDecayaQ  A LearningRateSchedule that uses an exponential decay schedule.

    When training a model, it is often useful to lower the learning rate as
    the training progresses. This schedule applies an exponential decay function
    to an optimizer step, given a provided initial learning rate.

    The schedule is a 1-arg callable that produces a decayed learning
    rate when passed the current optimizer step. This can be useful for changing
    the learning rate value across different invocations of optimizer functions.
    It is computed as:

    ```python
    def decayed_learning_rate(step):
      return initial_learning_rate * decay_rate ^ (step / decay_steps)
    ```

    If the argument `staircase` is `True`, then `step / decay_steps` is
    an integer division and the decayed learning rate follows a
    staircase function.

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate.
    Example: When fitting a Keras model, decay every 100000 steps with a base
    of 0.96:

    ```python
    initial_learning_rate = 0.1
    lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
        initial_learning_rate,
        decay_steps=100000,
        decay_rate=0.96,
        staircase=True)

    model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=lr_schedule),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    model.fit(data, labels, epochs=5)
    ```

    The learning rate schedule is also serializable and deserializable using
    `tf.keras.optimizers.schedules.serialize` and
    `tf.keras.optimizers.schedules.deserialize`.

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as `initial_learning_rate`.
    FNc                    ,   t    || _|| _|| _|| _|| _dS )a  Applies exponential decay to the learning rate.

        Args:
          initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a
            Python number.  The initial learning rate.
          decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number.
            Must be positive.  See the decay computation above.
          decay_rate: A scalar `float32` or `float64` `Tensor` or a
            Python number.  The decay rate.
          staircase: Boolean.  If `True` decay the learning rate at discrete
            intervals
          name: String.  Optional name of the operation.  Defaults to
            'ExponentialDecay'.
        Nsuper__init__initial_learning_ratedecay_steps
decay_rate	staircasenamer   r%   r&   r'   r(   r)   r   r   r   r$      s   

zExponentialDecay.__init__c           	      C   s   t | jpd?}t j| jdd}|j}t | j|}t | j|}t ||}|| }| j	r4t 
|}t j|t |||dW  d    S 1 sJw   Y  d S )Nr    r%   r)   )tf
name_scoper)   convert_to_tensorr%   dtypecastr&   r'   r(   floormultiplypow)	r   r   r)   r%   r0   r&   r'   global_step_recomppr   r   r   r      s   
$zExponentialDecay.__call__c                 C      | j | j| j| j| jdS Nr%   r&   r'   r(   r)   r9   r   r   r   r   r         zExponentialDecay.get_configFNr   r   r   r   r$   r   r   __classcell__r   r   r+   r   r    e   s    7r    z1keras.optimizers.schedules.PiecewiseConstantDecayc                       s2   e Zd ZdZd	 fdd	Zdd Zdd Z  ZS )
PiecewiseConstantDecaya  A LearningRateSchedule that uses a piecewise constant decay schedule.

    The function returns a 1-arg callable to compute the piecewise constant
    when passed the current optimizer step. This can be useful for changing the
    learning rate value across different invocations of optimizer functions.

    Example: use a learning rate that's 1.0 for the first 100001 steps, 0.5
      for the next 10000 steps, and 0.1 for any additional steps.

    ```python
    step = tf.Variable(0, trainable=False)
    boundaries = [100000, 110000]
    values = [1.0, 0.5, 0.1]
    learning_rate_fn = keras.optimizers.schedules.PiecewiseConstantDecay(
        boundaries, values)

    # Later, whenever we perform an optimization step, we pass in the step.
    learning_rate = learning_rate_fn(step)
    ```

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate. The learning rate schedule is also serializable and
    deserializable using `tf.keras.optimizers.schedules.serialize` and
    `tf.keras.optimizers.schedules.deserialize`.

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as the boundary tensors.

      The output of the 1-arg function that takes the `step`
      is `values[0]` when `step <= boundaries[0]`,
      `values[1]` when `step > boundaries[0]` and `step <= boundaries[1]`, ...,
      and values[-1] when `step > boundaries[-1]`.
    Nc              
      s^   t    t|t|d kr$td| dt| d| dt| d	|| _|| _|| _dS )a  Piecewise constant from boundaries and interval values.

        Args:
          boundaries: A list of `Tensor`s or `int`s or `float`s with strictly
            increasing entries, and with all elements having the same type as
            the optimizer step.
          values: A list of `Tensor`s or `float`s or `int`s that specifies the
            values for the intervals defined by `boundaries`. It should have one
            more element than `boundaries`, and all elements should have the
            same type.
          name: A string. Optional name of the operation. Defaults to
            'PiecewiseConstant'.

        Raises:
          ValueError: if the number of elements in the lists do not match.
           zZThe length of boundaries should be 1 less than the length of values. Received: boundaries=z of length z, and values=.N)r#   r$   len
ValueError
boundariesvaluesr)   )r   rC   rD   r)   r+   r   r   r$      s    

zPiecewiseConstantDecay.__init__c                    s^  t | jpd t jt jt j| j}t jt jt j| j t |}t	|D ]\}}|j
j|j
jkrDt ||j
j}|||< q,g }|||d k fddf |||d k fddf t|d d |dd   dd D ]\}}}	||k||k@ }
||
|	fddf qw fd	d}t j||d
dW  d    S 1 sw   Y  d S )NPiecewiseConstantr   c                          d S Nr   r   r   rD   r   r   <lambda>%      z1PiecewiseConstantDecay.__call__.<locals>.<lambda>c                      rF   )NrK   r   r   rH   r   r   rI   '  rJ   r?   c                 S   s   | S Nr   )vr   r   r   rI   .  s    c                      rF   rG   r   r   rH   r   r   rI   2  rJ   T)	exclusive)r-   r.   r)   nestmap_structurer/   flattenrC   rD   	enumerater0   
base_dtyper1   appendzipcase)r   r   rC   x_recompibpred_fn_pairslowhighrM   preddefaultr   rH   r   r     s4   
$zPiecewiseConstantDecay.__call__c                 C   s   | j | j| jdS )NrC   rD   r)   r_   r   r   r   r   r   5  s   z!PiecewiseConstantDecay.get_configrL   r<   r   r   r+   r   r>      s
    $r>   z*keras.optimizers.schedules.PolynomialDecayc                       :   e Zd ZdZ				d fdd	Zdd	 Zd
d Z  ZS )PolynomialDecaya
  A LearningRateSchedule that uses a polynomial decay schedule.

    It is commonly observed that a monotonically decreasing learning rate, whose
    degree of change is carefully chosen, results in a better performing model.
    This schedule applies a polynomial decay function to an optimizer step,
    given a provided `initial_learning_rate`, to reach an `end_learning_rate`
    in the given `decay_steps`.

    It requires a `step` value to compute the decayed learning rate. You
    can just pass a TensorFlow variable that you increment at each training
    step.

    The schedule is a 1-arg callable that produces a decayed learning rate
    when passed the current optimizer step. This can be useful for changing the
    learning rate value across different invocations of optimizer functions.
    It is computed as:

    ```python
    def decayed_learning_rate(step):
      step = min(step, decay_steps)
      return ((initial_learning_rate - end_learning_rate) *
              (1 - step / decay_steps) ^ (power)
             ) + end_learning_rate
    ```

    If `cycle` is True then a multiple of `decay_steps` is used, the first one
    that is bigger than `step`.

    ```python
    def decayed_learning_rate(step):
      decay_steps = decay_steps * ceil(step / decay_steps)
      return ((initial_learning_rate - end_learning_rate) *
              (1 - step / decay_steps) ^ (power)
             ) + end_learning_rate
    ```

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate.
    Example: Fit a model while decaying from 0.1 to 0.01 in 10000 steps using
    sqrt (i.e. power=0.5):

    ```python
    ...
    starter_learning_rate = 0.1
    end_learning_rate = 0.01
    decay_steps = 10000
    learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(
        starter_learning_rate,
        decay_steps,
        end_learning_rate,
        power=0.5)

    model.compile(optimizer=tf.keras.optimizers.SGD(
                      learning_rate=learning_rate_fn),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    model.fit(data, labels, epochs=5)
    ```

    The learning rate schedule is also serializable and deserializable using
    `tf.keras.optimizers.schedules.serialize` and
    `tf.keras.optimizers.schedules.deserialize`.

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as `initial_learning_rate`.
    -C6?      ?FNc                    2   t    || _|| _|| _|| _|| _|| _dS )a  Applies a polynomial decay to the learning rate.

        Args:
          initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a
            Python number.  The initial learning rate.
          decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number.
            Must be positive.  See the decay computation above.
          end_learning_rate: A scalar `float32` or `float64` `Tensor` or a
            Python number.  The minimal end learning rate.
          power: A scalar `float32` or `float64` `Tensor` or a
            Python number. The power of the polynomial. Defaults to `1.0`.
          cycle: A boolean, whether it should cycle beyond decay_steps.
          name: String.  Optional name of the operation. Defaults to
            'PolynomialDecay'.
        N)r#   r$   r%   r&   end_learning_ratepowercycler)   )r   r%   r&   re   rf   rg   r)   r+   r   r   r$     s   

zPolynomialDecay.__init__c              	   C   s   t | jpdj}t j| jdd}|j}t | j|}t | j|}t ||}t | j	|}| j
rKt t |ddt j|| j	 }	t ||	}nt ||}t ||}
t jt || t d|
 |||dW  d    S 1 suw   Y  d S )Nra   r%   r,   r   rc   r?   )r-   r.   r)   r/   r%   r0   r1   re   rf   r&   rg   whereequalmathceilr3   minimumdivideaddr4   )r   r   r)   r%   r0   re   rf   r5   decay_steps_recomp
multiplierr6   r   r   r   r     s:   
$zPolynomialDecay.__call__c                 C      | j | j| j| j| j| jdS )Nr%   r&   re   rf   rg   r)   rr   r   r   r   r   r        zPolynomialDecay.get_config)rb   rc   FNr<   r   r   r+   r   ra   =  s    J!%ra   z+keras.optimizers.schedules.InverseTimeDecayc                       r   )InverseTimeDecayaT  A LearningRateSchedule that uses an inverse time decay schedule.

    When training a model, it is often useful to lower the learning rate as
    the training progresses. This schedule applies the inverse decay function
    to an optimizer step, given a provided initial learning rate.
    It requires a `step` value to compute the decayed learning rate. You can
    just pass a TensorFlow variable that you increment at each training step.

    The schedule is a 1-arg callable that produces a decayed learning
    rate when passed the current optimizer step. This can be useful for changing
    the learning rate value across different invocations of optimizer functions.
    It is computed as:

    ```python
    def decayed_learning_rate(step):
      return initial_learning_rate / (1 + decay_rate * step / decay_step)
    ```

    or, if `staircase` is `True`, as:

    ```python
    def decayed_learning_rate(step):
      return initial_learning_rate / (1 + decay_rate * floor(step / decay_step))
    ```

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate.
    Example: Fit a Keras model when decaying 1/t with a rate of 0.5:

    ```python
    ...
    initial_learning_rate = 0.1
    decay_steps = 1.0
    decay_rate = 0.5
    learning_rate_fn = keras.optimizers.schedules.InverseTimeDecay(
      initial_learning_rate, decay_steps, decay_rate)

    model.compile(optimizer=tf.keras.optimizers.SGD(
                      learning_rate=learning_rate_fn),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    model.fit(data, labels, epochs=5)
    ```

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as `initial_learning_rate`.
    FNc                    r!   )a  Applies inverse time decay to the initial learning rate.

        Args:
          initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a
            Python number.  The initial learning rate.
          decay_steps: How often to apply decay.
          decay_rate: A Python number.  The decay rate.
          staircase: Whether to apply decay in a discrete staircase, as opposed
            to continuous, fashion.
          name: String.  Optional name of the operation.  Defaults to
            'InverseTimeDecay'.
        Nr"   r*   r+   r   r   r$     s   

zInverseTimeDecay.__init__c                 C   s   t | jpdN}t j| jdd}|j}t | j|}t | j|}t ||}|| }| j	r4t 
|}t t d|}	t |	t ||}
t j||
|dW  d    S 1 sYw   Y  d S )Nrt   r%   r,   r?   )r-   r.   r)   r/   r%   r0   r1   r&   r'   r(   r2   constantrn   r3   rm   )r   r   r)   r%   r0   r&   r'   r5   r6   constdenomr   r   r   r   '  s   
$zInverseTimeDecay.__call__c                 C   r7   r8   r9   r   r   r   r   r   8  r:   zInverseTimeDecay.get_configr;   r<   r   r   r+   r   rt     s    8rt   z&keras.optimizers.schedules.CosineDecayzkeras.experimental.CosineDecayc                       sJ   e Zd ZdZ				d fdd	Zdd Zd	d
 Zdd Zdd Z  Z	S )CosineDecaya  A LearningRateSchedule that uses a cosine decay with optional warmup.

    See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983),
    SGDR: Stochastic Gradient Descent with Warm Restarts.

    For the idea of a linear warmup of our learning rate,
    see [Goyal et al.](https://arxiv.org/pdf/1706.02677.pdf).

    When we begin training a model, we often want an initial increase in our
    learning rate followed by a decay. If `warmup_target` is an int, this
    schedule applies a linear increase per optimizer step to our learning rate
    from `initial_learning_rate` to `warmup_target` for a duration of
    `warmup_steps`. Afterwards, it applies a cosine decay function taking our
    learning rate from `warmup_target` to `alpha` for a duration of
    `decay_steps`. If `warmup_target` is None we skip warmup and our decay
    will take our learning rate from `initial_learning_rate` to `alpha`.
    It requires a `step` value to  compute the learning rate. You can
    just pass a TensorFlow variable that you increment at each training step.

    The schedule is a 1-arg callable that produces a warmup followed by a
    decayed learning rate when passed the current optimizer step. This can be
    useful for changing the learning rate value across different invocations of
    optimizer functions.

    Our warmup is computed as:

    ```python
    def warmup_learning_rate(step):
        completed_fraction = step / warmup_steps
        total_delta = target_warmup - initial_learning_rate
        return completed_fraction * total_delta
    ```

    And our decay is computed as:

    ```python
    if warmup_target is None:
        initial_decay_lr = initial_learning_rate
    else:
        initial_decay_lr = warmup_target

    def decayed_learning_rate(step):
        step = min(step, decay_steps)
        cosine_decay = 0.5 * (1 + cos(pi * step / decay_steps))
        decayed = (1 - alpha) * cosine_decay + alpha
        return initial_decay_lr * decayed
    ```

    Example usage without warmup:

    ```python
    decay_steps = 1000
    initial_learning_rate = 0.1
    lr_decayed_fn = tf.keras.optimizers.schedules.CosineDecay(
        initial_learning_rate, decay_steps)
    ```

    Example usage with warmup:

    ```python
    decay_steps = 1000
    initial_learning_rate = 0
    warmup_steps = 1000
    target_learning_rate = 0.1
    lr_warmup_decayed_fn = tf.keras.optimizers.schedules.CosineDecay(
        initial_learning_rate, decay_steps, warmup_target=target_learning_rate,
        warmup_steps=warmup_steps
    )
    ```

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate. The learning rate schedule is also serializable and
    deserializable using `tf.keras.optimizers.schedules.serialize` and
    `tf.keras.optimizers.schedules.deserialize`.

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as `initial_learning_rate`.
            Nr   c                    s2   t    || _|| _|| _|| _|| _|| _dS )ai  Applies cosine decay to the learning rate.

        Args:
          initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a
            Python int. The initial learning rate.
          decay_steps: A scalar `int32` or `int64` `Tensor` or a Python int.
            Number of steps to decay over.
          alpha: A scalar `float32` or `float64` `Tensor` or a Python int.
            Minimum learning rate value for decay as a fraction of
            `initial_learning_rate`.
          name: String. Optional name of the operation.  Defaults to
            'CosineDecay'.
          warmup_target: None or a scalar `float32` or `float64` `Tensor` or a
            Python int. The target learning rate for our warmup phase. Will cast
            to the `initial_learning_rate` datatype. Setting to None will skip
            warmup and begins decay phase from `initial_learning_rate`.
            Otherwise scheduler will warmup from `initial_learning_rate` to
            `warmup_target`.
          warmup_steps: A scalar `int32` or `int64` `Tensor` or a Python int.
            Number of steps to warmup over.
        N)r#   r$   r%   r&   alphar)   warmup_stepswarmup_target)r   r%   r&   rz   r)   r|   r{   r+   r   r   r$     s   

zCosineDecay.__init__c           	      C   s   t | jpd/ || }t jtj|d}ddt ||   }d| j | | j }t ||W  d    S 1 s:w   Y  d S )Nrx   r0         ?rc   r?   )	r-   r.   r)   ru   rj   picosrz   r3   )	r   r   r&   decay_from_lrr0   completed_fractiontf_picosine_decayeddecayedr   r   r   _decay_function  s   
$zCosineDecay._decay_functionc                 C   sP   t | jpd || }|| }|| | W  d    S 1 s!w   Y  d S )Nrx   )r-   r.   r)   )r   r   r{   r|   r%   r   total_step_deltar   r   r   _warmup_function  s
   
$zCosineDecay._warmup_functionc                    s   t jpdj t jjddjt j t |jd u r;t 	 
 W  d    S t jt jt 	  t k fdd fddW  d    S 1 suw   Y  d S )Nrx   r%   r,   c                      s     S rL   )r   r   )r5   r%   r   r{   r|   r   r   rI     s    z&CosineDecay.__call__.<locals>.<lambda>c                      s      S rL   )r   r   )r&   r0   r5   r   r{   r|   r   r   rI     s    )r-   r.   r)   r/   r%   r0   r1   r&   r|   rl   r   r{   condr   r   )r&   r0   r5   r%   r   r{   r|   r   r     s6   
$zCosineDecay.__call__c                 C   rq   )Nr%   r&   rz   r)   r|   r{   r   r   r   r   r   r     rs   zCosineDecay.get_config)ry   NNr   )
r   r   r   r   r$   r   r   r   r   r=   r   r   r+   r   rx   B  s    U')rx   z.keras.optimizers.schedules.CosineDecayRestartsz&keras.experimental.CosineDecayRestartsc                       r`   )CosineDecayRestartsa  A LearningRateSchedule that uses a cosine decay schedule with restarts.

    See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983),
    SGDR: Stochastic Gradient Descent with Warm Restarts.

    When training a model, it is often useful to lower the learning rate as
    the training progresses. This schedule applies a cosine decay function with
    restarts to an optimizer step, given a provided initial learning rate.
    It requires a `step` value to compute the decayed learning rate. You can
    just pass a TensorFlow variable that you increment at each training step.

    The schedule is a 1-arg callable that produces a decayed learning
    rate when passed the current optimizer step. This can be useful for changing
    the learning rate value across different invocations of optimizer functions.

    The learning rate multiplier first decays
    from 1 to `alpha` for `first_decay_steps` steps. Then, a warm
    restart is performed. Each new warm restart runs for `t_mul` times more
    steps and with `m_mul` times initial learning rate as the new learning rate.

    Example usage:
    ```python
    first_decay_steps = 1000
    lr_decayed_fn = (
      tf.keras.optimizers.schedules.CosineDecayRestarts(
          initial_learning_rate,
          first_decay_steps))
    ```

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate. The learning rate schedule is also serializable and
    deserializable using `tf.keras.optimizers.schedules.serialize` and
    `tf.keras.optimizers.schedules.deserialize`.

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as `initial_learning_rate`.
           @rc   ry   Nc                    rd   )a~  Applies cosine decay with restarts to the learning rate.

        Args:
          initial_learning_rate: A scalar `float32` or `float64` Tensor or a
            Python number. The initial learning rate.
          first_decay_steps: A scalar `int32` or `int64` `Tensor` or a Python
            number. Number of steps to decay over.
          t_mul: A scalar `float32` or `float64` `Tensor` or a Python number.
            Used to derive the number of iterations in the i-th period.
          m_mul: A scalar `float32` or `float64` `Tensor` or a Python number.
            Used to derive the initial learning rate of the i-th period.
          alpha: A scalar `float32` or `float64` Tensor or a Python number.
            Minimum learning rate value as a fraction of the
            initial_learning_rate.
          name: String. Optional name of the operation. Defaults to 'SGDRDecay'.
        N)r#   r$   r%   first_decay_steps_t_mul_m_mulrz   r)   )r   r%   r   t_mulm_mulrz   r)   r+   r   r   r$   /  s   

zCosineDecayRestarts.__init__c              	      s   t | jpd~}t j| jdd}|j}t | j|}t | j|}t | j	|t | j
|}t ||}||  dfdd	t t d fdd	 fd
d	\}	 ||	 }
d|
 dt t jtj|d    }d| | | }t j|||dW  d    S 1 sw   Y  d S )N	SGDRDecayr%   r,   Fc                    st   |r-t t jd| d    t j  }d |  d   }| |  |  } || fS t | }| |8 } || fS )zHelper for `cond` operation.rc   )r-   r2   rj   log)r   	geometric	i_restartsum_r)r   r   r   compute_step_  s   

z2CosineDecayRestarts.__call__.<locals>.compute_steprc   c                          ddS )NFr   r   r   r   r   r   r   rI   t      z.CosineDecayRestarts.__call__.<locals>.<lambda>c                      r   )NTr   r   r   r   r   r   rI   u  r   r~   r}   r?   F)r-   r.   r)   r/   r%   r0   r1   r   rz   r   r   r   ri   r   ru   rj   r   r3   )r   r   r)   r%   r0   r   rz   r   r5   r   m_facr   r   r   )r   r   r   r   r   Q  s>   

$zCosineDecayRestarts.__call__c                 C   rq   )N)r%   r   r   r   rz   r)   )r%   r   r   r   rz   r)   r   r   r   r   r     rs   zCosineDecayRestarts.get_config)r   rc   ry   Nr<   r   r   r+   r   r     s    ,"6r   c                       r`   )LinearCosineDecayas  A LearningRateSchedule that uses a linear cosine decay schedule.

    See [Bello et al., ICML2017] Neural Optimizer Search with RL.
    https://arxiv.org/abs/1709.07417

    For the idea of warm starts here controlled by `num_periods`,
    see [Loshchilov & Hutter, ICLR2016] SGDR: Stochastic Gradient Descent
    with Warm Restarts. https://arxiv.org/abs/1608.03983

    Note that linear cosine decay is more aggressive than cosine decay and
    larger initial learning rates can typically be used.

    When training a model, it is often recommended to lower the learning rate as
    the training progresses. This schedule applies a linear cosine decay
    function to an optimizer step, given a provided initial learning rate.
    It requires a `step` value to compute the decayed learning rate. You can
    just pass a TensorFlow variable that you increment at each training step.

    The schedule is a 1-arg callable that produces a decayed learning
    rate when passed the current optimizer step. This can be useful for changing
    the learning rate value across different invocations of optimizer functions.
    It is computed as:

    ```python
    def decayed_learning_rate(step):
      step = min(step, decay_steps)
      linear_decay = (decay_steps - step) / decay_steps
      cosine_decay = 0.5 * (
          1 + cos(pi * 2 * num_periods * step / decay_steps))
      decayed = (alpha + linear_decay) * cosine_decay + beta
      return initial_learning_rate * decayed
    ```

    Example usage:
    ```python
    decay_steps = 1000
    lr_decayed_fn = (
      tf.keras.experimental.LinearCosineDecay(
        initial_learning_rate, decay_steps))
    ```

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate. The learning rate schedule is also serializable and
    deserializable using `tf.keras.optimizers.schedules.serialize` and
    `tf.keras.optimizers.schedules.deserialize`.

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as `initial_learning_rate`.
    r~   ry   MbP?Nc                    rd   )aj  Applies linear cosine decay to the learning rate.

        Args:
          initial_learning_rate: A scalar `float32` or `float64` Tensor or a
            Python number. The initial learning rate.
          decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number.
            Number of steps to decay over.
          num_periods: Number of periods in the cosine part of the decay.
            See computation above.
          alpha: See computation above.
          beta: See computation above.
          name: String.  Optional name of the operation.  Defaults to
            'LinearCosineDecay'.
        N)r#   r$   r%   r&   num_periodsrz   betar)   )r   r%   r&   r   rz   r   r)   r+   r   r   r$     s   

zLinearCosineDecay.__init__c              	   C   s   t | jpdl}t j| jdd}|j}t | j|}t | j|}t | j	|}t | j
|}t ||}	t |	|}	||	 | }
|	| }d| | }ddt t jtj|d|   }||
 | | }t j|||dW  d    S 1 sww   Y  d S )Nr   r%   r,   r   r~   rc   r}   )r-   r.   r)   r/   r%   r0   r1   r&   r   rz   r   rl   r   ru   rj   r   r3   )r   r   r)   r%   r0   r&   r   rz   r   r5   linear_decayedr   fractionr   linear_cosine_decayedr   r   r   r     s4   $zLinearCosineDecay.__call__c                 C   rq   )Nr%   r&   r   rz   r   r)   r   r   r   r   r   r     rs   zLinearCosineDecay.get_config)r~   ry   r   Nr<   r   r   r+   r   r     s    8 r   c                       s@   e Zd ZdZ							d fdd		Zd
d Zdd Z  ZS )NoisyLinearCosineDecaya	  A LearningRateSchedule that uses a noisy linear cosine decay schedule.

    See [Bello et al., ICML2017] Neural Optimizer Search with RL.
    https://arxiv.org/abs/1709.07417

    For the idea of warm starts here controlled by `num_periods`,
    see [Loshchilov & Hutter, ICLR2016] SGDR: Stochastic Gradient Descent
    with Warm Restarts. https://arxiv.org/abs/1608.03983

    Note that linear cosine decay is more aggressive than cosine decay and
    larger initial learning rates can typically be used.

    When training a model, it is often recommended to lower the learning rate as
    the training progresses. This schedule applies a noisy linear cosine decay
    function to an optimizer step, given a provided initial learning rate.
    It requires a `step` value to compute the decayed learning rate. You can
    just pass a TensorFlow variable that you increment at each training step.

    The schedule is a 1-arg callable that produces a decayed learning
    rate when passed the current optimizer step. This can be useful for changing
    the learning rate value across different invocations of optimizer functions.
    It is computed as:

    ```python
    def decayed_learning_rate(step):
      step = min(step, decay_steps)
      linear_decay = (decay_steps - step) / decay_steps)
      cosine_decay = 0.5 * (
          1 + cos(pi * 2 * num_periods * step / decay_steps))
      decayed = (alpha + linear_decay + eps_t) * cosine_decay + beta
      return initial_learning_rate * decayed
    ```
    where eps_t is 0-centered gaussian noise with variance
    initial_variance / (1 + global_step) ** variance_decay

    Example usage:
    ```python
    decay_steps = 1000
    lr_decayed_fn = (
      tf.keras.experimental.NoisyLinearCosineDecay(
        initial_learning_rate, decay_steps))
    ```

    You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`
    as the learning rate. The learning rate schedule is also serializable and
    deserializable using `tf.keras.optimizers.schedules.serialize` and
    `tf.keras.optimizers.schedules.deserialize`.

    Returns:
      A 1-arg callable learning rate schedule that takes the current optimizer
      step and outputs the decayed learning rate, a scalar `Tensor` of the same
      type as `initial_learning_rate`.
    rc   皙?r~   ry   r   Nc
           
         sP   t    || _|| _|| _|| _|| _|| _|| _|| _	|	| _
t|| _dS )au  Applies noisy linear cosine decay to the learning rate.

        Args:
          initial_learning_rate: A scalar `float32` or `float64` Tensor or a
            Python number. The initial learning rate.
          decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number.
            Number of steps to decay over.
          initial_variance: initial variance for the noise. See computation
            above.
          variance_decay: decay for the noise's variance. See computation above.
          num_periods: Number of periods in the cosine part of the decay.
            See computation above.
          alpha: See computation above.
          beta: See computation above.
          seed: Integer, optional random seed to enable deterministic behavior.
          name: String.  Optional name of the operation.  Defaults to
            'NoisyLinearCosineDecay'.
        N)r#   r$   r%   r&   initial_variancevariance_decayr   rz   r   seedr)   r   RandomGenerator_random_generator)
r   r%   r&   r   r   r   rz   r   r   r)   r+   r   r   r$   F  s   
zNoisyLinearCosineDecay.__init__c              	   C   sL  t | jpd}t j| jdd}|j}t | j|}t | j|}t | j	|}t | j
|}t | j|}	t | j|}
t ||}t ||}|| | }|t d| | }t |}|| jj|j|d }|| }d| | }ddt t jtj|d|   }|	| | |
 }t j|||dW  d    S 1 sw   Y  d S )	Nr   r%   r,   rc   )stddevr   r~   r}   )r-   r.   r)   r/   r%   r0   r1   r&   r   r   r   rz   r   rl   r4   sqrtr   random_normalshaper   ru   rj   r   r3   )r   r   r)   r%   r0   r&   r   r   r   rz   r   r5   r   variancestdnoisy_linear_decayedr   r   r   noisy_linear_cosine_decayedr   r   r   r   q  sL   
$zNoisyLinearCosineDecay.__call__c              
   C   s*   | j | j| j| j| j| j| j| j| jd	S )N	r%   r&   r   r   r   rz   r   r   r)   r   r   r   r   r   r     s   z!NoisyLinearCosineDecay.get_config)rc   r   r~   ry   r   NNr<   r   r   r+   r   r     s    :+(r   z$keras.optimizers.schedules.serializeFc                 C   s   |rt | S t| S )aD  Serializes a `LearningRateSchedule` into a JSON-compatible dict.

    Args:
      learning_rate_schedule: The `LearningRateSchedule` object to serialize.

    Returns:
      A JSON-serializable dict representing the object's config.

    Example:

    >>> lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
    ...   0.1, decay_steps=100000, decay_rate=0.96, staircase=True)
    >>> tf.keras.optimizers.schedules.serialize(lr_schedule)
    {'module': 'keras.optimizers.schedules',
    'class_name': 'ExponentialDecay', 'config': {...},
    'registered_name': None}
    )legacy_serializationserialize_keras_objectr   )learning_rate_scheduleuse_legacy_formatr   r   r   	serialize  s
   
r   z&keras.optimizers.schedules.deserializec                 C   s,   |rt j| t |ddS tj| t |ddS )a  Instantiates a `LearningRateSchedule` object from a serialized form.

    Args:
      config: The serialized form of the `LearningRateSchedule`.
        Dictionary of the form {'class_name': str, 'config': dict}.
      custom_objects: A dictionary mapping class names (or function names) of
        custom (non-Keras) objects to class/functions.

    Returns:
      A `LearningRateSchedule` object.

    Example:

    ```python
    # Configuration for PolynomialDecay
    config = {
      'class_name': 'PolynomialDecay',
      'config': {'cycle': False,
        'decay_steps': 10000,
        'end_learning_rate': 0.01,
        'initial_learning_rate': 0.1,
        'name': None,
        'power': 0.5}}
    lr_schedule = tf.keras.optimizers.schedules.deserialize(config)
    ```
    decay)module_objectscustom_objectsprintable_module_name)r   deserialize_keras_objectglobalsr   )r   r   r   r   r   r   deserialize  s   r   r   )NF)r   r   rj   tensorflow.compat.v2compatv2r-   	keras.srcr   keras.src.savingr   keras.src.saving.legacyr   r    tensorflow.python.util.tf_exportr   r   r    r>   ra   rt   rx   r   r   r   r   r   r   r   r   r   <module>   sJ   Fkk k > | 