
    x-j                    t   d dl mZ d dlmZmZmZmZ d dlmZ d dl	Z	d dl	m
Z
 d dlmZ d dlmZ d dlmZ d d	lmZ d
dlmZ d
dlmZmZmZmZmZ d
dlmZ erd dlmZ d dl	mZ g dZ d Z!e	j"        e	j#        e	j$        e	j%        e	j&        e	j'        e	j(        e	j)        e	j*        e	j+        g
Z,e,\
  Z-Z.Z/Z0Z1Z2Z3Z4Z5Z6e-e/e/e0e1e2e3e4e-e6g
e/e.e/e0e1e2e3e4e.e6g
e/e/e/e0e1e2e3e4e/e6g
e0e0e0e0e1e2e3e4e0e6g
e1e1e1e1e1e2e3e4e1e6g
e2e2e2e2e2e2e3e4e2e3g
e3e3e3e3e3e3e3e4e3e3g
e4e4e4e4e4e4e4e4e4e4g
e-e.e/e0e1e2e3e4e5e6g
e6e6e6e6e6e3e3e4e6e6g
g
Z7d  e8e,          D             Z9 eddhdd          dgd            Z: G d de          Z; edd hd!d"          	 	 dhdd$did+            Z< edd hd,d-          	 	 dhdd$did.            Z=djd0Z> G d1 d2e          Z?dkd8Z@dld9ZAdld:ZB edd hd;d<          dd$dmd?            ZC edd hd@dA          dd$dmdB            ZD G dC dDe          ZEdndodFZF G dG dHe          ZG edd hdIdJ          	 	 	 	 dpdqdN            ZHe	 	 	 	 drdsdU            ZIe	 	 	 	 drdtdX            ZIe	 	 	 	 drdudY            ZIe	 	 	 	 drdvdZ            ZI edd hd[d\          	 	 	 	 dwd^            ZI eh d_d`da          	 dxdydf            ZJdS )z    )annotations)TYPE_CHECKINGAnyLiteral
NamedTuple)overloadN)_C_ops)core)Variable)in_dynamic_mode)ForbidKeywordsDecorator   )nn)disable_torch_proxyenable_torch_proxy"extend_torch_proxy_blocked_modulespaddle_triton_funuse_torch_proxy_guard)_check_out_status)Sequence)Tensor)
equalslogdetsortsplitminmaxuniquemedian	nanmedianseedc                .    | dk    rt                      S d S )Npaddle_triton)r   )names    V/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/paddle/compat/__init__.py__getattr__r&   ;   s!     """     c                t    i | ]5\  }}t          t                    D ]\  }}||ft          |         |         6S  )	enumerate_types_promote_matrix).0it1jt2s        r%   
<dictcomp>r2   [   s_       26""  	2 Hoa #   r'   xyzpaddle.compat.equalzpaddle.equal)illegal_keys	func_namecorrect_nameinputr   otherreturnboolc                   | j         |j         k    r't          j        | |                                          S t                              | j         |j                   }| j         |k    r|                     |          } |j         |k    r|                    |          }t          j        | |                                          S )a  

    ``True`` if two tensors have the same size and elements, ``False`` otherwise.

    Note:
        Tensors containing NaNs are never equal to each other. Additionally, this function does not differentiate between the data types of the tensors during comparison.

    Args:
        input (Tensor): Tensor, data type is bool, float16, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128.
        other (Tensor): Tensor, data type is bool, float16, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128.

    Returns:
        Bool: ``True`` if two tensors have the same size and elements, ``False`` otherwise.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([1, 2, 3])
            >>> y = paddle.to_tensor([1, 3, 2])
            >>> result1 = paddle.compat.equal(x, y)
            >>> print(result1)
            False
    )dtypepaddle	equal_allitemPROMOTE_DICTgetcast)r8   r9   common_dtypes      r%   r   r   b   s    D {ek!!u--22444##EK==L{l""

<(({l""

<((E5))..000r'   c                  $    e Zd ZU ded<   ded<   dS )MedianRetTyper   valuesindicesN__name__
__module____qualname____annotations__r)   r'   r%   rF   rF      "         NNNOOOOOr'   rF   axiszpaddle.compat.medianzpaddle.medianFoutdim
int | NonekeepdimrQ   %tuple[Tensor, Tensor] | Tensor | NoneTensor | MedianRetTypec               D   |Ct          |d           t          j        | ||d          }|t          j        ||           |S |S t          |d           t          j        | ||d|          \  }}|t	          |d         |d         	          S t	          ||	          S )
a+  
    Returns the median of the values in input.

    Args:
        input (Tensor): The input tensor.
        dim (int|None, optional): The dimension to reduce. If None, computes the median over all elements. Default is None.
        keepdim (bool, optional): Whether the output tensor has dim retained or not. Default is False.
        out (Tensor|tuple[Tensor, Tensor], optional): If provided, the result will be written into this tensor.
            For global median (dim=None), out must be a single tensor.
            For median along a dimension (dim specified, including dim=-1), out must be a tuple of two tensors (values, indices).

    Returns:
        Tensor|MedianRetType: If dim is None, returns a single tensor. If dim is specified (including dim=-1),
        returns a named tuple MedianRetType(values: Tensor, indices: Tensor).

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
            >>> result = paddle.compat.median(x)
            >>> print(result)
            Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True, 5)

            >>> ret = paddle.compat.median(x, dim=1)
            >>> print(ret.values)
            Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True, [2, 5, 8])
            >>> print(ret.indices)
            Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True, [1, 1, 1])

            >>> # Using out parameter
            >>> out_values = paddle.zeros([3], dtype='int64')
            >>> out_indices = paddle.zeros([3], dtype='int64')
            >>> paddle.compat.median(x, dim=1, out=(out_values, out_indices))
            >>> print(out_values)
            Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True, [2, 5, 8])
    NFr   rO   rT   modeT)rO   rT   rY   rQ   r   r   rG   rH   )r   r>   r   assignrF   r8   rR   rT   rQ   resultrG   rH   s          r%   r   r      s    d {#u%%%u3eLLL?M&#&&&J#t$$$ -W5c
 
 
 ? AA????FG<<<<r'   zpaddle.compat.nanmedianzpaddle.nanmedianc                  |Ct          |d           t          j        | ||d          }|t          j        ||           |S |S t          |d           t          j        | ||d          \  }}t          j        |t          j        |                    }|St          j        ||d                    t          j        ||d                    t          |d         |d                   S t          ||          S )	a  
    Returns the median of the values in input, ignoring NaN values.

    Args:
        input (Tensor): The input tensor.
        dim (int|None, optional): The dimension to reduce. If None, computes the nanmedian over all elements. Default is None.
        keepdim (bool, optional): Whether the output tensor has dim retained or not. Default is False.
        out (Tensor|tuple[Tensor, Tensor], optional): If provided, the result will be written into this tensor.
            For global nanmedian (dim=None), out must be a single tensor.
            For nanmedian along a dimension (dim specified, including dim=-1), out must be a tuple of two tensors (values, indices).

    Returns:
        Tensor|MedianRetType: The median values, ignoring NaN. If dim is None, returns a single tensor. If dim is specified (including dim=-1),
        returns a named tuple MedianRetType(values: Tensor, indices: Tensor).

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import numpy as np

            >>> x = paddle.to_tensor([[1, float('nan'), 3], [4, 5, 6], [float('nan'), 8, 9]], dtype='float32')
            >>> result = paddle.compat.nanmedian(x)
            >>> print(result)
            Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True, 5.0)

            >>> ret = paddle.compat.nanmedian(x, dim=1)
            >>> print(ret.values)
            Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, [1.0, 5.0, 8.0])
            >>> print(ret.indices)
            Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True, [0, 1, 1])

            >>> # Using out parameter
            >>> out_values = paddle.zeros([3], dtype='float32')
            >>> out_indices = paddle.zeros([3], dtype='int64')
            >>> paddle.compat.nanmedian(x, dim=1, out=(out_values, out_indices))
            >>> print(out_values)
            Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, [1.0, 5.0, 8.0])
    NFr   rX   Tr   r   rZ   )r   r>   r    r[   maximum
zeros_likerF   r\   s          r%   r    r       s   f {#u%%%!%c7OOO?M&#&&&J#t$$$ *W5
 
 

 .&*;G*D*DEE?M&#a&)))M'3q6*** AA????FG<<<<r'   intc                 x    t          j                                                    } t          j        |            | S )aS  Sets the seed for generating random numbers to a non-deterministic
    random number on all devices. Returns a 64 bit number used to seed the RNG.
    Returns:
        Returns: int64, the seed used to seed the RNG.
    Examples:
        .. code-block:: python

            >>> import paddle
            >>> seed = paddle.compat.seed()
    )r
   default_cpu_generatorr!   r>   )r!   s    r%   r!   r!   "  s3     %'',,..D
KKr'   c                  $    e Zd ZU ded<   ded<   dS )MinMaxRetTyper   rG   rH   NrI   r)   r'   r%   re   re   2  rN   r'   re   r6   strargsr   kwargsc                    d fd	fd}d }d}t                    }|t                    z   }|dk    r
             |dk    ro|dk    r\  }}n0|dk    rd         } |d          }n |d	          } |d          }|&t          |t          t          j        j        f          r
             nf|dk    r`|r	d         }nId	v r	d	         }n<d
v r8d
         }t          |t          t          j        j        f          s
             |
             |[t          |t          t          j        j        f          s5t          |          t          ur d  dt          |           d          ||fS )N c                    d D             }|                     d                                 D                        d                    |          }d d|  d| d d d	}t          |          S )
Nc                6    g | ]}t          |          j        S r)   typerJ   )r-   vs     r%   
<listcomp>zO_min_max_param_checker.<locals>.invalid_arguments_exception.<locals>.<listcomp>9  s!    444!T!WW%444r'   c                F    g | ]\  }}| d t          |          j         S )=rm   )r-   kro   s      r%   rp   zO_min_max_param_checker.<locals>.invalid_arguments_exception.<locals>.<listcomp>:  s3    OOO1Q33a!133OOOr'   , z%Invalid arguments for `paddle.compat.z`:
zGot: (paddle.Tensor input, z;), but expect one of:
 - (input: paddle.Tensor) for reduce_zL on all dims.
 - (input: paddle.Tensor, other: paddle.Tensor) -> see paddle.zOimum
 - (input: paddle.Tensor, int dim (cannot be None), bool keepdim = False)
)extenditemsjoin	TypeError)error_prefix	type_strs	signature	error_msgrg   r6   rh   s       r%   invalid_arguments_exceptionz;_min_max_param_checker.<locals>.invalid_arguments_exception8  s    44t444	OOOOOPPPIIi((	[I [ [< [ [*3[ [4=[ [ NW[ [ [ 	 ###r'   c                R    d }	 |          }n# t           $ r              d w xY w|S N)KeyError)keyresr}   rh   s     r%   try_get_keysz,_min_max_param_checker.<locals>.try_get_keysF  sI    	:+CC 	: 	: 	:--//T9	:
s    $F   r   r   rT   rR   r9   zBThe second input must be int or Tensor or implicit None in compat.z, but received z.
)rj   )len
isinstancer   r>   pirValuern   ra   )	r6   rg   rh   r   dim_or_otherrT   num_argstotal_arg_numr}   s	   ```     @r%   _min_max_param_checkerr   7  s<   $ $ $ $ $ $ $ $      LG4yyHs6{{*Mq))+++	!		q==$(!L'']]7L"l9--GG'<..L"l9--G:8VZ%56$
 $
 .-///   
!		 	87LL%e}F""%g!,6:;K0LMM 855777--/// 	 <(FJ4D)EFF 	!c)))) CQZ  C  Ckop|k}k}  C  C  C
 
 	
   r'   c                    | j         }|t          j        k    s0|t          j        k    s |t          j        k    s|t          j        k    r| j        st          d| d          dS dS )z@Prevent integral input tensor type to have `stop_gradient=False`zTensors with integral type: 'z' should stop gradient.N)r=   r>   int32int64uint8int16stop_gradientrx   r8   in_dtypes     r%   _min_max_tensor_allow_gradr   {  sz    {HFL  v|##v|##v|##" 	QQQQ  	 	 $#r'   c                    | j         }|t          j        k    s |t          j        k    s|t          j        k    rt          d| d          dS )zPpaddle.min/argmin(max/argmax), paddle.take_along_axis reject the following typesz*Non-CUDA GPU placed Tensor does not have 'zZ' op registered.
Paddle support following DataTypes: int32, int64, float64, float32, uint8N)r=   r>   float16bfloat16r   rx   r   s     r%   _min_max_allow_cpu_compositer     sd    {HFN""v&&v|##X X X X
 
 	
 $#r'   zpaddle.compat.minz
paddle.min-Tensor | tuple[Tensor, Tensor] | list[Tensor]Tensor | MinMaxRetTypec                  t          | t          j        j        t          j        f          s%t          dt          |           j         d          t          |            t          dg|R i |\  }}d}|&t          |d           t          j        |           }nmt          |t                    r2t          |d           | j        rt                      r| j                                        st#          |            t          j        | |d          }t          j        | ||          }|rt)          ||	          }nt)          |                    |          |                    |          	          }nt-          j        | ||d          \  }	}
d|
_        t)          |	|
	          }n[t)          | t          j        g t          j        | j        
          	          }n%t          |d           t-          j        | |          }|kt          |t(                    rAt          j        |j        |d                    t          j        |j        |d                    nt          j        ||           |S )a  

    Computes the minimum of tensor elements. There are mainly 3 cases (functionalities):

    1. paddle.compat.min(input: Tensor): reduce min over all dims, return a single value Tensor
    2. paddle.compat.min(input: Tensor, dim: int (cannot be None), keepdim=False): reduce min over the given dim,
        returns a named tuple MinMaxRetType(values: Tensor, indices: Tensor)
    3. paddle.compat.min(input: Tensor, other: Tensor): see `paddle.minimum`

    Special warning: the gradient behavior is NOT well-documented by PyTorch, the actual behavior should be:

    1. Case 1: the same as `min`
    2. Case 2: NOT evenly distributing the gradient for equal minimum elements! PyTorch actually only propagates to the elements with indices,
        for example: Tensor([1, 1, 1]) -> min(..., dim=0) -> values=Tensor(0, ...), indices=Tensor(0), the gradient for input tensor won't be
        Tensor([1/3, 1/3, 1/3]) as stated in their documentation, but will be Tensor([1, 0, 0]). This API implements a similar backward kernel.
    3. Case 3: the same as `minimum`

    Args:
        input (Tensor): A tensor, the data type is bfloat16, float16, float32, float64, int32, int64 on GPU.
            uint8, int32, int64, float32, float64 are allowed on CPU.
        dim (int, optional): The dim along which the minimum is computed.
            If this is not specified: see case 1, note that: `None` cannot be passed to this (TypeError will be thrown)
            compute the minimum over all elements of `input` and return a Tensor with a single element,
            otherwise must be in the range :math:`[-input.ndim, input.ndim)`.
            If :math:`dim < 0`, the axis to reduce is :math:`input.ndim + dim`.
            Warning: if `dim` is specified, execute static graph will throw exceptions
            when not on a GPU device, since max_with_index is not implemented for non-GPU devices
        keepdim (bool, optional): Whether to reserve the reduced dimension in the
            output Tensor. The result tensor will have one fewer dimension
            than the `input` unless :attr:`keepdim` is true, default
            value is False. Note that if `dim` does not appear in neither (`*args`) or (`**kwargs`), this parameter cannot be passed alone
        other (Tensor, optional): the other tensor to perform `paddle.minimum` with. This Tensor should
            have the same or broadcast-able shape as the `input`. Note that (`dim` & `keepdim`) and `other` are mutually exclusive
            meaning that trying to composite both will result in TypeError
        out (Tensor|tuple[Tensor, Tensor], optional): the output Tensor or tuple of (Tensor, int64 Tensor) that can be optionally
            given to be used as output buffers. For case 1 and 3 out is just a Tensor, while for case 2 we expect a tuple


    Returns:
        - For case 1. A single value Tensor (0-dim)
        - For case 2. A named tuple MinMaxRetType(values: Tensor, indices: Tensor), `values` has the same data type as the `input`,
            while indices is always an int64 Tensor, with exactly the same shape as `values`.
            MinMaxRetType can be used (indexed, packed, unpacked) in the same way as a regular tuple
        - For case 3. See `paddle.minimum` (:ref:`api_paddle_minimum`)


    Examples:
        .. code-block:: python

            >>> import paddle

            >>> # data_x is a Tensor with shape [2, 4]
            >>> # the axis is a int element
            >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
            ...                       [0.1, 0.2, 0.6, 0.7]],
            ...                       dtype='float64', stop_gradient=False)
            >>> # Case 1: reduce over all dims
            >>> result1 = paddle.compat.min(x)
            >>> result1
            Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=False,
            0.10000000)

            >>> # Case 2: reduce over specified dim
            >>> x.clear_grad()
            >>> result2 = paddle.compat.min(x, dim=1)
            >>> result2
            MinMaxRetType(values=Tensor(shape=[2], dtype=float64, place=Place(gpu:0), stop_gradient=False,
                [0.20000000, 0.10000000]), indices=Tensor(shape=[2], dtype=int64, place=Place(gpu:0), stop_gradient=True,
                [0, 0]))
            >>> result2[0].backward()
            >>> x.grad
            Tensor(shape=[2, 4], dtype=float64, place=Place(gpu:0), stop_gradient=False,
                [[1., 0., 0., 0.],
                 [1., 0., 0., 0.]])

            >>> # Case 3: equivalent to `paddle.minimum`
            >>> x.clear_grad()
            >>> y = paddle.to_tensor([[0.5, 0.4, 0.1, 0.2],
            ...                       [0.3, 0.1, 0.6, 0.7]],
            ...                       dtype='float64', stop_gradient=False)
            >>> result3 = paddle.compat.min(x, y)
            >>> result3
            Tensor(shape=[2, 4], dtype=float64, place=Place(gpu:0), stop_gradient=False,
                [[0.20000000, 0.30000000, 0.10000000, 0.20000000],
                 [0.10000000, 0.10000000, 0.60000000, 0.70000000]])
    9input should be a tensor, but got an instance with type ''r   NFTrO   rT   rO   rZ   r=   devicer   r   )r   r>   r   r   r   rx   rn   rJ   r   r   r   r   ra   ndimr   placeis_gpu_placer   argmintake_along_axisre   squeeze_r	   min_with_indexr   zerosr   minimumr[   rG   rH   r8   rQ   rg   rh   r   rT   retrH   rG   valsindss              r%   r   r     s   B efj.>?? 
_UH\___
 
 	
 u%%%25J4JJJ6JJL'
C#u%%%j	L#	&	& !2#t$$$: 	   ?)A)A)C)C ?,U333 !-L$OOO/7    'vwGGGCC'%LAA ' 0 0l 0 C C  CC
 $2<% 
d &*"#4>>>fl5;    CC 	#u%%%nUL11
c=)) 	$M#*c!f---M#+s1v....M#s###Jr'   zpaddle.compat.maxz
paddle.maxc                  t          | t          j        j        t          j        f          s%t          dt          |           j         d          t          |            t          dg|R i |\  }}d}|&t          |d           t          j        |           }nmt          |t                    r2t          |d           | j        rt                      r| j                                        st#          |            t          j        | |d          }t          j        | ||          }|rt)          ||	          }nt)          |                    |          |                    |          	          }nt-          j        | ||d          \  }	}
d|
_        t)          |	|
	          }n[t)          | t          j        g t          j        | j        
          	          }n%t          |d           t-          j        | |          }|kt          |t(                    rAt          j        |j        |d                    t          j        |j        |d                    nt          j        ||           |S )a  

    Computes the maximum of tensor elements. There are mainly 3 cases (functionalities):

    1. paddle.compat.max(input: Tensor): reduce max over all dims, return a single value Tensor
    2. paddle.compat.max(input: Tensor, dim: int (cannot be None), keepdim=False): reduce max over the given dim,
        returns a named tuple MinMaxRetType(values: Tensor, indices: Tensor)
    3. paddle.compat.max(input: Tensor, other: Tensor): see `paddle.maximum`

    Special warning: the gradient behavior is NOT well-documented by PyTorch, the actual behavior should be:

    1. Case 1: the same as `max`
    2. Case 2: NOT evenly distributing the gradient for equal maximum elements! PyTorch actually only propagates to the elements with indices,
        for example: Tensor([1, 1, 1]) -> max(..., dim=0) -> values=Tensor(0, ...), indices=Tensor(0), the gradient for input tensor won't be
        Tensor([1/3, 1/3, 1/3]) as stated in their documentation, but will be Tensor([1, 0, 0]). This API implements a similar backward kernel.
    3. Case 3: the same as `maximum`

    Args:
        input (Tensor): A tensor, the data type is bfloat16, float16, float32, float64, int32, int64 on GPU.
            uint8, int32, int64, float32, float64 are allowed on CPU.
        dim (int, optional): The dim along which the maximum is computed.
            If this is not specified: see case 1, note that: `None` cannot be passed to this (TypeError will be thrown)
            compute the maximum over all elements of `input` and return a Tensor with a single element,
            otherwise must be in the range :math:`[-input.ndim, input.ndim)`.
            If :math:`dim < 0`, the axis to reduce is :math:`input.ndim + dim`.
            Warning: if `dim` is specified, execute static graph will throw exceptions
            when not on a GPU device, since max_with_index is not implemented for non-GPU devices
        keepdim (bool, optional): Whether to reserve the reduced dimension in the
            output Tensor. The result tensor will have one fewer dimension
            than the `input` unless :attr:`keepdim` is true, default
            value is False. Note that if `dim` does not appear in neither (`*args`) or (`**kwargs`), this parameter cannot be passed alone
        other (Tensor, optional): the other tensor to perform `paddle.maximum` with. This Tensor should
            have the same or broadcast-able shape as the `input`. Note that (`dim` & `keepdim`) and `other` are mutually exclusive
            meaning that trying to composite both will result in TypeError
        out (Tensor|tuple[Tensor, Tensor], optional): the output Tensor or tuple of (Tensor, int64 Tensor) that can be optionally
            given to be used as output buffers. For case 1 and 3 out is just a Tensor, while for case 2 we expect a tuple


    Returns:
        - For case 1. A single value Tensor (0-dim)
        - For case 2. A named tuple MinMaxRetType(values: Tensor, indices: Tensor), `values` has the same data type as the `input`,
            while indices is always an int64 Tensor, with exactly the same shape as `values`.
            MinMaxRetType can be used (indexed, packed, unpacked) in the same way as a regular tuple
        - For case 3. See `paddle.maximum` (:ref:`api_paddle_maximum`)


    Examples:
        .. code-block:: python

            >>> import paddle

            >>> # data_x is a Tensor with shape [2, 4]
            >>> # the axis is a int element
            >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
            ...                       [0.1, 0.2, 0.6, 0.7]],
            ...                       dtype='float64', stop_gradient=False)
            >>> # Case 1: reduce over all dims
            >>> result1 = paddle.compat.max(x)
            >>> result1
            Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=False,
            0.90000000)

            >>> # Case 2: reduce over specified dim
            >>> x.clear_grad()
            >>> result2 = paddle.compat.max(x, dim=1)
            >>> result2
            MinMaxRetType(values=Tensor(shape=[2], dtype=float64, place=Place(gpu:0), stop_gradient=False,
                [0.90000000, 0.70000000]), indices=Tensor(shape=[2], dtype=int64, place=Place(gpu:0), stop_gradient=True,
                [3, 3]))
            >>> result2[0].backward()
            >>> x.grad
            Tensor(shape=[2, 4], dtype=float64, place=Place(gpu:0), stop_gradient=False,
                [[0., 0., 0., 1.],
                 [0., 0., 0., 1.]])

            >>> # Case 3: equivalent to `paddle.maximum`
            >>> x.clear_grad()
            >>> y = paddle.to_tensor([[0.5, 0.4, 0.1, 0.2],
            ...                       [0.3, 0.1, 0.6, 0.7]],
            ...                       dtype='float64', stop_gradient=False)
            >>> result3 = paddle.compat.max(x, y)
            >>> result3
            Tensor(shape=[2, 4], dtype=float64, place=Place(gpu:0), stop_gradient=False,
                [[0.50000000, 0.40000000, 0.50000000, 0.90000000],
                 [0.30000000, 0.20000000, 0.60000000, 0.70000000]])
    r   r   r   NFTr   r   rZ   r   r   r   )r   r>   r   r   r   rx   rn   rJ   r   r   r   r   ra   r   r   r   r   r   argmaxr   re   r   r	   max_with_indexr   r   r   r_   r[   rG   rH   r   s              r%   r   r   2  s   B efj.>?? 
_UH\___
 
 	
 u%%%25J4JJJ6JJL'
C#u%%%j	L#	&	& 2#t$$$: 	   ?)A)A)C)C ?,U333 -L$OOO/7    'vwGGGCC'%LAA ' 0 0l 0 C C  CC
 $2<% 
d &*"#4>>>fl5;    CC 	#u%%%nUL11
c=)) 	$M#*c!f---M#+s1v....M#s###Jr'   c                  $    e Zd ZU ded<   ded<   dS )SlogdetResultr   sign	logabsdetNrI   r)   r'   r%   r   r     s'         LLLr'   r   SlogdetResult | Nonec                    t          j        | |          \  }}|6t          j        ||d                    t          j        ||d                    t	          ||          S )a
  
    (PyTorch Compatible API) Calculates the sign and natural logarithm of the absolute value of a square matrix's or batches square matrices' determinant.
    The determinant can be computed with ``sign * exp`` (logabsdet).

    Supports input of float, double, complex64, complex128.

    Notes:
        1. For matrices that have zero determinant, this returns ``(0, -inf)``.

        2. For matrices with complex value, the :math:`abs(det)` is the modulus of the determinant,
        and therefore :math:`sign = det / abs(det)`.

        3. The return structure of this API has been revised **from a single stacked Tensor of shape `[2, *]` (where index 0 was sign and index 1 was logabsdet) to a tuple of two independent Tensors `(sign, logabsdet)`** (see `PR #72505 <https://github.com/PaddlePaddle/Paddle/pull/72505>`_).
        This modification may cause incompatibility with models previously exported for inference that relied on the old return structure.

    Args:
        x (Tensor): the batch of matrices of size :math:`(*, n, n)`
            where math:`*` is one or more batch dimensions.
        out(SlogdetResult, optional): The tuple of output tensor, contains ``abs`` and ``logabsdet``.

    Returns:
        SlogdetResult: A tuple containing two Tensors: (sign, logabsdet).
        The first Tensor represents the signs of the determinants and the second Tensor
        represents the natural logarithms of the absolute values of the determinants.
        Each output Tensor has a shape of :math:`(*)`, where :math:`*` matches the
        batch dimensions of the input `x`.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> x = paddle.to_tensor([[1., 0.], [0., 1.]])
            >>> A = paddle.compat.slogdet(x)
            >>> print(A.sign)
            Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=True,
                   1.)
            >>> print(A.logabsdet)
            Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=True,
                   0.)
    rP   Nr   r   )r	   
slogdet_v2r>   r[   r   )r3   rQ   r   r   s       r%   r   r     s_    R 's333OD)
dCF###iQ(((y)))r'   c                  $    e Zd ZU ded<   ded<   dS )SortRetTyper   rG   rH   NrI   r)   r'   r%   r   r     rN   r'   r   zpaddle.compat.sortzpaddle.sort
descendingstablec                    t          |d           t          j        | |||          \  }}|6t          j        ||d                    t          j        ||d                    t          ||          S )a5
  

    Sorts the input along the given dimension, and returns the sorted output and indices tensor. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the :attr:`descending` as True.

    Args:
        input (Tensor): An input N-D Tensor with type float32, float64, int16,
            int32, int64, uint8, float16, bfloat16
        dim (int, optional): Dimension to compute indices along. The effective range
            is [-R, R), where R is Rank(x). when dim<0, it works the same way
            as dim+R. Default is -1.
        descending (bool, optional) : Descending is a flag, if set to true,
            algorithm will sort by descending order, else sort by
            ascending order. Default is false.
        stable (bool, optional): Whether to use stable sorting algorithm or not.
            When using stable sorting algorithm, the order of equivalent elements
            will be preserved. Default is False.
        out (tuple, optional) : the output tuple/list of (Tensor, Tensor) that
            can be optionally given to be used as output buffers

    Returns:
        SortRetType, a named tuple which contains `values` and `indices`, can be accessed through either indexing
        (e.g. `result[0]` for values and `result[1]` for indices), or by `result.values` & `result.indices`

    Examples:

    .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[5,8,9,5],
            ...                       [0,0,1,7],
            ...                       [6,9,2,4]],
            ...                      dtype='float32')
            >>> out1 = paddle.compat.sort(input=x, dim=-1)
            >>> out2 = paddle.compat.sort(x, 1, descending=True)
            >>> out1
            SortRetType(values=Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
                   [[5., 5., 8., 9.],
                    [0., 0., 1., 7.],
                    [2., 4., 6., 9.]]), indices=Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
                   [[0, 3, 1, 2],
                    [0, 1, 2, 3],
                    [2, 3, 0, 1]]))
            >>> out2
            SortRetType(values=Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
                   [[9., 8., 5., 5.],
                    [7., 1., 0., 0.],
                    [9., 6., 4., 2.]]), indices=Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
                   [[2, 1, 0, 3],
                    [3, 2, 0, 1],
                    [1, 0, 3, 2]]))
    T)expect_multipleNr   r   rZ   )r   r	   argsortr>   r[   r   )r8   rR   r   r   rQ   outputsrH   s          r%   r   r     sv    @ c40000~eS*fEEGW
gs1v&&&gs1v&&&gw7777r'   .sortedreturn_inverseLiteral[True]return_countstuple[Tensor, Tensor, Tensor]c                    d S r   r)   r8   r   r   r   rR   s        r%   r   r   K  s	     %(Cr'   Literal[False]tuple[Tensor, Tensor]c                    d S r   r)   r   s        r%   r   r   U  	      Cr'   c                    d S r   r)   r   s        r%   r   r   _  r   r'   c                    d S r   r)   r   s        r%   r   r   i  s	     Sr'   zpaddle.compat.uniquezpaddle.uniqueTc                4    t          j        | ||||          S )a.  
    Returns the unique elements of `input` in ascending order.

    Args:
        input(Tensor): The input tensor, it's data type should be float32, float64, int32, int64.
        sorted(bool, optional): Does not affect the return result, same as PyTorch.
        return_inverse(bool, optional): If True, also return the indices for where elements in
            the original input ended up in the returned unique tensor.
        return_counts(bool, optional): If True, also return the counts for each unique element.
        dim(int, optional): The axis to apply unique. If None, the input will be flattened.
            Default: None.

    Returns:
        tuple (output, inverse_indices, counts). `output` is the unique tensor for `input`. \
            `inverse_indices` is provided only if `return_inverse` \
            is True. `counts` is provided only if `return_counts` is True.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([2, 3, 3, 1, 5, 3])
            >>> unique = paddle.compat.unique(x)
            >>> print(unique)
            Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [1, 2, 3, 5])

            >>> _, inverse_indices, counts = paddle.compat.unique(x, return_inverse=True, return_counts=True)
            >>> print(inverse_indices)
            Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
            [1, 2, 2, 0, 3, 2])
            >>> print(counts)
            Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [1, 1, 3, 1])

            >>> x = paddle.to_tensor([[2, 1, 3], [3, 0, 1], [2, 1, 3]])
            >>> unique = paddle.compat.unique(x)
            >>> print(unique)
            Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [0, 1, 2, 3])

            >>> unique = paddle.compat.unique(x, dim=0)
            >>> print(unique)
            Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[2, 1, 3],
             [3, 0, 1]])
    )r   r   rO   r   )r>   r   r   s        r%   r   r   s  s-    x =%#   r'   >   r3   rO   r$   num_or_sectionszpaddle.compat.splitzpaddle.splittensorsplit_size_or_sectionsint | Sequence[int]tuple[Tensor, ...]c                	   fd}dd}t          t          t          f          rlt                    D ]\\  }}d}t          |t                    r#t          |                    d                    }n|}|dk     rt          d| d|           ]t                      rt          |t                    r|                    d          }|t          | j
                  z   dk    s
J d	            |dk     r|t          | j
                  z   n|}t          t          t          f          rgt          j                                      rGt                    D ]7\  }}	t          |	t                    r|                                         |<   8n5t          t
                    s t          d
t                     d          t          t
                    rdk    s
J d             | || j
        |                    t          t                    r#t          t!          j        | |                    S t          t!          j        | |                    S t          t!          j        | |                    S t          |t          j        j                  rt          d          t          |t
                    rDt          | j
                  |z   dk    s
J d	            |dk     rt          | j
                  |z   n|}| j
        }
t          t
          t          t          f          st          d          t          t
                    rĉdk    s
J d             | || j
        |                    t          t                    rat          j                                      rt          j                                      t          t!          j        | |                    S t          t!          j        | |                    S t          |t
                    r/|
|         dk    r#t                    |
|         k    s
J d            t          j                                      rt          j                                      t          t!          j        | |                    S )a
  
    (PyTorch Compatible API) Split the input tensor into multiple sub-Tensors.

    Args:
        tensor (Tensor): A N-D Tensor. The data type is bool, bfloat16, float16, float32, float64, uint8, int8, int32 or int64.
        split_size_or_sections (int|list|tuple):
            If split_size_or_sections is an integer type, then tensor will be split into equally sized chunks (if possible).
            Last chunk will be smaller if the tensor size along the given dimension dim is not divisible by split_size.
            If split_size_or_sections is a list, then tensor will be split into len(split_size_or_sections) chunks with sizes
            in dim according to split_size_or_sections. Negative inputs are not allowed. For example: for a dim with 9 channels,
            [2, 3, -1] will not be interpreted as [2, 3, 4], but will be rejected and an exception will be thrown.
        dim (int|Tensor, optional): The dim along which to split, it can be a integer or a ``0-D Tensor``
            with shape [] and data type  ``int32`` or ``int64``.
            If :math::`dim < 0`, the dim to split along is :math:`rank(x) + dim`. Default is 0.
    Returns:
        tuple(Tensor), The tuple of segmented Tensors.

    Note:
        This is a pytorch compatible API that follows the function signature and behavior of torch.split.
        To use the original split of paddle, please consider `paddle.split`

    Examples:

        .. code-block:: pycon

            >>> import paddle

            >>> # x is a Tensor of shape [3, 8, 5]
            >>> x = paddle.rand([3, 8, 5])

            >>> out0, out1, out2 = paddle.compat.split(x, split_size_or_sections=3, dim=1)
            >>> print(out0.shape)
            paddle.Size([3, 3, 5])
            >>> print(out1.shape)
            paddle.Size([3, 3, 5])
            >>> print(out2.shape)
            paddle.Size([3, 2, 5])

            >>> out0, out1, out2 = paddle.compat.split(x, split_size_or_sections=[1, 2, 5], dim=1)
            >>> print(out0.shape)
            paddle.Size([3, 1, 5])
            >>> print(out1.shape)
            paddle.Size([3, 2, 5])
            >>> print(out2.shape)
            paddle.Size([3, 5, 5])

            >>> # dim is negative, the real dim is (rank(x) + dim)=1
            >>> out0, out1, out2 = paddle.compat.split(x, split_size_or_sections=3, dim=-2)
            >>> print(out0.shape)
            paddle.Size([3, 3, 5])
            >>> print(out1.shape)
            paddle.Size([3, 3, 5])
            >>> print(out2.shape)
            paddle.Size([3, 2, 5])
    c                    |z  }|z  }|dk    r|S fdt          |          D             }|                    |           |S )Nr   c                    g | ]}S r)   r)   )r-   _r   s     r%   rp   z/split.<locals>.GetSplitSize.<locals>.<listcomp>  s'       +,&  r'   )rangeappend)
split_sizeshape_on_dimremaining_numnum_complete_sectionsectionsr   s        r%   GetSplitSizezsplit.<locals>.GetSplitSize  su    $'==+/EEA''   056J0K0K  H OOM***Or'   rR   ra   r:   c                    t          |           }t          |t                    r%|| k     s||k    rt          d| d| d|           | |         S )Nz:(InvalidArgument) The dim is expected to be in range of [-rt   z), but got )r   r   ra   
ValueError)shaperR   shape_ranges      r%   GetShapeOnDimInRangez#split.<locals>.GetShapeOnDimInRange  sr    %jjc3 	k\!!SK%7%7 }Q\}}`k}}x{}}   Szr'   r   zWpaddle.compat.split expects split_sizes have only non-negative entries, but got size = z on dim z(rank(x) + dim) must >= 0zjThe type of 'split_size_or_sections' in split must be int, list or tuple in imperative mode, but received .z.split_size_or_sections must be greater than 0.zv'dim' is not allowed to be a pir.Value in a static graph: 
pir.Value can not be used for indexing python lists/tuples.z\The type of 'split_size_or_sections' in split must be int, list or tuple in imperative mode.zClen(split_size_or_sections) must not be more than input.shape[dim].N)rR   ra   r:   ra   )r   listtupler*   r   ra   r@   r   r   r   r   r>   utils_contain_varrx   rn   r	   r   split_with_numr   r   get_int_tensor_list)r   r   rR   r   r   r.   section_size	shape_valindexr@   input_shapes    `         r%   r   r     sK   @
 
 
 
 
    (4-88 
()?@@ 		 		OA|I,11 ) 1 1! 4 455		(	a  Hnz  H  H  EF  H  H    
  PLc8$$ 	((1++CS&&&!+++-H++++.77sS&&&&,tUm<< 	|(()?@@ !#,-C#D#D ! !KE4!$11 !8N!9$&& /u5 2C88 	< !788< < <  
 ,c22 	L)A---@ .-- &2\&(<(<V\3(O(O& &" 0$77 V\&2H#NNOOO)&2H#NN   f.DcJJKKKc6:+,, 	P   c3 	@v|$$s*a///1L////2Qww3v|$$s**CCl03e2DEE 	n   ,c22 	L)A---@ .-- &2\&(<(<V\3(O(O& &" 0$77 	<,,-CDD -3\-M-M.. .* V\&2H#NNOOO)&2H#NN   #s## C(81(<(<122k#6FFFFY GFF |(()?@@ )/)I)I** *& f.DcJJKKKr'   )r8   r   r9   r   r:   r;   )NF)
r8   r   rR   rS   rT   r;   rQ   rU   r:   rV   )r:   ra   )r6   rf   rg   r   rh   r   )r8   r   )
r8   r   rg   r   rQ   r   rh   r   r:   r   r   )r3   r   rQ   r   r:   r   )r   FFN)
r8   r   rR   ra   r   r;   r   r;   r:   r   )....)r8   r   r   r;   r   r   r   r   rR   rS   r:   r   )r8   r   r   r;   r   r   r   r   rR   rS   r:   r   )r8   r   r   r;   r   r   r   r   rR   rS   r:   r   )r8   r   r   r;   r   r   r   r   rR   rS   r:   r   )TFFN)r   )r   r   r   r   rR   ra   r:   r   )K
__future__r   typingr   r   r   r   typing_extensionsr   r>   r	   paddle.baser
   paddle.base.frameworkr   paddle.frameworkr   paddle.utils.decorator_utilsr   rj   r   proxyr   r   r   r   r   r   r   collections.abcr   r   __all__r&   r   int8r   r   r   r   float32float64r;   r   r+   u1i1i2i4i8f2f4f8b1bfr,   r*   rA   r   rF   r   r    r!   re   r   r   r   r   r   r   r   r   r   r   r   r)   r'   r%   <module>r	     s   # " " " " " : : : : : : : : : : : : & & & & & &              * * * * * *      A @ @ @ @ @                    % $ $ $ $ $ ((((((  # # # L
K
L
L
L
N
N
N
K
O
 *0 &BBBBB RRRR,RRRR,RRRR,RRRR,RRRR,RRRR,RRRR,RRRR,RRRR,RRRR, 6""   s#  
&1 &1 &1 
&1R    J   
 v$    ;=
 26;= ;= ;= ;= ;= 
;=| v'#   B=
 26B= B= B= B= B= 
B=J        J   
A! A! A! A!H   
 
 
 
 v!   :>R R R R R 
Rj v!   :>O O O O O 
Od    J   
-* -* -* -* -*`    *   
 v"   @8 @8 @8 @8 
@8F 
 $'#&( ( ( ( 
( 
 %(#&        
  
 $'$'        
  
 %($'    
 v$    = = = 
=@ 999#   MNlL lL lL lL 
lL lL lLr'   