binary.py 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
from paddle import _C_ops
16
from paddle.fluid.framework import dygraph_only, core
17 18 19
from paddle import in_dynamic_mode
from paddle.fluid.layer_helper import LayerHelper
from .unary import cast
20 21 22

__all__ = []

23 24 25 26 27 28 29 30 31
_int_dtype_ = [
    core.VarDesc.VarType.UINT8,
    core.VarDesc.VarType.INT8,
    core.VarDesc.VarType.INT16,
    core.VarDesc.VarType.INT32,
    core.VarDesc.VarType.INT64,
    core.VarDesc.VarType.BOOL,
]

32 33 34 35

@dygraph_only
def matmul(x, y, name=None):
    """
36
    Note:
37
        This API is only supported from ``CUDA 11.0`` .
38

39 40
    Applies matrix multiplication of two Tensors.

41
    The supported input/output Tensor type are as follows:
42

43 44 45 46 47 48 49 50 51
    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.
52
    the shape of `x` should be `[*, M, K]` , and the shape of `y` should be `[*, K, N]` , where `*`
53 54 55
    is zero or more batch dimensions.

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

60
    Returns:
61
        SparseTensor|DenseTensor: Determined by `x` and `y` .
62 63 64 65 66 67 68 69

    Examples:

        .. code-block:: python

            import paddle

            # csr @ dense -> dense
70 71 72 73
            crows = [0, 1, 2, 3]
            cols = [1, 2, 0]
            values = [1., 2., 3.]
            csr = paddle.incubate.sparse.sparse_csr_tensor(crows, cols, values, [3, 3])
74 75 76
            # Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True,
            #        crows=[0, 1, 2, 3],
            #        cols=[1, 2, 0],
77 78 79 80 81 82 83 84 85 86 87 88
            #        values=[1., 2., 3.])
            dense = paddle.ones([3, 2])
            out = paddle.incubate.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.incubate.sparse.sparse_coo_tensor(indices, values, [3, 3])
89
            # Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True,
90
            #        indices=[[0, 1, 2],
91
            #                 [1, 2, 0]],
92 93 94 95 96 97 98
            #        values=[1., 2., 3.])
            dense = paddle.ones([3, 2])
            out = paddle.incubate.sparse.matmul(coo, dense)
            # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[1., 1.],
            #         [2., 2.],
            #         [3., 3.]])
99
    """
100
    return _C_ops.sparse_matmul(x, y)
101 102 103 104 105


@dygraph_only
def masked_matmul(x, y, mask, name=None):
    """
106
    Note:
107
        This API is only supported from ``CUDA 11.3`` .
108

109 110
    Applies matrix multiplication of two Dense Tensors.

111
    The supported input/output Tensor layout are as follows:
112

113 114 115 116 117 118 119 120 121 122 123
    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:
124 125 126
        x (DenseTensor): The input tensor. It is DenseTensor. The data type can be float32 or float64.
        y (DenseTensor): The input tensor. It is DenseTensor. The data type can be float32 or float64.
        mask (SparseTensor): The mask tensor, which can be SparseCooTensor/SparseCsrTensor. It specify sparse coordinates. The data type can be float32 or float64.
127 128 129
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
130
        SparseTensor: SparseCooTensor or SparseCsrTensor, which is same with `mask` .
131 132 133 134 135 136 137 138 139

    Examples:

        .. code-block:: python

            import paddle
            paddle.seed(100)

            # dense @ dense * csr_mask -> csr
140 141 142 143 144 145 146 147 148 149 150 151 152 153
            crows = [0, 2, 3, 5]
            cols = [1, 3, 2, 0, 1]
            values = [1., 2., 3., 4., 5.]
            dense_shape = [3, 4]
            mask = paddle.incubate.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.incubate.sparse.masked_matmul(x, y, mask)
154 155 156
            # 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],
157
            #        values=[0.98986477, 0.97800624, 1.14591956, 0.68561077, 0.94714981])
158 159

    """
160
    return _C_ops.sparse_masked_matmul(x, y, mask)
161 162 163 164 165


@dygraph_only
def mv(x, vec, name=None):
    """
166
    Note:
167 168
        This API is only supported from ``CUDA 11.0`` .

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

171 172 173
    The supported input/output Tensor layout are as follows:

    Note:
174 175
        x[SparseCsrTensor] @ vec[DenseTensor] -> out[DenseTensor]
        x[SparseCooTensor] @ vec[DenseTensor] -> out[DenseTensor]
176 177 178

    It supports backward propagation.

179
    The shape of `x` should be `[M, N]` , and the shape of `vec` should be `[N]` ,
180 181 182
    and the shape of `out` will be `[M]` .

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

187
    Returns:
188
        DenseTensor: 1D DenseTensor whose dtype is same with input.
189 190 191 192

    Examples:

        .. code-block:: python
193

194 195 196 197
            import paddle
            paddle.seed(100)

            # csr @ dense -> dense
198 199 200 201 202 203 204 205 206 207 208 209 210 211
            crows = [0, 2, 3, 5]
            cols = [1, 3, 2, 0, 1]
            values = [1., 2., 3., 4., 5.]
            dense_shape = [3, 4]
            csr = paddle.incubate.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.incubate.sparse.mv(csr, vec)
            # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [-3.85499096, -2.42975140, -1.75087738])
212 213

    """
214
    return _C_ops.sparse_mv(x, vec)
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256


def add(x, y, name=None):
    """
    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
        from paddle.fluid.framework import _test_eager_guard

        paddle.device.set_device("cpu")

        with _test_eager_guard():
            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.incubate.sparse.add(sparse_x, sparse_y)
            print(sparse_z.to_dense())

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

    """
    if y.dtype != x.dtype:
Z
zhangkaihuo 已提交
257
        y = cast(y, None, x.dtype)
258 259 260 261 262 263 264 265 266 267 268 269 270

    if in_dynamic_mode():
        return _C_ops.sparse_add(x, y)
    else:
        op_type = 'sparse_add'
        inputs = {'x': x, 'y': y}
        helper = LayerHelper(op_type)
        out = helper.create_sparse_variable_for_type_inference(x.dtype)
        helper.append_op(type=op_type,
                         inputs=inputs,
                         outputs={'out': out},
                         attrs={})
        return out
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313


@dygraph_only
def subtract(x, y, name=None):
    """
    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
        from paddle.fluid.framework import _test_eager_guard

        paddle.device.set_device("cpu")

        with _test_eager_guard():
            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.incubate.sparse.subtract(sparse_x, sparse_y)
            print(sparse_z.to_dense())

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

    """
    if y.dtype != x.dtype:
314 315
        y = _C_ops.sparse_cast(y, None, x.dtype)
    return _C_ops.sparse_subtract(x, y)
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358


@dygraph_only
def multiply(x, y, name=None):
    """
    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
        from paddle.fluid.framework import _test_eager_guard

        paddle.device.set_device("cpu")

        with _test_eager_guard():
            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.incubate.sparse.multiply(sparse_x, sparse_y)
            print(sparse_z.to_dense())

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

    """
    if isinstance(y, (int, float)):
359
        return _C_ops.sparse_scale(x, float(y), 0.0, True)
360 361
    else:
        if y.dtype != x.dtype:
362 363
            y = _C_ops.sparse_cast(y, None, x.dtype)
        return _C_ops.sparse_multiply(x, y)
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406


@dygraph_only
def divide(x, y, name=None):
    """
    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
        from paddle.fluid.framework import _test_eager_guard

        paddle.device.set_device("cpu")

        with _test_eager_guard():
            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.incubate.sparse.divide(sparse_x, sparse_y)
            print(sparse_z.to_dense())

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

    """
    if x.dtype in _int_dtype_:
407
        x = _C_ops.sparse_cast(x, None, core.VarDesc.VarType.FP32)
408 409

    if isinstance(y, (int, float)):
410
        return _C_ops.sparse_divide_scalar(x, float(y))
411 412
    else:
        if y.dtype != x.dtype:
413 414
            y = _C_ops.sparse_cast(y, None, x.dtype)
        return _C_ops.sparse_divide(x, y)
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447


@dygraph_only
def is_same_shape(x, y):
    """
    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.incubate.sparse.is_same_shape(x, y)
            # True
            paddle.incubate.sparse.is_same_shape(x, z)
            # False

    """
    return x.is_same_shape(y)