graph_send_recv.py 8.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2021 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
import numpy as np
16

17
import paddle
姜永久 已提交
18
from paddle import _C_ops
19 20
from paddle.fluid.data_feeder import (
    check_dtype,
21 22
    check_type,
    check_variable_and_dtype,
23 24
    convert_dtype,
)
25
from paddle.fluid.framework import Variable
26
from paddle.fluid.layer_helper import LayerHelper
27
from paddle.framework import in_dynamic_mode
28
from paddle.utils import deprecated
29 30


31 32 33 34
@deprecated(
    since="2.4.0",
    update_to="paddle.geometric.send_u_recv",
    level=1,
35 36 37 38 39
    reason="graph_send_recv in paddle.incubate will be removed in future",
)
def graph_send_recv(
    x, src_index, dst_index, pool_type="sum", out_size=None, name=None
):
40 41 42 43
    r"""

    Graph Learning Send_Recv combine operator.

44
    This operator is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory
45
    consumption in the process of message passing. Take `x` as the input tensor, we first use `src_index`
46
    to gather the corresponding data, and then use `dst_index` to update the corresponding position of output tensor
47
    in different pooling types, like sum, mean, max, or min. Besides, we can set `out_size` to get necessary output shape.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

    .. code-block:: text

           Given:

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

           src_index = [0, 1, 2, 0]

           dst_index = [1, 2, 1, 0]

           pool_type = "sum"

63 64
           out_size = None

65 66 67 68 69 70 71 72 73
           Then:

           Out = [[0, 2, 3],
                  [2, 8, 10],
                  [1, 4, 5]]

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

    Returns:
86 87
        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
88
                      the 0th dimension.
89 90 91 92 93

    Examples:

        .. code-block:: python

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
            >>> 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")
            >>> src_index = indexes[:, 0]
            >>> dst_index = indexes[:, 1]
            >>> out = paddle.incubate.graph_send_recv(x, src_index, dst_index, pool_type="sum")
            >>> print(out)
            Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[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")
            >>> src_index = indexes[:, 0]
            >>> dst_index = indexes[:, 1]
            >>> out_size = paddle.max(dst_index) + 1
            >>> out = paddle.incubate.graph_send_recv(x, src_index, dst_index, pool_type="sum", out_size=out_size)
            >>> print(out)
            Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[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")
            >>> src_index = indexes[:, 0]
            >>> dst_index = indexes[:, 1]
            >>> out = paddle.incubate.graph_send_recv(x, src_index, dst_index, pool_type="sum")
            >>> print(out)
            Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[0. , 2. , 3. ],
             [2. , 8. , 10.],
             [0. , 0. , 0. ]])
128 129 130 131 132
    """

    if pool_type not in ["sum", "mean", "max", "min"]:
        raise ValueError(
            "pool_type should be `sum`, `mean`, `max` or `min`, but received %s"
133 134
            % pool_type
        )
135

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

138
    if in_dynamic_mode():
139
        out_size = convert_out_size_to_list(out_size)
140
        return _C_ops.send_u_recv(
141 142 143 144 145 146 147 148 149 150 151 152
            x, src_index, dst_index, pool_type.upper(), out_size
        )

    check_variable_and_dtype(
        x, "X", ("float32", "float64", "int32", "int64"), "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"
    )
153
    if out_size:
154 155 156 157 158 159
        check_type(
            out_size,
            'out_size',
            (int, np.int32, np.int64, Variable),
            'graph_send_recv',
        )
160
    if isinstance(out_size, Variable):
161 162 163
        check_dtype(
            out_size.dtype, 'out_size', ['int32', 'int64'], 'graph_send_recv'
        )
164 165 166

    helper = LayerHelper("graph_send_recv", **locals())
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
167 168 169
    dst_count = helper.create_variable_for_type_inference(
        dtype="int32", stop_gradient=True
    )
170 171

    inputs = {"X": x, "Src_index": src_index, "Dst_index": dst_index}
172
    attrs = {"reduce_op": pool_type.upper()}
173 174 175 176 177 178 179 180 181 182
    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,
    )
183
    return out
184 185 186 187 188 189 190 191 192 193 194 195


def convert_out_size_to_list(out_size):
    """
    Convert out_size(int, np.int32, np.int64, Variable) to list
    in imperative mode.
    """
    if out_size is None:
        out_size = [0]
    elif isinstance(out_size, (int, np.int32, np.int64)):
        out_size = [out_size]
    else:
196
        out_size = [int(out_size)]
197 198 199 200 201 202
    return out_size


def get_out_size_tensor_inputs(inputs, attrs, out_size, op_type):
    """
    Convert out_size(int, np.int32, np.int64, Variable) to inputs
203
    and attrs in static graph mode.
204 205 206 207 208 209 210
    """
    if out_size is None:
        attrs['out_size'] = [0]
    elif isinstance(out_size, (int, np.int32, np.int64)):
        attrs['out_size'] = [out_size]
    elif isinstance(out_size, Variable):
        out_size.stop_gradient = True
211 212 213 214 215 216 217 218
        check_dtype(
            out_size.dtype,
            'out_size',
            ['int32', 'int64'],
            op_type,
            '(When type of out_size in' + op_type + ' is Variable.)',
        )
        if convert_dtype(out_size.dtype) == 'int64':
219
            out_size = paddle.cast(out_size, 'int32')
220 221 222
        inputs["Out_size"] = out_size
    else:
        raise TypeError("Out_size only supports Variable or int.")