
    AVh                        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	 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 Zd Z	 	 	 	 d'dZ edg      ej<                  	 	 	 	 d(d              Z edg       ej<                  d)d              Z  edg      ej<                  	 	 	 	 	 d*d              Z! edg       ej<                  	 	 	 	 d+d               Z" ed!g       ej<                  	 	 	 	 	 	 d,d"              Z# ed!g      ej<                  	 	 	 	 	 	 	 d-d#              Z$d$ Z%d% Z&d& Z'y).zOperations for embeddings.    )compat)composite_tensor)constant_op)dtypes)indexed_slices)ops)sparse_tensor)tensor_shape)	array_ops)array_ops_stack)clip_ops)data_flow_grad)data_flow_ops)math_ops)resource_variable_ops)
sparse_ops)	variables)core)dispatch)	tf_exportc           
          d }|| S  ||      \  }} ||       \  }}t        j                  | ||r|rt        t        ||                  S t	        j                  ||            S )a  Helper function for _embedding_lookup_and_transform.

  This function optionally clips embeddings to an l2-norm of max_norm.

  Args:
    params: A `Tensor` of embeddings retrieved by `gather`.
    ids: The `ids` argument that was passed to `gather`.
    max_norm: If not `None`, each embedding is clipped if its l2-norm is larger
      than this value.

  Returns:
    A `Tensor` with the same type as `params`.
  c                     t        j                  |       j                         j                  }|r|dfS t	        j
                  |       dfS )a/  Helper function to retrieve the rank of a tensor.

    Args:
      x: Something convertible to `Tensor`.

    Returns:
      Either a pair `(rank, True)` where `rank` is an integer or a pair
      `(rank, False)` where `rank` is an integer `Tensor`. In either case,
      `rank` is the rank of `x`.
    TF)r   convert_to_tensor	get_shapendimsr   rank)xr   s     S/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/embedding_ops.py_rankz_clip.<locals>._rank7   sD       #--/55D4Z^^A%%    )axes)r   clip_by_normlistranger   )paramsidsmax_normr   ids_rank
ids_staticparams_rankparams_statics           r   _clipr,   (   sv    &" Ms(J$V}+}			2<Dx-.
9 9 +6	
9 9r    c                     t        j                         rLt        | d      r@t        j                  t        j                         j                  | j                              S t        j                  |       S )Nhandle)r   inside_functionhasattrcolocate_withget_default_graphcapturer.   )params    r   _colocate_withr5   S   sS    wuh7 S224<<U\\JKKU##r    Nc                 x   | t        d      t        | t        t        f      r| st        d      t        | t        j
                        rt        |       } t        | t              s| g} t        j                  |d| |gz         5 }t        |       }t        d | D              st        j                  | d      } t        j                  |d      }|d	k(  r|r|j                         j                  d	k(  ret        | d
         5  t!        t#        j$                  | d
   ||      ||      }|r ||      }ddd       t#        j&                        cddd       S t#        j(                  |dg      }t+        j,                  t#        j.                  |t0        j2                              }	|dk(  r||z  }
||z  }n|dk(  rt5        j6                  t5        j8                  | d
   j                         d
               }t-        d	|      D ]A  }|t5        j6                  t5        j8                  | |   j                         d
               z  }C |j:                  r+t=        j>                  |j:                  |j@                        }ng }t-        |      D ]  }t5        j8                  | |   j                         d
         }||jC                  |       @t        | |         5  |jC                  t#        jD                  | |         d
          ddd        t+        jF                  t+        jH                  tK        jL                  |      |j@                              }||z  }||z  }t+        jN                  ||d	z   z  ||z
  |z        }
t#        jP                  |
|k  ||d	z   z  ||z
  |z        }nt        d| d      t+        jH                  |
t0        j2                        }
tS        jT                  ||
|      }tS        jT                  |	|
|      }g }t-        |      D ]{  }||   }t        jV                  d      5  t        | |         5  t#        j$                  | |   |      }|r |t!        |||            }ddd       ddd       |jC                         } tS        jX                  |||      }|C| d
   j                         d	d }| d	d D ]$  }|j[                  |j                         d	d       }& n|j                         d	d }|j]                         r|}nO|5t        | d
         5  t#        jD                  | d
         }ddd       d	d }nt#        jD                  |      d	d }t#        j(                  |t#        j^                  t#        jD                  |      |gd
            }|ja                  |j                         jc                  |             |st!        |||      }|cddd       S # 1 sw Y   xY w# 1 sw Y   xxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   yxY w)a  Helper function for embedding_lookup and _compute_sampled_logits.

  This function is a generalization of embedding_lookup that optionally
  applies a caller-specified transformation to each embedding. This is
  done through the `transform_fn` argument. If provided, the function is
  applied to each partitioned tensor of retrieved embeddings, colocated
  with the embeddings. This function will be called with a single `Tensor`
  argument of the same type as the `params` tensor and should return a
  `Tensor`. The shape of the argument will be the same as `params` except
  for the size of the first dimension. The first dimension of the result's
  shape must be the same size as the argument's.

  Args:
    params: See embedding_lookup.
    ids: See embedding_lookup.
    partition_strategy: See embedding_lookup.
    name: See embedding_lookup.
    max_norm: See embedding_lookup.
    transform_fn: An optional function to apply to each retrieved embedding. If
      max_norm is provided, transform_fn is applied to the norm-limited
      embeddings.

  Returns:
    See embedding_lookup for details.
  Raises:
    ValueError: If `params` is empty.
  Nzparams must be specifiedz9Length of params is currently 0. Need at least one param.embedding_lookupc              3   P   K   | ]  }t        |t        j                           y w)N)
isinstancer   BaseResourceVariable).0ps     r   	<genexpr>z2_embedding_lookup_and_transform.<locals>.<genexpr>   s&       	1+@@As   $&r%   namer&      r   )out_typemoddivz!Unrecognized partition strategy: z&.Must be one of either `mod` or `div`.)2
ValueErrorr9   r#   tupler   PartitionedVariabler   
name_scopelenanyr   %convert_n_to_tensor_or_indexed_slicesr   r   r   r5   r,   r   gatheridentityreshaper   r$   sizer   int32r
   	Dimensiondimension_valuevaluer   constantdtypeappendshape
reduce_sumcastr   stackmaximumwherer   dynamic_partition	device_v2parallel_dynamic_stitch
merge_withis_fully_definedconcat	set_shapeconcatenate)r%   r&   partition_strategyr?   r'   transform_fnnpresultflat_idsoriginal_indicesp_assignmentsnew_ids
dim_0_sizer<   num_total_idsdim_0_sizesparam_p_dimids_per_partitionextras
gather_idspindicespartitioned_resultpidsretelement_shape_selement_shape_dparams_shapes                              r   _embedding_lookup_and_transformr{   ]   s    B ^
/
00u&v
 0 1 1	556&\F	FD	!XF
~~d.#? @4	VB   CC
x!f


%
0C	Qw(=(=(B&)$ (VAY$7hH'&	( '%@ @2 ""3-h!
..FLL
9
 
u	$ 2b.& "++(()<)<)>q)ABD
q" 	FA
..**6!9+>+>+@+CDF F*	F %..z/?/?P-+9 Ba&66vay7J7J7LQ7OPK&  -!&), B""9??6!9#=a#@AB BB #--mmO11+>OQ-)R/# ((6G!6K)L*2V*;):*;<
 //-&"8"*.?!.C"D#+f#48I"IK /0B/C D4 45 	5 mmM6<<@m 227M2Nj001A1>Dh Ry 
*!!}]]4  	CfQi( C%%fQi6F $E&$$ABfC	C 	!!&)
* 11
&T3c 
	 )--/3 	JA+66q{{}QR7HI/	J --/!"- 
	)	)	+) F1I& 	4"3,	4&qr*#//#.qr2 
y!5 GKMc 
mmCMMO//@ACh'A@ @( (TB BBC C	C 	C6	4 	4_@ @s   A>X01W03X0FX0+W=D.X06X/X
	4X<B.X0*X$B#X00W:	5X0=XX0
XXX!X0$X-	)X00X9znn.embedding_lookup)v1c                 &    	 t        | ||||d      S )a
  Looks up embeddings for the given `ids` from a list of tensors.

  This function is used to perform parallel lookups on the list of tensors in
  `params`.  It is a generalization of `tf.gather`, where `params` is
  interpreted as a partitioning of a large embedding tensor.  `params` may be
  a `PartitionedVariable` as returned by using `tf.compat.v1.get_variable()`
  with a partitioner.

  If `len(params) > 1`, each element `id` of `ids` is partitioned between
  the elements of `params` according to the `partition_strategy`.
  In all strategies, if the id space does not evenly divide the number of
  partitions, each of the first `(max_id + 1) % len(params)` partitions will
  be assigned one more id.

  If `partition_strategy` is `"mod"`, we assign each id to partition
  `p = id % len(params)`. For instance,
  13 ids are split across 5 partitions as:
  `[[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8], [4, 9]]`

  If `partition_strategy` is `"div"`, we assign ids to partitions in a
  contiguous manner. In this case, 13 ids are split across 5 partitions as:
  `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`

  If the input ids are ragged tensors, partition variables are not supported and
  the partition strategy and the max_norm are ignored.
  The results of the lookup are concatenated into a dense
  tensor. The returned tensor has shape `shape(ids) + shape(params)[1:]`.

  Args:
    params: A single tensor representing the complete embedding tensor, or a
      list of P tensors all of same shape except for the first dimension,
      representing sharded embedding tensors.  Alternatively, a
      `PartitionedVariable`, created by partitioning along dimension 0. Each
      element must be appropriately sized for the given `partition_strategy`.
    ids: A `Tensor` or a 'RaggedTensor' with type `int32` or `int64` containing
      the ids to be looked up in `params`.
      Caution: Out-of-bounds indices will result in undefined behavior, which
        will differ between devices and backends.
    partition_strategy: A string specifying the partitioning strategy, relevant
      if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default
      is `"mod"`.
    name: A name for the operation (optional).
    validate_indices: DEPRECATED. If this operation is assigned to CPU, values
      in `indices` are always validated to be within range.  If assigned to GPU,
      out-of-bound indices result in safe but unspecified behavior, which may
      include raising an error.
    max_norm: If not `None`, each embedding is clipped if its l2-norm is larger
      than this value.

  Returns:
    A `Tensor` or a 'RaggedTensor', depending on the input, with the same type
    as the tensors in `params`.

  Raises:
    ValueError: If `params` is empty.
  N)r%   r&   re   r?   r'   rf   )r{   )r%   r&   re   r?   validate_indicesr'   s         r   r7   r7     s*    DB 
)
+
 r    c                 "    t        | |d||      S )ax  Looks up embeddings for the given `ids` from a list of tensors.

  This function is used to perform parallel lookups on the list of tensors in
  `params`.  It is a generalization of `tf.gather`, where `params` is
  interpreted as a partitioning of a large embedding tensor.

  If `len(params) > 1`, each element `id` of `ids` is partitioned between the
  elements of `params` according to the "div" partition strategy, which means we
  assign ids to partitions in a contiguous manner. For instance, 13 ids are
  split across 5 partitions as:
  `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`.

  If the id space does not evenly divide the number of partitions, each of the
  first `(max_id + 1) % len(params)` partitions will be assigned one more id.

  The results of the lookup are concatenated into a dense
  tensor. The returned tensor has shape `shape(ids) + shape(params)[1:]`.

  Args:
    params: A single tensor representing the complete embedding tensor, or a
      list of tensors all of same shape except for the first dimension,
      representing sharded embedding tensors following "div" partition strategy.
    ids: A `Tensor` with type `int32` or `int64` containing the ids to be looked
      up in `params`.
    max_norm: If not `None`, each embedding is clipped if its l2-norm is larger
      than this value.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with the same type as the tensors in `params`.

    For instance, if `params` is a 5x2 matrix:

    ```python
    [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
    ```

    or a list of matrices:

    ```python
    params[0]: [[1, 2], [3, 4]]
    params[1]: [[5, 6], [7, 8]]
    params[2]: [[9, 10]]
    ```

    and `ids` is:

    ```python
    [0, 3, 4]
    ```

    The output will be a 3x2 matrix:

    ```python
    [[1, 2], [7, 8], [9, 10]]
    ```

  Raises:
    ValueError: If `params` is empty.
  rD   )r'   )r7   )r%   r&   r'   r?   s       r   embedding_lookup_v2r   w  s    ~ 
&#udX	FFr    znn.embedding_lookup_sparsec                    |d}|dvrt        d|       t        | t        j                        rt	        |       } t        | t              s| g} t        |t
        j                        st        dt        |             |du }|st        |t
        j                        st        dt        |             |j                  j                         j                  |j                  j                                |j                  j                         j                  |j                  j                                |j                  j                         j                  |j                  j                                t        j                  |d| |gz         5 }|j                  dddf   }	|j                  }
t!        | |	||
||||||
      cddd       S # 1 sw Y   yxY w)	aZ  Looks up embeddings for the given ids and weights from a list of tensors.

  This op assumes that there is at least one id for each row in the dense tensor
  represented by sp_ids (i.e. there are no rows with empty features), and that
  all the indices of sp_ids are in canonical row-major order.

  `sp_ids` and `sp_weights` (if not None) are `SparseTensor`s or `RaggedTensor`s
  with rank of 2. For `SpareTensor`s with left-aligned non-zero entries which
  can be described as `RaggedTensor`s, use of `RaggedTensor`s can yield higher
  performance.

  It also assumes that all id values lie in the range [0, p0), where p0
  is the sum of the size of params along dimension 0.

  Args:
    params: A single tensor representing the complete embedding tensor, or a
      list tensors all of same shape except for the first dimension,
      representing sharded embedding tensors. Alternatively, a
      `PartitionedVariable`, created by partitioning along dimension 0. Each
      element must be appropriately sized for the given `partition_strategy`.
    sp_ids: N x M `SparseTensor` of int64 ids where N is typically batch size
      and M is arbitrary or a `RaggedTensor` with rank 2.
    sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as
      `sparse_ids`, containing float / double weights corresponding to
      `sparse_ids`, or `None` if all weights are assumed to be 1.0.
    partition_strategy: A string specifying the partitioning strategy, relevant
      if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default
      is `"mod"`. See `tf.nn.embedding_lookup` for more details.
    name: Optional name for the op.
    combiner: A string specifying the reduction op. Currently "mean", "sqrtn"
      and "sum" are supported. "sum" computes the weighted sum of the embedding
      results for each row. "mean" is the weighted sum divided by the total
      weight. "sqrtn" is the weighted sum divided by the square root of the sum
      of the squares of the weights. Defaults to `mean`.
    max_norm: If not `None`, each embedding is clipped if its l2-norm is larger
      than this value, before combining.
    allow_fast_lookup: An optional boolean specifying whether to allow
      simplified embedding lookups when `params` is a single tensor and
      `max_norm` is `None`. Setting this flag to `True` during training can
      cause the use of dense gradients with increased memory footprint.

  Returns:
    A dense tensor representing the combined embeddings for the
    sparse ids. For each row in the dense tensor represented by `sp_ids`, the op
    looks up the embeddings for all ids in that row, multiplies them by the
    corresponding weight, and combines these embeddings as specified.

    In other words, if

      `shape(combined params) = [p0, p1, ..., pm]`

    and

      `shape(sp_ids) = shape(sp_weights) = [d0, d1]`

    then

      `shape(output) = [d0, p1, ..., pm]`.

    For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are

      ```python
      [0, 0]: id 1, weight 2.0
      [0, 1]: id 3, weight 0.5
      [1, 0]: id 0, weight 1.0
      [2, 3]: id 1, weight 3.0
      ```

    with `combiner`="mean", then the output will be a 3x20 matrix where

      ```python
      output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
      output[1, :] = (params[0, :] * 1.0) / 1.0
      output[2, :] = (params[1, :] * 3.0) / 3.0
      ```

  Raises:
    TypeError: If `sp_ids` is not a `SparseTensor` or `RaggedTensor`, or if
    `sp_weights` is neither `None` nor of the same type as `sp_ids`.
    ValueError: If `combiner` is not one of {"mean", "sqrtn", "sum"}.
  Nmean)r   sqrtnsumz6combiner must be one of 'mean', 'sqrtn' or 'sum', got z!sp_ids must be SparseTensor, got z3sp_weights must be either None or SparseTensor,got embedding_lookup_sparser   )rE   r9   r   rG   r#   r	   SparseTensor	TypeErrortypevaluesr   assert_is_compatible_withindicesdense_shaper   rH   embedding_lookup_sparse_impl)r%   sp_ids
sp_weightsre   r?   combinerr'   allow_fast_lookupignore_weightssegment_idsr&   s              r   r   r     s   z H--

@
KM M	556&\F	FD	!XF	FM66	7
7V~F
GG%.	j-"<"<= !*-.0 1 1
MM77##%'
NN88$$&(
  "<<((*,
 ~~d5x') ,0..A&K
--C'  s   3GGc           
      &    t        | ||d||||      S )a&  Looks up embeddings for the given ids and weights from a list of tensors.

  `params` is a dense tensor or a list of dense tensors, and `sp_ids` is a 2D
  `tf.SparseTensor` or `tf.RaggedTensor` indicating the indices of `params` to
  gather.

  This op is best described with an example. Suppose `params` is an embedding
  table of size `(4, 2)` and `sp_ids` has 3 rows. Since `sp_ids` is sparse or
  ragged, not every row has the same number of elements. The output has shape
  (3, 2). Each row of `sp_ids` is a list of indices, where each index selects a
  row of `params`. For a given row of `sp_ids`, the rows of `params` are
  gathered based on the indices in `sp_ids`, then combined by taking their sum
  or mean.

  >>> params = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.float32)
  >>> sp_ids = tf.SparseTensor(indices=[[0, 0], [0, 1], [1, 0], [2, 0]],
  ...                          values=[0, 1, 3, 2], dense_shape=(3, 2))
  >>> tf.nn.embedding_lookup_sparse(params, sp_ids, sp_weights=None,
  ...                               combiner='sum').numpy()
  array([[4., 6.], [7., 8.], [5., 6.]], dtype=float32)

  In this example, `sp_ids` has 3 rows, so the output has 3 rows. Row 0 of
  `sp_ids` has values 0 and 1, so it selects rows 0 and 1 from `params`, which
  are `[1, 2]` and `[3, 4]`. The rows are summed since `combiner='sum'`,
  resulting in the output row of `[4, 6]`.

  Since row 1 and 2 of `sp_ids` only have one value each, they simply select the
  corresponding row from `params` as the output row. Row 1 has value `3` so
  it selects the `params` elements `[7, 8]` and row 2 has the value 2 so it
  selects the `params` elements `[5, 6]`.

  If `sparse_weights` is specified, it must have the same shape as `sp_ids`.
  `sparse_weights` is used to assign a weight to each slice of `params`. For
  example:

  >>> params = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.float32)
  >>> sp_ids = tf.SparseTensor(indices=[[0, 0], [0, 1], [1, 0], [2, 0]],
  ...                          values=[0, 1, 3, 2], dense_shape=(3, 2))
  >>> sparse_weights = tf.SparseTensor(indices=[[0, 0], [0, 1], [1, 0], [2, 0]],
  ...                                  values=[0.1, 1.0, 0.5, 2.0],
  ...                                  dense_shape=(3, 2))
  >>> tf.nn.embedding_lookup_sparse(params, sp_ids, sp_weights=sparse_weights,
  ...                               combiner='sum').numpy()
  array([[3.1, 4.2], [3.5, 4.], [10., 12.]], dtype=float32)

  In general, `params` can have shape `(p0, ..., pn)` and `sp_ids` can have `M`
  rows, where each row can have any number of elements. The output has shape
  `(M, p1, ..., pn)`. Each slice of the output `output[i, ...]` is obtained as
  follows: The `combiner` argument is used to combine the values
  `params[sp_ids[i, j], ...] * sparse_weights[i, j]` for each `j` in `range(0,
  len(sp_ids[i]))`, e.g. by taking the sum or mean of the values.

  This op assumes that there is at least one id for each row in the dense tensor
  represented by sp_ids (i.e. there are no rows with empty features), and that
  all the indices of sp_ids are in canonical row-major order.

  `sp_ids` and `sp_weights` (if not None) are `SparseTensor`s or `RaggedTensor`s
  with rank of 2. For `SpareTensor`s with left-aligned non-zero entries which
  can be described as `RaggedTensor`s, use of `RaggedTensor`s can yield higher
  performance.

  This op assumes that all id values lie in the range [0, p0), where p0
  is `params.shape[0]`. If you want a version of this op that prunes id values
  less than 0, see `tf.nn.safe_embedding_lookup_sparse`

  If `len(params) > 1`, each element of `sp_ids` is partitioned between the
  elements of `params` according to the "div" partition strategy, which means we
  assign ids to partitions in a contiguous manner. For instance, 13 ids are
  split across 5 partitions as:
  `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`.

  If the id space does not evenly divide the number of partitions, each of the
  first `(max_id + 1) % len(params)` partitions will be assigned one more id.

  Args:
    params: A single tensor representing the complete embedding tensor, or a
      list of tensors all of same shape except for the first dimension,
      representing sharded embedding tensors following "div" partition strategy.
    sp_ids: N x M `SparseTensor` of int64 ids where N is typically batch size
      and M is arbitrary or a `RaggedTensor` with rank 2.
    sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as
      `sparse_ids`, containing float / double weights corresponding to
      `sparse_ids`, or `None` if all weights are assumed to be 1.0.
    combiner: A string specifying the reduction op. Currently "mean", "sqrtn"
      and "sum" are supported. "sum" computes the weighted sum of the embedding
      results for each row. "mean" is the weighted sum divided by the total
      weight. "sqrtn" is the weighted sum divided by the square root of the sum
      of the squares of the weights. Defaults to `mean`.
    max_norm: If not `None`, each embedding is clipped if its l2-norm is larger
      than this value, before combining.
    name: Optional name for the op.
    allow_fast_lookup: An optional boolean specifying whether to allow
      simplified embedding lookups when `params` is a single tensor and
      `max_norm` is `None`. Setting this flag to `True` during training can
      cause the use of dense gradients with increased memory footprint.

  Returns:
    A dense tensor representing the combined embeddings for the
    sparse ids. For each row in the dense tensor represented by `sp_ids`, the op
    looks up the embeddings for all ids in that row, multiplies them by the
    corresponding weight, and combines these embeddings as specified.

    In other words, if

      `shape(combined params) = [p0, p1, ..., pm]`

    and

      `shape(sp_ids) = shape(sp_weights) = [d0, d1]`

    then

      `shape(output) = [d0, p1, ..., pm]`.

    For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are

      ```python
      [0, 0]: id 1, weight 2.0
      [0, 1]: id 3, weight 0.5
      [1, 0]: id 0, weight 1.0
      [2, 3]: id 1, weight 3.0
      ```

    with `combiner`="mean", then the output will be a 3x20 matrix where

      ```python
      output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
      output[1, :] = (params[0, :] * 1.0) / 1.0
      output[2, :] = (params[1, :] * 3.0) / 3.0
      ```

  Raises:
    TypeError: If `sp_ids` is not a `SparseTensor`, or if `sp_weights` is
      neither `None` nor `SparseTensor`.
    ValueError: If `combiner` is not one of {"mean", "sqrtn", "sum"}.
  rD   )r   )r%   r   r   r   r'   r?   r   s          r   embedding_lookup_sparse_v2r   C  s*    f 
!
	
 	r    znn.safe_embedding_lookup_sparsec                 *    t        | |||||d||	      S )a]  Lookup embedding results, accounting for invalid IDs and empty features.

  The partitioned embedding in `embedding_weights` must all be the same shape
  except for the first dimension. The first dimension is allowed to vary as the
  vocabulary size is not necessarily a multiple of num of shards.

  This is similar to `tf.nn.embedding_lookup_sparse`, except invalid IDs (< 0)
  are pruned from input IDs and weights, as well as any IDs with non-positive
  weight. For an entry with no features, the embedding vector for `default_id`
  is returned, or the 0-vector if `default_id` is not supplied. See
  `tf.nn.embedding_lookup_sparse` for more information on how sparse embedding
  lookups work in general.

  The ids and weights may be multi-dimensional `SparseTensor`s or
  `RaggedTensor`s with rank of 2. For `SpareTensor`s with left-aligned non-zero
  entries which can be described as `RaggedTensor`s, use of `RaggedTensor`s can
  yield higher performance.

  If `len(embedding_weights) > 1`, each element `id` of `ids` is partitioned
  between the elements of `embedding_weights` according to the "div" partition
  strategy, which means we assign ids to partitions in a contiguous manner. For
  instance, 13 ids are split across 5 partitions as:
  `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`.

  If the id space does not evenly divide the number of partitions, each of the
  first `(max_id + 1) % len(embedding_weights)` partitions will be assigned one
  more id.

  Args:
    embedding_weights: A single tensor representing the complete embedding
      tensor, or a list of tensors all of same shape except for the first
      dimension, representing sharded embedding tensors following "div"
      partition strategy.
    sparse_ids: `SparseTensor` of shape `[d_0, d_1, ..., d_n]` containing the
      ids, where `d_0` is typically batch size, or a `RaggedTensor` with rank 2.
    sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as
      `sparse_ids`, containing float weights corresponding to `sparse_ids`, or
      `None` if all weights are assumed to be 1.0.
    combiner: A string specifying how to combine embedding results for each
      entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the
      default.
    default_id: The id to use for an entry with no features. Defaults to
      0-vector.
    max_norm: If not `None`, all embeddings are l2-normalized to max_norm before
      combining.
    name: A name for this operation (optional).
    allow_fast_lookup: An optional boolean specifying whether to allow
      simplified embedding lookups when `params` is a single tensor and
      `max_norm` is `None`. Setting this flag to `True` during training can
      cause the use of dense gradients with increased memory footprint.

  Returns:
    A dense tensor representing the combined embeddings for the
    sparse ids. For each row in the dense tensor represented by `sparse_ids`,
    the op looks up the embeddings for all ids in that row, multiplies them by
    the corresponding weight, and combines these embeddings as specified.

    In other words, if

      `shape(combined embedding_weights) = [p0, p1, ..., pm]`

    and

      `shape(sparse_ids) = shape(sparse_weights) = [d0, d1, ..., dn]`

    then

      `shape(output) = [d0, d1, ... dn-1, p1, ..., pm]`.

    For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are

      ```python
      [0, 0]: id 1, weight 2.0
      [0, 1]: id 3, weight 0.5
      [1, 0]: id -1, weight 1.0
      [2, 3]: id 1, weight 3.0
      ```

    `default_id` is 0.

    with `combiner`="mean", then the output will be a 3x20 matrix where

      ```python
      output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
      output[1, :] = (params[0, :] * 1.0) / 1.0
      output[2, :] = (params[1, :] * 3.0) / 3.0
      ```

  Raises:
    ValueError: if `embedding_weights` is empty.
  rD   )sparse_weightsr   
default_idr?   re   r'   r   )safe_embedding_lookup_sparse)embedding_weights
sparse_idsr   r   r   r'   r?   r   s           r   safe_embedding_lookup_sparse_v2r     s-    N 
&#)

 
r    c	                    | t        d|  d      t        | t        j                        rt	        |       } t        | t              s| g} t        |       dk  rt        d|  d      ||j                  nd}	| D 
cg c]@  }
t        j                  |
      r|	d|
j                  fv r|
nt        j                  |
|	      B } }
t        j                  |d| ||gz         5 }|j                  }t        j                  |j                  j                         d         }|t!        j"                  |      n|}t%        j&                  |t)        j*                  t!        j,                  |dg|dz
  g            t!        j.                  ||dz
        g      }|5t1        j2                  |j4                  |j6                  |j                        }t9        ||      \  }}|dk7  rt;        ||      \  }}t%        j<                  ||xs d      \  }}|t%        j<                  |d	      \  }}t?        | |||||dn|||
      }|t!        j@                  t!        jB                  |ddg      tE        jF                  dt!        jH                  |      d   g            }t!        jJ                  |t!        jL                  |      ||      }t!        jB                  |t!        jN                  t!        j,                  t)        jP                  |tR        jT                        dg|dz
  g      t!        j,                  t!        jH                  |      dgdg      gd            }|jW                  t        jX                  t        jZ                  |      dz
  j\                        j_                  |j                         dd              |cddd       S c c}
w # 1 sw Y   yxY w)aM  Lookup embedding results, accounting for invalid IDs and empty features.

  The partitioned embedding in `embedding_weights` must all be the same shape
  except for the first dimension. The first dimension is allowed to vary as the
  vocabulary size is not necessarily a multiple of `P`.  `embedding_weights`
  may be a `PartitionedVariable` as returned by using
  `tf.compat.v1.get_variable()` with a
  partitioner.

  Invalid IDs (< 0) are pruned from input IDs and weights, as well as any IDs
  with non-positive weight. For an entry with no features, the embedding vector
  for `default_id` is returned, or the 0-vector if `default_id` is not supplied.

  The ids and weights may be multi-dimensional `SparseTensor`s or
  `RaggedTensor`s with rank of 2. For `SpareTensor`s with left-aligned non-zero
  entries which can be described as `RaggedTensor`s, use of `RaggedTensor`s can
  yield higher performance. Embeddings are always aggregated along the last
  dimension.

  Args:
    embedding_weights: A single tensor representing the complete embedding
      tensor, or a list tensors all of same shape except for the first
      dimension, representing sharded embedding tensors. Alternatively, a
      `PartitionedVariable`, created by partitioning along dimension 0. Each
      element must be appropriately sized for the given `partition_strategy`.
    sparse_ids: `SparseTensor` of shape `[d_0, d_1, ..., d_n]` containing the
      ids, where `d_0` is typically batch size, or a `RaggedTensor` with rank 2.
    sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as
      `sparse_ids`, containing float weights corresponding to `sparse_ids`, or
      `None` if all weights are assumed to be 1.0.
    combiner: A string specifying how to combine embedding results for each
      entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the
      default.
    default_id: The id to use for an entry with no features.
    name: A name for this operation (optional).
    partition_strategy: A string specifying the partitioning strategy. Currently
      `"div"` and `"mod"` are supported. Default is `"div"`.
    max_norm: If not `None`, all embeddings are l2-normalized to max_norm before
      combining.
    allow_fast_lookup: An optional boolean specifying whether to allow
      simplified embedding lookups when `params` is a single tensor and
      `max_norm` is `None`. Setting this flag to `True` during training can
      cause the use of dense gradients with increased memory footprint.

  Returns:
    A dense tensor representing the combined embeddings for the
    sparse ids. For each row in the dense tensor represented by `sp_ids`, the op
    looks up the embeddings for all ids in that row, multiplies them by the
    corresponding weight, and combines these embeddings as specified.

    In other words, if

      `shape(combined embedding_weights) = [p0, p1, ..., pm]`

    and

      `shape(sparse_ids) = shape(sparse_weights) = [d0, d1, ..., dn]`

    then

      `shape(output) = [d0, d1, ... dn-1, p1, ..., pm]`.

    For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are

      ```python
      [0, 0]: id 1, weight 2.0
      [0, 1]: id 3, weight 0.5
      [1, 0]: id -1, weight 1.0
      [2, 3]: id 1, weight 3.0
      ```

    `default_id` is 0.

    with `combiner`="mean", then the output will be a 3x20 matrix where

      ```python
      output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
      output[1, :] = (params[0, :] * 1.0) / 1.0
      output[2, :] = (params[1, :] * 3.0) / 3.0
      ```

  Raises:
    ValueError: if `embedding_weights` is empty.
  NzMissing embedding_weights .r@   rU   r7   r   r   g      ?)r   re   r?   r'   r   rA   r>   )0rE   r9   r   rG   r#   rI   rU   r   is_resource_variabler   r   rH   r   r
   rR   r   r   rO   r   sparse_reshaper   reduce_prodslicerL   r	   r   r   r   _prune_invalid_ids_prune_invalid_weightssparse_fill_empty_rowsr   tilerN   r   rZ   rW   r\   
zeros_likerb   rY   r   rP   rc   unknown_shaperQ   rS   rd   )r   r   r   r   r   r?   re   r'   r   rU   wscopeoriginal_shapeoriginal_rank_dimoriginal_rankis_row_empty_rh   final_results                      r   r   r   V  s   B 
12C1DAF
GG!9#@#@A./	%t	,*+	a
12C1DAF
GG"0"<.

$%
 !	  "66q9$(   %01  ~~d.0A!>213 4 B7<++N$44((*1-/ $ 	~&*;  **:OONQC-!2C1DE	G):;8 J
 !$11*2D2D2@2G2G2<2H2HJn
 "4J!OJ5#9
n$& j.  *@@JO! %J!$;;NCPna$-'TU+	F  ^^


L2q'
2


IOOF$;A$> ?
@Bl 
	,,V4f5Jf $$OOnfll;aS"#% OOIOOF3aS2$?	

 	L ""##$56:AA	

+f&&(,
-
 EB BB Bs   ;AN?KOOc
                 
   d}
t        j                  |d      }t        |       dk(  rHt        | d   t        j
                  t        j                  f      st        j                  | d   d      g} t        |       dk(  rt        | d   t        j                        so| d   j                  |j                  k(  rS|Q|s|rMt        j                  ddd	      r6|}| d   }t        |t        j                        r|j                         }|s*d
}
n't        j                  |      \  }}t!        | |||      }|s|j"                  t$        j&                  k7  r$t)        j*                  |t$        j&                        }|j,                  }t        j.                  ||      }|j"                  }|j"                  t$        j0                  t$        j2                  fv r$t)        j*                  |t$        j4                        }|j"                  |j"                  k7  r t)        j*                  ||j"                        }t        j6                  t        j8                  |      dz
  d      }t        j:                  |      }t        j<                  ||j"                        }t        j>                  ||gd      }|jA                         }t        jB                  ||      }|jA                         jD                  R|jG                  |jI                  tK        |jA                         jD                  dz
        D cg c]  }d c}             ||z  }|dk(  rt)        jL                  |||	      }n|dk(  rEt)        jL                  ||      }t)        jL                  ||      }t)        jN                  |||	      }n||dk(  rpt)        jL                  ||      }t)        jP                  |d      }t)        jL                  ||      }t)        jR                  |      }t)        jN                  |||	      }nJ d       |j"                  |k7  rt)        j*                  ||      }|S |j"                  t$        j&                  t$        jT                  fvr$t)        j*                  |t$        j&                        }|J |dk(  rt)        jV                  ||||	|
      }|S |dk(  rt)        jX                  ||||	|
      }|S |dk(  rt)        jZ                  ||||	|
      }|S J d       c c}w )z/Implementation of sparse embedding aggregation.Fr   r>   r@   r   r%   i  	      T)re   r'   r   r   r   r      zUnrecognized combiner)r?   sparse_gradient).r   r   rI   r9   r   Tensorr   CompositeTensordevicer   forward_compatibler   r:   read_value_no_copyr   uniquer7   rU   r   rP   r   rY   r   rL   float16bfloat16float32expand_dimsr   rW   onesrb   r   rN   r   rc   rd   r$   segment_sum
div_no_nanpowsqrtint64sparse_segment_sumsparse_segment_meansparse_segment_sqrt_n)r%   r   r   r&   r   r   r'   r   re   r?   need_sparse_segment_gradientidx
embeddingsweightsoriginal_dtype
ones_shapeweights_shaper   bcast_weights_shapeorig_weights_shaper   
weight_sumweights_squaredweight_sum_sqrts                           r   r   r     s{    "'%%kF+[AjQi$++/??@ ##F1IH=>F 
&kQ$4$D$DE
)

k00
0


!:!:4B!G CJ*3HHI 002j%)"$HC!(:XJ 
FLL(MM+v||<kG!!*c2J%%NFNNFOO<< ==V^^<j}}
(((gz'7'78g &&y~~j'AA'EqIJOOG,M>>*M,?,?@D#**M4+@!D **,)<=G ##/

(
(
 4 4 6 < <q @ABQqB 'J5''
KdKj	V	''
K@j''=j&&z:DIj	W	''
K@j Wa0o''Ej j1o&&z?Nj+++U>)==^<j@ 
= v|| <<MM+v||<k??5..


6j4 
' 
V	//


6j$ 
 
W	11


6j 
 ,++Ug Cs   $	Tc                 0   t        j                  | j                  d      }|Ct        j                  |t	        j
                  |j                  t        j                              }t        j                  | |      } |t        j                  ||      }| |fS )z7Prune invalid IDs (< 0) from the input ids and weights.r   r   )
r   greater_equalr   logical_andr   	ones_liker   boolr   sparse_retain)r   r   is_id_valids      r   r   r     s    &&z'8'8!<+&&N11EGK ''
K@*--nkJN	^	##r    c                     |Lt        j                  |j                  d      }t        j                  | |      } t        j                  ||      }| |fS )z;Prune invalid weights (< 0) from the input ids and weights.r   )r   greaterr   r   r   )r   r   is_weights_valids      r   r   r     sR    ''(=(=qA))*6FGJ--n>NON	^	##r    )rC   NNN)rC   NTN)NN)rC   NNNF)NNNF)Nr   NNNF)Nr   NNrD   NF)(__doc__tensorflow.python.compatr   tensorflow.python.frameworkr   r   r   r   r   r	   r
   tensorflow.python.opsr   r   r   r   r   r   r   r   r   tensorflow.python.typesr   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   r,   r5   r{   add_dispatch_supportr7   r   r   r   r   r   r   r   r    r    r   <module>r      s   ! + 8 3 . 6 + 5 4 + 1 * 0 / * 7 , + ( + 6(9V$ 8=)--115k\ $%&	 	g  'gT  R(	=G  )=G@ +,-	
 	E  .EP 'B/	
 	Z  0Zz ,4	 	o  5od 012	 	r  3rj@F
$$r    