send_recv.py 18.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   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.

import numpy as np
from paddle.fluid.layer_helper import LayerHelper
17 18 19 20 21
from paddle.fluid.framework import (
    _non_static_mode,
    _in_legacy_dygraph,
    in_dygraph_mode,
)
22
from paddle.fluid.framework import Variable
23 24 25 26 27 28
from paddle.fluid.data_feeder import (
    check_variable_and_dtype,
    check_type,
    check_dtype,
    convert_dtype,
)
29
from paddle import _C_ops, _legacy_C_ops
30

31 32 33 34 35
from .utils import (
    convert_out_size_to_list,
    get_out_size_tensor_inputs,
    reshape_lhs_rhs,
)
36

37 38
__all__ = []

39

40 41 42
def send_u_recv(
    x, src_index, dst_index, reduce_op="sum", out_size=None, name=None
):
43 44 45
    """
    Graph Learning message passing api.

46
    This api is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory
47
    consumption in the process of message passing. Take `x` as the input tensor, we first use `src_index`
48
    to gather the corresponding data, and then use `dst_index` to update the corresponding position of output tensor
49
    in different reduce ops, like sum, mean, max, or min. Besides, we can use `out_size` to set necessary output shape.
50 51 52 53 54

    .. code-block:: text

           Given:

55
           x = [[0, 2, 3],
56 57 58 59 60 61 62
                [1, 4, 5],
                [2, 6, 7]]

           src_index = [0, 1, 2, 0]

           dst_index = [1, 2, 1, 0]

63
           reduce_op = "sum"
64 65 66 67 68

           out_size = None

           Then:

69
           out = [[0, 2, 3],
70 71 72 73 74
                  [2, 8, 10],
                  [1, 4, 5]]

    Args:
        x (Tensor): The input tensor, and the available data type is float32, float64, int32, int64.
75
                    And we support float16 in gpu version.
76
        src_index (Tensor): An 1-D tensor, and the available data type is int32, int64.
77 78
        dst_index (Tensor): An 1-D tensor, and should have the same shape as `src_index`.
                            The available data type is int32, int64.
79
        reduce_op (str): Different reduce ops, including `sum`, `mean`, `max`, `min`.
80
                         Default value is `sum`.
81
        out_size (int|Tensor|None): We can set `out_size` to get necessary output shape. If not set or
82
                                    out_size is smaller or equal to 0, then this input will not be used.
83
                                    Otherwise, `out_size` should be equal with or larger than
84 85 86 87 88
                                    max(dst_index) + 1.
        name (str, optional): Name for the operation (optional, default is None).
                              For more information, please refer to :ref:`api_guide_Name`.

    Returns:
89 90
        - out (Tensor), the output tensor, should have the same shape and same dtype as input tensor `x`.
          If `out_size` is set correctly, then it should have the same shape as `x` except the 0th dimension.
91 92 93 94 95 96 97 98

    Examples:
        .. code-block:: python

            import paddle

            x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32")
            indexes = paddle.to_tensor([[0, 1], [1, 2], [2, 1], [0, 0]], dtype="int32")
99
            src_index, dst_index = indexes[:, 0], indexes[:, 1]
100
            out = paddle.geometric.send_u_recv(x, src_index, dst_index, reduce_op="sum")
101 102 103 104
            # Outputs: [[0., 2., 3.], [2., 8., 10.], [1., 4., 5.]]

            x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32")
            indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32")
105
            src_index, dst_index = indexes[:, 0], indexes[:, 1]
106
            out_size = paddle.max(dst_index) + 1
107
            out = paddle.geometric.send_u_recv(x, src_index, dst_index, reduce_op="sum", out_size=out_size)
108 109 110 111
            # Outputs: [[0., 2., 3.], [[2., 8., 10.]]]

            x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32")
            indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32")
112
            src_index, dst_index = indexes[:, 0], indexes[:, 1]
113
            out = paddle.geometric.send_u_recv(x, src_index, dst_index, reduce_op="sum")
114 115 116 117
            # Outputs: [[0., 2., 3.], [2., 8., 10.], [0., 0., 0.]]

    """

118
    if reduce_op not in ["sum", "mean", "max", "min"]:
119
        raise ValueError(
120
            "reduce_op should be `sum`, `mean`, `max` or `min`, but received %s"
121 122
            % reduce_op
        )
123 124 125 126 127

    # TODO(daisiming): Should we add judgement for out_size: max(dst_index) + 1.

    if _in_legacy_dygraph():
        out_size = convert_out_size_to_list(out_size)
128 129 130 131 132 133 134 135 136 137
        out, tmp = _legacy_C_ops.graph_send_recv(
            x,
            src_index,
            dst_index,
            None,
            'reduce_op',
            reduce_op.upper(),
            'out_size',
            out_size,
        )
138 139 140
        return out
    if in_dygraph_mode():
        out_size = convert_out_size_to_list(out_size)
141 142 143
        return _C_ops.graph_send_recv(
            x, src_index, dst_index, reduce_op.upper(), out_size
        )
144

145
    check_variable_and_dtype(
146 147 148 149 150 151 152 153 154 155 156
        x,
        "X",
        ("float32", "float64", "int32", "int64", "float16"),
        "graph_send_recv",
    )
    check_variable_and_dtype(
        src_index, "Src_index", ("int32", "int64"), "graph_send_recv"
    )
    check_variable_and_dtype(
        dst_index, "Dst_index", ("int32", "int64"), "graph_send_recv"
    )
157
    if out_size:
158 159 160 161 162 163
        check_type(
            out_size,
            'out_size',
            (int, np.int32, np.int64, Variable),
            'graph_send_recv',
        )
164
    if isinstance(out_size, Variable):
165 166 167
        check_dtype(
            out_size.dtype, 'out_size', ['int32', 'int64'], 'graph_send_recv'
        )
168 169 170

    helper = LayerHelper("send_u_recv", **locals())
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
171 172 173
    dst_count = helper.create_variable_for_type_inference(
        dtype="int32", stop_gradient=True
    )
174 175

    inputs = {"X": x, "Src_index": src_index, "Dst_index": dst_index}
176
    attrs = {"reduce_op": reduce_op.upper()}
177 178 179 180 181 182 183 184 185 186
    get_out_size_tensor_inputs(
        inputs=inputs, attrs=attrs, out_size=out_size, op_type='graph_send_recv'
    )

    helper.append_op(
        type="graph_send_recv",
        inputs=inputs,
        outputs={"Out": out, "Dst_count": dst_count},
        attrs=attrs,
    )
187
    return out
188 189


190 191 192 193 194 195 196 197 198 199
def send_ue_recv(
    x,
    y,
    src_index,
    dst_index,
    message_op="add",
    reduce_op="sum",
    out_size=None,
    name=None,
):
200 201 202 203
    """

    Graph Learning message passing api.

204
    This api is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory
205
    consumption in the process of message passing. Take `x` as the input tensor, we first use `src_index`
206 207
    to gather the corresponding data, after computing with `y` in different message ops like add/sub/mul/div, then use `dst_index` to
    update the corresponding position of output tensor in different reduce ops, like sum, mean, max, or min.
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    Besides, we can use `out_size` to set necessary output shape.

    .. code-block:: text

           Given:

           x = [[0, 2, 3],
                [1, 4, 5],
                [2, 6, 7]]

           y = [1, 1, 1]

           src_index = [0, 1, 2, 0]

           dst_index = [1, 2, 1, 0]

           message_op = "add"

           reduce_op = "sum"

           out_size = None

           Then:

           out = [[1, 3, 4],
                  [4, 10, 12],
                  [2, 5, 6]]
235

236 237 238 239 240 241
    Args:
        x (Tensor): The input node feature tensor, and the available data type is float32, float64, int32, int64.
                    And we support float16 in gpu version.
        y (Tensor): The input edge feature tensor, and the available data type is float32, float64, int32, int64.
                    And we support float16 in gpu version.
        src_index (Tensor): An 1-D tensor, and the available data type is int32, int64.
242
        dst_index (Tensor): An 1-D tensor, and should have the same shape as `src_index`.
243 244 245 246 247 248 249 250 251 252 253 254
                            The available data type is int32, int64.
        message_op (str): Different message ops for x and e, including `add`, `sub`, `mul`, `div`.
        reduce_op (str): Different reduce ops, including `sum`, `mean`, `max`, `min`.
                         Default value is `sum`.
        out_size (int|Tensor|None): We can set `out_size` to get necessary output shape. If not set or
                                    out_size is smaller or equal to 0, then this input will not be used.
                                    Otherwise, `out_size` should be equal with or larger than
                                    max(dst_index) + 1.
        name (str, optional): Name for the operation (optional, default is None).
                              For more information, please refer to :ref:`api_guide_Name`.

    Returns:
255 256
        - out (Tensor), the output tensor, should have the same shape and same dtype as input tensor `x`.
          If `out_size` is set correctly, then it should have the same shape as `x` except the 0th dimension.
257 258 259 260 261 262 263 264 265

    Examples:
        .. code-block:: python

            import paddle

            x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32")
            y = paddle.to_tensor([1, 1, 1, 1], dtype="float32")
            indexes = paddle.to_tensor([[0, 1], [1, 2], [2, 1], [0, 0]], dtype="int32")
266
            src_index, dst_index = indexes[:, 0], indexes[:, 1]
267 268 269 270 271 272
            out = paddle.geometric.send_ue_recv(x, y, src_index, dst_index, message_op="add", reduce_op="sum")
            # Outputs: [[1., 3., 4.], [4., 10., 12.], [2., 5., 6.]]

            x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32")
            y = paddle.to_tensor([1, 1, 1], dtype="float32")
            indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32")
273
            src_index, dst_index = indexes[:, 0], indexes[:, 1]
274 275 276 277 278 279 280
            out_size = paddle.max(dst_index) + 1
            out = paddle.geometric.send_ue_recv(x, y, src_index, dst_index, message_op="add", reduce_op="sum", out_size=out_size)
            # Outputs: [[1., 3., 4.], [[4., 10., 12.]]]

            x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32")
            y = paddle.to_tensor([1, 1, 1], dtype="float32")
            indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32")
281
            src_index, dst_index = indexes[:, 0], indexes[:, 1]
282 283 284 285 286 287 288
            out = paddle.geometric.send_ue_recv(x, y, src_index, dst_index, message_op="add", reduce_op="sum")
            # Outputs: [[1., 3., 4.], [4., 10., 12.], [0., 0., 0.]]

    """

    if message_op not in ["add", "sub", "mul", "div"]:
        raise ValueError(
289 290 291
            "message_op should be `add`, `sub`, `mul`, `div`, but received %s"
            % message_op
        )
292 293 294 295

    if reduce_op not in ["sum", "mean", "max", "min"]:
        raise ValueError(
            "reduce_op should be `sum`, `mean`, `max` or `min`, but received %s"
296 297
            % reduce_op
        )
298 299 300 301 302 303 304 305

    x, y = reshape_lhs_rhs(x, y)

    if message_op == 'sub':
        message_op = 'add'
        y = -y
    if message_op == "div":
        message_op = 'mul'
306
        y = 1.0 / (y + 1e-12)
307 308 309 310 311

    # TODO(daisiming): Should we add judgement for out_size: max(dst_index) + 1.

    if _in_legacy_dygraph():
        out_size = convert_out_size_to_list(out_size)
312 313 314 315 316 317 318 319 320 321 322 323 324
        out, tmp = _legacy_C_ops.graph_send_ue_recv(
            x,
            y,
            src_index,
            dst_index,
            None,
            'message_op',
            message_op.upper(),
            'reduce_op',
            reduce_op.upper(),
            'out_size',
            out_size,
        )
325 326 327
        return out
    if in_dygraph_mode():
        out_size = convert_out_size_to_list(out_size)
328 329 330 331 332 333 334 335 336
        return _C_ops.graph_send_ue_recv(
            x,
            y,
            src_index,
            dst_index,
            message_op.upper(),
            reduce_op.upper(),
            out_size,
        )
337 338

    check_variable_and_dtype(
339 340 341 342 343
        x,
        "X",
        ("float32", "float64", "int32", "int64", "float16"),
        "graph_send_ue_recv",
    )
344
    check_variable_and_dtype(
345 346 347 348 349 350 351 352 353 354 355
        y,
        "Y",
        ("float32", "float64", "int32", "int64", "float16"),
        "graph_send_ue_recv",
    )
    check_variable_and_dtype(
        src_index, "Src_index", ("int32", "int64"), "graph_send_ue_recv"
    )
    check_variable_and_dtype(
        dst_index, "Dst_index", ("int32", "int64"), "graph_send_ue_recv"
    )
356
    if out_size:
357 358 359 360 361 362
        check_type(
            out_size,
            'out_size',
            (int, np.int32, np.int64, Variable),
            'graph_send_ue_recv',
        )
363
    if isinstance(out_size, Variable):
364 365 366
        check_dtype(
            out_size.dtype, 'out_size', ['int32', 'int64'], 'graph_send_ue_recv'
        )
367 368 369

    helper = LayerHelper("send_ue_recv", **locals())
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
370 371 372
    dst_count = helper.create_variable_for_type_inference(
        dtype="int32", stop_gradient=True
    )
373 374 375

    inputs = {"X": x, "Y": y, "Src_index": src_index, "Dst_index": dst_index}
    attrs = {"message_op": message_op.upper(), "reduce_op": reduce_op.upper()}
376 377 378 379 380 381 382 383 384 385 386 387 388
    get_out_size_tensor_inputs(
        inputs=inputs,
        attrs=attrs,
        out_size=out_size,
        op_type='graph_send_ue_recv',
    )

    helper.append_op(
        type="graph_send_ue_recv",
        inputs=inputs,
        outputs={"Out": out, "Dst_count": dst_count},
        attrs=attrs,
    )
389
    return out
390 391 392 393 394 395 396


def send_uv(x, y, src_index, dst_index, message_op="add", name=None):
    """

    Graph Learning message passing api.

397 398
    This api is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory
    consumption in the process of message passing. Take `x` as the source node feature tensor, take `y` as
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    the destination node feature tensor. Then we use `src_index` and `dst_index` to gather the corresponding data,
    and then compute the edge features in different message_ops like `add`, `sub`, `mul`, `div`.

    .. code-block:: text

           Given:

           x = [[0, 2, 3],
                [1, 4, 5],
                [2, 6, 7]]

           y = [[0, 1, 2],
                [2, 3, 4],
                [4, 5, 6]]

           src_index = [0, 1, 2, 0]

           dst_index = [1, 2, 1, 0]

           message_op = "add"

           Then:

           out = [[2, 5, 7],
                  [5, 9, 11],
                  [4, 9, 11],
                  [0, 3, 5]]

    Args:
        x (Tensor): The source node feature tensor, and the available data type is float32, float64, int32, int64. And we support float16 in gpu version.
        y (Tensor): The destination node feature tensor, and the available data type is float32, float64, int32, int64. And we support float16 in gpu version.
        src_index (Tensor): An 1-D tensor, and the available data type is int32, int64.
431 432
        dst_index (Tensor): An 1-D tensor, and should have the same shape as `src_index`.
                            The available data type is int32, int64.
433
        message_op (str): Different message ops for x and y, including `add`, `sub`, `mul` and `div`.
434 435 436 437
        name (str, optional): Name for the operation (optional, default is None).
                              For more information, please refer to :ref:`api_guide_Name`.

    Returns:
438
        - out (Tensor), the output tensor.
439 440

    Examples:
441

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
        .. code-block:: python

            import paddle

            x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32")
            y = paddle.to_tensor([[0, 1, 2], [2, 3, 4], [4, 5, 6]], dtype="float32")
            indexes = paddle.to_tensor([[0, 1], [1, 2], [2, 1], [0, 0]], dtype="int32")
            src_index = indexes[:, 0]
            dst_index = indexes[:, 1]
            out = paddle.geometric.send_uv(x, y, src_index, dst_index, message_op="add")
            # Outputs: [[2., 5., 7.], [5., 9., 11.], [4., 9., 11.], [0., 3., 5.]]

    """

    if message_op not in ['add', 'sub', 'mul', 'div']:
        raise ValueError(
458 459 460
            "message_op should be `add`, `sub`, `mul`, `div`, but received %s"
            % message_op
        )
461 462 463 464 465 466 467 468

    x, y = reshape_lhs_rhs(x, y)

    if message_op == 'sub':
        message_op = 'add'
        y = -y
    if message_op == 'div':
        message_op = 'mul'
469
        y = 1.0 / (y + 1e-12)
470 471

    if in_dygraph_mode():
472 473 474
        return _C_ops.graph_send_uv(
            x, y, src_index, dst_index, message_op.upper()
        )
475 476
    else:
        if _in_legacy_dygraph():
477 478 479
            return _legacy_C_ops.graph_send_uv(
                x, y, src_index, dst_index, "message_op", message_op.upper()
            )
480 481 482
        else:
            helper = LayerHelper("send_uv", **locals())
            check_variable_and_dtype(
483 484 485 486 487 488 489 490 491 492 493 494 495 496
                x,
                'x',
                ['int32', 'int64', 'float32', 'float64', 'float16'],
                'graph_send_uv',
            )
            check_variable_and_dtype(
                y,
                'y',
                ['int32', 'int64', 'float32', 'float64', 'float16'],
                'graph_send_uv',
            )
            check_variable_and_dtype(
                src_index, 'src_index', ['int32', 'int64'], 'graph_send_uv'
            )
497
            check_variable_and_dtype(
498 499
                dst_index, 'dst_index', ['int32', 'int64'], 'graph_send_uv'
            )
500 501 502 503 504 505
            out = helper.create_variable_for_type_inference(dtype=x.dtype)

            inputs = {
                'x': x,
                'y': y,
                'src_index': src_index,
506
                'dst_index': dst_index,
507 508
            }
            attrs = {'message_op': message_op.upper()}
509 510 511 512 513 514
            helper.append_op(
                type="graph_send_uv",
                inputs=inputs,
                attrs=attrs,
                outputs={"out": out},
            )
515
            return out