reindex.py 11.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   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 paddle
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.framework import _non_static_mode, Variable
from paddle.fluid.data_feeder import check_variable_and_dtype
19
from paddle import _legacy_C_ops
20 21 22 23

__all__ = []


24 25 26
def reindex_graph(
    x, neighbors, count, value_buffer=None, index_buffer=None, name=None
):
27 28 29 30
    """
    Reindex Graph API.

    This API is mainly used in Graph Learning domain, which should be used
S
Siming Dai 已提交
31
    in conjunction with `paddle.geometric.sample_neighbors` API. And the main purpose
32
    is to reindex the ids information of the input nodes, and return the
33 34
    corresponding graph edges after reindex.

S
Siming Dai 已提交
35 36 37 38
    Take input nodes x = [0, 1, 2] as an example. If we have neighbors = [8, 9, 0, 4, 7, 6, 7], and count = [2, 3, 2],
    then we know that the neighbors of 0 is [8, 9], the neighbors of 1 is [0, 4, 7], and the neighbors of 2 is [6, 7].
    Then after graph_reindex, we will have 3 different outputs: reindex_src: [3, 4, 0, 5, 6, 7, 6], reindex_dst: [0, 0, 1, 1, 1, 2, 2]
    and out_nodes: [0, 1, 2, 8, 9, 4, 7, 6]. We can see that the numbers in `reindex_src` and `reindex_dst` is the corresponding index
39 40
    of nodes in `out_nodes`.

S
Siming Dai 已提交
41 42 43
    Note:
        The number in x should be unique, otherwise it would cause potential errors. We will reindex all the nodes from 0.

44 45 46 47 48
    Args:
        x (Tensor): The input nodes which we sample neighbors for. The available
                    data type is int32, int64.
        neighbors (Tensor): The neighbors of the input nodes `x`. The data type
                            should be the same with `x`.
49
        count (Tensor): The neighbor count of the input nodes `x`. And the
50 51 52 53 54
                        data type should be int32.
        value_buffer (Tensor|None): Value buffer for hashtable. The data type should be int32,
                                    and should be filled with -1. Only useful for gpu version.
        index_buffer (Tensor|None): Index buffer for hashtable. The data type should be int32,
                                    and should be filled with -1. Only useful for gpu version.
55
                                    `value_buffer` and `index_buffer` should be both not None
56 57 58
                                    if you want to speed up by using hashtable buffer.
        name (str, optional): Name for the operation (optional, default is None).
                              For more information, please refer to :ref:`api_guide_Name`.
59

60
    Returns:
S
Siming Dai 已提交
61
        - reindex_src (Tensor), the source node index of graph edges after reindex.
62

S
Siming Dai 已提交
63
        - reindex_dst (Tensor), the destination node index of graph edges after reindex.
64

S
Siming Dai 已提交
65
        - out_nodes (Tensor), the index of unique input nodes and neighbors before reindex, where we put the input nodes `x` in the front, and put neighbor nodes in the back.
66

S
Siming Dai 已提交
67 68
    Examples:
        .. code-block:: python
69

S
Siming Dai 已提交
70 71 72 73 74 75 76 77 78 79 80
            import paddle
            x = [0, 1, 2]
            neighbors = [8, 9, 0, 4, 7, 6, 7]
            count = [2, 3, 2]
            x = paddle.to_tensor(x, dtype="int64")
            neighbors = paddle.to_tensor(neighbors, dtype="int64")
            count = paddle.to_tensor(count, dtype="int32")
            reindex_src, reindex_dst, out_nodes = paddle.geometric.reindex_graph(x, neighbors, count)
            # reindex_src: [3, 4, 0, 5, 6, 7, 6]
            # reindex_dst: [0, 0, 1, 1, 1, 2, 2]
            # out_nodes: [0, 1, 2, 8, 9, 4, 7, 6]
81 82

    """
83 84 85
    use_buffer_hashtable = (
        True if value_buffer is not None and index_buffer is not None else False
    )
86 87

    if _non_static_mode():
88 89 90 91 92 93 94 95 96
        reindex_src, reindex_dst, out_nodes = _legacy_C_ops.graph_reindex(
            x,
            neighbors,
            count,
            value_buffer,
            index_buffer,
            "flag_buffer_hashtable",
            use_buffer_hashtable,
        )
97 98 99
        return reindex_src, reindex_dst, out_nodes

    check_variable_and_dtype(x, "X", ("int32", "int64"), "graph_reindex")
100 101 102
    check_variable_and_dtype(
        neighbors, "Neighbors", ("int32", "int64"), "graph_reindex"
    )
103 104 105
    check_variable_and_dtype(count, "Count", ("int32"), "graph_reindex")

    if use_buffer_hashtable:
106 107 108 109 110 111
        check_variable_and_dtype(
            value_buffer, "HashTable_Value", ("int32"), "graph_reindex"
        )
        check_variable_and_dtype(
            index_buffer, "HashTable_Index", ("int32"), "graph_reindex"
        )
112 113 114 115 116

    helper = LayerHelper("reindex_graph", **locals())
    reindex_src = helper.create_variable_for_type_inference(dtype=x.dtype)
    reindex_dst = helper.create_variable_for_type_inference(dtype=x.dtype)
    out_nodes = helper.create_variable_for_type_inference(dtype=x.dtype)
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    helper.append_op(
        type="graph_reindex",
        inputs={
            "X": x,
            "Neighbors": neighbors,
            "Count": count,
            "HashTable_Value": value_buffer if use_buffer_hashtable else None,
            "HashTable_Index": index_buffer if use_buffer_hashtable else None,
        },
        outputs={
            "Reindex_Src": reindex_src,
            "Reindex_Dst": reindex_dst,
            "Out_Nodes": out_nodes,
        },
        attrs={"flag_buffer_hashtable": use_buffer_hashtable},
    )
133 134 135
    return reindex_src, reindex_dst, out_nodes


136 137 138
def reindex_heter_graph(
    x, neighbors, count, value_buffer=None, index_buffer=None, name=None
):
139 140 141 142
    """
    Reindex HeterGraph API.

    This API is mainly used in Graph Learning domain, which should be used
S
Siming Dai 已提交
143
    in conjunction with `paddle.geometric.sample_neighbors` API. And the main purpose
144 145 146
    is to reindex the ids information of the input nodes, and return the
    corresponding graph edges after reindex.

S
Siming Dai 已提交
147 148 149 150 151 152 153 154
    Take input nodes x = [0, 1, 2] as an example. For graph A, suppose we have neighbors = [8, 9, 0, 4, 7, 6, 7], and count = [2, 3, 2],
    then we know that the neighbors of 0 is [8, 9], the neighbors of 1 is [0, 4, 7], and the neighbors of 2 is [6, 7]. For graph B,
    suppose we have neighbors = [0, 2, 3, 5, 1], and count = [1, 3, 1], then we know that the neighbors of 0 is [0], the neighbors of 1 is [2, 3, 5],
    and the neighbors of 3 is [1]. We will get following outputs: reindex_src: [3, 4, 0, 5, 6, 7, 6, 0, 2, 8, 9, 1], reindex_dst: [0, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 2]
    and out_nodes: [0, 1, 2, 8, 9, 4, 7, 6, 3, 5].

    Note:
        The number in x should be unique, otherwise it would cause potential errors. We support multi-edge-types neighbors reindexing in reindex_heter_graph api. We will reindex all the nodes from 0.
155 156 157 158

    Args:
        x (Tensor): The input nodes which we sample neighbors for. The available
                    data type is int32, int64.
159
        neighbors (list|tuple): The neighbors of the input nodes `x` from different graphs.
160
                                The data type should be the same with `x`.
161
        count (list|tuple): The neighbor counts of the input nodes `x` from different graphs.
162 163 164 165 166 167 168 169 170 171 172
                            And the data type should be int32.
        value_buffer (Tensor|None): Value buffer for hashtable. The data type should be int32,
                                    and should be filled with -1. Only useful for gpu version.
        index_buffer (Tensor|None): Index buffer for hashtable. The data type should be int32,
                                    and should be filled with -1. Only useful for gpu version.
                                    `value_buffer` and `index_buffer` should be both not None
                                    if you want to speed up by using hashtable buffer.
        name (str, optional): Name for the operation (optional, default is None).
                              For more information, please refer to :ref:`api_guide_Name`.

    Returns:
S
Siming Dai 已提交
173
        - reindex_src (Tensor), the source node index of graph edges after reindex.
174

S
Siming Dai 已提交
175
        - reindex_dst (Tensor), the destination node index of graph edges after reindex.
176

S
Siming Dai 已提交
177 178 179 180 181
        - out_nodes (Tensor), the index of unique input nodes and neighbors before reindex,
                              where we put the input nodes `x` in the front, and put neighbor
                              nodes in the back.

    Examples:
182 183
        .. code-block:: python

S
Siming Dai 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            import paddle
            x = [0, 1, 2]
            neighbors_a = [8, 9, 0, 4, 7, 6, 7]
            count_a = [2, 3, 2]
            x = paddle.to_tensor(x, dtype="int64")
            neighbors_a = paddle.to_tensor(neighbors_a, dtype="int64")
            count_a = paddle.to_tensor(count_a, dtype="int32")
            neighbors_b = [0, 2, 3, 5, 1]
            count_b = [1, 3, 1]
            neighbors_b = paddle.to_tensor(neighbors_b, dtype="int64")
            count_b = paddle.to_tensor(count_b, dtype="int32")
            neighbors = [neighbors_a, neighbors_b]
            count = [count_a, count_b]
            reindex_src, reindex_dst, out_nodes = paddle.geometric.reindex_heter_graph(x, neighbors, count)
            # reindex_src: [3, 4, 0, 5, 6, 7, 6, 0, 2, 8, 9, 1]
            # reindex_dst: [0, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 2]
            # out_nodes: [0, 1, 2, 8, 9, 4, 7, 6, 3, 5]
201 202

    """
203 204 205
    use_buffer_hashtable = (
        True if value_buffer is not None and index_buffer is not None else False
    )
206 207 208 209

    if _non_static_mode():
        neighbors = paddle.concat(neighbors, axis=0)
        count = paddle.concat(count, axis=0)
210 211 212 213 214 215 216 217 218
        reindex_src, reindex_dst, out_nodes = _legacy_C_ops.graph_reindex(
            x,
            neighbors,
            count,
            value_buffer,
            index_buffer,
            "flag_buffer_hashtable",
            use_buffer_hashtable,
        )
219 220 221 222 223 224 225 226 227 228 229
        return reindex_src, reindex_dst, out_nodes

    if isinstance(neighbors, Variable):
        neighbors = [neighbors]
    if isinstance(count, Variable):
        count = [count]

    neighbors = paddle.concat(neighbors, axis=0)
    count = paddle.concat(count, axis=0)

    check_variable_and_dtype(x, "X", ("int32", "int64"), "heter_graph_reindex")
230 231 232
    check_variable_and_dtype(
        neighbors, "Neighbors", ("int32", "int64"), "graph_reindex"
    )
233 234 235
    check_variable_and_dtype(count, "Count", ("int32"), "graph_reindex")

    if use_buffer_hashtable:
236 237 238 239 240 241
        check_variable_and_dtype(
            value_buffer, "HashTable_Value", ("int32"), "graph_reindex"
        )
        check_variable_and_dtype(
            index_buffer, "HashTable_Index", ("int32"), "graph_reindex"
        )
242 243 244 245 246 247 248

    helper = LayerHelper("reindex_heter_graph", **locals())
    reindex_src = helper.create_variable_for_type_inference(dtype=x.dtype)
    reindex_dst = helper.create_variable_for_type_inference(dtype=x.dtype)
    out_nodes = helper.create_variable_for_type_inference(dtype=x.dtype)
    neighbors = paddle.concat(neighbors, axis=0)
    count = paddle.concat(count, axis=0)
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    helper.append_op(
        type="graph_reindex",
        inputs={
            "X": x,
            "Neighbors": neighbors,
            "Count": count,
            "HashTable_Value": value_buffer if use_buffer_hashtable else None,
            "HashTable_Index": index_buffer if use_buffer_hashtable else None,
        },
        outputs={
            "Reindex_Src": reindex_src,
            "Reindex_Dst": reindex_dst,
            "Out_Nodes": out_nodes,
        },
        attrs={"flag_buffer_hashtable": use_buffer_hashtable},
    )
265
    return reindex_src, reindex_dst, out_nodes