Ë
    •\;je,  ã                   ó¤   — d dl mZmZmZmZ d dlmZ ddlmZm	Z	 ddl
mZ ddlmZ ddlmZmZmZ g Z edd	d
d¬«      dd„«       Zdd„Zd„ Zdd„Zy)é    )Ú_C_opsÚ_legacy_C_opsÚin_dynamic_modeÚtensor)Ú
deprecatedé   )Ú
check_typeÚcheck_variable_and_dtype)ÚLayerHelper)ÚVariable)Úconvert_np_dtype_to_dtype_ÚcoreÚin_dynamic_or_pir_modez2.5.2zpaddle.diag_embedé   z<diag_embed in paddle.nn.functional will be removed in future)ÚsinceÚ	update_toÚlevelÚreasonc                 ó2   — t        j                  | |||«      S )N)r   Ú
diag_embed)ÚinputÚoffsetÚdim1Údim2s       úgG:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/nn/functional/extension.pyr   r   !   s   € ô ×Ñ˜U F¨D°$Ó7Ð7ó    Nc                 ó.  — t        «       r—t        |t        j                  j                  «      st        |«      }|�ft        |t        j                  j                  «      rd|f}t        j                  | |g|¢­Ž }nd|d|f}t        j                  | dg|¢­Ž }d|_
        |S t        di t        «       ¤Ž}|j                  |¬«      }d| gi}d|j                  i}|�t        |t        «      r||d<   n||d<   |j!                  d|d	|i|¬
«       d|_
        |S )aÆ  
    **SequenceMask Layer**

    This layer outputs a mask according to the input :code:`x` and
    :code:`maxlen` with data type of :code:`dtype`.

    Supposing :code:`x` is a Tensor with shape [d_1, d_2, ..., d_n], the
    :code:`y` is a mask with shape [d_1, d_2, ..., d_n, maxlen], where:

    .. math::

        y(i_1, i_2,..., i_n, j) = (j < x(i_1, i_2,..., i_n))

    .. code-block:: text

        Case:

        Consider input:
            x = [3, 1, 1, 0]    max_len = 4

        then we get out:
            mask = [[1, 1, 1, 0],
                    [1, 0, 0, 0],
                    [1, 0, 0, 0],
                    [0, 0, 0, 0]]

    Args:
        x (Variable): Input tensor of sequence_mask layer, \
            whose elements are integers less than :code:`maxlen`. \
            Tensor or LodTensor with shape [d_1, d_2, ..., d_n].
        maxlen (int, optional): Maximum length of the sequence. If :code:`maxlen` \
                           is None, it would be replace with :math:`max(x)`.
        dtype (np.dtype|paddle.dtype|str, optional): Data type of the output, \
             ``int64`` by default.
        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, The output sequence mask. Tensor with shape [d_1, d_2, ..., d_n, maxlen] \
            and data type of :code:`dtype`. The data type should be bool, float32, float64, int8, \
            int32 or int64.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> lengths = paddle.to_tensor([10, 9, 8])
            >>> mask = paddle.nn.functional.sequence_mask(lengths)

            >>> print(mask)
            Tensor(shape=[3, 10], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
             [1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
             [1, 1, 1, 1, 1, 1, 1, 1, 0, 0]])

    NÚ	out_dtypeÚmaxlenTÚsequence_mask©ÚdtypeÚXÚMaxLenTensorÚY©ÚtypeÚinputsÚoutputsÚattrs)r    )r   Ú
isinstancer   ÚVarDescÚVarTyper   ÚeagerÚTensorr   r    Ústop_gradientr   ÚlocalsÚ"create_variable_for_type_inferencer"   r   Ú	append_op)Úxr   r"   Únamer*   ÚoutÚhelperr(   s           r   r    r    +   s#  € ôx ÔÜ˜%¤§¡×!5Ñ!5Ô6Ü.¨uÓ5ˆEØÐÜ˜&¤$§*¡*×"3Ñ"3Ô4Ø$ eÐ,�Ü#×1Ñ1°!°VÐD¸eÒD‘à$ e¨X°vÐ>�Ü#×1Ñ1°!°TÐB¸EÒB�Ø $ˆCÔØˆJäÑ5¬F«HÑ5€FØ
×
3Ñ
3¸%Ð
3Ó
@€Cà�A�3ˆZ€FØ˜#Ÿ)™)Ð$€EØÐÜ�fœhÔ'Ø%+ˆF�>Ò"à$ˆE�(‰Oà
×ÑØ V°c¸3°ZÀuð ô ð €CÔØ€Jr   c                 ó’  — | j                   dk7  rt        d«      ‚| j                   |j                   k7  rt        d«      ‚t        «       rt        j                  | |«      S t        di t        «       ¤Ž}t        | dddgd«       t        |dddgd«       |j                  | j                  ¬	«      }|j                  d| |d
œd|i¬«       |S )aÔ	  
    To be used after beam search. After beam search, we get selected ids at
    each time step and the corresponding parents in the search tree. Both ids
    and parents have the layout :attr:`[max_time, batch_size, beam_size]`. Then
    :attr:`gather_tree` is used to backtrace from the last time step and
    generate the full sequences by collecting selected ids.

    Here is an example:

    .. code-block:: text

            Given:
                ids = [[[2 2]
                        [6 1]]
                       [[3 9]
                        [6 1]]
                       [[0 1]
                        [9 0]]]
                parents = [[[0 0]
                            [1 1]]
                           [[1 0]
                            [1 0]]
                           [[0 0]
                            [0 1]]]

            Then:
                gather_tree(ids, parents)
                         = [[[2 2]
                             [1 6]]
                            [[3 3]
                             [6 1]]
                            [[0 1]
                             [9 0]]]

    Args:
        ids(Tensor): A Tensor with shape :attr:`[length, batch_size, beam_size]`
            and data type :attr:`int32` or :attr:`int64`. It contains the selected
            ids of all time steps.
        parents(Tensor): A Tensor with the same shape and data type as :attr:`ids`,
            It contains the parents corresponding to selected ids when searching
            among beams.

    Returns:
            A Tensor with the same shape and data type as :attr:`ids`. \
            It contains the full sequences. The sequences are collected from \
            :attr:`ids` by backtracing according to :attr:`parents`.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> ids = paddle.to_tensor([[[2, 2], [6, 1]], [[3, 9], [6, 1]], [[0, 1], [9, 0]]])

            >>> parents = paddle.to_tensor([[[0, 0], [1, 1]], [[1, 0], [1, 0]], [[0, 0], [0, 1]]])

            >>> final_sequences = paddle.nn.functional.gather_tree(ids, parents)
            >>> [[[2, 2], [1, 6]], [[3, 3], [6, 1]], [[0, 1], [9, 0]]]
            >>> final_sequences = paddle.nn.functional.gather_tree(ids, parents)
            >>> print(final_sequences)
            Tensor(shape=[3, 2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[[2, 2],
              [1, 6]],
             [[3, 3],
              [6, 1]],
             [[0, 1],
              [9, 0]]])


    r   zLThe input ids must be a 3D tensor with shape [length, batch_size, beam_size]z4The ids's shape must be the same as parents' shape. Úgather_treeÚidsÚint32Úint64Úparentsr!   )ÚIdsÚParentsÚOut)r'   r(   r)   )r9   )ÚndimÚ
ValueErrorr   r   r9   r   r1   r
   r2   r"   r3   )r:   r=   r7   r6   s       r   r9   r9   ‡   sÔ   € ðN ‡x�x�1‚}ÜØZó
ð 	
ð ‡x�x�7—<‘<ÒÜÐOÓPÐPäÔÜ×!Ñ! # wÓ/Ð/äÑ7¬f«hÑ7ˆÜ   e¨g°wÐ-?ÀÔOÜ Ø�Y ¨'Ð 2°Mô	
ð ×7Ñ7¸c¿i¹iÐ7ÓHˆà×ÑØØ¨7Ñ3Ø˜C�Lð 	ô 	
ð ˆ
r   c           	      ó¦  — |dvrt        d|› d�«      ‚t        «       rt        j                  | |||«      S t	        di t        «       ¤Ž}t        | dg d¢d«       t        |dt        d«       t        |dt        d«       |j                  | j                  ¬	«      }t        |t        «      st        d
«      ‚|j                  dd| id|i|||dœ¬«       |S )a»  

    **Temporal Shift Operator**

    Calculate the temporal shifting features for Input(X).

    Input(X) should be in shape of [N*T, C, H, W] or [N*T, H, W, C], while
    N is the batch size, T is the temporal segment number specified by
    :attr:`seg_num`, C is the channel number, H and W is the height and
    width of features.

    Temporal Shifting is calculated as follows when data format is NCHW:

    Step 1: Reshape Input(X) to [N, T, C, H, W].

    Step 2: Pad 0 to reshaping result in the 2nd(T) dimension with
    padding width as 1 on each side, padding result will be in shape
    of [N, T+2, C, H, W].

    Step 3: Assume :attr:`shift_ratio` is :math:`1/4`, slice padding
    result as follows:

    $$
    slice1 = x[:, :T, :C/4, :, :]
    $$
    $$
    slice2 = x[:, 2:T+2, C/4:C/2, :, :]
    $$
    $$
    slice3 = x[:, 1:T+1, C/2:, :, :]
    $$

    Step 4: Concatenate three slices along the 3rd(C) dimension and
    reshape result to [N*T, C, H, W].

    For details of temporal shifting, please refer to paper:
    `Temporal Shift Module <http://arxiv.org/abs/1811.08383>`_ .

    Args:
        x(Tensor): ${x_comment}
        seg_num(int): ${seg_num_comment}
        shift_ratio(float): ${shift_ratio_comment}
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
        data_format(str, optional): Data format that specifies the layout of input.
            It can be "NCHW" or "NHWC". Default: "NCHW".

    Returns:
        out(Tensor): The temporal shifting result is a tensor with the
        same shape and same data type as the input.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import paddle.nn.functional as F

            >>> input = paddle.randn([6, 4, 2, 2])
            >>> out = F.temporal_shift(x=input, seg_num=2, shift_ratio=0.2)
    )ÚNCHWÚNHWCzJAttr(data_format) should be 'NCHW' or 'NHWC'. Received Attr(data_format): Ú.Útemporal_shiftr4   )Úfloat16Úuint16Úfloat32Úfloat64Úseg_numÚshift_ratior!   zseg_num must be int type.r#   r@   )rL   rM   Údata_formatr&   )rG   )rB   r   r   rG   r   r1   r
   r	   ÚintÚfloatr2   r"   r+   Ú	TypeErrorr3   )r4   rL   rM   r5   rN   r7   r6   s          r   rG   rG   è   sô   € ð| Ð*Ñ*Üð+Ø+6¨-°qð:ó
ð 	
ô ÔÜ×$Ñ$ Q¨°¸kÓJÐJäÑ:´³Ñ:ˆÜ ØØÚ7Øô		
ô 	�7˜I¤sÐ,<Ô=Ü�; ¬uÐ6FÔGà×7Ñ7¸a¿g¹gÐ7ÓFˆä˜'¤3Ô'ÜÐ7Ó8Ð8à×ÑØ!Ø˜�8Ø˜C�Là"Ø*Ø*ñð	 	ô 		
ð ˆ
r   )r   éþÿÿÿéÿÿÿÿ)Nr<   N)g      Ð?NrD   )Úpaddler   r   r   r   Úpaddle.utilsr   Úbase.data_feederr	   r
   Úbase.layer_helperr   Úcommon_ops_importr   Ú	frameworkr   r   r   Ú__all__r   r    r9   rG   © r   r   Ú<module>r\      sd   ð÷$ BÓ AÝ #ç DÝ ,Ý )÷ñ ð €ñ Ø
Ø!Ø
ØIô	ò8óð8óYòx^ôB_r   