
    BVh!                         d Z ddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ  ed	g
       G d dej                                Zy)zAOptimizer that implements cross-shard gradient reduction for TPU.    )ops)losses)
tf_logging)tpu_function)tpu_ops)	optimizer)	tf_exportztpu.CrossShardOptimizer)v1c                   z     e Zd ZdZej
                  j                  d df fd	Zd Zd
dZ	ddZ
d Zd Zd	 Z xZS )CrossShardOptimizerz7An optimizer that averages gradients across TPU shards.Nc                 <   t         j                  j                  t         j                  j                  f}||vrt	        d| d|       t        |t        j                        st        d| d      t        t        | /  d|       || _        || _        || _        y)a  Construct a new cross-shard optimizer.

    Args:
      opt: An existing `Optimizer` to encapsulate.
      reduction: The reduction to apply to the shard losses.
      name: Optional name prefix for the operations created when applying
        gradients. Defaults to "CrossShardOptimizer".
      group_assignment: Optional 2d int32 lists with shape
        [num_groups, num_replicas_per_group] which describles how to apply
        optimizer to subgroups.

    Raises:
      ValueError: If reduction is not a valid cross-shard reduction.
    z&Argument `reduction` should be one of z. Received: z]CrossShardOptimizer only works with tf.training.Optimizer and not Keras Optimizer. Received: z. If you are using TPUStrategy, Keras Optimizer will sum gradients across replicas.If you want to average your gradients, rescale your loss with: `loss /= global_batch_size`FN)r   	ReductionSUMMEAN
ValueError
isinstancer   	Optimizer	TypeErrorsuperr   __init___opt
_reduction_group_assignment)selfopt	reductionnamegroup_assignmentaccepted_reductions	__class__s         S/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/tpu/tpu_optimizer.pyr   zCrossShardOptimizer.__init__    s    & "++//1A1A1F1FG++23F2G H k#$ $ c9../((+u -(() ) 

t-eT:DIDO-D    c                    |syt        |t              rt        d |D              st        d|       t	               }|D ]  }|D ]  }|j                  |         t	        t        |            |k7  rt        d| d|       |D cg c]  }t        |       c}t        fdD              rd   S t        d|       c c}w )	aK  Verify group_assignment and get the subgroup size".

    Args:
      group_assignment: list of group ids for applying the optimizer
        to subgroups.
      num_shards: The number of TPU shards.

    Returns:
      The size of one subgroup in group_assignment.

    Raises:
      ValueError: If group_assignment is invalid.
    Nc              3   <   K   | ]  }t        |t                y wN)r   list).0is     r!   	<genexpr>zDCrossShardOptimizer._verify_and_get_subgroup_size.<locals>.<genexpr>W   s     >
1d#>s   z?Argument `group_assignment` must be a list of lists. Received: z;Argument `group_assignment` must be a permutation of range(z). Received: c              3   .   K   | ]  }d    |k(    yw)r   N )r'   sizesubgroup_size_lists     r!   r)   zDCrossShardOptimizer._verify_and_get_subgroup_size.<locals>.<genexpr>g   s     
HTa D(
Hs   r   zIThe size of each subgroup in `group_assignment` must be equal. Received: )r   r&   allr   setaddrangelen)r   r   
num_shardsreplica_idsgr(   groupr-   s          @r!   _verify_and_get_subgroup_sizez1CrossShardOptimizer._verify_and_get_subgroup_sizeF   s    '.>-=>>'(*+ + %K  ! 5,,m,<+=?@ @ 3CC#e*C

H5G
HH"" ..>-?A B B	 Ds   
Cc                 v   t        j                         j                  }|t        j                  d       d}| j                  | j                  |      }|dkD  rC| j                  t        j                  j                  k(  r| j                  rd|z  }nd|z  }||z  } | j                  j                  |fd|i|S )a1  Compute gradients of "loss" for the variables in "var_list".

    This simply wraps `compute_gradients()` from the real optimizer. The
    gradients will be aggregated in `apply_gradients()` so that user can
    modify the gradients like clipping with per replica global norm if needed.
    The global norm with aggregated gradients can be bad as one replica's huge
    gradients can hurt the gradients from other replicas.

    When the CrossShardOptimizer is constructed with
    `reduction == losses.Reduction.MEAN` (default), this function scales the
    loss by `1.0 / num_shards` before computing the gradients. Assuming the
    optimizer uses the default implementation of `compute_gradients()`, the
    gradients of the scaled loss are scaled by `1.0 / num_shards` compared to
    the gradients of the original loss. This scaling factor is important because
    `apply_gradients()` sums gradients across shards, rather than averaging
    them. However, the scaling factor must be taken into account when clipping
    the norm of the gradients or performing other postprocessing.

    Args:
      loss: A Tensor containing the value to minimize.
      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 `GraphKey.TRAINABLE_VARIABLES`.
      **kwargs: Keyword arguments for compute_gradients().

    Returns:
      A list of (gradient, variable) pairs.

    Raises:
      ValueError: If not within a tpu_shard_context or group_assignment is
        invalid.
    zjCrossShardOptimizer should be used within a tpu_shard_context, but got unset number_of_shards. Assuming 1.   g      ?var_list)r   get_tpu_contextnumber_of_shardsloggingwarningr7   r   r   r   r   r   r   compute_gradients)r   lossr:   kwargsr3   subgroup_sizescales          r!   r?   z%CrossShardOptimizer.compute_gradientsm   s    B --/@@Joo45 j66t7M7M7ACM A~$//V-=-=-B-BB			m#j 
emd&499&&tIhI&IIr"   c                 6   g }|D ]j  \  }}||j                  ||f       t        j                  |      5  |j                  t        j                  || j
                        |f       ddd       l | j                  j                  |||      S # 1 sw Y   xY w)a  Apply gradients to variables.

    Calls tpu_ops.cross_replica_sum() to sum gradient contributions across
    replicas, and then applies the real optimizer.

    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 gradients. If `global_step` was not None,
      that operation also increments `global_step`.

    Raises:
      ValueError: If the grads_and_vars is malformed.
    N)appendr   colocate_withr   cross_replica_sumr   r   apply_gradients)r   grads_and_varsglobal_stepr   summed_grads_and_varsgradvars          r!   rH   z#CrossShardOptimizer.apply_gradients   s    * % 3s	$$dC[1t$ 	3

&
&(A(AD**),-0(2 3	3 	3	3 99$$%:KNN	3 	3s   2BB	c                 :     | j                   j                  |i |S )a=  Return a slot named "name" created for "var" by the Optimizer.

    This simply wraps the get_slot() from the actual optimizer.

    Args:
      *args: Arguments for get_slot().
      **kwargs: Keyword arguments for get_slot().

    Returns:
      The `Variable` for the slot if it was created, `None` otherwise.
    )r   get_slotr   argsrA   s      r!   rO   zCrossShardOptimizer.get_slot   s      499t.v..r"   c                 :     | j                   j                  |i |S )a  Return a list of the names of slots created by the `Optimizer`.

    This simply wraps the get_slot_names() from the actual optimizer.

    Args:
      *args: Arguments for get_slot().
      **kwargs: Keyword arguments for get_slot().

    Returns:
      A list of strings.
    )r   get_slot_namesrP   s      r!   rS   z"CrossShardOptimizer.get_slot_names   s      $499##T4V44r"   c                 6    | j                   j                         S )z7Forwarding the variables from the underlying optimizer.)r   	variables)r   s    r!   rU   zCrossShardOptimizer.variables   s    99  r"   r%   )NN)__name__
__module____qualname____doc__r   r   r   r   r7   r?   rH   rO   rS   rU   __classcell__)r    s   @r!   r   r      sF    ?  ))..) $	$.L%BN2JhO>/5!r"   r   N)rY   tensorflow.python.frameworkr   tensorflow.python.ops.lossesr   tensorflow.python.platformr   r=   tensorflow.python.tpur   tensorflow.python.tpu.opsr   tensorflow.python.trainingr    tensorflow.python.util.tf_exportr	   r   r   r+   r"   r!   <module>rb      sO     H , / < . - 0 6 ()*A!)-- A! +A!r"   