o
    QeÂ>  ã                   @   sê   d dl mZmZ d dlmZmZ d dl mZ d dlmZ ddl	m
Z
 g ZejjjejjjejjjejjjejjjejjjgZeddd	„ƒZedd
d„ƒZeddd„ƒZddd„Zeddd„ƒZeddd„ƒZeddd„ƒZedd„ ƒZdS )é    )Ú_C_opsÚ_legacy_C_ops)Údygraph_onlyÚcore)Úin_dynamic_mode)ÚLayerHelperé   )ÚcastNc                 C   ó   t  | |¡S )a¦
  
    Note:
        This API is only supported from ``CUDA 11.0`` .

    Applies matrix multiplication of two Tensors.

    The supported input/output Tensor layout are as follows:

    Note:
        x[SparseCsrTensor] @ y[SparseCsrTensor] -> out[SparseCsrTensor]
        x[SparseCsrTensor] @ y[DenseTensor] -> out[DenseTensor]
        x[SparseCooTensor] @ y[SparseCooTensor] -> out[SparseCooTensor]
        x[SparseCooTensor] @ y[DenseTensor] -> out[DenseTensor]

    It supports backward propagation.

    Dimensions `x` and `y` must be >= 2D. Automatic broadcasting of Tensor is not supported.
    the shape of `x` should be `[*, M, K]` , and the shape of `y` should be `[*, K, N]` , where `*`
    is zero or more batch dimensions.

    Args:
        x (Tensor): The input tensor. It can be SparseCooTensor/SparseCsrTensor. The data type can be float32 or float64.
        y (Tensor): The input tensor. It can be SparseCooTensor/SparseCsrTensor/DenseTensor. The data type can be float32 or float64.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: Its layout is determined by that of `x` and `y` .

    Examples:

        .. code-block:: python

            # required: gpu
            import paddle

            # csr @ dense -> dense
            crows = [0, 1, 2, 3]
            cols = [1, 2, 0]
            values = [1., 2., 3.]
            csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, [3, 3])
            # Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True,
            #        crows=[0, 1, 2, 3],
            #        cols=[1, 2, 0],
            #        values=[1., 2., 3.])
            dense = paddle.ones([3, 2])
            out = paddle.sparse.matmul(csr, dense)
            # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[1., 1.],
            #         [2., 2.],
            #         [3., 3.]])

            # coo @ dense -> dense
            indices = [[0, 1, 2], [1, 2, 0]]
            values = [1., 2., 3.]
            coo = paddle.sparse.sparse_coo_tensor(indices, values, [3, 3])
            # Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True,
            #        indices=[[0, 1, 2],
            #                 [1, 2, 0]],
            #        values=[1., 2., 3.])
            dense = paddle.ones([3, 2])
            out = paddle.sparse.matmul(coo, dense)
            # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[1., 1.],
            #         [2., 2.],
            #         [3., 3.]])
    )r   Zsparse_matmul©ÚxÚyÚname© r   úDD:\Projects\ConvertPro\env\Lib\site-packages\paddle/sparse/binary.pyÚmatmul!   s   Dr   c                 C   s   t  | ||¡S )a!	  
    Note:
        This API is only supported from ``CUDA 11.3`` .

    Applies matrix multiplication of two Dense Tensors.

    The supported input/output Tensor layout are as follows:

    Note:
        x[DenseTensor] @ y[DenseTensor] * mask[SparseCooTensor] -> out[SparseCooTensor]
        x[DenseTensor] @ y[DenseTensor] * mask[SparseCsrTensor] -> out[SparseCsrTensor]

    It supports backward propagation.

    Dimensions `x` and `y` must be  >= 2D. Automatic broadcasting of Tensor is not supported.
    the shape of `x` should be `[*, M, K]` , and the shape of `y` should be `[*, K, N]` , and the shape of `mask` should be `[*, M, N]` ,
    where `*` is zero or more batch dimensions.

    Args:
        x (Tensor): The input tensor. It is DenseTensor. The data type can be float32 or float64.
        y (Tensor): The input tensor. It is DenseTensor. The data type can be float32 or float64.
        mask (Tensor): The mask tensor, which can be SparseCooTensor/SparseCsrTensor. It specify sparse coordinates. The data type can be float32 or float64.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: SparseCoo or SparseCsr, which is determined by that of `mask` .

    Examples:

        .. code-block:: python

            # required: gpu
            import paddle
            paddle.seed(100)

            # dense @ dense * csr_mask -> csr
            crows = [0, 2, 3, 5]
            cols = [1, 3, 2, 0, 1]
            values = [1., 2., 3., 4., 5.]
            dense_shape = [3, 4]
            mask = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
            # Tensor(shape=[3, 4], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True,
            #       crows=[0, 2, 3, 5],
            #       cols=[1, 3, 2, 0, 1],
            #       values=[1., 2., 3., 4., 5.])

            x = paddle.rand([3, 5])
            y = paddle.rand([5, 4])

            out = paddle.sparse.masked_matmul(x, y, mask)
            # Tensor(shape=[3, 4], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True,
            #        crows=[0, 2, 3, 5],
            #        cols=[1, 3, 2, 0, 1],
            #        values=[0.98986477, 0.97800624, 1.14591956, 0.68561077, 0.94714981])

    )r   Zsparse_masked_matmul)r   r   Úmaskr   r   r   r   Úmasked_matmulh   s   :r   c                 C   r
   )a³  
    Note:
        This API is only supported from ``CUDA 11.0`` .

    Applies matrix-vector product of Sparse Matrix 'x' and Dense vector 'vec' .

    The supported input/output Tensor layout are as follows:

    Note:
        x[SparseCsrTensor] @ y[DenseTensor] -> out[SparseCsrTensor]
        x[SparseCooTensor] @ y[DenseTensor] -> out[SparseCooTensor]

    It supports backward propagation.

    The shape of `x` should be `[M, N]` , and the shape of `y` should be `[N]` ,
    and the shape of `out` will be `[M]` .

    Args:
        x (Tensor): The input 2D tensor. It must be SparseCooTensor/SparseCsrTensor. The data type can be float32 or float64.
        y (Tensor): The input 1D tensor. It must be DenseTensor vector. The data type can be float32 or float64.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: 1D Tensor.

    Examples:

        .. code-block:: python

            # required: gpu
            import paddle
            from paddle.fluid.framework import _test_eager_guard
            paddle.seed(100)

            # csr @ dense -> dense
            with _test_eager_guard():
                crows = [0, 2, 3, 5]
                cols = [1, 3, 2, 0, 1]
                values = [1., 2., 3., 4., 5.]
                dense_shape = [3, 4]
                csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
                # Tensor(shape=[3, 4], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True,
                #        crows=[0, 2, 3, 5],
                #        cols=[1, 3, 2, 0, 1],
                #        values=[1., 2., 3., 4., 5.])
                vec = paddle.randn([4])

                out = paddle.sparse.mv(csr, vec)
                # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
                #        [-3.85499096, -2.42975140, -1.75087738])

    )r   Z	sparse_mv)r   Zvecr   r   r   r   Úmv¥   s   6r   c                 C   sh   |j | j krt|d| j ƒ}tƒ rt | |¡S d}| |dœ}t|ƒ}| | j ¡}|j||d|ii d� |S )uÈ  
    Add two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse
    typeï¼ˆSparseCooTensor or SparseCsrTensorï¼‰.If input is SparseCooTensor, x and y's sparse_dim should be identical.
    The equation is:

    .. math::
        out = x + y

    Args:
        x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: the result tensor.

    Examples:

    ..  code-block:: python

        import paddle

        paddle.device.set_device("cpu")

        x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32')
        y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32')
        sparse_x = x.to_sparse_csr()
        sparse_y = y.to_sparse_csr()
        sparse_z = paddle.sparse.add(sparse_x, sparse_y)
        print(sparse_z.to_dense())

        # [[ 0., -1.,  0.,  0.],
        # [ 0.,  2., -6.,  0.],
        # [ 6.,  8.,  4.,  8.]]

    NÚ
sparse_add©r   r   Úout)ÚtypeÚinputsZoutputsÚattrs)Údtyper	   r   r   r   r   Z)create_sparse_variable_for_type_inferenceZ	append_op)r   r   r   Zop_typer   Úhelperr   r   r   r   ÚaddÞ   s   %
ÿr   c                 C   s(   |j | j krt |d| j ¡}t | |¡S )uÒ  
    Subtract two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse
    typeï¼ˆSparseCooTensor or SparseCsrTensorï¼‰.If input is SparseCooTensor, x and y's sparse_dim should be identical.
    The equation is:

    .. math::
        out = x - y

    Args:
        x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: the result tensor.

    Examples:

    ..  code-block:: python

        import paddle

        paddle.device.set_device("cpu")

        x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32')
        y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32')
        sparse_x = x.to_sparse_csr()
        sparse_y = y.to_sparse_csr()
        sparse_z = paddle.sparse.subtract(sparse_x, sparse_y)
        print(sparse_z.to_dense())

        # [[ 0., -1.,  0.,  4.],
        # [ 0., -2.,  0.,  0.],
        # [ 2.,  2., -4., -8.]]

    N)r   r   Úsparse_castZsparse_subtractr   r   r   r   Úsubtract  s   &r   c                 C   sJ   t |ttfƒrt | t|ƒdd¡S |j| jkrt |d| j¡}t | |¡S )uÒ  
    Multiply two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse
    typeï¼ˆSparseCooTensor or SparseCsrTensorï¼‰.If input is SparseCooTensor, x and y's sparse_dim should be identical.
    The equation is:

    .. math::
        out = x * y

    Args:
        x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: the result tensor.

    Examples:

    ..  code-block:: python

        import paddle

        paddle.device.set_device("cpu")

        x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32')
        y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32')
        sparse_x = x.to_sparse_csr()
        sparse_y = y.to_sparse_csr()
        sparse_z = paddle.sparse.multiply(sparse_x, sparse_y)
        print(sparse_z.to_dense())

        # [[ 0.,  0.,  0., -4.],
        # [ 0.,  0.,  9.,  0.],
        # [ 8., 15.,  0.,  0.]]

    g        TN)Ú
isinstanceÚintÚfloatr   Zsparse_scaler   r   Zsparse_multiplyr   r   r   r   Úmultiply>  s
   &r#   c                 C   sd   | j tv rt | dtjjj¡} t|t	t
fƒrt | t
|ƒ¡S |j | j kr,t |d| j ¡}t | |¡S )u"  
    Divide two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse
    typeï¼ˆSparseCooTensor or SparseCsrTensorï¼‰.If input is SparseCooTensor, x and y's sparse_dim should be identical.
    The equation is:

    .. math::
        out = x / y

    Args:
        x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: the result tensor.

    Examples:

    ..  code-block:: python

        import paddle

        paddle.device.set_device("cpu")

        x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32')
        y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32')
        sparse_x = x.to_sparse_csr()
        sparse_y = y.to_sparse_csr()
        sparse_z = paddle.sparse.divide(sparse_x, sparse_y)
        print(sparse_z.to_dense())

        # [[ nan      , -inf.     ,  nan      , -1.       ],
        # [ nan      ,  0.       ,  1.       ,  nan      ],
        # [ 2.       , 1.66666663,  0.       ,  0.       ]]

    N)r   Ú_int_dtype_r   r   r   ÚVarDescÚVarTypeZFP32r    r!   r"   Zsparse_divide_scalarZsparse_divider   r   r   r   Údividel  s   
&r'   c                 C   s
   |   |¡S )a>  
    Return the results of shape comparison between two Tensors, check whether x.shape equal to y.shape.
    Any two type Tensor among DenseTensor/SparseCooTensor/SparseCsrTensor are supported.

    Args:
        x (Tensor): The input tensor. It can be DenseTensor/SparseCooTensor/SparseCsrTensor.
        y (Tensor): The input tensor. It can be DenseTensor/SparseCooTensor/SparseCsrTensor.

    Returns:
        bool: True for same shape and False for different shape.

    Examples:

        .. code-block:: python

            import paddle

            x = paddle.rand([2, 3, 8])
            y = paddle.rand([2, 3, 8])
            y = y.to_sparse_csr()
            z = paddle.rand([2, 5])

            paddle.sparse.is_same_shape(x, y)
            # True
            paddle.sparse.is_same_shape(x, z)
            # False

    )Úis_same_shaper   r   r   r   r(   �  s   
r(   )N)Zpaddler   r   Zpaddle.fluid.frameworkr   r   r   Zpaddle.fluid.layer_helperr   Zunaryr	   Ú__all__r%   r&   ZUINT8ZINT8ZINT16ZINT32ZINT64ÚBOOLr$   r   r   r   r   r   r#   r'   r(   r   r   r   r   Ú<module>   s8   ú
F<
85*-0