
    BVh                        d Z ddlZddlZddlZddlmZmZmZmZmZm	Z	m
Z
mZmZmZ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)  edejT                  e#jV                        Z,ee,ee   ee jZ                     geee,f   f   Z.eee/e/f   e/f   Z0 G d dejb                        Z2 e)d       G d de2             Z3 e)d       G d de2             Z4 e)d       G d  d!e2             Z5 e)d"       G d# d$e2             Z6 e)d%       G d& d'e2             Z7 e)d(       G d) d*e2             Z8 e)d+       G d, d-             Z9 e)d.       G d/ d0             Z: e)d1       G d2 d3             Z; e)d4       G d5 d6             Z<d7ejz                  d8dfd9Z>d:ee?   d8ee?   fd;Z@d<ej                  d8ee   fd=ZBy)>z>Companion classes for mid level API for TPU Embeddings in TF2.    N)AnyCallableDictIterableListOptionalSequenceTextTupleTypeVarUnion)logging)optimization_parameters_pb2)tpu_embedding_configuration_pb2)device_util)sharded_variable)tpu_strategy)device_spec)dtypes)ops)TensorShape)	array_ops)init_ops_v2)math_ops)	variables)tpu_ops)core)	tf_exportTableVariablec                   (   e Zd ZdZ	 	 	 ddeeeg ef   f   dedee   dee   dee   ded	ee	   d
ee
   defdZej                  dee   fd       Zej                  deej$                     fd       Zdej*                  fdZej                  dedej0                  f   fd       Zej                  dedej6                  f   fd       Zdddeeej$                  gej<                  f   deeej<                  f   fdZ de!dee!ef   fdZ"de#fdZ$y)
_Optimizerz6Base class for all optimizers, with common parameters.Nlearning_rateuse_gradient_accumulationclip_weight_minclip_weight_maxweight_decay_factor-multiply_weight_decay_factor_by_learning_rate	clipvalueslot_variable_creation_fnlow_dimensional_packing_statusc
                 &   || _         || _        || _        || _        |s|t	        d| d      |d}nt        |t              sd|z  |f}|\  | _        | _        || _	        || _
        |t        |      st	        d|       || _        |	| _        y )NzWhen `use_gradient_accumulation` is False, gradient clipping cannot be used and `clipvalue` should be left as None. Received value z for argument `clipvalue`.)NNg      zRArgument `slot_variable_creation_fn` must be either None or a callable. Received: )r"   r#   r$   r%   
ValueError
isinstancetupleclip_gradient_minclip_gradient_maxr&   r'   callabler)   r*   )
selfr"   r#   r$   r%   r&   r'   r(   r)   r*   s
             \/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/tpu/tpu_embedding_v2_utils.py__init__z_Optimizer.__init__5   s     'D%>D"*D*D$)>%;&@BC C i	5)?I.i5>2DD22D5 	6 	"-./!!: ;=> > &?D"*HD'    returnc                     t         )zReturns the name of all the slot variables.

    This does not include the 'parameters' variable and these names must match
    the names of the slots variables as used in the corresponding
    `tpu_ops.load_tpu_embedding_*` ops.
    NotImplementedErrorr2   s    r3   _slot_namesz_Optimizer._slot_names\   s
     r5   c                     t         )zfReturns initializers for slot variables.

    This returns a parallel list to self._slot_names().
    r8   r:   s    r3   _slot_initializersz_Optimizer._slot_initializersf   s
     r5   
parametersc                    | j                   r t        j                  j                  |_        nt        j                  j
                  |_        | j                  %| j                  |j                  j                  _	        | j                  %| j                  |j                  j                  _	        | j                  %| j                  |j                  j                  _	        | j                  %| j                  |j                  j                  _	        | j                  r$| j                  |_        | j                   rd|_        | j"                  |_        y)z8Sets the optimizer fields in the OptimizationParameters.NT)r#   r   GradientAccumulationStatusENABLEDgradient_accumulation_statusDISABLEDr$   clipping_limitslowervaluer%   upperr/   gradient_clipping_limitsr0   r&   r'   r*   r2   r>   s     r3   _set_optimization_parametersz'_Optimizer._set_optimization_parametersn   s    %%
%
@
@
H
H - &
@
@
I
I - '/3/C/Cj  &&,'/3/C/Cj  &&,)8<8N8Nj))//5)8<8N8Nj))//5'+'?'?j$		;	;CG
@ 	++ -r5   .c                     t         )z,Returns the load function for the optimizer.r8   r:   s    r3   _loadz_Optimizer._load   
     r5   c                     t         )z0Returns the retrieve function for the optimizer.r8   r:   s    r3   	_retrievez_Optimizer._retrieve   rM   r5   tableTableConfigvariable_creatorc                     | j                   /| j                  || j                         | j                               S i }t        | j                         | j                               D ]  \  }} |||      ||<    |S )a  Creates slot variables for table.

    Args:
      table: The table variable to create slots for.
      variable_creator: A function which creates variables. Takes parameters
        'name', 'initializer'.

    Returns:
      A dict of variables, keyed by self._slot_names().
    )r)   r;   r=   zip)r2   rP   rR   slotsslotinitializers         r3   _create_slotsz_Optimizer._create_slots   s     %%1++E43C3C3E,0,C,C,EG G e"4#3#3#5#'#:#:#< > :
$&t[9d: lr5   otherc                     t        || j                        r[t        t        | j                  j                         |j                  j                               D cg c]
  \  }}||k(   c}}      S yc c}}w )NF)r-   	__class__allrT   __dict__items)r2   rY   attr1attr2s       r3   __eq__z_Optimizer.__eq__   sf    %(!$--"5"5"79M9M9OPeU 5. 	 	
 s   A3
c                 Z    t        t        | j                  j                                     S N)hashr.   r]   r^   r:   s    r3   __hash__z_Optimizer.__hash__   s    dmm))+,--r5   )NNF)%__name__
__module____qualname____doc__r   floatr   boolr   ClipValueTypeSlotVarCreationFnTyper4   abcabstractmethodr   r
   r;   r   Initializerr=   r   OptimizationParametersrJ   r   	OperationrL   r   TensorrO   tf_variablesVariabler   rX   r   ra   intre    r5   r3   r!   r!   2   s   > ,0CG-2%I5(2u9"556%I "&%I  	%I
  %I $E?%I 6:%I -(%I "**?!@%I '+%IN 4:   ${'>'>"?  3JJ> Xc3==01   #t{{"23    $(?(?!@!-!6!6"7 8 D,'''(	2# %T	"2 . .r5   r!   )	metaclassz*tpu.experimental.embedding.CustomOptimizerc                       e Zd ZdZ	 	 	 	 ddej
                  deeeg ef   f   de	e
e      de	e
ej                        de	e
eeeg ef   f         def fdZde
e   fd	Zde
ej                     fd
Zdedej(                  f   fdZdedej,                  f   fdZedeeeeg ef   f   df   fd       Zedej6                  fd       Z xZS )CustomOptimizeraP  Optimization parameters for custom optimizer for TPU embeddings.

  This optimizer gives the user the ability to define a custom optimizer
  for running embedding lookups on TPU v5p.

  The custom computation should be a function which takes gradient, embedding
  table, a list of slot variables, learning_rate and a list of hyperparameters.
  The function should perform the gradient update on the embedding_table +
  slot_variables and return the updated embedding_table and slot_variables. e.g.

  ```python
  @tf.function
  def sgd_optimizer_computation(
      gradient,
      embedding_table,
      slot_variables,
      learning_rate,
      hyperparameters,
  ):
    del slot_variables, hyperparameters
    return embedding_table - gradient * learning_rate
  ```

  Above is a simple example of a sgd optimizer. You can also define a more
  complex optimizer which updates multiple tables and slot variables.

  ```python
  @def_function.function
  def adagrad_optimizer_computation(
      gradient,
      embedding_table,
      slot_variables,
      learning_rate,
      hyperparameters,
  ):
    del hyperparameters
    accumulator = slot_variables[0]
    new_accumulator = accumulator + gradient * gradient
    updated_embedding_table = (
        embedding_table
        - learning_rate * gradient / math_ops.sqrt(new_accumulator)
    )
    return (updated_embedding_table, new_accumulator)
  ```

  The custom computation is defined as a per-row update function and it will be
  auto scaled for the entire table (slot variables).

  NOTE: This optimizer can only be used with the `TPUEmbeddingV2` class.

  Pass this to `tf.tpu.experimental.embedding.TPUEmbeddingV2` via the
  `optimizer` argument to set the global optimizer and its parameters:

  ```python
  optimizer = tf.tpu.experimental.embedding.CustomOptimizer(
        custom_computation=adagrad_optimizer_computation,
        learning_rate=1.0,
        slot_names=['accumulators'],
        slot_initializers=[
            tf.constant_initializer(0.1, support_partition=True)
        ],
    )
  embedding = tf.tpu.experimental.embedding.TPUEmbeddingV2(
      ...
      optimizer=optimizer)
  ```

  This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the
  optimizer parameter to set a table specific optimizer. This will override the
  optimizer and parameters for global embedding optimizer defined above:

  ```python
  table_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...,
      optimizer=optimizer)
  table_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)

  feature_config = (
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_one),
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_two))

  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=optimizer)
  ```
  In this example, the optimizer of the first table will be the one specified
  in the table config. The second table will use the optimizer specified in the
  TPUEmbedding argument.
  custom_computationr"   
slot_namesslot_initializershyperparametersr6   c                 >   t         |   |dd d d d d d d	       t        |r|nd      | _        t        |r|nd      | _        t        | j                        }t        | j                        }||k7  rt        d| d| d      t        |r|nd      | _        || _        y )NF)r#   r$   r%   r&   r'   r(   r)   r*   rw   zThe number of slot_names (z.) must match the number of slot_initializers (z).)	superr4   r.   _slot_names_attr_slot_initializers_attrlenr,   _hyperparameters_custom_computation)	r2   r{   r"   r|   r}   r~   num_slot_namesnum_slot_initializersr[   s	           r3   r4   zCustomOptimizer.__init__  s     
G"' 6:"&',  
 "
*CD#(.B$D  ../N < <=..&~&6 7$%R) 
 "_/"MD1Dr5   c                 ,    t        | j                        S rc   )listr   r:   s    r3   r;   zCustomOptimizer._slot_namesC  s    %%&&r5   c                 ,    t        | j                        S rc   )r   r   r:   s    r3   r=   z"CustomOptimizer._slot_initializersF  s    ,,--r5   .c                     t        d      )NzSCustom optimizer does not support load op since it is only used for TPUEmbeddingV2.r8   r:   s    r3   rL   zCustomOptimizer._loadI  s    
	 r5   c                     t        d      )NzWCustom optimizer does not support retrieve op since it is only used for TPUEmbeddingV2.r8   r:   s    r3   rO   zCustomOptimizer._retrieveO  s    
	 r5   c                     | j                   S rc   )r   r:   s    r3   r~   zCustomOptimizer.hyperparametersU  s       r5   c                     | j                   S rc   )r   r:   s    r3   r{   z"CustomOptimizer.custom_computationY  s    ###r5   ){Gz?NNN)rf   rg   rh   ri   r   PolymorphicFunctionr   rj   r   r   r   strr   rp   r   r4   r
   r;   r=   r   rr   rL   rs   rO   propertyr   r~   ConcreteFunctionr{   __classcell__r[   s   @r3   rz   rz      s[   ^F :>(,CGKO"222"2 5(2u9"556"2 49%	"2
 "${'>'>"?@"2  U5(2u92E+E%F GH"2 "2H'4: '.${'>'>"? .Xc3==01 #t{{"23  !uU5(2u92E+E%F%KL ! ! $$"7"7 $ $r5   rz   ztpu.experimental.embedding.SGDc                   8    e Zd ZdZ	 	 	 	 	 	 	 	 ddeeeg ef   f   dedee   dee   dee   dee   dee	   d	ef fd
Z
dee   fdZdeej                     fdZdej$                  f fdZdedej*                  f   fdZdedej0                  f   fdZ xZS )SGDa!  Optimization parameters for stochastic gradient descent for TPU embeddings.

  Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`
  argument to set the global optimizer and its parameters:

  ```
  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      ...
      optimizer=tf.tpu.experimental.embedding.SGD(0.1))
  ```

  This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the
  optimizer parameter to set a table specific optimizer. This will override the
  optimizer and parameters for global embedding optimizer defined above:

  ```
  table_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...,
      optimizer=tf.tpu.experimental.embedding.SGD(0.2))
  table_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)

  feature_config = (
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_one),
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_two))

  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=tf.tpu.experimental.embedding.SGD(0.1))
  ```

  In the above example, the first feature will be looked up in a table that has
  a learning rate of 0.2 while the second feature will be looked up in a table
  that has a learning rate of 0.1.

  See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a
  complete description of these parameters and their impacts on the optimizer
  algorithm.
  r"   r#   r$   r%   r&   r'   r(   r*   c	                 4    t         	|   |||||||d|	       y)a  Optimization parameters for stochastic gradient descent.

    Args:
      learning_rate: The learning rate. It should be a floating point value or a
        callable taking no arguments for a dynamic learning rate.
      use_gradient_accumulation: setting this to `False` makes embedding
        gradients calculation less accurate but faster.
      clip_weight_min: the minimum value to clip by; None means -infinity.
      clip_weight_max: the maximum value to clip by; None means +infinity.
      weight_decay_factor: amount of weight decay to apply; None means that the
        weights are not decayed. Weights are decayed by multiplying the weight
        by this factor each step.
      multiply_weight_decay_factor_by_learning_rate: if true,
        `weight_decay_factor` is multiplied by the current learning rate.
      clipvalue: Controls clipping of the gradient. Set to either a single
        positive scalar value to get clipping or a tiple of scalar values (min,
        max) to set a separate maximum or minimum. If one of the two entries is
        None, then there will be no clipping that direction. Note if this is
        set, you may see a decrease in performance as  gradient accumulation
        will be enabled (it is normally off for SGD as it has no affect on
        accuracy). See
        'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for more
        information on gradient accumulation and its impact on tpu embeddings.
      low_dimensional_packing_status: Status of the low-dimensional embedding
        packing optimization controls whether to optimize the packing of
        1-dimensional, 2-dimensional, and 4-dimensional embedding tables in
        memory.
    N)r   r4   )
r2   r"   r#   r$   r%   r&   r'   r(   r*   r[   s
            r3   r4   zSGD.__init__  s.    N 
G!5&
r5   r6   c                     g S rc   rw   r:   s    r3   r;   zSGD._slot_names      Ir5   c                     g S rc   rw   r:   s    r3   r=   zSGD._slot_initializers  r   r5   r>   c                 X    t         |   |       |j                  j                          y rc   )r   rJ   stochastic_gradient_descentSetInParentr2   r>   r[   s     r3   rJ   z SGD._set_optimization_parameters  s"    	G(4**668r5   .c                 "    t         j                  S rc   )r   9load_tpu_embedding_stochastic_gradient_descent_parametersr:   s    r3   rL   z	SGD._load  s    LLLr5   c                 "    t         j                  S rc   )r   =retrieve_tpu_embedding_stochastic_gradient_descent_parametersr:   s    r3   rO   zSGD._retrieve  s    PPPr5   )r   TNNNNNF)rf   rg   rh   ri   r   rj   r   rk   r   rl   r4   r   r
   r;   r   rp   r=   r   rq   rJ   r   rr   rL   r   rs   rO   r   r   s   @r3   r   r   ^  s   +^ :>(,)-)--1FJ+/-215(2u9"5561 "&1  	1
  1 $E?1 6>d^1 -(1 '+1f4: ${'>'>"? 93JJ9
MXc3==01 MQ#t{{"23 Qr5   r   z"tpu.experimental.embedding.Adagradc                   J    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 ddeeeg ef   f   dededee   dee   dee   dee   d	ee	   d
ee
   def fdZdee   fdZdeej                      fdZdej&                  f fdZdedej,                  f   fdZdedej2                  f   fdZ xZS )Adagrada&  Optimization parameters for Adagrad with TPU embeddings.

  Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`
  argument to set the global optimizer and its parameters:

  ```python
  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      ...
      optimizer=tf.tpu.experimental.embedding.Adagrad(0.1))
  ```

  This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the
  optimizer parameter to set a table specific optimizer. This will override the
  optimizer and parameters for global embedding optimizer defined above:

  ```python
  table_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...,
      optimizer=tf.tpu.experimental.embedding.Adagrad(0.2))
  table_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)

  feature_config = (
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_one),
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_two))

  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=tf.tpu.experimental.embedding.Adagrad(0.1))
  ```

  In the above example, the first feature will be looked up in a table that has
  a learning rate of 0.2 while the second feature will be looked up in a table
  that has a learning rate of 0.1.

  See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a
  complete description of these parameters and their impacts on the optimizer
  algorithm.
  r"   initial_accumulator_valuer#   r$   r%   r&   r'   r)   r(   r*   c                 h    t         |   |||||||	||
	       |dk  rt        d|       || _        y)a  Optimization parameters for Adagrad.

    Args:
      learning_rate: The learning rate. It should be a floating point value or a
        callable taking no arguments for a dynamic learning rate.
      initial_accumulator_value: initial accumulator for Adagrad.
      use_gradient_accumulation: setting this to `False` makes embedding
        gradients calculation less accurate but faster.
      clip_weight_min: the minimum value to clip by; None means -infinity.
      clip_weight_max: the maximum value to clip by; None means +infinity.
      weight_decay_factor: amount of weight decay to apply; None means that the
        weights are not decayed.
      multiply_weight_decay_factor_by_learning_rate: if true,
        `weight_decay_factor` is multiplied by the current learning rate.
      slot_variable_creation_fn: If you wish do directly control the creation of
        the slot variables, set this to a callable taking three parameters: a
        table variable, a list of slot names to create for it, and a list of
        initializers. This function should return a dict with the slot names as
        keys and the created variables as values with types matching the table
        variable. When set to None (the default), uses the built-in variable
        creation.
      clipvalue: Controls clipping of the gradient. Set to either a single
        positive scalar value to get clipping or a tuple of scalar values (min,
        max) to set a separate maximum or minimum. If one of the two entries is
        None, then there will be no clipping that direction.
      low_dimensional_packing_status: Status of the low-dimensional embedding
        packing optimization controls whether to optimize the packing of
        1-dimensional, 2-dimensional, and 4-dimensional embedding tables in
        memory.
    r   IArgument `initial_accumulator_value` must be a positive float. Received: N)r   r4   r,   r   )r2   r"   r   r#   r$   r%   r&   r'   r)   r(   r*   r[   s              r3   r4   zAdagrad.__init__  s_    V 
G!5!&
 !A%0134 4 &?D"r5   r6   c                     dgS )Naccumulatorsrw   r:   s    r3   r;   zAdagrad._slot_names=  s    r5   c                 F    t        j                  | j                  d      gS NT)support_partitionr   Constantr   r:   s    r3   r=   zAdagrad._slot_initializers@  s%    **d	
 r5   r>   c                 X    t         |   |       |j                  j                          y rc   )r   rJ   adagradr   r   s     r3   rJ   z$Adagrad._set_optimization_parametersG  s"    	G(4""$r5   .c                 "    t         j                  S rc   )r   %load_tpu_embedding_adagrad_parametersr:   s    r3   rL   zAdagrad._loadL  s    888r5   c                 "    t         j                  S rc   )r   )retrieve_tpu_embedding_adagrad_parametersr:   s    r3   rO   zAdagrad._retrieveO  s    <<<r5   )
MbP?皙?TNNNNNNFrf   rg   rh   ri   r   rj   r   rk   r   rm   rl   r4   r   r
   r;   r   rp   r=   r   rq   rJ   r   rr   rL   r   rs   rO   r   r   s   @r3   r   r     s-   +^ :?),(,)-)--1FJCG+/-2:?5(2u9"556:? "':? "&	:?
  :?  :? $E?:? 6>d^:? "**?!@:? -(:? '+:?x4: ${'>'>"? %3JJ%
9Xc3==01 9=#t{{"23 =r5   r   z*tpu.experimental.embedding.AdagradMomentumc                   b    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddeeeg ef   f   dedededededed	ee   d
ee   dee   dee   dee	   dee
   def fdZdee   fdZdeej                      fdZdej&                  f fdZdedej,                  f   fdZdedej2                  f   fdZ xZS )AdagradMomentumaI  Optimization parameters for Adagrad + Momentum with TPU embeddings.

  Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`
  argument to set the global optimizer and its parameters:

  ```python
  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      ...
      optimizer=tf.tpu.experimental.embedding.AdagradMomentum(0.1))
  ```

  This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the
  optimizer parameter to set a table specific optimizer. This will override the
  optimizer and parameters for global embedding optimizer defined above:

  ```python
  table_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...,
      optimizer=tf.tpu.experimental.embedding.AdagradMomentum(0.2))
  table_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)

  feature_config = (
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_one),
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_two))

  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=tf.tpu.experimental.embedding.AdagradMomentum(0.1))
  ```

  In the above example, the first feature will be looked up in a table that has
  a learning rate of 0.2 while the second feature will be looked up in a table
  that has a learning rate of 0.1.

  See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a
  complete description of these parameters and their impacts on the optimizer
  algorithm.
  r"   momentumuse_nesterovexponentbeta2epsilonr#   r$   r%   r&   r'   r)   r(   r*   c                     t         |   ||||	|
||||	       |dk  rt        d      |dk  rt        d      || _        || _        || _        || _        || _        y)aL  Optimization parameters for Adagrad + Momentum.

    Args:
      learning_rate: The learning rate. It should be a floating point value or a
        callable taking no arguments for a dynamic learning rate.
      momentum: Moving average parameter for the momentum accumulator.
      use_nesterov: Whether to use the Nesterov variant of momentum. See
        Sutskever et al., 2013.
      exponent: Exponent for the Adagrad accumulator.
      beta2: Moving average parameter for the Adagrad accumulator.
      epsilon: initial accumulator for Adagrad accumulator.
      use_gradient_accumulation: setting this to `False` makes embedding
        gradients calculation less accurate but faster.
      clip_weight_min: the minimum value to clip by; None means -infinity.
      clip_weight_max: the maximum value to clip by; None means +infinity.
      weight_decay_factor: amount of weight decay to apply; None means that the
        weights are not decayed.
      multiply_weight_decay_factor_by_learning_rate: if true,
        `weight_decay_factor` is multiplied by the current learning rate.
      slot_variable_creation_fn: If you wish do directly control the creation of
        the slot variables, set this to a callable taking three parameters: a
        table variable, a list of slot names to create for it, and a list of
        initializers. This function should return a dict with the slot names as
        keys and the created variables as values with types matching the table
        variable. When set to None (the default), uses the built-in variable
        creation.
      clipvalue: Controls clipping of the gradient. Set to either a single
        positive scalar value to get clipping or a tuple of scalar values (min,
        max) to set a separate maximum or minimum. If one of the two entries is
        None, then there will be no clipping that direction.
      low_dimensional_packing_status: Status of the low-dimensional embedding
        packing optimization controls whether to optimize the packing of
        1-dimensional, 2-dimensional, and 4-dimensional embedding tables in
        memory.
    r   z*Adagrad momentum: epsilon must be positivez/Adagrad momentum: Precondition exponent must >0N)r   r4   r,   r   r   r   r   r   )r2   r"   r   r   r   r   r   r#   r$   r%   r&   r'   r)   r(   r*   r[   s                  r3   r4   zAdagradMomentum.__init__  sz    h 
G!5!&
 !|CDD1}HIIDM$DDMDJDLr5   r6   c                 
    ddgS )Nr   momentarw   r:   s    r3   r;   zAdagradMomentum._slot_names      I&&r5   c                 Z    t        j                  d      t        j                  d      gS r   r   r   r:   s    r3   r=   z"AdagradMomentum._slot_initializers  (    t4t4 r5   r>   c                 f   t         |   |       |j                  j                          | j                  |j                  _        | j
                  |j                  _        | j                  |j                  _        | j                  |j                  _        | j                  |j                  _        y rc   )	r   rJ   adagrad_momentumr   r   r   r   r   r   r   s     r3   rJ   z,AdagradMomentum._set_optimization_parameters  s     
G(4++-+/==J(/3/@/@J,+/==J((,

J%*.,,J'r5   .c                 "    t         j                  S rc   )r   .load_tpu_embedding_adagrad_momentum_parametersr:   s    r3   rL   zAdagradMomentum._load  s    AAAr5   c                 "    t         j                  S rc   )r   2retrieve_tpu_embedding_adagrad_momentum_parametersr:   s    r3   rO   zAdagradMomentum._retrieve  s    EEEr5   )r           F      g|=TNNNNNNFr   r   s   @r3   r   r   S  st   +^ :? (,)-)--1FJCG+/-2G5(2u9"556G G 	G
 G G G "&G  G  G $E?G 6>d^G "**?!@G -(G '+GR'4: '${'>'>"? 	73JJ	7BXc3==01 BF#t{{"23 Fr5   r   ztpu.experimental.embedding.FTRLc            !       n    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddeeeg ef   f   dedededededed	ee   d
ee   dee   dee   dee	   dee
   dededef  fdZdee   fdZdeej                      fdZdej&                  f fdZdedej,                  f   fdZdedej2                  f   fdZ xZS )FTRLat  Optimization parameters for FTRL with TPU embeddings.

  See Algorithm 1 of this
  [paper](https://research.google.com/pubs/archive/41159.pdf).

  Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`
  argument to set the global optimizer and its parameters:

  ```python
  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      ...
      optimizer=tf.tpu.experimental.embedding.FTRL(0.1))
  ```

  This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the
  optimizer parameter to set a table specific optimizer. This will override the
  optimizer and parameters for global embedding optimizer defined above:

  ```python
  table_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...,
      optimizer=tf.tpu.experimental.embedding.FTRL(0.2))
  table_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)

  feature_config = (
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_one),
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_two))

  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=tf.tpu.experimental.embedding.FTRL(0.1))
  ```

  In the above example, the first feature will be looked up in a table that has
  a learning rate of 0.2 while the second feature will be looked up in a table
  that has a learning rate of 0.1.

  See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a
  complete description of these parameters and their impacts on the optimizer
  algorithm.
  r"   learning_rate_powerl1_regularization_strengthl2_regularization_strengthbetar   r#   r$   r%   r&   r'   r)   r(    multiply_linear_by_learning_rateallow_zero_accumulatorr*   c                     t         |   ||||	|
||||	       |dk  rt        d|       || _        || _        || _        || _        || _        || _        || _	        y)a  Optimization parameters for Adagrad.

    Args:
      learning_rate: The learning rate. It should be a floating point value or a
        callable taking no arguments for a dynamic learning rate.
      learning_rate_power: A float value, must be less or equal to zero.
        Controls how the learning rate decreases during training. Use zero for a
        fixed learning rate.
      l1_regularization_strength: A float value, must be greater than or equal
        to zero.
      l2_regularization_strength: A float value, must be greater than or equal
        to zero.
      beta: A float value, representing the beta value from the paper.
      initial_accumulator_value: The starting value for accumulators. Only zero
        or positive values are allowed.
      use_gradient_accumulation: setting this to `False` makes embedding
        gradients calculation less accurate but faster.
      clip_weight_min: the minimum value to clip by; None means -infinity.
      clip_weight_max: the maximum value to clip by; None means +infinity.
      weight_decay_factor: amount of weight decay to apply; None means that the
        weights are not decayed.
      multiply_weight_decay_factor_by_learning_rate: if true,
        `weight_decay_factor` is multiplied by the current learning rate.
      slot_variable_creation_fn: If you wish do directly control the creation of
        the slot variables, set this to a callable taking three parameters: a
        table variable, a list of slot names to create for it, and a list of
        initializers. This function should return a dict with the slot names as
        keys and the created variables as values with types matching the table
        variable. When set to None (the default), uses the built-in variable
        creation.
      clipvalue: Controls clipping of the gradient. Set to either a single
        positive scalar value to get clipping or a tuple of scalar values (min,
        max) to set a separate maximum or minimum. If one of the two entries is
        None, then there will be no clipping that direction.
      multiply_linear_by_learning_rate: If set to True, a modified formula is
        used for FTRL that treats the "linear" accumulator as being
        pre-multiplied by the learning rate (i.e., the accumulator named
        "linear" actually stores "linear * learning_rate"). Other than
        checkpoint compatibility, this is mathematically equivalent for a static
        learning rate; for a dynamic learning rate, it is nearly the same as
        long as the learning rate does not change quickly. The benefit of this
        is that the modified formula handles zero and near-zero learning rates
        without producing NaNs, improving flexibility for learning rate ramp-up.
      allow_zero_accumulator: If set to True, changes some internal formulas to
        allow zero and near-zero accumulator values at the cost of some
        performance; this only needs to be set if you are using an initial
        accumulator value of zero, which is uncommon.
      low_dimensional_packing_status: Status of the low-dimensional embedding
        packing optimization controls whether to optimize the packing of
        1-dimensional, 2-dimensional, and 4-dimensional embedding tables in
        memory.
    r   r   N)
r   r4   r,   r   r   r   r   r   r   r   )r2   r"   r   r   r   r   r   r#   r$   r%   r&   r'   r)   r(   r   r   r*   r[   s                    r3   r4   zFTRL.__init__  s    N 
G!5!&
 !A%0134 4 &?D"2D&@D#&@D#DI,LD)"8Dr5   r6   c                 
    ddgS )Nr   linearsrw   r:   s    r3   r;   zFTRL._slot_namesv  r   r5   c                 p    t        j                  | j                  d      t        j                  d      gS r   r   r:   s    r3   r=   zFTRL._slot_initializersy  s5    **d	
 	t4	 r5   r>   c                    t         |   |       |j                  }| j                  |_        | j
                  |_        | j                  |_        | j                  |_	        | j                  |_        | j                  |_        y rc   )r   rJ   ftrlr   l1r   l2r   lr_powerr   r   multiply_linear_by_lrr   )r2   r>   r   r[   s      r3   rJ   z!FTRL._set_optimization_parameters  si     
G(4??D--DG--DG,,DM		DI!%!F!FD"&"="=Dr5   .c                 "    t         j                  S rc   )r   "load_tpu_embedding_ftrl_parametersr:   s    r3   rL   z
FTRL._load      555r5   c                 "    t         j                  S rc   )r   &retrieve_tpu_embedding_ftrl_parametersr:   s    r3   rO   zFTRL._retrieve      999r5   )r   g      r   r   r   r   TNNNNNNFFFr   r   s   @r3   r   r     s   .d :?#'*-*-),(,)-)--1FJCG+//4%*-2#\95(2u9"556\9 !\9 #(	\9
 #(\9 \9 "'\9 "&\9  \9  \9 $E?\9 6>d^\9 "**?!@\9 -(\9 )-\9  #!\9" '+#\9|'4: '${'>'>"? 
>3JJ
>6Xc3==01 6:#t{{"23 :r5   r   ztpu.experimental.embedding.Adamc                   b    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddeeeg ef   f   dedededededed	ee   d
ee   dee   dee   dee	   dee
   def fdZdee   fdZdeej                      fdZdej&                  f fdZdedej,                  f   fdZdedej2                  f   fdZ xZS )Adama  Optimization parameters for Adam with TPU embeddings.

  Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`
  argument to set the global optimizer and its parameters:

  NOTE: By default this optimizer is lazy, i.e. it will not apply the gradient
  update of zero to rows that were not looked up. You can change this behavior
  by setting `lazy_adam` to `False`.

  ```python
  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      ...
      optimizer=tf.tpu.experimental.embedding.Adam(0.1))
  ```

  This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the
  optimizer parameter to set a table specific optimizer. This will override the
  optimizer and parameters for global embedding optimizer defined above:

  ```python
  table_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...,
      optimizer=tf.tpu.experimental.embedding.Adam(0.2))
  table_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)

  feature_config = (
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_one),
      tf.tpu.experimental.embedding.FeatureConfig(
          table=table_two))

  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=tf.tpu.experimental.embedding.Adam(0.1))
  ```

  In the above example, the first feature will be looked up in a table that has
  a learning rate of 0.2 while the second feature will be looked up in a table
  that has a learning rate of 0.1.

  See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a
  complete description of these parameters and their impacts on the optimizer
  algorithm.
  r"   beta_1beta_2r   	lazy_adamsum_inside_sqrtr#   r$   r%   r&   r'   r)   r(   r*   c                 B   t         t        |   ||||	|
||||	       |dk  s|dk\  rt        d| d      |dk  s|dk\  rt        d| d      |dk  rt        dj	                  |            |s|st        d      || _        || _        || _        || _        || _	        y)	a	  Optimization parameters for Adam.

    See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a
    complete description of these parameters and their impacts on the optimizer
    algorithm.

    Args:
      learning_rate: The learning rate. It should be a floating point value or a
        callable taking no arguments for a dynamic learning rate.
      beta_1: A float value. The exponential decay rate for the 1st moment
        estimates.
      beta_2: A float value. The exponential decay rate for the 2nd moment
        estimates.
      epsilon: A small constant for numerical stability.
      lazy_adam: Use lazy Adam instead of Adam. Lazy Adam trains faster.
      sum_inside_sqrt: When this is true, the Adam update formula is changed
        from `m / (sqrt(v) + epsilon)` to `m / sqrt(v + epsilon**2)`. This
        option improves the performance of TPU training and is not expected to
        harm model quality.
      use_gradient_accumulation: Setting this to `False` makes embedding
        gradients calculation less accurate but faster.
      clip_weight_min: the minimum value to clip by; None means -infinity.
      clip_weight_max: the maximum value to clip by; None means +infinity.
      weight_decay_factor: amount of weight decay to apply; None means that the
        weights are not decayed.
      multiply_weight_decay_factor_by_learning_rate: if true,
        `weight_decay_factor` is multiplied by the current learning rate.
      slot_variable_creation_fn: If you wish do directly control the creation of
        the slot variables, set this to a callable taking three parameters: a
        table variable, a list of slot names to create for it, and a list of
        initializers. This function should return a dict with the slot names as
        keys and the created variables as values with types matching the table
        variable. When set to None (the default), uses the built-in variable
        creation.
      clipvalue: Controls clipping of the gradient. Set to either a single
        positive scalar value to get clipping or a tiple of scalar values (min,
        max) to set a separate maximum or minimum. If one of the two entries is
        None, then there will be no clipping that direction.
      low_dimensional_packing_status: Status of the low-dimensional embedding
        packing optimization controls whether to optimize the packing of
        1-dimensional, 2-dimensional, and 4-dimensional embedding tables in
        memory.
    r   g      ?z2Argument `beta_1` must be >= 0 and < 1. Received: .z2Argument `beta_2` must be >= 0 and < 1. Received: z!epsilon must be positive; got {}.z{When disabling lazy Adam (`lazy_adam=False`), gradient accumulation must be used. Set `use_gradient_accumulation` to False.N)
r   r   r4   r,   formatr   r   r   r   r   )r2   r"   r   r   r   r   r   r#   r$   r%   r&   r'   r)   r(   r*   r[   s                  r3   r4   zAdam.__init__  s    x 
$!5!&
 {fl>vha
HJ J{fl>vha
HJ J"}:AA'JKK$Y67 7
 DKDKDLDN*Dr5   r6   c                 
    ddgS )Nr   
velocitiesrw   r:   s    r3   r;   zAdam._slot_names"  s    |$$r5   c                 Z    t        j                  d      t        j                  d      gS r   r   r:   s    r3   r=   zAdam._slot_initializers%  r   r5   r>   c                 <   t         t        |   |       | j                  |j                  _        | j                  |j                  _        | j                  |j                  _        | j                   |j                  _
        | j                  |j                  _        y rc   )r   r   rJ   r   adambeta1r   r   r   r   use_non_lazy_adamr   use_sum_inside_sqrtr   s     r3   rJ   z!Adam._set_optimization_parameters+  si     
$2:> KKJOO KKJOO"llJOO,0NN(:JOO%*.*>*>JOO'r5   .c                 "    t         j                  S rc   )r   "load_tpu_embedding_adam_parametersr:   s    r3   rL   z
Adam._load5  r   r5   c                 "    t         j                  S rc   )r   &retrieve_tpu_embedding_adam_parametersr:   s    r3   rO   zAdam._retrieve8  r   r5   )r   g?g+?gHz>TTTNNNNNNFr   r   s   @r3   r   r     sp   /f :?"(,)-)--1FJCG+/-2Y+5(2u9"556Y+ Y+ 	Y+
 Y+ Y+ Y+ "&Y+  Y+  Y+ $E?Y+ 6>d^Y+ "**?!@Y+ -(Y+ '+Y+v%4: %${'>'>"? ?3JJ?6Xc3==01 6:#t{{"23 :r5   r   z-tpu.experimental.embedding.QuantizationConfigc                   J    e Zd ZdZdededefdZdej                  fdZ	d Z
y	)
QuantizationConfigac  Settings for simulated quantization of the tpu embedding table.

  When simulated quantization is enabled, the results of the embedding lookup
  are clipped and quantized according to the settings here before the combiner
  is applied.

  For example, to quantize `input` the following is done:
  ```python
  if input < lower
    input = lower
  if input > upper
    input = upper
  quantum = (upper - lower) / (num_buckets - 1)
  input = math.floor((input - lower) / quantum + 0.5) * quantum + lower
  ```

  See tensorflow/core/protobuf/tpu/optimization_parameters.proto for more
  details.

  NOTE: This does not change the storage type of the embedding table, that will
  continue to be float32 as will the saved variable in the checkpoint. You will
  have to manually quantize the variable (typically with the same algorithm and
  settings as above) manually.
  num_bucketsrE   rG   c                 V    |dk  rt        d| d      || _        || _        || _        y)a[  Simulated quantizaiton configuration.

    Args:
      num_buckets: The number of quantization buckets, must be atleast 2.
      lower: The lower bound for the quantization range.
      upper: The upper bound for the quantization range.

    Returns:
      `QuantizationConfig`.

    Raises:
      ValueError: if `num_buckets` is less than 2.
    r   znum_buckets is z0, must be at least 2 for simulated quantization.N)r,   r   rE   rG   )r2   r   rE   rG   s       r3   r4   zQuantizationConfig.__init__W  s@     Q 61 2 3 3 #DDJDJr5   r>   c                    d|j                   _        | j                  |j                   _        | j                  |j                   j                  j                  _        | j                  |j                   j                  j                  _        y )NT)simulated_quantizationenabledr   rE   rD   rF   rG   rI   s     r3   rJ   z/QuantizationConfig._set_optimization_parametersm  s`    04J%%-484D4DJ%%1DHJJJ%%55;;ADHJJJ%%55;;Ar5   c                 f    dj                  | j                  | j                  | j                        S )NzQQuantizationConfig(num_buckets={num_buckets!r}, lower={lower!r}, upper={upper!r}))r   rE   rG   )r   r   rE   rG   r:   s    r3   __repr__zQuantizationConfig.__repr__t  s2    %v ,,jjjj  &  "#r5   N)rf   rg   rh   ri   rv   rj   r4   r   rq   rJ   r  rw   r5   r3   r   r   <  s;    2# e E ,O3JJO#r5   r   z&tpu.experimental.embedding.TableConfigc                       e Zd ZdZ	 	 	 	 	 	 ddededeeegdf      dee   de	dee	   d	e
d
ee   fdZd Zdej                  j                  dedeeg ef   ef   fdZy)rQ   a9  Configuration data for one embedding table.

  This class holds the configuration data for a single embedding table. It is
  used as the `table` parameter of a
  `tf.tpu.experimental.embedding.FeatureConfig`. Multiple
  `tf.tpu.experimental.embedding.FeatureConfig` objects can use the same
  `tf.tpu.experimental.embedding.TableConfig` object. In this case a shared
  table will be created for those feature lookups.

  ```python
  table_config_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)
  table_config_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)
  feature_config = {
      'feature_one': tf.tpu.experimental.embedding.FeatureConfig(
          table=table_config_one),
      'feature_two': tf.tpu.experimental.embedding.FeatureConfig(
          table=table_config_one),
      'feature_three': tf.tpu.experimental.embedding.FeatureConfig(
          table=table_config_two)}
  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=tf.tpu.experimental.embedding.Adam(0.1))
  ```

  The above configuration has 2 tables, and three features. The first two
  features will be looked up in the first table and the third feature will be
  looked up in the second table.

  Nvocabulary_sizedimrW   	optimizercombinernamequantization_configlayoutc	                    t        |t              r|dk  rt        d|       t        |t              r|dk  rt        d|       |t        |      st        d|       |-t	        j
                  ddt        j                  |      z        }d}	||	vrt        d	|	 d
|       |t        j                  d       || _
        || _        || _        || _        || _        || _        || _        || _        y)a  Embedding table configuration.

    Args:
      vocabulary_size: Size of the table's vocabulary (number of rows).
      dim: The embedding dimension (width) of the table.
      initializer: A callable initializer taking one parameter, the shape of the
        variable that will be initialized. Will be called once per task, to
        initialize that task's shard of the embedding table. If not specified,
        defaults to `truncated_normal_initializer` with mean `0.0` and standard
        deviation `1/sqrt(dim)`.
      optimizer: An optional instance of an optimizer parameters class, instance
        of one of `tf.tpu.experimental.embedding.SGD`,
        `tf.tpu.experimental.embedding.Adagrad` or
        `tf.tpu.experimental.embedding.Adam`. If set will override the global
        optimizer passed to `tf.tpu.experimental.embedding.TPUEmbedding`.
      combiner: A string specifying how to reduce if there are multiple entries
        in a single row. Currently 'mean', 'sqrtn', 'sum' are supported, with
        'mean' the default. 'sqrtn' often achieves good accuracy, in particular
        with bag-of-words columns. For more information, see
        `tf.nn.embedding_lookup_sparse`.
      name: An optional string used to name the table. Must be defined if
        running on SparseCore.
      quantization_config: The simulated quantization config. An instance of
        `tf.tpu.experimental.embedding.QuantizationConfig`. See the class for
        more documentation.
      layout: If the table already has its layout computed, you can pass it in
        here. Otherwise, we will compute it for you. Most users should leave
        this as None.

    Returns:
      `TableConfig`.

    Raises:
      ValueError: if `vocabulary_size` is not a positive integer.
      ValueError: if `dim` is not a positive integer.
      ValueError: if `initializer` is specified and is not callable.
      ValueError: if `combiner` is not supported.
    r   zFArgument `vocabulary_size` must be an int and must be >= 1. Received: zPArgument `dim` (embedding dimension) must be an int and must be >= 1. Received: Nz?Argument `initializer` must be a callable (or None). Received: r   )meanstddev)r  sumsqrtnz#Argument `combiner` must be one of z. Received: zuName of the table config must be specified for running on SparseCore. Different table configs must have unique names.)r-   rv   r,   r1   r   TruncatedNormalmathsqrtr   warningr  r  rW   r	  r
  r  r  r  )
r2   r  r  rW   r	  r
  r  r  r  accepted_combinerss
             r3   r4   zTableConfig.__init__  sB   f os+/B&')* * c33788;u>? ? 	(;*?"m%& & //S7837GIk1))/0B/C Dj"# # |ooI
 +DDH"DDNDMDI2DDKr5   c           	         | j                   }t        |t        j                        rut	        j
                  t        j                  |      }|j                  dk(  rBt        j                  |j                  dt        j                  | j                        z        rd }dj                  | j                  | j                  || j                  | j                  | j                   | j"                        S )Nr   r   zTableConfig(vocabulary_size={vocabulary_size!r}, dim={dim!r}, initializer={initializer!r}, optimizer={optimizer!r}, combiner={combiner!r}, name={name!r}, quantization_config={quantization!r}))r  r  rW   r	  r
  r  quantization)rW   r-   r   r  typingcastr  r  iscloser  r  r  r   r  r	  r
  r  r  )r2   rW   s     r3   r  zTableConfig.__repr__  s    ""K+{::;KK ; ;[Ik


c
!ll;--q4881D/DE4 5;F $ 4 4HH'..YY!55 5; 5r5   table_descriptor	num_hostslearning_rate_indexc                    | j                   |_         t        | j                  |      |_        | j                  |_        |j
                  }| j                  rt        | j                  j                        r3|| j                  j                     |j                  j                  _
        n%| j                  j                  |j                  _        | j                  j                  r)t        j                  j                  j                   |_        | j                  j#                  |       | j$                  r| j$                  j#                  |       yy)z-Set the table descriptor from the table data.N)r  maxr  r  	dimensionoptimization_parametersr	  r1   r"   dynamictagconstantr*   r   LowDimensionalPackingStatusStatusrA   rJ   r  )r2   r  r  r  r>   s        r3   _set_table_descriptorz!TableConfig._set_table_descriptor  s     !II (+4+?+?'K$!%!99J
 ~~	$....	/ < <= 	  ((, -1NN,H,H
  )		6	6'CCJJRR 	1 nn11*=
;;JG  r5   )NNr  NNN)rf   rg   rh   ri   rv   r   r   r   r!   r
   r   r4   r  r   TPUEmbeddingConfigurationTableDescriptorr   r)  rw   r5   r3   rQ   rQ   |  s    !N 6:(,!04 #WW W HcUD[12	W
 *%W W TNW .W smWr0!H7  !H 	!H
  S 13 67!Hr5   rQ   z+tpu.experimental.embedding.RowIdInitializerc                   j    e Zd ZdZd	defdZdeee   ef   de	j                  dej                  fdZy)
RowIdInitializerz>An initializer that initializes the table with vocabulary ids.offsetc                     || _         y rc   )r.  )r2   r.  s     r3   r4   zRowIdInitializer.__init__:  s	    DKr5   shapedtyper6   c                     t        j                  | j                  | j                  |d   z   d|      d d d f   t        j                  ||      z  S )Nr   r   )startlimitdeltar1  )r1  )r   ranger.  r   ones)r2   r0  r1  s      r3   __call__zRowIdInitializer.__call__=  sN     >>kkuQx!7qgU34 4r5   N)r   )rf   rg   rh   ri   rv   r4   r   r	   r   r   DTyper   rs   r8  rw   r5   r3   r-  r-  6  sD    FS 4#344=C\\4{{4r5   r-  z(tpu.experimental.embedding.FeatureConfigc                   X    e Zd ZdZ	 	 	 	 d
dedededeee	e   e
f      dee   f
dZd	 Zy)FeatureConfigaM  Configuration data for one embedding feature.

  This class holds the configuration data for a single embedding feature. The
  main use is to assign features to `tf.tpu.experimental.embedding.TableConfig`s
  via the table parameter:

  ```python
  table_config_one = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)
  table_config_two = tf.tpu.experimental.embedding.TableConfig(
      vocabulary_size=...,
      dim=...)
  feature_config = {
      'feature_one': tf.tpu.experimental.embedding.FeatureConfig(
          table=table_config_one),
      'feature_two': tf.tpu.experimental.embedding.FeatureConfig(
          table=table_config_one),
      'feature_three': tf.tpu.experimental.embedding.FeatureConfig(
          table=table_config_two)}
  embedding = tf.tpu.experimental.embedding.TPUEmbedding(
      feature_config=feature_config,
      batch_size=...
      optimizer=tf.tpu.experimental.embedding.Adam(0.1))
  ```

  The above configuration has 2 tables, and three features. The first two
  features will be looked up in the first table and the third feature will be
  looked up in the second table.

  You can also specify the output shape for each feature. The output shape
  should be the expected activation shape excluding the table dimension. For
  dense and sparse tensor, the output shape should be the same as the input
  shape excluding the last dimension. For ragged tensor, the output shape can
  mismatch the input shape.

  NOTE: The `max_sequence_length` will be only used when the input tensor has
  rank 2 and the `output_shape` is not set in the feature config.

  When feeding features into `embedding.enqueue` they can be `tf.Tensor`s,
  `tf.SparseTensor`s or `tf.RaggedTensor`s. When the argument
  `max_sequence_length` is 0, the default, you should expect a output of
  `embedding.dequeue` for this feature of shape `(batch_size, dim)`. If
  `max_sequence_length` is greater than 0, the feature is embedded as a sequence
  and padded up to the given length. The shape of the output for this feature
  will be `(batch_size, max_sequence_length, dim)`.
  NrP   max_sequence_lengthvalidate_weights_and_indicesoutput_shaper  c                 .   t        |t              st        dt        |       d      t        |t              r|dk  rt        d|       || _        || _        || _        t        |      | _	        t        |t              st        d|       || _        y)aU  Feature configuration.

    Args:
      table: An instance of `tf.tpu.experimental.embedding.TableConfig`,
        describing the table in which this feature should be looked up.
      max_sequence_length: If positive, the feature is a sequence feature with
        the corresponding maximum sequence length. If the sequence is longer
        than this, it will be truncated. If 0, the feature is not a sequence
        feature.
      validate_weights_and_indices: If true, uses safe_embedding_lookup during
        serving which ensures there are no empty rows and all weights and ids
        are positive at the expense of extra compute cost.
      output_shape: Optional argument to config the output shape of the feature
        activation. If provided, the feature feeding to the `embedding.enqueue`
        has to match the shape (for ragged tensor, the input shape and output
        shape can mismatch). If not provided, the shape can be either provided
        to the `embedding.build` or auto detected at the runtime.
      name: An optional string used to name the table. Must be defined if
        running on SparseCore.

    Returns:
      `FeatureConfig`.

    Raises:
      ValueError: if `table` is not an instance of
        `tf.tpu.experimental.embedding.TableConfig`.
      ValueError: if `max_sequence_length` not an integer or is negative.
    z"Argument `table` has invalid type z7. Expected `tf.tpu.experimental.embedding.TableConfig`.r   zJArgument `max_sequence_length` must be an int and must be >= 0. Received: zEArgument `validate_weights_and_indices` must be a boolean. Received: N)r-   rQ   r,   typerv   rP   r<  r  r   r>  rk   r=  )r2   rP   r<  r=  r>  r  s         r3   r4   zFeatureConfig.__init__w  s    D e[);DK= IO O P P )3/3F3J*+-. . DJ2DDI#L1D$d,3467 7 )ED%r5   c                     dj                  | j                  | j                  | j                  | j                  | j
                        S )NzFeatureConfig(table={table!r}, max_sequence_length={max_sequence_length!r}, validate_weights_and_indices={validate_weights_and_indices!r}, output_shape={output_shape!r}, name={name!r}))rP   r<  r=  r>  r  )r   rP   r<  r=  r>  r  r:   s    r3   r  zFeatureConfig.__repr__  sH    < =CFjj$($<$<-1-N-N!..YY =C = !r5   )r   TNN)rf   rg   rh   ri   rQ   rv   rk   r   r   r   r   r
   r4   r  rw   r5   r3   r;  r;  E  sl    .d +,48GK&*6E!6E$'6E .26E &eDI{,B&CD	6E
 d^6Ep	!r5   r;  configr6   c                     t        j                  d       t        |       j                         D ]  }t        j                  |        t        j                  d       y)a  Logs a TPUEmbeddingConfiguration proto across multiple statements.

  Args:
    config: TPUEmbeddingConfiguration proto to log.  Necessary because
      logging.info has a maximum length to each log statement, which
      particularly large configs can exceed.
  z+Beginning log of TPUEmbeddingConfiguration.z+Done with log of TPUEmbeddingConfiguration.N)r   infor   
splitlines)rB  lines     r3   log_tpu_embedding_configurationrG    sF     
,,<=&k$$& dLL	,,<=r5   device_stringsc                 r    t        d | D        d       }|D cg c]  }|j                          c}S c c}w )Nc              3   Z   K   | ]#  }t         j                  j                  |       % y wrc   )r   DeviceSpecV2from_string).0specs     r3   	<genexpr>z,_sort_device_spec_strings.<locals>.<genexpr>  s!     Md{++D1Ms   )+c                 H    | j                   | j                  | j                  fS rc   )replicataskdevice_index)ss    r3   <lambda>z+_sort_device_spec_strings.<locals>.<lambda>  s    QYY7 r5   )key)sorted	to_string)rH  sorted_specsrN  s      r3   _sort_device_spec_stringsrZ    s4    MnM
7, (4	4t$..
	44	4s   4strategyc                     g }t        | j                  j                        D ]-  }t        j                  |      }||vs|j                  |       / t        |      | j                  j                  k(  sJ |S )zReturns a sorted list of CPU devices for the remote jobs.

  Args:
    strategy: A TPUStrategy object.

  Returns:
    A sorted list of device host strings.
  )rZ  extendedworker_devicesr   get_host_for_deviceappendr   r  )r[  list_of_hosts
tpu_devicehosts       r3   get_list_of_hostsrd    sv     --h.?.?.N.NO !j**:6D= 4 ! 
]	x00::	::	:	r5   )Cri   rn   r  r  r   r   r   r   r   r   r	   r
   r   r   r   abslr   tensorflow.core.protobuf.tpur   r   tensorflow.python.distributer   r   r   tensorflow.python.frameworkr   r   r   (tensorflow.python.framework.tensor_shaper   tensorflow.python.opsr   r   r   r   rt   tensorflow.python.tpu.opsr   tensorflow.python.typesr    tensorflow.python.util.tf_exportr   ShardedVariableru   r   rp   rm   rj   rl   ABCMetar!   rz   r   r   r   r   r   r   rQ   r-  r;  r*  rG  r   rZ  TPUStrategyrd  rw   r5   r3   <module>rq     s   E 
   g g g g  D H 4 9 5 3 . + @ + - * ; - ( 6 )9)I)I$--/ DJ[%<%< =>}	  eE5L)501H.3;; H.V 78]$j ]$ 9]$@ +,pQ* pQ -pQf /0}=j }= 1}=@ 78OFj OF 9OFd ,-j:: j: .j:Z ,-d:: d: .d:N :;<# <# <<#~ 34vH vH 5vHr 894 4 :4 56r! r! 7r!j>+EE>JN>5hsm 5S	 5 8 8 T$Z r5   