
    zj                       d Z ddlmZ ddlZddlmZmZmZ ddlZ	ddl
Z
ddl
mZ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mZ dd	lmZ dd
lmZ ddlmZ erddl
mZ ddlm Z m!Z! g Z"	 	 	 d|d}dZ#	 	 	 	 	 	 d~dd4Z$ddd7Z%	 ddd<Z&	 ddd=Z'	 	 dddBZ(e	 	 	 	 	 	 	 dddO            Z)e	 	 	 	 	 	 	 dddR            Z)e	 	 	 	 	 	 	 dddT            Z)	 	 	 	 	 	 	 ddUZ)	 	 ddd]Z*	 dddbZ+	 dddkZ,	 	 	 	 	 	 	 	 dddsZ-	 	 dddxZ.	 ddzZ/	 dd{Z0dS )z5
incubate layers just related to the neural network.
    )annotationsN)TYPE_CHECKINGLiteraloverload)_C_ops_legacy_C_ops)coreunique_name)check_dtype
check_typecheck_variable_and_dtype)Variableconvert_np_dtype_to_dtype_in_dynamic_or_pir_mode)LayerHelper)	ParamAttr)in_pir_mode)Tensor)	DTypeLikeParamAttrLike        T   inputr   	pool_typeLiteral['sum']cvm	pad_valuefloatuse_cvmbool
cvm_offsetintreturnc           
     "  	
 t          di t                      
|                                dk    rt          d|z             t	          | dt
          d           t          | t
                    r| D ]}t          |ddgd           
                                	
	                                }	
fdt          t          |                    D             }
                    d||dd|i|                                |||d	
           |S )a<  
    :api_attr: Static Graph

    This OP is the fusion of sequence_pool and continuous_value_model op.

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

    Args:
        input(Tensor): Input is List of DenseTensor.
        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_cvmSUMzBfused_seqpool_cvm only support SUM pooling now, and your type is: r   float32c                :    g | ]}                               S  "create_variable_for_type_inference.0idtypehelpers     i/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/incubate/layers/nn.py
<listcomp>z%fused_seqpool_cvm.<locals>.<listcomp>p   7        	11%88      )XCVMOut)pooltyper   r   r!   typeinputsoutputsattrs)r%   )r   localsupper
ValueErrorr   list
isinstancer   input_dtypemultiple_inputrangelen	append_op)r   r   r   r   r   r!   _inputr;   outsr/   r0   s            @@r1   r%   r%   1   se   \ 9999FE!!P
 
 	

 ugt%8999%  	 	F$).A      E""$$F    s6{{##  D
  C((!))"$	
 
	  
 
 
 Kr4   r'   num_emb	space_lenpyramid_layerrand_lendrop_out_percentis_training
use_filterwhite_list_lenblack_list_lenseedlr
param_attrParamAttrLike | Noneparam_attr_wlparam_attr_blname
str | Nonedistribute_update_varslist[str] | Noner/   r   c                   t          di t                      }||z   dg}|                    |||d          }d|_        | |d}|dk    r)|dg}|                    |||d          }d|_        ||d<   |	dk    r)|	dg}|                    |||d          }d|_        ||d	<   d
}|rt	          |t
                    sJ g }|r|                    |j                   |r|                    |j                   |r|                    |j                   |D ]}||vrt          d|           d	                    |          }t                      rMt          j        |d         |d         |d         |d	         |||||t          |          |||	|
||          \  }}|S |                    |          }|                    |          }|                    |          }|                    d||||d|||||||||	|
||d           |S )a  
    **Pyramid hash embedding**

    Args:
        input (Tensor): DenseTensor<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|None, 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|None, optional): Specified parameters of white filter. Default: None.
        param_attr_bl (ParamAttr|None, optional): Specified parameters of black filter. Default: None.
        distribute_update_vars(list[ParamAttr.name]|None, optional): Decided which params should be updated in distribute training.
            Used in Distribute Transpiler to create a trainer/server program. Default: None.
        name (str|None, 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: DenseTensor of pyramid hash embedding.
    search_pyramid_hash   Fattrshaper/   is_biasT)r5   Wr   	WhiteList	BlackList z)Pyramid Hash layer didn't have parameter ,r5   rd   pyramid_hash)r7   
X_Temp_OutDropPos)rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   r[   r9   N)r^   )r   r>   create_parameterstop_gradientrB   rA   appendrY   r@   joinr   r   ri   r"   r+   rG   ) r   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rW   rX   rY   r[   r/   r0   w_shapew
input_varswl_shape
white_listbl_shape
black_listdistribute_update_vars_strspecial_name_listparamresdrop_pos
x_temp_outs                                    r1   r^   r^      s   l ;;&((;;F8#Q'GweU 	  	 	A AO1%%J"A&,,heU - 
 

 $(
 ",
;"A&,,heU - 
 

 $(
 ",
;!# F0$77777 	6$$Z_555 	9$$]%7888 	9$$]%7888+ 	 	E--- GGG   . &)XX.D%E%E" ,+sOsO{#{#&!
 
X$ 
77>><<UCC>>uEE
zhOO"&!.$$4*("0"0*D 	 	 	
 	
 	
( 
r4   xint | Tensor | Nonec                   t          di t                      }|                    | j                  }|                    t          j                  }||j        j        dk    r|j        j        }| t          j        	                    dd          }i }t          |t                    rv||d<   t                      r9t          j        dgdd          }t          j        | ||d                   \  }}}|S |                    t%          j        d	          dd
          }t                      rt          j        | |d          \  }}}|S |                    d| |d|||d|           |S )a=  
    This layer shuffle input tensor :attr:`x` . Normally, :attr:`x` is 2-D DenseTensor.

    :attr:`x` is a DenseTensor 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 DenseTensor 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 DenseTensor 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_batchr/   Nr   i  i  startup_seedint64shuffle_batch_seedF)rY   r/   persistable)r5   Seed)r7   
ShuffleIdxSeedOutr9   )r   )r   r>   r+   r/   npr   main_programrandom_seedrandomrandintrB   r"   r   paddlefullr   r   create_variabler
   generaterG   )r}   rS   r0   outshuffle_idxop_attrs_s          r1   r   r     s   N 55FHH55F

3
3!'
3
B
BC;;"(;KKK|+71<<".|y  //H$ #' == 		;sAw//D,Qh~6NOOICAJ)) )*>??! *  D
 }} (D!44	Q

%%;4HH	     Jr4   list[Tensor]start_indexlengthc                   t          | t                    s(t          j        dt	          |            d           | g} t          |           D ],\  }}t          |dt          |          z   dz   g dd           -t          |dt          d           t          |dt          d           d	| i}||d
}t          di t                      }|                    |                                          }|                    d|d|gi|           |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 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)
    zAThe type of input in partial_concat should be list, but received .input[])float16r'   float64uint16int32r   	complex64
complex128partial_concatr   r   r5   )r   r   r   r7   r9   )r   )rB   rA   warningswarnr:   	enumerater   strr   r"   r   r>   r+   rC   rG   	r   r   r   idr}   r;   r=   r0   r   s	            r1   r   r   Z  sY   X eT"" ^PTUZP[P[^^^	
 	
 	
 5!! 
 
A s2ww$	 	 	 	
 	
 	
 	
 {MC2BCCCvx#(89995\F'6::E66VXX66F

3
3&:L:L:N:N
3
O
OC
	     Jr4   c                V   t          |           D ],\  }}t          |dt          |          z   dz   g dd           -d| i}i }||d<   ||d<   t          di t	                      }|                    |                                          }|                    d|d	|gi|
           |S )a\  
    **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 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)
    r   r   )r'   r   r   r   partial_sumr5   r   r   r   r7   r9   )r   )r   r   r   r   r>   r+   rC   rG   r   s	            r1   r   r     s    T 5!! 
 
A s2ww$444		
 	
 	
 	
 5\FE&E-E(O33&((33F

3
3&:L:L:N:N
3
O
OC
6EC5>     Jr4   r   	node_nums
child_numstuple[Tensor, Tensor]c                    t          di t                      }t          |dddgd           t          |          }|                    |j        |d|z   g|t          j        j        	                    d                    }d	|_
        t                      rt          j        | |||          S |                    |
          }|                    |
          }	|                    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|None, 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/   r   r   z paddle.incubate.layers.tdm_child   r   ra   rb   r/   default_initializerTr   )r5   TreeInfo)ChildLeafMask)r   r/   )r:   r;   r<   r=   rm   )r   )r   r>   r   r   rl   rU   r   nninitializerConstantrm   r   r   r   r+   rG   )
r}   r   r   rU   r/   r0   c_dtype	tree_infochild	leaf_masks
             r1   r   r     s<   B 1111Fw'*,N   )//G''!j.)"I1::1==	 (  I #I}} C9j'BBB55E5BBE999FFI
I..Y77''::     9r4   .neg_samples_num_list	list[int]layer_node_num_listleaf_node_numtree_travel_attrtree_layer_attroutput_positiveoutput_listLiteral[True]
tree_dtype/tuple[list[Tensor], list[Tensor], list[Tensor]]c                    d S Nr)   r}   r   r   r   r   r   r   r   rS   r   r/   s              r1   tdm_samplerr   F  s	     7:cr4   Literal[False]tuple[Tensor, Tensor, Tensor]c                    d S r   r)   r   s              r1   r   r   V  s	     %(Cr4   Otuple[Tensor, Tensor, Tensor] | tuple[list[Tensor], list[Tensor], list[Tensor]]c                    d S r   r)   r   s              r1   r   r   f  s	      3r4   c                   t          di t                      }t          |	dddgd           t          |
dddgd           t          |
          }t	          |          t	          |          k    r0t          dt	          |           dt	          |           d	          |
J d            d}d}dg}t          |          D ]^\  }}|dz  }||z  }|                    |           ||         ||         k    r(t          d| d||          d| d||          d		          _||k     s
J d            ||g}|                    |||	t          j
        j                            d                    }|dg}|                    |||	t          j
        j                            d                    }t                      rt          j        | |||||||          S |                    |
          }d|_        |                    |
          }d|_        |                    |
          }d|_        |                    d| ||d|||d|||||d           |rg }g }g }d}d}|sd}|D ]}||z   |z   }t          j        |dg|g|g          }t          j        |dg|g|g          } t          j        |dg|g|g          }!t          j        |d||z   dg          }d|_        t          j        | d||z   dg          } d| _        t          j        |!d||z   dg          }!d|!_        |                    |           |                    |            |                    |!           |}|}|}|}|||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|None, 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|None, 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')

    r   r   r   r   z"paddle.incubate.layers.tdm_samplerr/   zmThe shape of negative samples list must match the shape of layers. But received len of neg_samples_num_list: z!,and len of layer_node_num_list: z, please check your input.Nz&leaf_node_num should not be None here.r   r_   zRThe number of negative samples must be less than the number of nodes in the layer z, But received negative nums z, and num of node at layer z is z0leaf_node_num must be less than total node nums.r   r   T)r5   TravelLayer)r7   LabelsMask)r   r   layer_offsetrS   r/   r9   )axesstartsendsr   )r   )r   r>   r   r   rF   r@   r   rn   rl   r   r   r   r   r   r   r   r+   rm   rG   slicereshape)"r}   r   r   r   r   r   r   r   rS   r   r/   r0   r   
layer_numsr   tree_layer_offset	layer_idxlayer_node_numtravel_shapetravellayer_shapelayerr   labelsmasklabels_list	mask_liststart_offsetpositive_flaglayer_sample_num
end_offsetlayer_sampleslayer_labels
layer_masks"                                     r1   r   r   y  s   ~ 33&((33F	',	   w'*,P   )//G
  C(;$<$<<<d9<=Q9R9Rd d/23F/G/Gd d d
 
 	

 $$&N$$$JI%./B%C%C 	 	!	>a
^#	  +++	*.A).LLLQ )Q QH\]fHgQ Q ENQ Q))4Q Q Q   M 9$$$: %$$ ":.L$$"I1::1==	 %  F a.K##"I1::1==	 $  E  

! 	
 	
 		
 
3
3%
3
@
@CC66U6CCFF4454AADD
&599vt<<$8.-
 
	      +	 	M 4 	& 	&%(88=HJ"L1#|nJ<  M "<aS,zl  L  A3~ZL  J #N$4}$DaH M +/M'!>r#3m#CQG L *.L&R!1M!A1E J (,J$}---|,,,Z(((%LLr4   r   rank_offsetrank_param_shaperank_param_attrr   max_rankmax_sizec                   t          di t                      }|                    d          }| j        }|d         |z  |z  |d         k    sJ |                    |||          }	d|	_        |                    |          }
|                    |d	          }|                    |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   )input_param_namer_   r   ra   rb   r/   FTr/   rm   )r5   
RankOffset	RankParam)r7   	InputHelpInsRank)MaxRankMaxSizer9   )r   )r   r>   rC   rb   rl   rm   r+   rG   )r   r   r   r   r   r   r0   r/   input_shape
rank_paramoutput
input_helpins_ranks                r1   r   r   _  s+   T 66VXX66F88E+Kq>H$x/3CA3FFFFF(($4E )  J  %J66u==F::4 ;  J 884 9  H +JOOZHMM"x88	     Mr4   
param_size	bias_size	bias_attractc                R   t          di t                      }t          | dt          d           | j        }|d         |d         k    sJ |d         |d         k    sJ |d         |d         k    sJ |d         |d         k    sJ |                                }t          |dddgd           |                    |||d	          }	|                    |||d	          }
|                    |          }|	                    d| |	|
d
d|i           |
                    |          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   r_   r'   r   Fr`   )Inputrd   Biasr7   )r:   r;   r<   )r  )r   r>   r   r   rb   rC   r   rl   r+   rG   append_activation)r   r  rU   r  r  r	  r0   r  r/   rq   bpre_acts               r1   r  r    sm   Z 00vxx00Fug:666+Kq>Z]****q>Z]****a=IaL((((q>Yq\))))  EwI 6
CCCz 	  	 	A 	iue 	  	 	A 77>>G
Q22     
 ##G,,,r4   r_   ypad_sizekernel_sizemax_displacementstride1stride2corr_type_multiplyc                    t          j                    r"d|d|d|d|d|d|f}t          j        | |g|R  }	nXt	          di t                      }
|
                    | j                  }	|
                    d| |d	||||||d
d|	i           |	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)

    r  r  r  r  r  r  correlationr   )Input1Input2)r  r  r  r  r  r  Output)r:   r;   r=   r<   )r  )	r   in_dynamic_moder   r  r   r>   r+   r/   rG   )r}   r  r  r  r  r  r  r  r=   r  r0   s              r1   r  r    s    l  
 
 *1a8%88877fhh77:::II1--$*$4""&8  v& 	 	
 	
 	
 Mr4   ?h㈵>momentumfloat | Tensorepsilonmoving_mean_namemoving_variance_namec
                B   t          di t                      }
t          | dg dd           t          |dg dd           t          j        j        j        }| j        }|d         }|g}|
                    |
j	        ||t          j        j                            d                    }|
                    |
j        ||d          }|
                    t          |t          j        j                            d	          d
          ||          }d|_        |
                    t          |t          j        j                            d          d
          ||          }d|_        |}|}|
                    |d          }|
                    |d          }|
                    t          j        j        j        d          }|
                    t          j        j        j                  }| |||||d}||d}||||||d}|
                    d|||           |S )am  
    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 0-D Tensor with
            shape [] 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|None, 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|None, 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|None, 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|None, 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 (str|None, optional): Activation type, linear|relu|prelu|... Default: None.
        name (str:None, 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   )r   r'   r   r   g      ?r   Tr`   r   F)rY   r   	trainabler   r   )r5   ZScaler  MeanVariance)r"  r   )YMeanOutVarianceOut	SavedMeanSavedVarianceReserveSpacefused_bn_add_activationr9   )r&  )r   r>   r   r	   VarDescVarTypeFP32rb   rl   rU   r   r   r   r   r  r   rm   r+   FP16rG   )r}   r  r   r"  rU   r  r#  r$  r	  rY   r0   bn_param_dtypex_shapechannel_numparam_shapescalebiasmeanvariancemean_outvariance_out
saved_meansaved_variancereserve_spacebatch_norm_outr;   r=   r<   s                               r1   r&  r&  D  s   \ 88vxx88F	75557I   	75557I   \).NgG"+K-K ##"I1::3??	 $  E ""	 #  D ""!	-66s;;
 
 

  #  D D&&%	-66s;;
 
 

  '  H "H HL::D ;  J >>D ?  N ==l"'t >  M >>! N
  F  X66E #'% G &	     r4   warmup_stepstotal_stepsbase_lrend_lrc           
     J   t          j                    rt          d          t          di t	                      }|                    d|dg          }|                    |t           j        j        	                    t          |          | z                       |                    dddg          }|                    |t           j        j        	                    d                     | |k    s
J d	            |                    d||d
||d| |||d           |S )Nz@pow2_decay_with_linear_warmup does not support dygraph mode yet.pow2_decay_with_linear_warmupTr_   )r   r/   rb   )valuer   r   z.warmup_steps cannot be larger than total_steps)LearningRateStep)LearningRateOutStepOut)rE  rF  rG  rH  r9   )rJ  )r   r  NotImplementedErrorr   r>   create_global_variableset_variable_initializerr   r   r   r   rG   )	rE  rF  rG  rH  r/   rY   r0   rT   steps	            r1   rJ  rJ    sk     
!N
 
 	
 EEFHHEEF		&	&4uQC	&	P	PB
##
	&&U7^^l-J&KK  
 ((s )  D ##fi#,,1,55   ;&&&8 '&& , "D11$&488(&	
 
	  
 
 
 Ir4   Fc           	        t          di t                      dk    rt          dz                                                                              }fdt          t          |                    D             }                    j        |d         gd          }	                    d||dd	|i|||d
           t          |          dk    r|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                :    g | ]}                               S r)   r*   r,   s     r1   r2   z&_pull_gpups_sparse.<locals>.<listcomp>h  r3   r4   r   Fr`   Idsrd   r7   sizeis_distributed	is_sparser9   r_   )rU  
r   r>   r@   rC   rD   rE   rF   rl   rU   rG   	r   rZ  r/   r[  r\  r;   rI   rq   r0   s	     `     @r1   _pull_gpups_sparser_  =  s:   F 9999F	M
 
 	
 ""$$F    s6{{##  D 	tAwiue 	  	 	A  A&&,"
 
	  	 	 	 4yyA~~AwKr4   c           	        t          di t                      dk    rt          dz                                                                              }fdt          t          |                    D             }                    j        |gd          }	                    d||dd|i|||d	
           t          |          dk    r|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                :    g | ]}                               S r)   r*   r,   s     r1   r2   z$_pull_box_sparse.<locals>.<listcomp>  r3   r4   Fr`   rW  r7   rY  r9   r_   r   )ra  r]  r^  s	     `     @r1   _pull_box_sparserc  ~  s6   @ 77fhh77F	M
 
 	
 ""$$F    s6{{##  D 	tfE5 	  	 	A A&&,"
 
	  	 	 	 4yyA~~AwKr4   )r   Tr   )r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r   )NNNNNr'   )&r   r   rJ   r"   rK   r"   rL   r"   rM   r"   rN   r   rO   r    rP   r    rQ   r"   rR   r"   rS   r"   rT   r   rU   rV   rW   rV   rX   rV   rY   rZ   r[   r\   r/   r   r#   r   r   )r}   r   rS   r~   r#   r   )r   r   )r   r   r   r"   r   r"   r#   r   )Nr   )r}   r   r   r"   r   r"   rU   rV   r/   r   r#   r   ).......)r}   r   r   r   r   r   r   r"   r   rV   r   rV   r   r    r   r   rS   r"   r   r   r/   r   r#   r   )r}   r   r   r   r   r   r   r"   r   rV   r   rV   r   r    r   r   rS   r"   r   r   r/   r   r#   r   )r}   r   r   r   r   r   r   r"   r   rV   r   rV   r   r    r   r    rS   r"   r   r   r/   r   r#   r   )NNTTr   r   r   )r   r   )r   r   r   r   r   r   r   r   r   r"   r   r"   r#   r   )r   r   r  r   rU   r   r  r   r  r   r	  rZ   r#   r   )r_   )r}   r   r  r   r  r"   r  r"   r  r"   r  r"   r  r"   r  r"   r#   r   )r  r  NNNNNN)r}   r   r  r   r   r!  r"  r   rU   rV   r  rV   r#  rZ   r$  rZ   r	  rZ   rY   rZ   r#   r   )r'   N)rE  r   rF  r   rG  r   rH  r   r/   r   rY   rZ   r#   r   )r'   FF)1__doc__
__future__r   r   typingr   r   r   numpyr   r   r   r   paddle.baser	   r
   paddle.base.data_feederr   r   r   paddle.base.frameworkr   r   r   paddle.base.layer_helperr   paddle.base.param_attrr   paddle.frameworkr   r   paddle._typingr   r   __all__r%   r^   r   r   r   r   r   r   r  r  r&  rJ  r_  rc  r)   r4   r1   <module>rp     s9    # " " " " "  3 3 3 3 3 3 3 3 3 3      ( ( ( ( ( ( ( ( ) ) ) ) ) ) ) )         
         
 1 0 0 0 0 0 , , , , , , ( ( ( ( ( ( 877777777
 P P P P P@ (,*.*./3 %K K K K K\E E E E ER >@M M M M Mb >@; ; ; ; ;D (,[ [ [ [ [| 
 .1,/!$: : : : 
: 
 .1,/"%( ( ( ( 
( 
 .1,/    
. 	

c c c cV B B B B BV D- D- D- D- D-^  V V V V Vx  #'+&*#''+J J J J Jd !) ) ) ) )Z CH> > > >D CH; ; ; ; ; ;r4   