neighbors.py 12.4 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.

S
Siming Dai 已提交
15
from paddle import _C_ops, _legacy_C_ops
16
from paddle.fluid.data_feeder import check_variable_and_dtype
S
Siming Dai 已提交
17
from paddle.fluid.framework import _non_static_mode, in_dygraph_mode
18
from paddle.fluid.layer_helper import LayerHelper
19 20 21 22

__all__ = []


23 24 25 26 27 28 29 30 31 32
def sample_neighbors(
    row,
    colptr,
    input_nodes,
    sample_size=-1,
    eids=None,
    return_eids=False,
    perm_buffer=None,
    name=None,
):
33
    """
34

35 36 37
    Graph Sample Neighbors API.

    This API is mainly used in Graph Learning domain, and the main purpose is to
38 39
    provide high performance of graph sampling method. For example, we get the
    CSC(Compressed Sparse Column) format of the input graph edges as `row` and
40
    `colptr`, so as to convert graph data into a suitable format for sampling.
41
    `input_nodes` means the nodes we need to sample neighbors, and `sample_sizes`
42 43
    means the number of neighbors and number of layers we want to sample.

44
    Besides, we support fisher-yates sampling in GPU version.
45 46 47 48 49 50 51 52 53 54

    Args:
        row (Tensor): One of the components of the CSC format of the input graph, and
                      the shape should be [num_edges, 1] or [num_edges]. The available
                      data type is int32, int64.
        colptr (Tensor): One of the components of the CSC format of the input graph,
                         and the shape should be [num_nodes + 1, 1] or [num_nodes + 1].
                         The data type should be the same with `row`.
        input_nodes (Tensor): The input nodes we need to sample neighbors for, and the
                              data type should be the same with `row`.
55
        sample_size (int, optional): The number of neighbors we need to sample. Default value is -1,
56
                           which means returning all the neighbors of the input nodes.
57
        eids (Tensor, optional): The eid information of the input graph. If return_eids is True,
58
                            then `eids` should not be None. The data type should be the
59
                            same with `row`. Default is None.
60 61
        return_eids (bool, optional): Whether to return eid information of sample edges. Default is False.
        perm_buffer (Tensor, optional): Permutation buffer for fisher-yates sampling. If `use_perm_buffer`
62 63
                              is True, then `perm_buffer` should not be None. The data type should
                              be the same with `row`. If not None, we will use fiser-yates sampling
64
                              to speed up. Only useful for gpu version. Default is None.
65 66 67 68
        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 已提交
69 70 71
        - out_neighbors (Tensor), the sample neighbors of the input nodes.

        - out_count (Tensor), the number of sampling neighbors of each input node, and the shape
72
          should be the same with `input_nodes`.
S
Siming Dai 已提交
73 74

        - out_eids (Tensor), if `return_eids` is True, we will return the eid information of the
75
          sample edges.
76 77 78

    Examples:
        .. code-block:: python
S
Siming Dai 已提交
79 80

            import paddle
81

S
Siming Dai 已提交
82 83 84 85 86 87 88 89 90 91
            # edges: (3, 0), (7, 0), (0, 1), (9, 1), (1, 2), (4, 3), (2, 4),
            #        (9, 5), (3, 5), (9, 6), (1, 6), (9, 8), (7, 8)
            row = [3, 7, 0, 9, 1, 4, 2, 9, 3, 9, 1, 9, 7]
            colptr = [0, 2, 4, 5, 6, 7, 9, 11, 11, 13, 13]
            nodes = [0, 8, 1, 2]
            sample_size = 2
            row = paddle.to_tensor(row, dtype="int64")
            colptr = paddle.to_tensor(colptr, dtype="int64")
            nodes = paddle.to_tensor(nodes, dtype="int64")
            out_neighbors, out_count = paddle.geometric.sample_neighbors(row, colptr, nodes, sample_size=sample_size)
92 93 94 95 96 97

    """

    if return_eids:
        if eids is None:
            raise ValueError(
98 99
                "`eids` should not be None if `return_eids` is True."
            )
100 101 102 103

    use_perm_buffer = True if perm_buffer is not None else False

    if _non_static_mode():
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        (
            out_neighbors,
            out_count,
            out_eids,
        ) = _legacy_C_ops.graph_sample_neighbors(
            row,
            colptr,
            input_nodes,
            eids,
            perm_buffer,
            "sample_size",
            sample_size,
            "return_eids",
            return_eids,
            "flag_perm_buffer",
            use_perm_buffer,
        )
121 122 123 124
        if return_eids:
            return out_neighbors, out_count, out_eids
        return out_neighbors, out_count

125 126 127 128 129 130 131 132 133
    check_variable_and_dtype(
        row, "Row", ("int32", "int64"), "graph_sample_neighbors"
    )
    check_variable_and_dtype(
        colptr, "Col_Ptr", ("int32", "int64"), "graph_sample_neighbors"
    )
    check_variable_and_dtype(
        input_nodes, "X", ("int32", "int64"), "graph_sample_neighbors"
    )
134
    if return_eids:
135 136 137
        check_variable_and_dtype(
            eids, "Eids", ("int32", "int64"), "graph_sample_neighbors"
        )
138
    if use_perm_buffer:
139 140 141 142 143 144
        check_variable_and_dtype(
            perm_buffer,
            "Perm_Buffer",
            ("int32", "int64"),
            "graph_sample_neighbors",
        )
145 146 147 148 149

    helper = LayerHelper("sample_neighbors", **locals())
    out_neighbors = helper.create_variable_for_type_inference(dtype=row.dtype)
    out_count = helper.create_variable_for_type_inference(dtype=row.dtype)
    out_eids = helper.create_variable_for_type_inference(dtype=row.dtype)
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    helper.append_op(
        type="graph_sample_neighbors",
        inputs={
            "Row": row,
            "Col_Ptr": colptr,
            "X": input_nodes,
            "Eids": eids if return_eids else None,
            "Perm_Buffer": perm_buffer if use_perm_buffer else None,
        },
        outputs={
            "Out": out_neighbors,
            "Out_Count": out_count,
            "Out_Eids": out_eids,
        },
        attrs={
            "sample_size": sample_size,
            "return_eids": return_eids,
            "flag_perm_buffer": use_perm_buffer,
        },
    )
170 171 172
    if return_eids:
        return out_neighbors, out_count, out_eids
    return out_neighbors, out_count
S
Siming Dai 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 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 314 315 316 317 318 319 320


def weighted_sample_neighbors(
    row,
    colptr,
    edge_weight,
    input_nodes,
    sample_size=-1,
    eids=None,
    return_eids=False,
    name=None,
):
    """
    Graph Weighted Sample Neighbors API.

    This API is mainly used in Graph Learning domain, and the main purpose is to
    provide high performance of graph weighted-sampling method. For example, we get the
    CSC(Compressed Sparse Column) format of the input graph edges as `row` and
    `colptr`, so as to convert graph data into a suitable format for sampling, and the
    input `edge_weight` should also match the CSC format. Besides, `input_nodes` means
    the nodes we need to sample neighbors, and `sample_sizes` means the number of neighbors
    and number of layers we want to sample. This API will finally return the weighted sampled
    neighbors, and the probability of being selected as a neighbor is related to its weight,
    with higher weight and higher probability.

    Args:
        row (Tensor): One of the components of the CSC format of the input graph, and
                      the shape should be [num_edges, 1] or [num_edges]. The available
                      data type is int32, int64.
        colptr (Tensor): One of the components of the CSC format of the input graph,
                         and the shape should be [num_nodes + 1, 1] or [num_nodes + 1].
                         The data type should be the same with `row`.
        edge_weight (Tensor): The edge weight of the CSC format graph edges. And the shape
                              should be [num_edges, 1] or [num_edges]. The available data
                              type is float32.
        input_nodes (Tensor): The input nodes we need to sample neighbors for, and the
                              data type should be the same with `row`.
        sample_size (int, optional): The number of neighbors we need to sample. Default value is -1,
                           which means returning all the neighbors of the input nodes.
        eids (Tensor, optional): The eid information of the input graph. If return_eids is True,
                            then `eids` should not be None. The data type should be the
                            same with `row`. Default is None.
        return_eids (bool, optional): Whether to return eid information of sample edges. Default is False.
        name (str, optional): Name for the operation (optional, default is None).
                              For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        - out_neighbors (Tensor), the sample neighbors of the input nodes.

        - out_count (Tensor), the number of sampling neighbors of each input node, and the shape
          should be the same with `input_nodes`.

        - out_eids (Tensor), if `return_eids` is True, we will return the eid information of the
          sample edges.

    Examples:
        .. code-block:: python

            import paddle

            # edges: (3, 0), (7, 0), (0, 1), (9, 1), (1, 2), (4, 3), (2, 4),
            #        (9, 5), (3, 5), (9, 6), (1, 6), (9, 8), (7, 8)
            row = [3, 7, 0, 9, 1, 4, 2, 9, 3, 9, 1, 9, 7]
            colptr = [0, 2, 4, 5, 6, 7, 9, 11, 11, 13, 13]
            weight = [0.1, 0.5, 0.2, 0.5, 0.9, 1.9, 2.0, 2.1, 0.01, 0.9, 0,12, 0.59, 0.67]
            nodes = [0, 8, 1, 2]
            sample_size = 2
            row = paddle.to_tensor(row, dtype="int64")
            colptr = paddle.to_tensor(colptr, dtype="int64")
            weight = paddle.to_tensor(weight, dtype="float32")
            nodes = paddle.to_tensor(nodes, dtype="int64")
            out_neighbors, out_count = paddle.geometric.weighted_sample_neighbors(row, colptr, weight, nodes, sample_size=sample_size)

    """

    if return_eids:
        if eids is None:
            raise ValueError(
                "`eids` should not be None if `return_eids` is True."
            )

    if in_dygraph_mode():
        (
            out_neighbors,
            out_count,
            out_eids,
        ) = _C_ops.weighted_sample_neighbors(
            row,
            colptr,
            edge_weight,
            input_nodes,
            eids,
            sample_size,
            return_eids,
        )
        if return_eids:
            return out_neighbors, out_count, out_eids
        return out_neighbors, out_count

    check_variable_and_dtype(
        row, "row", ("int32", "int64"), "weighted_sample_neighbors"
    )
    check_variable_and_dtype(
        colptr, "colptr", ("int32", "int64"), "weighted_sample_neighbors"
    )
    check_variable_and_dtype(
        edge_weight,
        "edge_weight",
        ("float32"),
        "weighted_sample_neighbors",
    )
    check_variable_and_dtype(
        input_nodes,
        "input_nodes",
        ("int32", "int64"),
        "weighted_sample_neighbors",
    )
    if return_eids:
        check_variable_and_dtype(
            eids, "eids", ("int32", "int64"), "weighted_sample_neighbors"
        )

    helper = LayerHelper("weighted_sample_neighbors", **locals())
    out_neighbors = helper.create_variable_for_type_inference(dtype=row.dtype)
    out_count = helper.create_variable_for_type_inference(dtype=row.dtype)
    out_eids = helper.create_variable_for_type_inference(dtype=row.dtype)
    helper.append_op(
        type="weighted_sample_neighbors",
        inputs={
            "row": row,
            "colptr": colptr,
            "edge_weight": edge_weight,
            "input_nodes": input_nodes,
            "eids": eids if return_eids else None,
        },
        outputs={
            "out_neighbors": out_neighbors,
            "out_count": out_count,
            "out_eids": out_eids,
        },
        attrs={
            "sample_size": sample_size,
            "return_eids": return_eids,
        },
    )
    if return_eids:
        return out_neighbors, out_count, out_eids
    return out_neighbors, out_count