o
    "j                     @   s~  d Z ddlZddlZddlZddlmZ ddlmZmZ ddl	m
Z
mZmZ ddlmZmZ ddlmZ ddlmZ g Z				
		d<ddZ	d=ddZ							d>ddZ						d?ddZd@ddZdAddZdAddZdBd!d"Z						 	 dCd#d$Z	%	dDd&d'Zd@d(d)ZdEd+d,Z d@d-d.Z!	/dFd0d1Z"	2	3						dGd4d5Z#	dHd6d7Z$		dId8d9Z%		dId:d;Z&dS )Jz5
incubate layers just related to the neural network.
    N)_legacy_C_ops)coreunique_name)check_dtype
check_typecheck_variable_and_dtype)Variableconvert_np_dtype_to_dtype_)LayerHelper)	ParamAttrFsumfloat32c           
      C   sz   t di t }|j|j||dd}||}	|du rdn|dkr#|n|d | }|jd| |dd|	i|||d	d
 |	S )a  
    **Embedding Sequence pool**

    This layer is the fusion of lookup table and sequence_pool.

    Args:
        input (Tensor): Input is a Tensor<int64> , which contains the IDs' information.
            The value of the input IDs should satisfy :math:`0<= id < size[0]`.
        size (tuple|list): The shape of the lookup_table parameter. It should
            have two elements which indicate the size of the dictionary of
            embedding and the size of each embedding vector respectively.
        is_sparse (bool, optional): The flag indicating whether to use sparse update.
            Default: False.
        padding_idx (int|long|None, optional): It will output all-zero padding data whenever
            lookup encounters :math:`padding\_idx` in Ids. If set :attr:`None`, it makes
            no effect to output. If :math:`padding\_idx < 0`, the :math:`padding\_idx`
            will automatically be converted to :math:`size[0] + padding\_idx` to use.
            Default: None.
        combiner (str, optional): The pooling type of sequence_pool, and only support `sum`.
            Default: sum.
        param_attr (ParamAttr, optional): Parameters for this layer. Default: None.
        dtype (np.dtype|core.VarDesc.VarType|str, optional): The dtype refers to the data type of output
            tensor. It can be float32, float_16, int etc. Default: float32.

    Returns:
        The Tensor of sequence pooling.

    Examples:
        .. code-block:: python

            >>> import numpy as np
            >>> import paddle
            >>> paddle.enable_static()

            >>> dict_size = 20
            >>> data_t = paddle.static.data(
            ...     name='word', shape=[-1, 1], dtype='int64', lod_level=1)
            >>> padding_idx = np.random.randint(1, 10)
            >>> out = paddle.incubate.layers.fused_embedding_seq_pool(
            ...     input=data_t,
            ...     size=[dict_size, 32],
            ...     param_attr='w',
            ...     padding_idx=padding_idx,
            ...     is_sparse=False)

    fused_embedding_seq_poolFattrshapedtypeZis_biasNr   IdsWOut)	is_sparsecombinerpadding_idxtypeinputsoutputsattrs)r   )r
   localscreate_parameter
param_attr"create_variable_for_type_inference	append_op)
inputsizer   r   r   r"   r   helperwout r*   Z/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/incubate/layers/nn.pyr   %   s*   7



r           T   c           	   	      s   t di t | dkrtd| t| dtd t| tr-| D ]
}t|ddgd q"  	 } fddt
t|D }jd||dd	|i| |||d
d |S )a8  
    :api_attr: Static Graph

    This OP is the fusion of sequence_pool and continuous_value_model op.

    **Note:** The Op only receives List of LoDTensor as input, only support SUM pooling now.

    Args:
        input(Tensor): Input is List of LoDTensor.
        pool_type(str): pooling type, only support SUM pooling now.
        cvm(Tensor): cvm Tensor.
        pad_value(float, optional): padding value of sequence pool. Default: 0.0.
        use_cvm(bool, optional): use cvm or not. Default: True.
        cvm_offset(int, optional): cvm offset. Default: 2, which means cvm contains show, click.

    Returns:
        Tensor : The tensor storing sequence pool and cvm of input.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()

            >>> data = paddle.static.data(name='x', shape=[-1, 1], dtype='int64', lod_level=1)
            >>> data2 = paddle.static.data(name='y', shape=[-1, 1], dtype='int64', lod_level=1)
            >>> inputs = [data, data2]
            >>> embs = paddle.incubate.layers.nn._pull_box_sparse(input=inputs, size=11, is_distributed=True, is_sparse=True)

            >>> label = paddle.static.data(name="label", shape=[-1, 1], dtype="int64", lod_level=1)
            >>> ones = paddle.static.data(name="ones", shape=[-1, 1], dtype="int64", lod_level=1)
            >>> show_clk = paddle.cast(paddle.concat([ones, label], axis=1), dtype='float32')
            >>> show_clk.stop_gradient = True

            >>> cvms = paddle.incubate.layers.fused_seqpool_cvm(embs, 'sum', show_clk)


    fused_seqpool_cvmZSUMzBfused_seqpool_cvm only support SUM pooling now, and your type is: r%   r   c                       g | ]}  qS r*   r#   .0ir   r'   r*   r+   
<listcomp>       z%fused_seqpool_cvm.<locals>.<listcomp>)XZCVMr   )Zpooltype	pad_valueuse_cvm
cvm_offsetr   N)r.   )r
   r    upper
ValueErrorr   list
isinstancer   input_dtypemultiple_inputrangelenr$   )	r%   Z	pool_typeZcvmr8   r9   r:   _inputr   outsr*   r4   r+   r.   u   s:   )


r.   333333?      ?c                 C   st   t d
i t }|j| jd}|jdd}|jd| |d|||||||d||dd d|_d|_|	r8||fS |S )a  
    **Multiclass NMS2**

    This operator is to do multi-class non maximum suppression (NMS) on
    boxes and scores.
    In the NMS step, this operator greedily selects a subset of detection bounding
    boxes that have high scores larger than score_threshold, if providing this
    threshold, then selects the largest nms_top_k confidences scores if nms_top_k
    is larger than -1. Then this operator prunes away boxes that have high IOU
    (intersection over union) overlap with already selected boxes by adaptive
    threshold NMS based on parameters of nms_threshold and nms_eta.
    After NMS step, at most keep_top_k number of total bboxes are to be kept
    per image if keep_top_k is larger than -1.

    Args:
        bboxes (Tensor): Two types of bboxes are supported:
                           1. (Tensor) A 3-D Tensor with shape
                           [N, M, 4 or 8 16 24 32] represents the
                           predicted locations of M bounding bboxes,
                           N is the batch size. Each bounding box has four
                           coordinate values and the layout is
                           [xmin, ymin, xmax, ymax], when box size equals to 4.
                           2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]
                           M is the number of bounding boxes, C is the
                           class number.
        scores (Tensor): Two types of scores are supported:
                           1. (Tensor) A 3-D Tensor with shape [N, C, M]
                           represents the predicted confidence predictions.
                           N is the batch size, C is the class number, M is
                           number of bounding boxes. For each category there
                           are total M scores which corresponding M bounding
                           boxes. Please note, M is equal to the 2nd dimension
                           of BBoxes.
                           2. (LoDTensor) A 2-D LoDTensor with shape [M, C].
                           M is the number of bbox, C is the class number.
                           In this case, input BBoxes should be the second
                           case with shape [M, C, 4].
        score_threshold (float): Threshold to filter out bounding boxes with
                                 low confidence score. If not provided,
                                 consider all boxes.
        nms_top_k (int): Maximum number of detections to be kept according to
                         the confidences after the filtering detections based
                         on score_threshold.
        keep_top_k (int): Number of total bboxes to be kept per image after NMS
                          step. -1 means keeping all bboxes after NMS step.
        nms_threshold (float, optional): The threshold to be used in NMS. Default: 0.3.
        normalized (bool, optional): Whether detections are normalized. Default: True.
        nms_eta (float, optional): The threshold to be used in NMS. Default: 1.0.
        background_label (int, optional): The index of background label, the background
                                label will be ignored. If set to -1, then all
                                categories will be considered. Default: 0.
        return_index(bool, optional): Whether return selected index. Default: False.
        name(str, optional): Name of the multiclass nms op. Default: None.

    Returns:
        A tuple with two dimensions of the tensor: (Out, Index) if return_index is True,
        otherwise, a tuple with one dimension of the tensor(Out) is returned.
        Out: A 2-D LoDTensor with shape [No, 6] represents the detections.
        Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
        or A 2-D LoDTensor with shape [No, 10] represents the detections.
        Each row has 10 values: [label, confidence, x1, y1, x2, y2, x3, y3,
        x4, y4]. No is the total number of detections.
        If all images have not detected results, all elements in LoD will be
        0, and output tensor is empty (None).
        Index: Only return when return_index is True. A 2-D LoDTensor with
        shape [No, 1] represents the selected index which type is Integer.
        The index is the absolute value cross batches. No is the same number
        as Out. If the index is used to gather other attribute such as age,
        one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where
        N is the batch size and M is the number of boxes.


    Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()
            >>> boxes = paddle.static.data(name='bboxes', shape=[-1, 81, 4],
            ...                           dtype='float32', lod_level=1)
            >>> scores = paddle.static.data(name='scores', shape=[-1, 81],
            ...                           dtype='float32', lod_level=1)
            >>> out, index = paddle.incubate.layers.multiclass_nms2(bboxes=boxes,
            ...                                   scores=scores,
            ...                                   background_label=0,
            ...                                   score_threshold=0.5,
            ...                                   nms_top_k=400,
            ...                                   nms_threshold=0.3,
            ...                                   keep_top_k=200,
            ...                                   normalized=False,
            ...                                   return_index=True)
    multiclass_nms2r   int)ZBBoxesZScores)background_labelscore_threshold	nms_top_knms_threshold
keep_top_knms_eta
normalized)r   Indexr   r   r   r   TN)rG   )r
   r    r#   r   r$   stop_gradient)ZbboxesZscoresrK   rL   rN   rM   rP   rO   rJ   Zreturn_indexnamer'   outputindexr*   r*   r+   rG      s*   h	rG   c                  C   sh  t di t }|| dg}|j|||dd}d|_| |d}|dkr7|dg}|j|||dd}d|_||d< |	dkrO|	dg}|j|||dd}d|_||d	< d
}|rt|tsZJ g }|rd||j |rl||j |rt||j |D ]}||vrtd| qvd	|}|
|}|
|}|
|}|jd||||d|||||||||	|
||dd |S )a  
    **Pyramid hash embedding**

    Args:
        input (Tensor): LoDTensor<int32> Tensor contained the IDs' information.
        num_emb (int): The embedding size of output.
        space_len (int): The length of pyramid hash embedding space.
        pyramid_layer (int): The number of pyramid layers. It should be greater than 2.
        rand_len (int): The minimum length of pyramid hash cell.
        drop_out_percent (float): The probability of dropping out the input token randomly.
            It should satisfy: [0., 1.].
        is_training (bool): Whether in training or testing phrase.
        use_filter (bool): If set True, the white filter and black filter should be given by
            :attr:`param_attr_wl` and :attr:`param_attr_bl` .
        white_list_len (int): If set :math:`white_list_len>0` , white filter with shape [white_list_len, 1]
            should be provided by param_attr_wl.
        black_list_len (int): If set :math:`black_list_len>0` , black filter with shape [black_list_len, 1]
            should be provided by param_attr_bl.
        seed (int): The number of random seed.
        lr (float): The learning rate of weight created by :attr:`param_attr` with shape [space_len+rand_len, 1]
            in this layer.
        param_attr (ParamAttr, optional): To specify the weight parameter property. Default: None, which means the
            default weight parameter property is used. See usage for details in :ref:`api_paddle_ParamAttr` .
        param_attr_wl (ParamAttr, optional): Specified parameters of white filter. Default: None.
        param_attr_bl (ParamAttr, optional): Specified parameters of black filter. Default: None.
        distribute_update_vars(list[ParamAttr.name], optional): Decided which params should be updated in distribute training.
            Used in Distribute Transpiler to create a trainer/server program. Default: None.
        name (str, optional): The default value is None.  Normally there is no need for user to set this property.
            For more information, please refer to :ref:`api_guide_Name` . Default: None.
        dtype (str, optional): The data type of output Tensor, float32. Default: float32.

    Returns:
        Tensor: LoDTensor of pyramid hash embedding.
    search_pyramid_hash   Fr   T)r7   r   r   Z	WhiteListZ	BlackList z)Pyramid Hash layer didn't have parameter ,Zpyramid_hash)r   Z
X_Temp_OutZDropPos)num_emb	space_lenpyramid_layerrand_lendrop_out_percentis_training
use_filterwhite_list_lenblack_list_lenseedlrdistribute_update_varsr   N)rW   )r
   r    r!   rS   r>   r=   appendrT   r<   joinr#   r$   ) r%   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   r"   Zparam_attr_wlZparam_attr_blrT   rf   r   r'   Zw_shaper(   Z
input_varsZwl_shapeZ
white_listZbl_shapeZ
black_listZdistribute_update_vars_strZspecial_name_listparamresZdrop_posZ
x_temp_outr*   r*   r+   rW   E  sx   6





rW   c                 C   s   t di t }|j| jd}|jtjd}|du r$|jjdkr$|jj}|du r/tj	dd}i }t
|trE||d< |jtdd	d
d}|jd| |d|||d|d |S )a5  
    This layer shuffle input tensor :attr:`x` . Normally, :attr:`x` is 2-D LoDTensor.

    :attr:`x` is a LoDTensor to be shuffled with shape :math:`[N_1, N_2, ..., N_k, D]` . Note that the last dim of input will not be shuffled.
    :math:`N_1 * N_2 * ... * N_k` numbers of elements with length :math:`D` will be shuffled randomly.

    Examples:

        .. code-block:: text

            Input:
              x.data = [[1, 2], [3, 4], [5, 6], [7, 8]]
              x.dims = [4, 2]

            Attrs:
              seed = 2019

            Output:
              Out.data =[[7, 8], [1, 2], [3, 4], [5, 6]]
              Out.dims = [4, 2]

    Args:
        x (Tensor): The input Tensor. The input Tensor is a N-D LoDTensor with type int, float32 or float64.
        seed (None|int|Tensor, optional): The start up seed. If set, seed will be set as the start up seed of shuffle engine.
            If not set(Default), start up seed of shuffle engine will be generated randomly. Default: None.

    Returns:
        Tensor: The shuffled LoDTensor with the same shape and lod as input.

    Examples:

        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()
            >>> x = paddle.static.data(name="x", shape=[-1, 4])
            >>> out = paddle.incubate.layers.shuffle_batch(x)
    shuffle_batchrH   Nr   i  i  Zstartup_seedZshuffle_batch_seedint64F)rT   r   persistable)r7   ZSeed)r   Z
ShuffleIdxZSeedOutr   )rk   )r
   r    r#   r   nprl   Zmain_programZrandom_seedrandomrandintr>   rI   Zcreate_variabler   generater$   )xrd   r'   r)   Zshuffle_idxZop_attrsr*   r*   r+   rk     s,   '

rk   r   c           	      C   s   t | tstdt|   | g} t| D ]\}}t|dt| d g dd qt|dt	d t|dt	d d| i}||d	}t
di t }|j| d
}|jd|d|gi|d |S )a  
    **Partial Concat**
    This OP concatenates the inputs according to the start index and length. This
    OP exists in incubate layers, which means that it is not shown to the public.
    Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be
    performed along the second dimension.

    .. code-block:: text

        Given:
            x = [[0, 1, 2],
                 [3, 4, 5]]
            y = [[6, 7 ,8],
                 [9, 10, 11]]
            output = partial_concat([x, y], start_index=0, length=2)

        We get:

            output = [[0, 1, 6, 7],
                      [3, 4, 9, 10]]

    Args:
        input(list): List of input Tensors with data type float32, float64, int32,
            int64, complex64, complex128.
        start_index(int32, optional): The start index of each instance for partial concatenation.
            Default is 0.
        length(int32, optional): The length of each instance for partial concatenation. Default is -1.
            Negative values for all elements after start_index.

    Returns:
        Tensor: A Tensor with the same data type as input's.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> x = paddle.randn(name="x", shape=[1,3], dtype="float32")
            >>> y = paddle.randn(name="y", shape=[1,3], dtype="float32")
            >>> concat = paddle.incubate.layers.partial_concat(
            ...     [x, y], start_index=0, length=2)
    zDThe type of input in partial_concat should be list, but received %s.input[])float16r   float64int32rl   Z	complex64Z
complex128partial_concatstart_indexlengthr7   )ry   rz   rH   r   r   N)rx   )r>   r=   warningswarnr   	enumerater   strr   rI   r
   r    r#   r?   r$   	r%   ry   rz   idrr   r   r   r'   r)   r*   r*   r+   rx     s6   
*	
rx   c           	      C   s   t | D ]\}}t|dt| d g dd qd| i}i }||d< ||d< tdi t }|j| d}|jd|d	|gi|d
 |S )ai  
    **PartialSum**
    This Op can sum the vars by specifying the initial position(start_index) and length(length).
    This Op exists in incubate layers, which means that it is not shown to the public.
    Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be
    performed along the second dimension.

    .. code-block:: text

        Given:
            x = [[0, 1, 2],
                 [3, 4, 5]]
            y = [[6, 7 ,8],
                 [9, 10, 11]]
            output = partial_sum([x, y], start_index=0, length=2)

        We get:

            output = [[6, 8],
                      [12, 14]]
    Args:
        input (list): List of input Tensors with data type float32, float64, int32,
            int64.
        start_index (int32, optional): The start index of each instance for partial sum. Default is 0.
        length (int32, optional): The length of each instance for partial sum. Default is -1.

    Returns:
        Tensor: A Tensor with the same data type as input's.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()

            >>> x = paddle.static.data(name="x", shape=[2, 3], dtype="float32")
            >>> y = paddle.static.data(name="y", shape=[2, 3], dtype="float32")
            >>> sum = paddle.incubate.layers.partial_sum([x,y], start_index=0, length=2)
    rs   rt   )r   rv   rw   rl   partial_sumr7   ry   rz   rH   r   r   N)r   )r}   r   r~   r
   r    r#   r?   r$   r   r*   r*   r+   r   M  s"   (r   rw   c           
      C   s   t di t }t|dddgd t|}|j|j|d| g|tjj	dd}d	|_
|j|d
}|j|d
}	|jd| |d||	d||dd	d ||	fS )a
  
    **Tdm Child**
     According to the input node_id on the given tree, return the corresponding child node_id and
      whether child is a leaf node by leaf_mask value.

    .. code-block:: text

        Given:
            tree[[0], [1, 2], [3, 4], [5, 6]] # A binary tree with seven nodes
            x = [[2], [3]]
            node_nums = 7
            child_nums = 2

        We get:
            child = [[5, 6],
                     [0, 0]]
            leaf_mask = [[1, 1],
                         [0, 0]]

    Args:
        x (Tensor): Tensor contained the node_id information, dtype support int32/int64.
        node_nums (int): Number of total nodes.
        child_nums (int): Maximum number of child nodes per node.
        param_attr (ParamAttr, optional): To specify the tdm-tree-info parameter property. Default: None, which means the
            default weight parameter property is used. See usage for details in: ref: `api_paddle_ParamAttr`, should
            has shape (node_nums, 3 + child_nums), dtype support int32/int64.
            The dimension[1] of tdm-tree-info contains the following:
            1. Item_id (int, shape(1)), if node is a leaf node, give its item_id corresponding to node_id, else give 0.
            2. Layer_id (int, shape(1)), indicates which layer the node is on.
            3. Parent_id (int, shape(1)), node's parent node.
            4. Child_id (int, shape(child_nums)), all child node's node_id of this node should be given.
            If the number of child nodes is insufficient, padding 0 until child nums equal to child_nums.
        dtype (str, optional): The data type of output child and leaf_mask, support int32/int64. Default: int32.

    Returns:
        tuple: A tuple including input node's child(Tensor) and leaf_mask(Tensor).
            If child is a leaf node, leaf_mask equal ot 1, otherwise equal to 0.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import numpy as np
            >>> paddle.enable_static()

            >>> x = paddle.static.data(name="x", shape=[None, 1], dtype="int32", lod_level=1)
            >>> tree_info = [[0,0,0,1,2],
            ...             [0,1,0,3,4],[0,1,0,5,6],
            ...             [0,2,1,0,0],[1,2,1,0,0],[2,2,2,0,0],[3,2,2,0,0]]
            >>> tree_info_np = np.array(tree_info)
            >>> tree_info_np = np.reshape(tree_info_np, (7,5))
            >>> node_nums = 7
            >>> child_nums = 2
            >>> child, leaf_mask  = paddle.incubate.layers.tdm_child(x, node_nums, child_nums,
            ...                     param_attr=paddle.ParamAttr(
            ...                     initializer=paddle.nn.initializer.Assign(tree_info_np)))

    	tdm_childr   rw   rl   z paddle.incubate.layers.tdm_child   r   r   r   r   Zdefault_initializerTrH   )r7   ZTreeInfo)ZChildZLeafMask)
child_numsr   )r   r   r   r   rS   N)r   )r
   r    r   r	   r!   r"   paddlenninitializerConstantrS   r#   r$   )
rr   	node_numsr   r"   r   r'   c_dtypeZ	tree_infochildZ	leaf_maskr*   r*   r+   r     s,   ;
r   c           "   
   C   s  t di t }t|	dddgd t|
dddgd t|
}t|t|kr2tdt|t||dus:J d	d
}d
}d
g}t|D ]'\}}|d7 }||7 }|| || || krltd||| ||| qE||k suJ d||g}|j	|||	t
jjd
d}|dg}|j	|||	t
jjd
d}|j|
d}d|_|j|
d}d|_|j|
d}d|_|jd| ||d|||d|||||dd |rLg }g }g }d
}d}|sd
}|D ]g}|| | }t
j|dg|g|gd}t
j|dg|g|gd} t
j|dg|g|gd}!t
|d|| dg}d|_t
| d|| dg} d| _t
|!d|| dg}!d|!_|| ||  ||! |}q|}|}|}|||fS )a  
    **Tdm Sampler**
    According to the input positive samples at leaf node(x), do negative sampling layer by layer on the given tree.

    .. code-block:: text

        Given:
            tree[[0], [1, 2], [3, 4], [5, 6]] # A binary tree with seven nodes
            travel_list = [[1, 3], [1, 4], [2, 5], [2, 6]] # leaf node's travel path (exclude root node)
            layer_list = [[1, 2], [3, 4, 5, 6]] # two layer (exclude root node)

            x = [[0], [1], [2], [3]] # Corresponding to leaf node [[3], [4], [5], [6]]
            neg_samples_num_list = [0, 0] # negative sample nums = 0
            layer_node_num_list = [2, 4]
            leaf_node_num = 4
            output_list = False

        We get:
            out = [[1, 3], [1, 4], [2, 5], [2, 6]]
            labels = [[1, 1], [1, 1], [1, 1], [1, 1]]
            mask = [[1, 1], [1, 1], [1, 1], [1, 1]]

    Args:
        x (Tensor): Tensor contained the item_id(corresponding to leaf node) information, dtype support int32/int64.
        neg_samples_num_list (list(int)): Number of negative samples per layer.
        layer_node_num_list (list(int)): Number of nodes per layer, must has same shape with neg_samples_num_list.
        leaf_node_num (int): Number of leaf nodes.
        tree_travel_attr (ParamAttr, optional): To specify the tdm-travel parameter property. Default: None, which means the
            default weight parameter property is used. See usage for details in :ref:`api_paddle_ParamAttr`, should
            has shape (leaf_node_num, len(layer_node_num_list)), dtype support int32/int64.
        tree_layer_attr (ParamAttr, optional): To specify the tdm-layer parameter property. Default: None, which means the
            default weight parameter property is used. See usage for details in :ref:`api_paddle_ParamAttr`, should
            has shape (node_num, 1), dtype support int32/int64.
        output_positive (bool, optional): Whether to output positive samples (include label and mask )at the same time. Default: True.
        output_list (bool, optional): Whether to divide the output into layers and organize it into list format. Default: True.
        seed (int, optional): The number of random seed. Default: 0.
        tree_dtype (np.dtype|core.VarDesc.VarType|str, optional): The dtype of tdm-travel and tdm-layer, support int32/int64. Default: int32.
        dtype (np.dtype|core.VarDesc.VarType|str, optional): The dtype of output(sampling results, labels and masks). Default: int32.

    Returns:
        tuple: A tuple including sampling results, corresponding labels and masks. if output_positive = True, sampling
            result  will include both positive and negative samples. If sampling result is a positive sample, the label is 1,
            and if it is a negative sample, it is 0. If the tree is unbalanced, in order to ensure the consistency of the
            sampling result shape, the padding sample's mask = 0, the real sample's mask value = 1.
            If output_list = True, the result will organize into list format specified by layer information.
            Output Tensor have same type with tdm-travel and tdm-layer parameter(tree_dtype).

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import numpy as np
            >>> paddle.enable_static()

            >>> x = paddle.static.data(name="x", shape=[None, 1], dtype="int32", lod_level=1)
            >>> travel_list = [[1, 3], [1, 4], [2, 5], [2, 6]] # leaf node's travel path, shape(leaf_node_num, layer_num)
            >>> layer_list_flat = [[1], [2], [3], [4], [5], [6]] # shape(node_nums, 1)

            >>> neg_samples_num_list = [0, 0] # negative sample nums = 0
            >>> layer_node_num_list = [2, 4] #two layer (exclude root node)
            >>> leaf_node_num = 4

            >>> travel_array = np.array(travel_list)
            >>> layer_array = np.array(layer_list_flat)

            >>> sample, label, mask = paddle.incubate.layers.tdm_sampler(
            ...     x,
            ...     neg_samples_num_list,
            ...     layer_node_num_list,
            ...     leaf_node_num,
            ...     tree_travel_attr=paddle.ParamAttr(
            ...         initializer=paddle.nn.initializer.Assign(
            ...            travel_array)),
            ...     tree_layer_attr=paddle.ParamAttr(
            ...         initializer=paddle.nn.initializer.Assign(
            ...             layer_array)),
            ...     output_positive=True,
            ...     output_list=True,
            ...     seed=0,
            ...     tree_dtype='int32')

    tdm_sampler
tree_dtyperw   rl   z"paddle.incubate.layers.tdm_samplerr   zThe shape of negative samples list must match the shape of layers. But received len of neg_samples_num_list: {},and len of layer_node_num_list: {}, please check your input.Nz&leaf_node_num should not be None here.r   rX   zThe number of negative samples must be less than the number of nodes in the layer {}, But received negative nums {}, and num of node at layer {} is {}, please check your input.z0leaf_node_num must be less than total node nums.r   rH   T)r7   ZTravelZLayer)r   ZLabelsMask)neg_samples_num_listoutput_positiveZlayer_offset_lodrd   r   r   )ZaxesZstartsZendsr   )r   )r
   r    r   r	   rB   r<   formatr}   rg   r!   r   r   r   r   r#   rS   r$   sliceZreshape)"rr   r   Zlayer_node_num_listZleaf_node_numZtree_travel_attrZtree_layer_attrr   Zoutput_listrd   r   r   r'   r   Z
layer_numsr   Ztree_layer_offset_lodZ	layer_idxZlayer_node_numZtravel_shapetravelZlayer_shapelayerr)   labelsmaskZlabels_listZ	mask_liststart_offsetZpositive_flagZlayer_sample_num
end_offsetZlayer_samplesZlayer_labelsZ
layer_maskr*   r*   r+   r     s   _







r   r   c                 C   s   t di t }|jdd}| j}|d | | |d ksJ |j|||d}	d|	_||}
|j|dd	}|j|dd	}|jd| ||	d
|
||d||dd |
S )a  
    **Rank Attention layer**
    This Op can calculate rank attention between input and rank_param, and
    rank_param gives the organization of data. Notice: It currently supports
    GPU device.
    This Op exists in incubate layers, which means that it is not shown to the public.

    Args:
        input (Tensor): Tensor with data type float32, float64.
        rank_offset (Tensor): Tensor with data type int32.
        rank_para_shape (list[int]): The shape of rank_param.
        rank_param_attr (ParamAttr): Attribute initializer of rank_param.
        max_rank (int, optional): The max rank of input's ranks. Default is 3.
        max_size (int, optional): The max size of input's ranks. Default is 0.
    Returns:
        Tensor: A Tensor with the same data type as input's.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()

            >>> input = paddle.static.data(name="input", shape=[None, 2], dtype="float32")
            >>> rank_offset = paddle.static.data(name="rank_offset", shape=[None, 7], dtype="int32")
            >>> out = paddle.incubate.layers.rank_attention(input=input,
            ...                                             rank_offset=rank_offset,
            ...                                             rank_param_shape=[18,3],
            ...                                             rank_param_attr=
            ...                                             paddle.ParamAttr(learning_rate=1.0,
            ...                                                              name="ubm_rank_param.w_0"),
            ...                                             max_rank=3,
            ...                                             max_size=0)
    rank_attentionr%   )Zinput_param_namerX   r   r   r   r   FTr   rS   )r7   Z
RankOffsetZ	RankParam)r   Z	InputHelpZInsRank)ZMaxRankZMaxSizer   N)r   )r
   r    r?   r   r!   rS   r#   r$   )r%   Zrank_offsetZrank_param_shapeZrank_param_attrZmax_rankmax_sizer'   r   input_shapeZ
rank_paramrU   Z
input_helpZins_rankr*   r*   r+   r     s,   *


r   c                 C   s   t di t }t| dtd | j}|d |d ksJ |d |d ks&J |d |d ks0J |d |d ks:J | }t|dddgd |j|||dd	}	|j|||dd	}
||}|j	d| |	|
d
d|id |
|S )a  
    **Batch FC layer**
    This Op can calculate BatchFC. This is similar to matmul op,
    except that the bias and relu activation layers are added.
    Notice: It currently supports GPU device.
    This Op exists in incubate layers, which means that it is not shown to the public.

    Args:
        input (Tensor): Tensor with data type float32, float64.
        param_size (list[int]): The size of w.
        param_attr (ParamAttr): Attribute initializer of w.
        bias_size (list[int]): The size of bias.
        bias_attr (ParamAttr): Attribute initializer of bias.
        act (str, optional): Activation to be applied to the output of this layer. Default is None.

    Returns:
        Tensor: A Tensor with the same data type as input's.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()

            >>> input = paddle.static.data(name="input", shape=[16, 2, 3], dtype="float32")
            >>> out = paddle.incubate.layers.batch_fc(input=input,
            ...                                     param_size=[16, 3, 10],
            ...                                     param_attr=
            ...                                     paddle.ParamAttr(learning_rate=1.0,
            ...                                                      name="w_0"),
            ...                                     bias_size=[16, 10],
            ...                                     bias_attr=
            ...                                     paddle.ParamAttr(learning_rate=1.0,
            ...                                                      name="b_0"),
            ...                                     act="relu")
    batch_fcr%   r   r-   rX   r   rv   Fr   )ZInputr   Biasr   )r   r   r   N)r   )r
   r    r   r   r   r?   r   r!   r#   r$   Zappend_activation)r%   Z
param_sizer"   Z	bias_size	bias_attractr'   r   r   r(   bZpre_actr*   r*   r+   r     s,   &


r   @   c                    s   t di t    } fddtt|D } fddtt|D }jdd|i||d||dd t|d	krK|d
 |d
 fS ||fS )a  
    **Pull Box Extended Sparse Layer**
    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    BoxPS lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
        input (Tensor): Input is a Tensor<int64>, which contains the IDs information.
        size (int): The embedding size parameter, which indicates the size of
            each embedding vector respectively.
        extend_size (int, optional): The embedding size parameter in extended dim,
            which indicates the size of each embedding vector respectively. Default is 64.
        dtype (str, optional): The dtype refers to the data type of output tensor. Only supports float32 now. Default is float32.

    Returns:
        Tensor: The tensor storing the embeddings of the supplied inputs.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()

            >>> data = paddle.static.data(name='sequence', shape=[-1, 1], dtype='int64', lod_level=1)
            >>> emb, emb_ex = paddle.incubate.layers._pull_box_extended_sparse(input=data, size=8, extend_size=128)
    pull_box_extended_sparsec                    r/   r*   r0   r1   r4   r*   r+   r5   b  r6   z-_pull_box_extended_sparse.<locals>.<listcomp>c                    r/   r*   r0   r1   r4   r*   r+   r5   f  r6   r   )r   Z	OutExtend)Zemb_sizeZemb_extended_sizer   rX   r   N)r   )r
   r    r?   r@   rA   rB   r$   )r%   r&   Zextend_sizer   r   rD   Zouts_extendr*   r4   r+   _pull_box_extended_sparseD  s$   

r   c           	      C   s   t  rd|f}tj| ||g|R  S t| dddgd t|dddgd t|dddgd tdi t }|| j}| ||d}|j	d|d|id	|id
 |S )a  
    :alias_main: paddle.nn.functional.bilateral_slice
        :alias: paddle.nn.functional.bilateral_slice,paddle.nn.functional.vision.bilateral_slice
        :old_api: paddle.base.layers.bilateral_slice

    This operation implements bilateral slicing on the input according to the guide map.
    For more information of bilateral slicing, please refer to Deep Bilateral Learning for Real-Time Image Enhancement <https://groups.csail.mit.edu/graphics/hdrnet/data/hdrnet.pdf>_

    Args:
        x (Tensor): The input tensor, which is a 4-D tensor with shape
                     [N, C, H, W], N is the batch size, C is the channel
                     number, H and W is the feature height and width.
                     The data type is float32 and float64.
        guide (Tensor): Input grid tensor of shape [N, H, W]. The
                        data type is float32 and float64.
        grid (Tensor): Input grid tensor of shape [N, C, D, H, W]. The
                        data type is float32 and float64.
        has_offset (bool): Whether to slice with affine offset.
        name (str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.

    Returns:
        Tensor: Output of shape [N, C, H, W]. The data type is same as input tensor.

    Examples:

        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()

            >>> x = paddle.randn(name='x', shape=[1, 3, 101, 60], dtype='float32')
            >>> guide = paddle.randn(name='guide', shape=[1, 101, 60], dtype='float32')
            >>> grid = paddle.randn(name='grid', shape=[1, 12, 8, 10, 6], dtype='float32')

            >>> # without offset
            >>> output = paddle.incubate.layers.bilateral_slice(x, guide, grid, has_offset=False)

            >>> # has offset
            >>> output = paddle.incubate.layers.bilateral_slice(x, guide, grid, has_offset=True)

    
has_offsetrr   r   rv   bilateral_sliceguidegrid)r7   ZGuideZGridr   rR   N)r   )
r   in_dynamic_moder   r   r   r
   r    r#   r   r$   )	rr   r   r   r   rT   r   r'   r)   r   r*   r*   r+   r   u  s(   ,r   rX   c                 C   s   t  rd|d|d|d|d|d|f}tj| |g|R  }	|	S tdi t }
|
j| jd}	|
jd| |d	||||||d
d|	id |	S )a  

    This operation compute correlation of two tensor.
    For more information of correlation, please refer to PWC-Net:
    CNNs for Optical Flow Using Pyramid, Warping, and Cost Volume
    <https://arxiv.org/pdf/1709.02371.pdf>_

    Args:
        x (Tensor): The input x is 4-D Tensor with shape [N, C, H, W]. The data type is float32 and float64.
        y (Tensor): The input y is 4-D Tensor with shape [N, C, H, W]. The data type is float32 and float64.
        pad_size (int): Pad size. The data type is int.
        max_displacement (int): Max displacement. The data type is int.
        stride1 (int): stride size of x. The data type is int.
        stride2 (int): stride size of y. The data type is int.
        corr_type_multiply (int, optional): The type of multiply. The data type is int. Default: 1.

    Returns:
        Tensor: The data type is same as input tensor.

    Examples:

        .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()
            >>> x1 = paddle.static.data(name='x1',
            ...                         shape=[2, 3, 4, 5],
            ...                         dtype="float32")
            >>> x2 = paddle.static.data(name='x2',
            ...                         shape=[2, 3, 4, 5],
            ...                         dtype="float32")


            >>> out = paddle.incubate.layers.correlation(
            ...                 x1,
            ...                 x2,
            ...                 pad_size=4,
            ...                 kernel_size=1,
            ...                 max_displacement=4,
            ...                 stride1=1,
            ...                 stride2=1)

    pad_sizekernel_sizemax_displacementstride1stride2corr_type_multiplycorrelationrH   )ZInput1ZInput2)r   r   r   r   r   r   OutputrR   N)r   )	r   r   r   r   r
   r    r#   r   r$   )rr   yr   r   r   r   r   r   r   rU   r'   r*   r*   r+   r     s>   6r   ?h㈵>c
                 C   sd  t di t }
t| dg dd t|dg dd tjjj}| j}|d }|g}|
j|
j	||t
jjdd}|
j|
j||dd}|
jt|t
jjd	d
d||d}d|_|
jt|t
jjdd
d||d}d|_|}|}|
j|dd}|
j|dd}|
jtjjjdd}|
tjjj}| |||||d}||d}||||||d}|
jd|||d |S )aO  
    This Op performs batch norm on input x, and adds the result to input y. Then
    it performs activation on the sum. The data format of inputs must be NHWC
    `[batch, in_height, in_width, in_channels]`.

    Args:
        x (Tensor): The rank of input tensor can be 2, 3, 4, 5. The data type
            is float16.
        y (Tensor): The rank of input tensor can be 2, 3, 4, 5. The data type
            is float16.
        momentum (float|Tensor, optional): The value used for the moving_mean and
            moving_var computation. This should be a float number or a tensor with
            shape [1] and data type as float32. The updated formula is:
            :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)`
            :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)`
            Default is 0.9.
        epsilon (float, optional): A value added to the denominator for
            numerical stability. Default is 1e-05.
        param_attr (ParamAttr, optional): The parameter attribute for Parameter `scale`
            of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as param_attr, the name of scale can be set in ParamAttr.
            If the Initializer of the param_attr is not set, the parameter is initialized
            with Xavier. Default: None.
        bias_attr (ParamAttr, optional): The parameter attribute for the bias of batch_norm.
            If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr.
            If the Initializer of the bias_attr is not set, the bias is initialized zero.
            Default: None.
        moving_mean_name (str, optional): The name of moving_mean which store the global Mean. If it
            is set to None, batch_norm will save global mean with a random name, otherwise, batch_norm
            will save global mean with the string. Default: None.
        moving_variance_name (str, optional): The name of the moving_variance which store the global Variance.
            If it is set to None, batch_norm will save global variance with a random name, otherwise, batch_norm
            will save global variance with the string. Default: None.
        act (string, optional): Activation type, linear|relu|prelu|... Default: None.
        name (str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default. Default: None.

    Examples:
        .. code-block:: python

            >>> # doctest: +REQUIRES(env:GPU)
            >>> import paddle
            >>> paddle.enable_static()

            >>> def build_program(main_program, startup_program):
            ...     with paddle.static.program_guard(main_program, startup_program):
            ...         x = paddle.static.data(name='x', shape=[-1, 1, 28, 28], dtype='float32')
            ...         y = paddle.static.data(name="y", shape=[-1, 1], dtype='int64')
            ...         conv1_1 = paddle.static.nn.conv2d(
            ...             input=x,
            ...             filter_size=3,
            ...             num_filters=32,
            ...             stride=1,
            ...             padding=1,
            ...             act=None,
            ...             bias_attr=False,
            ...            data_format='NHWC')
            ...         conv1_2 = paddle.static.nn.conv2d(
            ...             input=x,
            ...             filter_size=3,
            ...             num_filters=32,
            ...             stride=1,
            ...             padding=1,
            ...             act=None,
            ...             bias_attr=False,
            ...             data_format='NHWC')
            ...         bn = paddle.static.nn.batch_norm(
            ...            input=conv1_1,
            ...             act=None,
            ...             data_layout='NHWC')
            ...         fused_bn_add_act = paddle.incubate.layers.fused_bn_add_act(conv1_2, bn)
            ...         prediction = paddle.static.nn.fc(x=fused_bn_add_act, size=10, activation='softmax')
            ...         loss = paddle.nn.functional.cross_entropy(
            ...             input=prediction, label=y,
            ...             reduction='none', use_softmax=False
            ...         )
            ...         loss = paddle.mean(loss)
            ...         sgd = paddle.optimizer.SGD(learning_rate=0.001)
            ...         sgd = paddle.static.amp.decorate(
            ...             sgd, use_dynamic_loss_scaling=True, init_loss_scaling=128.0)
            ...         sgd.minimize(loss)
            ...
            ...     return x, y, loss

            >>> iters = 5
            >>> batch_size = 16
            >>> support_gpu = paddle.is_compiled_with_cuda()
            >>> if support_gpu:
            ...     main_program = paddle.static.Program()
            ...     startup_program = paddle.static.Program()
            ...     place = paddle.CUDAPlace(0)
            ...     x, y, loss = build_program(main_program, startup_program)
            ...
            ...     feeder = paddle.DataFeeder(feed_list=[x, y], place=place)
            ...     train_reader = paddle.batch(
            ...         paddle.dataset.mnist.train(), batch_size=batch_size)
    fused_bn_add_actr%   )ru   r   rv   r   rF   r   Tr   r,   F)rT   r   Z	trainabler   r   )r7   ZZScaler   ZMeanZVariance)epsilonmomentum)YZMeanOutZVarianceOutZ	SavedMeanZSavedVarianceZReserveSpaceZfused_bn_add_activationr   N)r   )r
   r    r   r   ZVarDescZVarTypeZFP32r   r!   r"   r   r   r   r   r   r   rS   r#   ZFP16r$   )rr   r   r   r   r"   r   Zmoving_mean_nameZmoving_variance_namer   rT   r'   Zbn_param_dtypeZx_shapeZchannel_numZparam_shapescaleZbiasmeanZvarianceZmean_outZvariance_outZ
saved_meanZsaved_varianceZreserve_spaceZbatch_norm_outr   r   r   r*   r*   r+   r     s   n
		

	r   c           	   	   C   s   t  rtdtdi t }|jd|dgd}||t jjj	t
||  d |jdddgd}||t jjj	dd | |ksFJ d	|jd||d
||d| |||dd |S )Nz@pow2_decay_with_linear_warmup does not support dygraph mode yet.pow2_decay_with_linear_warmupTrX   )rm   r   r   )valuerl   r   z.warmup_steps cannot be larger than total_steps)ZLearningRateZStep)ZLearningRateOutZStepOut)warmup_stepstotal_stepsbase_lrend_lrr   )r   )r   r   NotImplementedErrorr
   r    Zcreate_global_variableZset_variable_initializerr   r   r   floatr$   )	r   r   r   r   r   rT   r'   re   stepr*   r*   r+   r     s<   
r   c                    s   t di t  dkrtd     } fddtt|D }jj|d g dd}j	d||d	d
|i|||dd t|dkrQ|d S |S )a  
    **Pull GpuPS Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    GpuPS lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
        input (Tensor): Input is a Tensor<int64>, which contains the IDs information.
        size (int|list of int): The embedding size parameter of each input, which indicates the size of
            each embedding vector respectively.
        dtype (str, optional): The dtype refers to the data type of output tensor. Only supportsfloat32 now. Default is float32.
        is_distributed (bool, optional): Whether to use distributed mode. Default is False.
        is_sparse (bool, optional): Whether to use sparse mode. Default is False.

    Returns:
        Tensor: The tensor storing the embeddings of the supplied inputs, whose size are indicated by size respectively.

    Examples:
        .. code-block:: python

            >>> import paddle.incubate as incubate
            >>> import paddle
            >>> paddle.enable_static()

            >>> slots = []
            >>> data_1 = paddle.static.data(name='sequence', shape=[-1,1], dtype='int64', lod_level=1)
            >>> slots.append(data_1)
            >>> data_2 = paddle.static.data(name='sequence', shape=[-1,1], dtype='int64', lod_level=1)
            >>> slots.append(data_2)
            >>> embs = incubate.layers.pull_gpups_sparse(input=slots, size=[11, 35])
    pull_gpups_sparser   z?GpuPS only support float type embedding now, and your type is: c                    r/   r*   r0   r1   r4   r*   r+   r5   0  r6   z&_pull_gpups_sparse.<locals>.<listcomp>r   Fr   r   r   r&   is_distributedr   r   rX   N)r   
r
   r    r<   r?   r@   rA   rB   r!   r"   r$   r%   r&   r   r   r   r   rD   r(   r*   r4   r+   _pull_gpups_sparse  s6   #

r   c                    s   t di t  dkrtd     } fddtt|D }jj|g dd}j	d||dd	|i|||d
d t|dkrO|d S |S )a  
    **Pull Box Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    BoxPS lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
        input (Tensor): Input is a Tensor<int64>, which contains the IDs information.
        size (int): The embedding size parameter, which indicates the size of
            each embedding vector respectively.
        dtype (str, optional): The dtype refers to the data type of output tensor. Only supports float32 now. Default is float32.
        is_distributed (bool, optional): Whether to use distributed mode. Default is False.
        is_sparse (bool, optional): Whether to use sparse mode. Default is False.

    Returns:
        Tensor: The tensor storing the embeddings of the supplied inputs.

    Examples:
        .. code-block:: python

            >>> import paddle.incubate as incubate
            >>> import paddle
            >>> paddle.enable_static()

            >>> x = paddle.static.data(name='x', shape=[-1, 1], dtype='int64', lod_level=1)
            >>> y = paddle.static.data(name='y', shape=[-1, 1], dtype='int64', lod_level=1)
            >>> emb_x, emb_y = incubate.layers._pull_box_sparse([x, y], size=1)
    pull_box_sparser   z?BoxPS only support float type embedding now, and your type is: c                    r/   r*   r0   r1   r4   r*   r+   r5   n  r6   z$_pull_box_sparse.<locals>.<listcomp>Fr   r   r   r   r   rX   r   N)r   r   r   r*   r4   r+   _pull_box_sparseF  s6    

r   )FNr   Nr   )r,   Tr-   )rE   TrF   r   FN)NNNNNr   )N)r   r   )Nrw   )NNTTr   rw   rw   )r   r   )r   r   )rX   )r   r   NNNNNN)r   N)r   FF)'__doc__r{   numpyrn   r   r   Zpaddle.baser   r   Zpaddle.base.data_feederr   r   r   Zpaddle.base.frameworkr   r	   Zpaddle.base.layer_helperr
   Zpaddle.base.param_attrr   __all__r   r.   rG   rW   rk   rx   r   r   r   r   r   r   r   r   r   r   r   r   r*   r*   r*   r+   <module>   s   
Q
T
 

z
@
N
<Z
 g

E
@
1K
\
 O
(
B