a
    .Sicq                     @   s  d Z ddlZddl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 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 ddlmZ ddlm Z  ddl!m"Z" dd Z#dd Z$dd Z%e&ej'G dd de(Z)G d d! d!e)Z*G d"d# d#e)Z+G d$d% d%e)Z,G d&d' d'e)Z-d(d) Z.e"d*gd+G d,d- d-ej/Z0dS ).zBase class for optimizers.    N)distribute_lib)distribute_utils)distribution_strategy_context)reduce_util)backprop)context)dtypes)indexed_slices)ops)	array_ops)control_flow_ops)	gradients)math_ops)resource_variable_ops)	state_ops)variable_scope)	variables)base)slot_creator)nest)	tf_exportc                    s    fdd}|S )Nc                     s   dd  | i |D S )Nc                 S   s    g | ]\}}|d ur||fqS N .0gvr   r   `/var/www/html/django/DPS/env/lib/python3.9/site-packages/tensorflow/python/training/optimizer.py
<listcomp>9       zBget_filtered_grad_fn.<locals>.filtered_grad_fn.<locals>.<listcomp>r   argskwargsgrad_fnr   r   filtered_grad_fn8   s    z.get_filtered_grad_fn.<locals>.filtered_grad_fnr   )r$   r%   r   r#   r   get_filtered_grad_fn.   s    
r&   c                 C   s.   t |\}}t| |t |d }||fS )a  Sums `values` associated with any non-unique `indices`.

  Args:
    values: A `Tensor` with rank >= 1.
    indices: A one-dimensional integer `Tensor`, indexing into the first
      dimension of `values` (as in an IndexedSlices object).
  Returns:
    A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a
    de-duplicated version of `indices` and `summed_values` contains the sum of
    `values` slices associated with each unique index.
  r   )r   uniquer   unsorted_segment_sumshape)valuesindicesunique_indicesZnew_index_positionssummed_valuesr   r   r   _deduplicate_indexed_slices>   s    r.   c                 C   sP   t | dr|  } t| r0t s0| j| jfS t | drJ| jj| jj	fS | j
S )zReturns slot key for `var`._distributed_containerop)hasattrr/   r   is_distributed_variabler
   #executing_eagerly_outside_functionsgraph_shared_namer0   name
_unique_id)varr   r   r   _var_keyQ   s    


r9   c                   @   s,   e Zd ZdZejdd Zejdd ZdS )_OptimizableVariablez;Interface for abstracting over variables in the optimizers.c                 C   s   t ddS )z2Returns the optimization target for this variable.Calling an abstract method.NNotImplementedErrorselfr   r   r   targetc   s    z_OptimizableVariable.targetc                 C   s   t ddS )z1Returns the update ops for updating the variable.r;   Nr<   r?   	optimizerr   r   r   r   	update_oph   s    z_OptimizableVariable.update_opN)__name__
__module____qualname____doc__abcabstractmethodr@   rC   r   r   r   r   r:   _   s
   
r:   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )_RefVariableProcessorzProcessor for Variable.c                 C   s
   || _ d S r   _vr?   r   r   r   r   __init__q   s    z_RefVariableProcessor.__init__c                 C   s
   d| j  S )Nz<_RefVariableProcessor(%s)>rK   r>   r   r   r   __str__t   s    z_RefVariableProcessor.__str__c                 C   s
   | j  S r   )rL   _refr>   r   r   r   r@   w   s    z_RefVariableProcessor.targetc                 C   s   t |tjrp||| j}| jjd urjt|g& | j| j| jW  d    S 1 s^0    Y  q|S n<t |tj	sJ d|df| jjd urt
d||| jS d S )Nz	Gradient z' is neither a tensor nor IndexedSlices.6Cannot use a constraint function on a sparse variable.)
isinstancer
   Tensor_apply_denserL   
constraintcontrol_dependenciesassignr	   IndexedSlicesRuntimeError_apply_sparse_duplicate_indicesr?   rB   r   rC   r   r   r   rC   z   s    6z_RefVariableProcessor.update_opN)rD   rE   rF   rG   rN   rO   r@   rC   r   r   r   r   rJ   n   s
   rJ   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	#_DenseReadResourceVariableProcessor&Processor for dense ResourceVariables.c                 C   s
   || _ d S r   rK   rM   r   r   r   rN      s    z,_DenseReadResourceVariableProcessor.__init__c                 C   s   | j S r   rK   r>   r   r   r   r@      s    z*_DenseReadResourceVariableProcessor.targetc                 C   sn   | || jjjd }| jjd urft|g& | j| j| jW  d    S 1 sZ0    Y  n|S d S Nr   )_resource_apply_denserL   r0   inputsrU   r
   rV   rW   r[   r   r   r   rC      s
    6z-_DenseReadResourceVariableProcessor.update_opNrD   rE   rF   rG   rN   r@   rC   r   r   r   r   r\      s   r\   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_DenseResourceVariableProcessorr]   c                 C   s
   || _ d S r   rK   rM   r   r   r   rN      s    z(_DenseResourceVariableProcessor.__init__c                 C   s   | j S r   rK   r>   r   r   r   r@      s    z&_DenseResourceVariableProcessor.targetc                 C   s   t |tjr4| jjd ur td||j| j|jS |	|| j}| jjd urt
|g& | j| j| jW  d    S 1 s0    Y  n|S d S )NrQ   )rR   r	   rX   rL   rU   rY   (_resource_apply_sparse_duplicate_indicesr*   r+   r_   r
   rV   rW   r[   r   r   r   rC      s    6z)_DenseResourceVariableProcessor.update_opNra   r   r   r   r   rb      s   rb   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_TensorProcessorzProcessor for ordinary Tensors.

  Even though a Tensor can't really be updated, sometimes it is useful to
  compute the gradients with respect to a Tensor using the optimizer. Updating
  the Tensor is, of course, unsupported.
  c                 C   s
   || _ d S r   rK   rM   r   r   r   rN      s    z_TensorProcessor.__init__c                 C   s   | j S r   rK   r>   r   r   r   r@      s    z_TensorProcessor.targetc                 C   s   t d| jd S )NzTrying to update a Tensor )r=   rL   rA   r   r   r   rC      s    z_TensorProcessor.update_opNra   r   r   r   r   rd      s   rd   c                 C   s   t  r$t| tjrt| S t| S t| r<| j	s<t| S | j
jdkrPt| S t| tjrdt| S t| tjrxt| S td| dS )zThe processor of v.VarHandleOpz$Trying to optimize unsupported type N)r   executing_eagerlyrR   r
   rS   rd   rb   r   is_resource_variable_in_graph_moder0   typer   VariablerJ   r=   r   r   r   r   _get_processor   s    rl   ztrain.Optimizer)v1c                       s^  e Zd ZdZdZdZdZdd Zdd Zd	d	ed	d
d	d	fddZ	d	ed	d
d	fddZ
edd ZdIddZdJddZdd Zdd Zdd Zdd Zejjf fdd	Z fdd ZdKd!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Z d3d4 Z!d5d6 Z"d7d8 Z#d9d: Z$d;d< Z%d=d> Z&d?d@ Z'dAdB Z(dCdD Z)dEdF Z*dGdH Z+  Z,S )L	Optimizera  Base class for optimizers.

  This class defines the API to add Ops to train a model.  You never use this
  class directly, but instead instantiate one of its subclasses such as
  `GradientDescentOptimizer`, `AdagradOptimizer`, or `MomentumOptimizer`.

  ### Usage

  ```python
  # Create an optimizer with the desired parameters.
  opt = GradientDescentOptimizer(learning_rate=0.1)
  # Add Ops to the graph to minimize a cost by updating a list of variables.
  # "cost" is a Tensor, and the list of variables contains tf.Variable
  # objects.
  opt_op = opt.minimize(cost, var_list=<list of variables>)
  ```

  In the training program you will just have to run the returned Op.

  ```python
  # Execute opt_op to do one step of training:
  opt_op.run()
  ```

  ### Processing gradients before applying them.

  Calling `minimize()` takes care of both computing the gradients and
  applying them to the variables.  If you want to process the gradients
  before applying them you can instead use the optimizer in three steps:

  1.  Compute the gradients with `compute_gradients()`.
  2.  Process the gradients as you wish.
  3.  Apply the processed gradients with `apply_gradients()`.

  Example:

  ```python
  # Create an optimizer.
  opt = GradientDescentOptimizer(learning_rate=0.1)

  # Compute the gradients for a list of variables.
  grads_and_vars = opt.compute_gradients(loss, <list of variables>)

  # grads_and_vars is a list of tuples (gradient, variable).  Do whatever you
  # need to the 'gradient' part, for example cap them, etc.
  capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars]

  # Ask the optimizer to apply the capped gradients.
  opt.apply_gradients(capped_grads_and_vars)
  ```

  ### Gating Gradients

  Both `minimize()` and `compute_gradients()` accept a `gate_gradients`
  argument that controls the degree of parallelism during the application of
  the gradients.

  The possible values are: `GATE_NONE`, `GATE_OP`, and `GATE_GRAPH`.

  <b>`GATE_NONE`</b>: Compute and apply gradients in parallel.  This provides
  the maximum parallelism in execution, at the cost of some non-reproducibility
  in the results.  For example the two gradients of `matmul` depend on the input
  values: With `GATE_NONE` one of the gradients could be applied to one of the
  inputs _before_ the other gradient is computed resulting in non-reproducible
  results.

  <b>`GATE_OP`</b>: For each Op, make sure all gradients are computed before
  they are used.  This prevents race conditions for Ops that generate gradients
  for multiple inputs where the gradients depend on the inputs.

  <b>`GATE_GRAPH`</b>: Make sure all gradients for all variables are computed
  before any one of them is used.  This provides the least parallelism but can
  be useful if you want to process all gradients before applying any of them.

  ### Slots

  Some optimizer subclasses, such as `MomentumOptimizer` and `AdagradOptimizer`
  allocate and manage additional variables associated with the variables to
  train.  These are called <i>Slots</i>.  Slots have names and you can ask the
  optimizer for the names of the slots that it uses.  Once you have a slot name
  you can ask the optimizer for the variable it created to hold the slot value.

  This can be useful if you want to log debug a training algorithm, report stats
  about the slots, etc.

  @compatibility(TF2)
  `tf.compat.v1.train.Optimizer` can be used in eager mode and `tf.function`,
  but it is not recommended. Please use the subclasses of
  `tf.keras.optimizers.Optimizer` instead in TF2. Please see [Basic training
  loops](https://www.tensorflow.org/guide/basic_training_loops) or
  [Writing a training loop from scratch]
  (https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch)
  for examples.

  If your TF1 code contains a `tf.compat.v1.train.Optimizer` symbol, whether it
  is used with or without a `tf.estimator.Estimator`, you cannot simply replace
  that with the corresponding `tf.keras.optimizers.Optimizer`s. To migrate to
  TF2, it is advised the whole training program used with `Estimator` to be
  migrated to Keras `Model.fit` based or TF2 custom training loops.

  #### Structural Mapping to Native TF2

  Before:

  ```python
  sgd_op = tf.compat.v1.train.GradientDescentOptimizer(3.0)
  opt_op = sgd_op.minimize(cost, global_step, [var0, var1])
  opt_op.run(session=session)
  ```

  After:

  ```python
  sgd = tf.keras.optimizers.SGD(3.0)
  sgd.minimize(cost_fn, [var0, var1])
  ```

  #### How to Map Arguments

  | TF1 Arg Name          | TF2 Arg Name    | Note                       |
  | :-------------------- | :-------------- | :------------------------- |
  | `use_locking`         | Not supported   | -                          |
  | `name`                | `name. `        | -                          |

  #### Before & After Usage Example

  Before:

  >>> g = tf.compat.v1.Graph()
  >>> with g.as_default():
  ...   var0 = tf.compat.v1.Variable([1.0, 2.0])
  ...   var1 = tf.compat.v1.Variable([3.0, 4.0])
  ...   cost = 5 * var0 + 3 * var1
  ...   global_step = tf.compat.v1.Variable(
  ...       tf.compat.v1.zeros([], tf.compat.v1.int64), name='global_step')
  ...   init_op = tf.compat.v1.initialize_all_variables()
  ...   sgd_op = tf.compat.v1.train.GradientDescentOptimizer(3.0)
  ...   opt_op = sgd_op.minimize(cost, global_step, [var0, var1])
  >>> session = tf.compat.v1.Session(graph=g)
  >>> session.run(init_op)
  >>> opt_op.run(session=session)
  >>> print(session.run(var0))
  [-14. -13.]


  After:
  >>> var0 = tf.Variable([1.0, 2.0])
  >>> var1 = tf.Variable([3.0, 4.0])
  >>> cost_fn = lambda: 5 * var0 + 3 * var1
  >>> sgd = tf.keras.optimizers.SGD(3.0)
  >>> sgd.minimize(cost_fn, [var0, var1])
  >>> print(var0.numpy())
  [-14. -13.]

  @end_compatibility


  r         c                 C   s.   |st d|| _|| _i | _i | _i | _dS )ab  Create a new Optimizer.

    This must be called by the constructors of subclasses.

    Args:
      use_locking: Bool. If True apply use locks to prevent concurrent updates
        to variables.
      name: A non-empty string.  The name to use for accumulators created
        for the optimizer.

    Raises:
      ValueError: If name is malformed.
    zMust specify the optimizer nameN)
ValueErrorZ_use_locking_name_slots_non_slot_dict_deferred_slot_restorations)r?   use_lockingr6   r   r   r   rN     s    zOptimizer.__init__c                 C   s   | j S r   )rr   r>   r   r   r   get_name  s    zOptimizer.get_nameNFc	                 C   sR   | j ||||||d}	dd |	D }
|
sBtddd |	D |f | j|	||dS )a  Add operations to minimize `loss` by updating `var_list`.

    This method simply combines calls `compute_gradients()` and
    `apply_gradients()`. If you want to process the gradient before applying
    them call `compute_gradients()` and `apply_gradients()` explicitly instead
    of using this function.

    Args:
      loss: A `Tensor` containing the value to minimize.
      global_step: Optional `Variable` to increment by one after the
        variables have been updated.
      var_list: Optional list or tuple of `Variable` objects to update to
        minimize `loss`.  Defaults to the list of variables collected in
        the graph under the key `GraphKeys.TRAINABLE_VARIABLES`.
      gate_gradients: How to gate the computation of gradients.  Can be
        `GATE_NONE`, `GATE_OP`, or  `GATE_GRAPH`.
      aggregation_method: Specifies the method used to combine gradient terms.
        Valid values are defined in the class `AggregationMethod`.
      colocate_gradients_with_ops: If True, try colocating gradients with
        the corresponding op.
      name: Optional name for the returned operation.
      grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.

    Returns:
      An Operation that updates the variables in `var_list`.  If `global_step`
      was not `None`, that operation also increments `global_step`.

    Raises:
      ValueError: If some of the variables are not `Variable` objects.

    @compatibility(eager)
    When eager execution is enabled, `loss` should be a Python function that
    takes no arguments and computes the value to be minimized. Minimization (and
    gradient computation) is done with respect to the elements of `var_list` if
    not None, else with respect to any trainable variables created during the
    execution of the `loss` function. `gate_gradients`, `aggregation_method`,
    `colocate_gradients_with_ops` and `grad_loss` are ignored when eager
    execution is enabled.
    @end_compatibility
    )var_listgate_gradientsaggregation_methodcolocate_gradients_with_ops	grad_lossc                 S   s   g | ]\}}|d ur|qS r   r   r   r   r   r   r     r   z&Optimizer.minimize.<locals>.<listcomp>zNo gradients provided for any variable, check your graph for ops that do not support gradients, between variables %s and loss %s.c                 S   s   g | ]\}}t |qS r   strr   _r   r   r   r   r     r   )global_stepr6   )compute_gradientsrq   apply_gradients)r?   lossr   rx   ry   rz   r{   r6   r|   grads_and_varsZvars_with_gradr   r   r   minimize  s     ,zOptimizer.minimizec                 C   s  t |rt 2}|dur$|| | }| |}W d   n1 sH0    Y  |du rb| }t|g ||||}	W d   n1 s0    Y  t	t
|	|S t rtd| |}|tjtjtjfvrtd| | |g |dur| |g |du r(t ttjj }n
t|}|ttjj7 }dd |D }
|s`tddd |
D }tj||||tjk||d}	|tjkrt|	}	t	t
|	|}| d	d |D  |S )
a[	  Compute gradients of `loss` for the variables in `var_list`.

    This is the first part of `minimize()`.  It returns a list
    of (gradient, variable) pairs where "gradient" is the gradient
    for "variable".  Note that "gradient" can be a `Tensor`, an
    `IndexedSlices`, or `None` if there is no gradient for the
    given variable.

    @compatibility(TF2)
    `tf.keras.optimizers.Optimizer` in TF2 does not provide a
    `compute_gradients` method, and you should use a `tf.GradientTape` to
    obtain the gradients:

    ```python
    @tf.function
    def train step(inputs):
      batch_data, labels = inputs
      with tf.GradientTape() as tape:
        predictions = model(batch_data, training=True)
        loss = tf.keras.losses.CategoricalCrossentropy(
            reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
      gradients = tape.gradient(loss, model.trainable_variables)
      optimizer.apply_gradients(zip(gradients, model.trainable_variables))
    ```

    Args:
      loss: A Tensor containing the value to minimize or a callable taking
        no arguments which returns the value to minimize. When eager execution
        is enabled it must be a callable.
      var_list: Optional list or tuple of `tf.Variable` to update to minimize
        `loss`.  Defaults to the list of variables collected in the graph
        under the key `GraphKeys.TRAINABLE_VARIABLES`.
      gate_gradients: How to gate the computation of gradients.  Can be
        `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.
      aggregation_method: Specifies the method used to combine gradient terms.
        Valid values are defined in the class `AggregationMethod`.
      colocate_gradients_with_ops: If True, try colocating gradients with
        the corresponding op.
      grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.

    Returns:
      A list of (gradient, variable) pairs. Variable is always present, but
      gradient can be `None`.

    Raises:
      TypeError: If `var_list` contains anything else than `Variable` objects.
      ValueError: If some arguments are invalid.
      RuntimeError: If called with eager execution enabled and `loss` is
        not callable.

    @compatibility(eager)
    When eager execution is enabled, `gate_gradients`, `aggregation_method`,
    and `colocate_gradients_with_ops` are ignored.
    @end_compatibility
    Nzb`loss` passed to Optimizer.compute_gradients should be a function when eager execution is enabled.zdgate_gradients must be one of: Optimizer.GATE_NONE, Optimizer.GATE_OP, Optimizer.GATE_GRAPH.  Not %sc                 S   s   g | ]}t |qS r   )rl   r   r   r   r   r   r   W  r   z/Optimizer.compute_gradients.<locals>.<listcomp>zNo variables to optimize.c                 S   s   g | ]}|  qS r   )r@   )r   pr   r   r   r   Z  r   )grad_ysry   rz   r{   c                 S   s(   g | ] \}}|d ur|j tjkr|qS r   )dtyper   resourcer   r   r   r   r   d  s   )callabler   GradientTapewatch_scale_losswatched_variablesr
   rV   gradientlistzipr   rf   rY   rn   	GATE_NONEGATE_OP
GATE_GRAPHrq   _assert_valid_dtypesr   trainable_variablesget_collection	GraphKeysTRAINABLE_RESOURCE_VARIABLESr   flatten_STREAMING_MODEL_PORTSr   r   tuple)r?   r   rx   ry   rz   r{   r|   tape
loss_valuegrads
processorsZvar_refsr   r   r   r   r     sb    <

(,





zOptimizer.compute_gradientsc                 C   sF   dt  _t tjjkrBt	 j
}|dkrB| d| 9 } dt  _| S )NFro   g      ?T)r
   get_default_graph_is_loss_scaled_by_optimizerr   Zget_loss_reductionds_reduce_utilReduceOpMEANdistribute_ctxget_strategyZnum_replicas_in_sync)r   num_replicasr   r   r   r   h  s    


zOptimizer._scale_lossc                    s>  t  rDt  rtdt fdd  t  j| j ||fdS t   sXt	dg } D ]t\}}|durzt
|}W n ty   td| Y n0 t|t
jtjfstd| t|}||||f q`t|}d	d
 |D }|s
t	ddd
 |D f t
  | | W d   n1 s40    Y  g }	t
j|| jdd}|   |D ]\}
}}|
du r|qdt st|r|jsd}n|jj}t
jd| ddN t
|" |	| | |
 W d   n1 s0    Y  W d   n1 s0    Y  qd|du r6| !|	|}nt
"| !|	dgz t
|N t|tj#rtj$|j%t
j&d|j'd|d}nt(j)|d|d}W d   n1 s0    Y  W d   n1 s0    Y  t st|t
jr|j}t
*t
j+j,}||vr|| |W  d   S 1 s00    Y  dS )a  Apply gradients to variables.

    This is the second part of `minimize()`. It returns an `Operation` that
    applies gradients.

    @compatibility(TF2)
    #### How to Map Arguments

    | TF1 Arg Name          | TF2 Arg Name    | Note                       |
    | :-------------------- | :-------------- | :------------------------- |
    | `grads_and_vars`      | `grads_and_vars`| -                          |
    | `global_step`         | Not supported.  | Use `optimizer.iterations` |
    | `name`                | `name. `        | -                          |

    Args:
      grads_and_vars: List of (gradient, variable) pairs as returned by
        `compute_gradients()`.
      global_step: Optional `Variable` to increment by one after the
        variables have been updated.
      name: Optional name for the returned operation.  Default to the
        name passed to the `Optimizer` constructor.

    Returns:
      An `Operation` that applies the specified gradients. If `global_step`
      was not None, that operation also increments `global_step`.

    Raises:
      TypeError: If `grads_and_vars` is malformed.
      ValueError: If none of the variables have gradients.
      RuntimeError: If you should use `_distributed_apply()` instead.
    zUUse `_distributed_apply()` instead of `apply_gradients()` in a cross-replica context.c                      s    S r   r   r   r   r   r   <lambda>  r   z+Optimizer.apply_gradients.<locals>.<lambda>)r!   zNo variables provided.NFGradient must be convertible to a Tensor or IndexedSlices, or None: %s5Gradient must be a Tensor, IndexedSlices, or None: %sc                 S   s   g | ]\}}}|d ur|qS r   r   )r   r   r   r   r   r   r   r     r   z-Optimizer.apply_gradients.<locals>.<listcomp>z+No gradients provided for any variable: %s.c                 S   s   g | ]\}}}t |qS r   r}   r   r   r   r   r     r   F)skip_on_eager update_updatero   )r   r6   )-r   has_strategyin_cross_replica_contextrY   r&   Zget_replica_contextZ
merge_call_distributed_applyr   rq   r
   #convert_to_tensor_or_indexed_slices	TypeErrorrR   rS   r	   rX   rl   append
init_scope_create_slots
name_scoperr   _preparer   rf   r   rg   rh   r0   r6   colocate_withrC   _finishrV   BaseResourceVariableassign_add_variable_ophandleconvert_to_tensorr   r   
assign_addget_collection_refr   TRAIN_OP)r?   r   r   r6   Zconverted_grads_and_varsr   r   r   rx   
update_opsgradr8   	processor
scope_nameapply_updatestrain_opr   r   r   r   r  s    '

*

V
P


zOptimizer.apply_gradientsc              	      s   j tjj|}dd |D }t||}t  | W d   n1 sR0    Y  fddt	|j
 }   fdd|D }dd } j |}	 j j|	||fd	d
}
|du rڈ j|
|d}nFt|
*  j j|tjdd|id}W d   n1 s0    Y  t s`t|tjr>|j}ttjj}||vr`|| |W  d   S 1 sz0    Y  dS )at  A version of `apply_gradients` for cross-replica context.

    This is a version of `apply_gradients()` for when you are using a
    `DistributionStrategy` and are in a cross-replica context. If in a
    replica context, use `apply_gradients()` as normal.

    Args:
      distribution: A `DistributionStrategy` object.
      grads_and_vars: List of (gradient, variable) pairs as returned by
        `compute_gradients()`, and then aggregated across replicas.
      global_step: Optional (mirrored) `Variable` to increment by one
        after the variables have been updated.
      name: Optional name for the returned operation.  Default to the
        name passed to the `Optimizer` constructor.

    Returns:
      An `Operation` that applies the specified gradients across all
      replicas. If `global_step` was not None, that operation also
      increments `global_step`
    c                 S   s   g | ]\}}|qS r   r   r   r   r   r   r     r   z0Optimizer._distributed_apply.<locals>.<listcomp>Nc                    s   | dusJ zt |}W n ty8   td| Y n0 t|t jtjfsXtd| t| }t	 sxt
| r| js| jdd }n| jj}t d|  | |W  d   S 1 s0    Y  dS )z&Apply gradients to a replica variable.Nr   r   :r   r   )r
   r   r   rR   rS   r	   rX   rl   r   rf   r   rg   rh   r6   splitr0   r   rC   )r   r   r   r   r>   r   r   r     s*    z,Optimizer._distributed_apply.<locals>.updatec                    s0   g | ](\}} j j||fd dD ]}|q"qS )Fr!   group)extendedr   )r   r   r8   r0   )distributionr   r   r   r   +  s
   

c                 S   s   |  |dS )Nr   )r   )r?   r   r   r   r   finish2  s    z,Optimizer._distributed_apply.<locals>.finishFr   r   )ro   r6   r    )r   Zbatch_reduce_tor   r   SUMr   r
   r   r   r   rr   r   non_slot_devicesZupdate_non_slotr   rV   r   r   r   r   rf   rR   rS   r0   r   r   r   r   )r?   r   r   r   r6   Zreduced_gradsrx   r   r   r   Zfinish_updatesr   r   r   )r   r?   r   r   r     s@    

(&


zOptimizer._distributed_applyc                 C   sF   | j |d}|sdS |t|d}t|rBt|sB| }|S )a>  Return a slot named `name` created for `var` by the Optimizer.

    Some `Optimizer` subclasses use additional variables.  For example
    `Momentum` and `Adagrad` use variables to accumulate updates.  This method
    gives access to these `Variable` objects if for some reason you need them.

    Use `get_slot_names()` to get the list of slot names created by the
    `Optimizer`.

    Args:
      var: A variable passed to `minimize()` or `apply_gradients()`.
      name: A string.

    Returns:
      The `Variable` for the slot if it was created, `None` otherwise.
    N)rs   getr9   r   r2   Z_get_on_device_or_primary)r?   r8   r6   named_slotsslotr   r   r   get_slotI  s    
zOptimizer.get_slotc                 C   s   t | j S )zReturn a list of the names of slots created by the `Optimizer`.

    See `get_slot()`.

    Returns:
      A list of strings.
    )sortedrs   keysr>   r   r   r   get_slot_namese  s    zOptimizer.get_slot_namesc                    sr   t  fdd  fdd|  D }| j D ],\}}| D ]\}} |rD|| qDq4t|dd dS )zA list of variables which encode the current state of `Optimizer`.

    Includes slot variables and additional global variables created by the
    optimizer in the current default graph.

    Returns:
      A list of variables.
    c                    s"   | j r| jj u S | j jkS d S r   )rh   r0   r4   
_graph_key)variable)current_graphr   r   _from_current_graphz  s    z0Optimizer.variables.<locals>._from_current_graphc                    s   g | ]} |r|qS r   r   r   )r   r   r   r     s   z'Optimizer.variables.<locals>.<listcomp>c                 S   s   | j S r   r   rk   r   r   r   r     r   z%Optimizer.variables.<locals>.<lambda>key)r
   r   _non_slot_variablesrs   itemsr   r   )r?   Zoptimizer_variablesr   Zvariable_dictZslot_for_variabler   )r   r   r   r   o  s    	zOptimizer.variablesc           
      C   s   t  }|rdn|j}||f}| j|d}|du r|   t }|j	|D |rn| j
|d}	|	durn|	}tj||dt|d}W d   n1 s0    Y  | j||d || j|< |S )z2Add an extra variable, not associated with a slot.Nr   F)r6   	trainableuse_resource)r6   	trackable)r
   r3   r4   rt   r   _maybe_initialize_trackabler   r   r   Zcolocate_vars_with_preload_simple_restorationr   r   r   rg   _handle_deferred_dependencies)
r?   initial_valuer6   r   eagerr4   r   r   distribution_strategyZrestored_initial_valuer   r   r   _create_non_slot_variable  s.    $

z#Optimizer._create_non_slot_variablec                    sf   i }t  j}t| j dd dD ]\\}}}|j|kr$|||< q$|tt| j	|fi | |S )zAFrom Trackable. Gather graph-specific non-slot variables to save.c                 S   s   | d d S r^   r   )itemr   r   r   r     r   z/Optimizer._trackable_children.<locals>.<lambda>r   )
r
   r   r   r   rt   r   r   superrn   _trackable_children)r?   	save_typer"   Z current_graph_non_slot_variablesZcurrent_graph_keyr6   r   Zvariable_object	__class__r   r   r     s    



zOptimizer._trackable_childrenc                    s>   t t| |}|dur|S t r(dnt }| j||dS )z>From Trackable. Find a non-slot variable in the current graph.N)r4   )r   rn   _lookup_dependencyr   rf   r
   r   _get_non_slot_variable)r?   r6   Zunconditionalr4   r   r   r   r     s
    zOptimizer._lookup_dependencyc                 C   s,   | j ||fd }t|dr$| S |S d S )Nr/   )rt   r   r1   )r?   r6   r4   Znon_slotr   r   r   r     s    
z Optimizer._get_non_slot_variablec                 C   s
   | j  S )zgAdditional variables created by the `Optimizer`.

    Returns:
      A list or tuple of variables.
    )rt   r*   r>   r   r   r   r     s    zOptimizer._non_slot_variablesc                 C   sD   |   }|D ]2}|jj}||vrtd||jdd |D f qdS )zAsserts tensors are all valid types (see `_valid_dtypes`).

    Args:
      tensors: Tensors to check.

    Raises:
      ValueError: If any tensor is not a valid type.
    z%Invalid type %r for %s, expected: %s.c                 S   s   g | ]}|qS r   r   r   r   r   r   r     r   z2Optimizer._assert_valid_dtypes.<locals>.<listcomp>N)_valid_dtypesr   
base_dtyperq   r6   )r?   tensorsZvalid_dtypestr   r   r   r   r     s    	zOptimizer._assert_valid_dtypesc                 C   s   t tjtjtjtjgS )zValid types for loss, variables and gradients.

    Subclasses should override to allow other float types.

    Returns:
      Valid types for loss, variables and gradients.
    )setr   float16bfloat16float32float64r>   r   r   r   r     s    zOptimizer._valid_dtypesc                 C   s   dS )zgCreate all slots needed by the variables.

    Args:
      var_list: A list of `Variable` objects.
    Nr   )r?   rx   r   r   r   r     s    zOptimizer._create_slotsc                 C   s   dS )zCreate all needed tensors before applying gradients.

    This is called with the name_scope using the "name" that
    users have chosen for the application of gradients.
    Nr   r>   r   r   r   r     s    zOptimizer._preparec                 C   s
   t  dS )zAdd ops to apply dense gradients to `var`.

    Args:
      grad: A `Tensor`.
      var: A `Variable` object.

    Returns:
      An `Operation`.
    Nr<   r?   r   r8   r   r   r   rT     s    
zOptimizer._apply_densec                 C   s
   t  dS )a(  Add ops to apply dense gradients to the variable `handle`.

    Args:
      grad: a `Tensor` representing the gradient.
      handle: a `Tensor` of dtype `resource` which points to the variable
       to be updated.

    Returns:
      An `Operation` which updates the value of the variable.
    Nr<   )r?   r   r   r   r   r   r_     s    zOptimizer._resource_apply_densec                 C   s   t ||d\}}| |||S )a  Add ops to apply sparse gradients to `handle`, with repeated indices.

    Optimizers which override this method must deal with repeated indices. See
    the docstring of `_apply_sparse_duplicate_indices` for details. By default
    the correct behavior, to sum non-unique indices and their associated
    gradients, is enforced by first pre-processing `grad` and `indices` and
    passing them on to `_resource_apply_sparse`. Optimizers which deal correctly
    with duplicate indices may instead override this method to avoid the
    overhead of summing.

    Args:
      grad: a `Tensor` representing the gradient for the affected indices.
      handle: a `Tensor` of dtype `resource` which points to the variable
       to be updated.
      indices: a `Tensor` of integral type representing the indices for
       which the gradient is nonzero. Indices may be repeated.

    Returns:
      An `Operation` which updates the value of the variable.
    r*   r+   )r.   _resource_apply_sparse)r?   r   r   r+   Zsummed_gradr,   r   r   r   rc     s    
z2Optimizer._resource_apply_sparse_duplicate_indicesc                 C   s
   t  dS )a  Add ops to apply sparse gradients to the variable `handle`.

    Similar to `_apply_sparse`, the `indices` argument to this method has been
    de-duplicated. Optimizers which deal correctly with non-unique indices may
    instead override `_resource_apply_sparse_duplicate_indices` to avoid this
    overhead.

    Args:
      grad: a `Tensor` representing the gradient for the affected indices.
      handle: a `Tensor` of dtype `resource` which points to the variable
       to be updated.
      indices: a `Tensor` of integral type representing the indices for
       which the gradient is nonzero. Indices are unique.

    Returns:
      An `Operation` which updates the value of the variable.
    Nr<   )r?   r   r   r+   r   r   r   r  6  s    z Optimizer._resource_apply_sparsec                 C   s2   t |j|jd\}}tj|||jd}| ||S )a  Add ops to apply sparse gradients to `var`, with repeated sparse indices.

    Optimizers which override this method must deal with IndexedSlices objects
    such as the following:

      IndexedSlicesValue(values=[1, 1], indices=[0, 0], dense_shape=[1])

    The correct interpretation is:

      IndexedSlicesValue(values=[2], indices=[0], dense_shape=[1])

    Many optimizers deal incorrectly with repeated indices when updating based
    on sparse gradients (e.g. summing squares rather than squaring the sum, or
    applying momentum terms multiple times). Adding first is always the correct
    behavior, so this is enforced here by reconstructing the IndexedSlices to
    have only unique indices, then calling _apply_sparse.

    Optimizers which deal correctly with repeated indices may instead override
    this method to avoid the overhead of summing indices.

    Args:
      grad: `IndexedSlices`.
      var: A `Variable` object.

    Returns:
      An `Operation`.
    r  )r+   r*   dense_shape)r.   r*   r+   r	   rX   r  _apply_sparse)r?   r   r8   r-   r,   Zgradient_no_duplicate_indicesr   r   r   rZ   J  s    
z)Optimizer._apply_sparse_duplicate_indicesc                 C   s
   t  dS )aB  Add ops to apply sparse gradients to `var`.

    The IndexedSlices object passed to `grad` in this function is by default
    pre-processed in `_apply_sparse_duplicate_indices` to remove duplicate
    indices (see its docstring for details). Optimizers which can tolerate or
    have correct special cases for duplicate sparse indices may override
    `_apply_sparse_duplicate_indices` instead of this function, avoiding that
    overhead.

    Args:
      grad: `IndexedSlices`, with no repeated indices.
      var: A `Variable` object.

    Returns:
      An `Operation`.
    Nr<   r   r   r   r   r  n  s    zOptimizer._apply_sparsec                 C   s   t j|d|iS )a  Do what is needed to finish the update.

    This is called with the `name_scope` using the "name" that
    users have chosen for the application of gradients.

    Args:
      update_ops: List of `Operation` objects to update variables.  This list
        contains the values returned by the `_apply_dense()` and
        `_apply_sparse()` calls.
      name_scope: String.  Name to use for the returned operation.

    Returns:
      The operation to apply updates.
    r6   )r   r   )r?   r   r   r   r   r   r     s    zOptimizer._finishc                 C   s(   | j |d}|du r$i }|| j |< |S )zReturns a dict for caching slots created under the given name.

    Args:
      slot_name: Name for the slot.

    Returns:
      A dict that maps primary `Variable` objects to the slot created
      for that variable, under the given slot name.
    N)rs   r   )r?   	slot_namer   r   r   r   
_slot_dict  s
    

zOptimizer._slot_dictc                 C   sL   |  |}t||vr@t|||}| j|||d ||t|< |t| S )a=  Find or create a slot for a variable.

    Args:
      var: A `Variable` object.
      val: A `Tensor`.  The initial value of the slot.
      slot_name: Name for the slot.
      op_name: Name to use when scoping the Variable that
        needs to be created for the slot.

    Returns:
      A `Variable` object.
    r  r   slot_variable)r  r9   r   Zcreate_slot_restore_slot_variable)r?   r8   valr  op_namer   new_slot_variabler   r   r   _get_or_make_slot  s    
zOptimizer._get_or_make_slotc           	      C   sP   |  |}t||vrDt|||||}| j|||d ||t|< |t| S )a  Find or create a slot for a variable, using an Initializer.

    Args:
      var: A `Variable` object.
      initializer: An `Initializer`.  The initial value of the slot.
      shape: Shape of the initial value of the slot.
      dtype: Type of the value of the slot.
      slot_name: Name for the slot.
      op_name: Name to use when scoping the Variable that
        needs to be created for the slot.

    Returns:
      A `Variable` object.
    r  )r  r9   r   Zcreate_slot_with_initializerr	  )	r?   r8   initializerr)   r   r  r  r   r  r   r   r   "_get_or_make_slot_with_initializer  s    

z,Optimizer._get_or_make_slot_with_initializerc                 C   sN   |  |}t||vrBtj||dd}| j|||d ||t|< |t| S )a  Find or create a slot initialized with 0.0.

    Args:
      var: A `Variable` object.
      slot_name: Name for the slot.
      op_name: Name to use when scoping the Variable that
        needs to be created for the slot.

    Returns:
      A `Variable` object.
    T)Zcopy_xla_shardingr  )r  r9   r   Zcreate_zeros_slotr	  )r?   r8   r  r  r   r  r   r   r   _zeros_slot  s    
zOptimizer._zeros_slotc                 C   sH   t |}| j|i |g }|jdd dd |D ]}|| q4dS )z.Restore a newly created slot variable's value.c                 S   s   | j S r   )restore_uid)positionr   r   r   r     r   z2Optimizer._restore_slot_variable.<locals>.<lambda>T)r   reverseN)r9   ru   r   popsortrestore)r?   r  r   r  variable_keyZdeferred_restorationscheckpoint_positionr   r   r   r	    s    
z Optimizer._restore_slot_variablec                 C   s   |  |}t|}||d}|du rht rh| rht jsht	j
|d}| j|||j|j|| jd}|dur||| n| j|i |g | dS )a  Restore a slot variable's value, possibly creating it.

    Called when a variable which has an associated slot variable is created or
    restored. When executing eagerly, we create the slot variable with a
    restoring initializer.

    No new variables are created when graph building. Instead,
    _restore_slot_variable catches these after normal creation and adds restore
    ops to the graph. This method is nonetheless important when graph building
    for the case when a slot variable has already been created but `variable`
    has just been added to a dependency graph (causing us to realize that the
    slot variable needs to be restored).

    Args:
      slot_variable_position: A `trackable._CheckpointPosition` object
        indicating the slot variable `Trackable` object to be restored.
      slot_name: The name of this `Optimizer`'s slot to restore into.
      variable: The variable object this slot is being created for.
    N)r  )r8   r  r)   r   r  r  )r  r9   r   r   rf   is_simple_variabler
   r   _variable_creator_stackr   CheckpointInitialValueCallabler  r)   r   rr   r  ru   
setdefaultr   )r?   Zslot_variable_positionr  r   r   r  r  r  r   r   r    _create_or_restore_slot_variable  s8    

z*Optimizer._create_or_restore_slot_variablec                 C   s   t |r| S |S )z'Call the function if param is callable.)r   )r?   paramr   r   r   _call_if_callable>  s    zOptimizer._call_if_callable)NN)NN)N)-rD   rE   rF   rG   r   r   r   rN   rw   r   r   staticmethodr   r   r   r   r   r   r   r   SaveType
CHECKPOINTr   r   r   r   r   r   r   r   rT   r_   rc   r  rZ   r  r   r  r  r  r  r	  r  r  __classcell__r   r   r   r   rn      sf    !'
<
{
	
{  
_
!
		$Brn   )1rG   rH   sixtensorflow.python.distributer   r   r   r   r   r   tensorflow.python.eagerr   r   tensorflow.python.frameworkr   r	   r
   tensorflow.python.opsr   r   r   r   r   r   r   r   tensorflow.python.trackabler   r   tensorflow.python.trainingr   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   r&   r.   r9   add_metaclassABCMetaobjectr:   rJ   r\   rb   rd   rl   	Trackablern   r   r   r   r   <module>   sJ   


