graph_services.py 37.5 KB
Newer Older
1
"""A set of graph services of getting subgraphs from DistGraph"""
2
from collections import namedtuple
3

4
import numpy as np
5

6
7
8
import torch

from .. import backend as F, graphbolt as gb
9
10
from ..base import EID, NID
from ..convert import graph, heterograph
11
12
13
14
from ..sampling import (
    sample_etype_neighbors as local_sample_etype_neighbors,
    sample_neighbors as local_sample_neighbors,
)
15
from ..subgraph import in_subgraph as local_in_subgraph
16
from ..utils import toindex
17
18
19
from .rpc import (
    recv_responses,
    register_service,
20
21
    Request,
    Response,
22
23
    send_requests_to_machine,
)
Jinjing Zhou's avatar
Jinjing Zhou committed
24

25
__all__ = [
26
27
28
29
    "sample_neighbors",
    "sample_etype_neighbors",
    "in_subgraph",
    "find_edges",
30
]
Jinjing Zhou's avatar
Jinjing Zhou committed
31
32

SAMPLING_SERVICE_ID = 6657
33
INSUBGRAPH_SERVICE_ID = 6658
34
EDGES_SERVICE_ID = 6659
35
36
OUTDEGREE_SERVICE_ID = 6660
INDEGREE_SERVICE_ID = 6661
37
ETYPE_SAMPLING_SERVICE_ID = 6662
Jinjing Zhou's avatar
Jinjing Zhou committed
38

39

40
41
class SubgraphResponse(Response):
    """The response for sampling and in_subgraph"""
Jinjing Zhou's avatar
Jinjing Zhou committed
42
43
44
45
46
47
48
49
50
51
52
53

    def __init__(self, global_src, global_dst, global_eids):
        self.global_src = global_src
        self.global_dst = global_dst
        self.global_eids = global_eids

    def __setstate__(self, state):
        self.global_src, self.global_dst, self.global_eids = state

    def __getstate__(self):
        return self.global_src, self.global_dst, self.global_eids

54

55
56
57
58
59
60
61
62
63
64
65
66
67
class FindEdgeResponse(Response):
    """The response for sampling and in_subgraph"""

    def __init__(self, global_src, global_dst, order_id):
        self.global_src = global_src
        self.global_dst = global_dst
        self.order_id = order_id

    def __setstate__(self, state):
        self.global_src, self.global_dst, self.order_id = state

    def __getstate__(self):
        return self.global_src, self.global_dst, self.order_id
Jinjing Zhou's avatar
Jinjing Zhou committed
68

69

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def _sample_neighbors_graphbolt(
    g, gpb, nodes, fanout, prob=None, replace=False
):
    """Sample from local partition via graphbolt.

    The input nodes use global IDs. We need to map the global node IDs to local
    node IDs, perform sampling and map the sampled results to the global IDs
    space again. The sampled results are stored in three vectors that store
    source nodes, destination nodes, etype IDs and edge IDs.

    [Rui][TODO] edge IDs are not returned as not supported yet.

    Parameters
    ----------
    g : FusedCSCSamplingGraph
        The local partition.
    gpb : GraphPartitionBook
        The graph partition book.
    nodes : tensor
        The nodes to sample neighbors from.
    fanout : tensor or int
        The number of edges to be sampled for each node.
    prob : tensor, optional
        The probability associated with each neighboring edge of a node.
    replace : bool, optional
        If True, sample with replacement.

    Returns
    -------
    tensor
        The source node ID array.
    tensor
        The destination node ID array.
    tensor
        The edge type ID array.
    tensor
        The edge ID array.
    """
    # 1. Map global node IDs to local node IDs.
    nodes = gpb.nid2localnid(nodes, gpb.partid)

    # 2. Perform sampling.
    # [Rui][TODO] `prob` and `replace` are not tested yet. Skip for now.
    assert (
        prob is None
    ), "DistGraphBolt does not support sampling with probability."
    assert (
        not replace
    ), "DistGraphBolt does not support sampling with replacement."

    # Sanity checks.
    assert isinstance(
        g, gb.FusedCSCSamplingGraph
    ), "Expect a FusedCSCSamplingGraph."
    assert isinstance(nodes, torch.Tensor), "Expect a tensor of nodes."
    if isinstance(fanout, int):
        fanout = torch.LongTensor([fanout])
    assert isinstance(fanout, torch.Tensor), "Expect a tensor of fanout."
    # [Rui][TODO] Support multiple fanouts.
    assert fanout.numel() == 1, "Expect a single fanout."

    subgraph = g._sample_neighbors(nodes, fanout)

    # 3. Map local node IDs to global node IDs.
    local_src = subgraph.indices
    local_dst = torch.repeat_interleave(
        subgraph.original_column_node_ids, torch.diff(subgraph.indptr)
    )
    global_nid_mapping = g.node_attributes[NID]
    global_src = global_nid_mapping[local_src]
    global_dst = global_nid_mapping[local_dst]

    return global_src, global_dst, subgraph.type_per_edge


145
146
147
148
def _sample_neighbors(
    local_g, partition_book, seed_nodes, fan_out, edge_dir, prob, replace
):
    """Sample from local partition.
149

150
151
    The input nodes use global IDs. We need to map the global node IDs to local node IDs,
    perform sampling and map the sampled results to the global IDs space again.
152
    The sampled results are stored in three vectors that store source nodes, destination nodes
153
    and edge IDs.
154
155
156
157
158
    """
    local_ids = partition_book.nid2localnid(seed_nodes, partition_book.partid)
    local_ids = F.astype(local_ids, local_g.idtype)
    # local_ids = self.seed_nodes
    sampled_graph = local_sample_neighbors(
159
160
161
162
163
164
165
166
        local_g,
        local_ids,
        fan_out,
        edge_dir,
        prob,
        replace,
        _dist_training=True,
    )
167
168
    global_nid_mapping = local_g.ndata[NID]
    src, dst = sampled_graph.edges()
169
170
171
    global_src, global_dst = F.gather_row(
        global_nid_mapping, src
    ), F.gather_row(global_nid_mapping, dst)
172
173
174
    global_eids = F.gather_row(local_g.edata[EID], sampled_graph.edata[EID])
    return global_src, global_dst, global_eids

175
176
177
178
179

def _sample_etype_neighbors(
    local_g,
    partition_book,
    seed_nodes,
180
    etype_offset,
181
182
183
184
185
186
187
    fan_out,
    edge_dir,
    prob,
    replace,
    etype_sorted=False,
):
    """Sample from local partition.
188
189
190
191
192
193
194
195

    The input nodes use global IDs. We need to map the global node IDs to local node IDs,
    perform sampling and map the sampled results to the global IDs space again.
    The sampled results are stored in three vectors that store source nodes, destination nodes
    and edge IDs.
    """
    local_ids = partition_book.nid2localnid(seed_nodes, partition_book.partid)
    local_ids = F.astype(local_ids, local_g.idtype)
196

197
    sampled_graph = local_sample_etype_neighbors(
198
199
        local_g,
        local_ids,
200
        etype_offset,
201
202
203
204
205
206
207
        fan_out,
        edge_dir,
        prob,
        replace,
        etype_sorted=etype_sorted,
        _dist_training=True,
    )
208
209
    global_nid_mapping = local_g.ndata[NID]
    src, dst = sampled_graph.edges()
210
211
212
    global_src, global_dst = F.gather_row(
        global_nid_mapping, src
    ), F.gather_row(global_nid_mapping, dst)
213
214
215
    global_eids = F.gather_row(local_g.edata[EID], sampled_graph.edata[EID])
    return global_src, global_dst, global_eids

216

217
218
def _find_edges(local_g, partition_book, seed_edges):
    """Given an edge ID array, return the source
219
    and destination node ID array ``s`` and ``d`` in the local partition.
220
221
222
223
224
225
226
227
    """
    local_eids = partition_book.eid2localeid(seed_edges, partition_book.partid)
    local_eids = F.astype(local_eids, local_g.idtype)
    local_src, local_dst = local_g.find_edges(local_eids)
    global_nid_mapping = local_g.ndata[NID]
    global_src = global_nid_mapping[local_src]
    global_dst = global_nid_mapping[local_dst]
    return global_src, global_dst
228

229

230
def _in_degrees(local_g, partition_book, n):
231
    """Get in-degree of the nodes in the local partition."""
232
233
234
235
    local_nids = partition_book.nid2localnid(n, partition_book.partid)
    local_nids = F.astype(local_nids, local_g.idtype)
    return local_g.in_degrees(local_nids)

236

237
def _out_degrees(local_g, partition_book, n):
238
    """Get out-degree of the nodes in the local partition."""
239
240
241
242
    local_nids = partition_book.nid2localnid(n, partition_book.partid)
    local_nids = F.astype(local_nids, local_g.idtype)
    return local_g.out_degrees(local_nids)

243

244
def _in_subgraph(local_g, partition_book, seed_nodes):
245
    """Get in subgraph from local partition.
246

247
248
    The input nodes use global IDs. We need to map the global node IDs to local node IDs,
    get in-subgraph and map the sampled results to the global IDs space again.
249
    The results are stored in three vectors that store source nodes, destination nodes
250
    and edge IDs.
251
252
253
254
255
256
257
258
259
260
261
262
    """
    local_ids = partition_book.nid2localnid(seed_nodes, partition_book.partid)
    local_ids = F.astype(local_ids, local_g.idtype)
    # local_ids = self.seed_nodes
    sampled_graph = local_in_subgraph(local_g, local_ids)
    global_nid_mapping = local_g.ndata[NID]
    src, dst = sampled_graph.edges()
    global_src, global_dst = global_nid_mapping[src], global_nid_mapping[dst]
    global_eids = F.gather_row(local_g.edata[EID], sampled_graph.edata[EID])
    return global_src, global_dst, global_eids


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
# --- NOTE 1 ---
# (BarclayII)
# If the sampling algorithm needs node and edge data, ideally the
# algorithm should query the underlying feature storage to get what it
# just needs to complete the job.  For instance, with
# sample_etype_neighbors, we only need the probability of the seed nodes'
# neighbors.
#
# However, right now we are reusing the existing subgraph sampling
# interfaces of DGLGraph (i.e. single machine solution), which needs
# the data of *all* the nodes/edges.  Going distributed, we now need
# the node/edge data of the *entire* local graph partition.
#
# If the sampling algorithm only use edge data, the current design works
# because the local graph partition contains all the in-edges of the
# assigned nodes as well as the data.  This is the case for
# sample_etype_neighbors.
#
# However, if the sampling algorithm requires data of the neighbor nodes
# (e.g. sample_neighbors_biased which performs biased sampling based on the
# type of the neighbor nodes), the current design will fail because the
# neighbor nodes (hence the data) may not belong to the current partition.
# This is a limitation of the current DistDGL design.  We should improve it
# later.

288

Jinjing Zhou's avatar
Jinjing Zhou committed
289
290
291
class SamplingRequest(Request):
    """Sampling Request"""

292
293
294
295
296
297
298
299
300
    def __init__(
        self,
        nodes,
        fan_out,
        edge_dir="in",
        prob=None,
        replace=False,
        use_graphbolt=False,
    ):
Jinjing Zhou's avatar
Jinjing Zhou committed
301
302
303
304
305
        self.seed_nodes = nodes
        self.edge_dir = edge_dir
        self.prob = prob
        self.replace = replace
        self.fan_out = fan_out
306
        self.use_graphbolt = use_graphbolt
Jinjing Zhou's avatar
Jinjing Zhou committed
307
308

    def __setstate__(self, state):
309
310
311
312
313
314
        (
            self.seed_nodes,
            self.edge_dir,
            self.prob,
            self.replace,
            self.fan_out,
315
            self.use_graphbolt,
316
        ) = state
Jinjing Zhou's avatar
Jinjing Zhou committed
317
318

    def __getstate__(self):
319
320
321
322
323
324
        return (
            self.seed_nodes,
            self.edge_dir,
            self.prob,
            self.replace,
            self.fan_out,
325
            self.use_graphbolt,
326
        )
Jinjing Zhou's avatar
Jinjing Zhou committed
327
328
329
330

    def process_request(self, server_state):
        local_g = server_state.graph
        partition_book = server_state.partition_book
331
332
333
334
335
        kv_store = server_state.kv_store
        if self.prob is not None:
            prob = [kv_store.data_store[self.prob]]
        else:
            prob = None
336
337
338
339
340
341
342
343
344
345
        if self.use_graphbolt:
            global_src, global_dst, etype_ids = _sample_neighbors_graphbolt(
                local_g,
                partition_book,
                self.seed_nodes,
                self.fan_out,
                prob,
                self.replace,
            )
            return SubgraphResponse(global_src, global_dst, etype_ids)
346
347
348
349
350
351
        global_src, global_dst, global_eids = _sample_neighbors(
            local_g,
            partition_book,
            self.seed_nodes,
            self.fan_out,
            self.edge_dir,
352
            prob,
353
354
            self.replace,
        )
355
356
        return SubgraphResponse(global_src, global_dst, global_eids)

357

358
359
360
class SamplingRequestEtype(Request):
    """Sampling Request"""

361
362
363
364
365
366
367
368
369
    def __init__(
        self,
        nodes,
        fan_out,
        edge_dir="in",
        prob=None,
        replace=False,
        etype_sorted=True,
    ):
370
371
372
373
374
        self.seed_nodes = nodes
        self.edge_dir = edge_dir
        self.prob = prob
        self.replace = replace
        self.fan_out = fan_out
375
        self.etype_sorted = etype_sorted
376
377

    def __setstate__(self, state):
378
379
380
381
382
383
384
385
        (
            self.seed_nodes,
            self.edge_dir,
            self.prob,
            self.replace,
            self.fan_out,
            self.etype_sorted,
        ) = state
386
387

    def __getstate__(self):
388
389
390
391
392
393
394
395
        return (
            self.seed_nodes,
            self.edge_dir,
            self.prob,
            self.replace,
            self.fan_out,
            self.etype_sorted,
        )
396
397
398
399

    def process_request(self, server_state):
        local_g = server_state.graph
        partition_book = server_state.partition_book
400
401
402
403
404
405
406
407
408
409
        kv_store = server_state.kv_store
        etype_offset = partition_book.local_etype_offset
        # See NOTE 1
        if self.prob is not None:
            probs = [
                kv_store.data_store[key] if key != "" else None
                for key in self.prob
            ]
        else:
            probs = None
410
411
412
413
        global_src, global_dst, global_eids = _sample_etype_neighbors(
            local_g,
            partition_book,
            self.seed_nodes,
414
            etype_offset,
415
416
            self.fan_out,
            self.edge_dir,
417
            probs,
418
419
420
            self.replace,
            self.etype_sorted,
        )
421
422
        return SubgraphResponse(global_src, global_dst, global_eids)

423

424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
class EdgesRequest(Request):
    """Edges Request"""

    def __init__(self, edge_ids, order_id):
        self.edge_ids = edge_ids
        self.order_id = order_id

    def __setstate__(self, state):
        self.edge_ids, self.order_id = state

    def __getstate__(self):
        return self.edge_ids, self.order_id

    def process_request(self, server_state):
        local_g = server_state.graph
        partition_book = server_state.partition_book
440
441
442
        global_src, global_dst = _find_edges(
            local_g, partition_book, self.edge_ids
        )
443
444

        return FindEdgeResponse(global_src, global_dst, self.order_id)
445

446

447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
class InDegreeRequest(Request):
    """In-degree Request"""

    def __init__(self, n, order_id):
        self.n = n
        self.order_id = order_id

    def __setstate__(self, state):
        self.n, self.order_id = state

    def __getstate__(self):
        return self.n, self.order_id

    def process_request(self, server_state):
        local_g = server_state.graph
        partition_book = server_state.partition_book
        deg = _in_degrees(local_g, partition_book, self.n)

        return InDegreeResponse(deg, self.order_id)

467

468
469
470
471
472
473
474
475
476
477
478
479
480
class InDegreeResponse(Response):
    """The response for in-degree"""

    def __init__(self, deg, order_id):
        self.val = deg
        self.order_id = order_id

    def __setstate__(self, state):
        self.val, self.order_id = state

    def __getstate__(self):
        return self.val, self.order_id

481

482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class OutDegreeRequest(Request):
    """Out-degree Request"""

    def __init__(self, n, order_id):
        self.n = n
        self.order_id = order_id

    def __setstate__(self, state):
        self.n, self.order_id = state

    def __getstate__(self):
        return self.n, self.order_id

    def process_request(self, server_state):
        local_g = server_state.graph
        partition_book = server_state.partition_book
        deg = _out_degrees(local_g, partition_book, self.n)

        return OutDegreeResponse(deg, self.order_id)

502

503
504
505
506
507
508
509
510
511
512
513
514
515
class OutDegreeResponse(Response):
    """The response for out-degree"""

    def __init__(self, deg, order_id):
        self.val = deg
        self.order_id = order_id

    def __setstate__(self, state):
        self.val, self.order_id = state

    def __getstate__(self):
        return self.val, self.order_id

516

517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
class InSubgraphRequest(Request):
    """InSubgraph Request"""

    def __init__(self, nodes):
        self.seed_nodes = nodes

    def __setstate__(self, state):
        self.seed_nodes = state

    def __getstate__(self):
        return self.seed_nodes

    def process_request(self, server_state):
        local_g = server_state.graph
        partition_book = server_state.partition_book
532
533
534
        global_src, global_dst, global_eids = _in_subgraph(
            local_g, partition_book, self.seed_nodes
        )
535
        return SubgraphResponse(global_src, global_dst, global_eids)
Jinjing Zhou's avatar
Jinjing Zhou committed
536
537
538
539


def merge_graphs(res_list, num_nodes):
    """Merge request from multiple servers"""
540
541
542
543
544
545
546
547
548
549
    if len(res_list) > 1:
        srcs = []
        dsts = []
        eids = []
        for res in res_list:
            srcs.append(res.global_src)
            dsts.append(res.global_dst)
            eids.append(res.global_eids)
        src_tensor = F.cat(srcs, 0)
        dst_tensor = F.cat(dsts, 0)
550
        eid_tensor = None if eids[0] is None else F.cat(eids, 0)
551
552
553
554
    else:
        src_tensor = res_list[0].global_src
        dst_tensor = res_list[0].global_dst
        eid_tensor = res_list[0].global_eids
555
    g = graph((src_tensor, dst_tensor), num_nodes=num_nodes)
556
557
    if eid_tensor is not None:
        g.edata[EID] = eid_tensor
Jinjing Zhou's avatar
Jinjing Zhou committed
558
559
    return g

560
561
562
563
564

LocalSampledGraph = namedtuple(
    "LocalSampledGraph", "global_src global_dst global_eids"
)

Jinjing Zhou's avatar
Jinjing Zhou committed
565

566
def _distributed_access(g, nodes, issue_remote_req, local_access):
567
    """A routine that fetches local neighborhood of nodes from the distributed graph.
568

569
570
571
572
573
    The local neighborhood of some nodes are stored in the local machine and the other
    nodes have their neighborhood on remote machines. This code will issue remote
    access requests first before fetching data from the local machine. In the end,
    we combine the data from the local machine and remote machines.
    In this way, we can hide the latency of accessing data on remote machines.
574
575
576
577

    Parameters
    ----------
    g : DistGraph
578
579
580
581
582
583
584
        The distributed graph
    nodes : tensor
        The nodes whose neighborhood are to be fetched.
    issue_remote_req : callable
        The function that issues requests to access remote data.
    local_access : callable
        The function that reads data on the local machine.
585
586
587

    Returns
    -------
peizhou001's avatar
peizhou001 committed
588
    DGLGraph
589
        The subgraph that contains the neighborhoods of all input nodes.
590
    """
Jinjing Zhou's avatar
Jinjing Zhou committed
591
    req_list = []
592
    partition_book = g.get_partition_book()
593
594
    if not isinstance(nodes, torch.Tensor):
        nodes = toindex(nodes).tousertensor()
595
596
    partition_id = partition_book.nid2partid(nodes)
    local_nids = None
597
    for pid in range(partition_book.num_partitions()):
598
599
600
601
602
        node_id = F.boolean_mask(nodes, partition_id == pid)
        # We optimize the sampling on a local partition if the server and the client
        # run on the same machine. With a good partitioning, most of the seed nodes
        # should reside in the local partition. If the server and the client
        # are not co-located, the client doesn't have a local partition.
603
        if pid == partition_book.partid and g.local_partition is not None:
604
605
606
            assert local_nids is None
            local_nids = node_id
        elif len(node_id) != 0:
607
            req = issue_remote_req(node_id)
Jinjing Zhou's avatar
Jinjing Zhou committed
608
            req_list.append((pid, req))
609
610
611
612
613
614
615
616
617

    # send requests to the remote machine.
    msgseq2pos = None
    if len(req_list) > 0:
        msgseq2pos = send_requests_to_machine(req_list)

    # sample neighbors for the nodes in the local partition.
    res_list = []
    if local_nids is not None:
618
619
620
        src, dst, eids = local_access(
            g.local_partition, partition_book, local_nids
        )
621
622
623
624
625
626
627
        res_list.append(LocalSampledGraph(src, dst, eids))

    # receive responses from remote machines.
    if msgseq2pos is not None:
        results = recv_responses(msgseq2pos)
        res_list.extend(results)

628
    sampled_graph = merge_graphs(res_list, g.num_nodes())
Jinjing Zhou's avatar
Jinjing Zhou committed
629
630
    return sampled_graph

631

632
def _frontier_to_heterogeneous_graph(g, frontier, gpb):
633
    # We need to handle empty frontiers correctly.
634
    if frontier.num_edges() == 0:
635
636
637
638
639
        data_dict = {
            etype: (np.zeros(0), np.zeros(0)) for etype in g.canonical_etypes
        }
        return heterograph(
            data_dict,
640
            {ntype: g.num_nodes(ntype) for ntype in g.ntypes},
641
642
            idtype=g.idtype,
        )
643

644
645
646
647
648
649
650
651
652
653
    etype_ids, frontier.edata[EID] = gpb.map_to_per_etype(frontier.edata[EID])
    src, dst = frontier.edges()
    etype_ids, idx = F.sort_1d(etype_ids)
    src, dst = F.gather_row(src, idx), F.gather_row(dst, idx)
    eid = F.gather_row(frontier.edata[EID], idx)
    _, src = gpb.map_to_per_ntype(src)
    _, dst = gpb.map_to_per_ntype(dst)

    data_dict = dict()
    edge_ids = {}
654
    for etid, etype in enumerate(g.canonical_etypes):
655
656
        type_idx = etype_ids == etid
        if F.sum(type_idx, 0) > 0:
657
            data_dict[etype] = (
658
659
660
                F.boolean_mask(src, type_idx),
                F.boolean_mask(dst, type_idx),
            )
661
            edge_ids[etype] = F.boolean_mask(eid, type_idx)
662
663
    hg = heterograph(
        data_dict,
664
        {ntype: g.num_nodes(ntype) for ntype in g.ntypes},
665
666
        idtype=g.idtype,
    )
667
668
669
670
671

    for etype in edge_ids:
        hg.edges[etype].data[EID] = edge_ids[etype]
    return hg

672
673
674
675
676
677
678
679
680
681

def sample_etype_neighbors(
    g,
    nodes,
    fanout,
    edge_dir="in",
    prob=None,
    replace=False,
    etype_sorted=True,
):
682
683
684
685
686
687
688
689
690
    """Sample from the neighbors of the given nodes from a distributed graph.

    For each node, a number of inbound (or outbound when ``edge_dir == 'out'``) edges
    will be randomly chosen.  The returned graph will contain all the nodes in the
    original graph, but only the sampled edges.

    Node/edge features are not preserved. The original IDs of
    the sampled edges are stored as the `dgl.EID` feature in the returned graph.

691
692
    This function assumes the input is a homogeneous ``DGLGraph`` with the edges
    ordered by their edge types. The sampled subgraph is also
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
    stored in the homogeneous graph format. That is, all nodes and edges are assigned
    with unique IDs (in contrast, we typically use a type name and a node/edge ID to
    identify a node or an edge in ``DGLGraph``). We refer to this type of IDs
    as *homogeneous ID*.
    Users can use :func:`dgl.distributed.GraphPartitionBook.map_to_per_ntype`
    and :func:`dgl.distributed.GraphPartitionBook.map_to_per_etype`
    to identify their node/edge types and node/edge IDs of that type.

    Parameters
    ----------
    g : DistGraph
        The distributed graph..
    nodes : tensor or dict
        Node IDs to sample neighbors from. If it's a dict, it should contain only
        one key-value pair to make this API consistent with dgl.sampling.sample_neighbors.
708
709
710
    fanout : int or dict[etype, int]
        The number of edges to be sampled for each node per edge type.  If an integer
        is given, DGL assumes that the same fanout is applied to every edge type.
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731

        If -1 is given, all of the neighbors will be selected.
    edge_dir : str, optional
        Determines whether to sample inbound or outbound edges.

        Can take either ``in`` for inbound edges or ``out`` for outbound edges.
    prob : str, optional
        Feature name used as the (unnormalized) probabilities associated with each
        neighboring edge of a node.  The feature must have only one element for each
        edge.

        The features must be non-negative floats, and the sum of the features of
        inbound/outbound edges for every node must be positive (though they don't have
        to sum up to one).  Otherwise, the result will be undefined.
    replace : bool, optional
        If True, sample with replacement.

        When sampling with replacement, the sampled subgraph could have parallel edges.

        For sampling without replacement, if fanout > the number of neighbors, all the
        neighbors are sampled. If fanout == -1, all neighbors are collected.
732
733
    etype_sorted : bool, optional
        Indicates whether etypes are sorted.
734
735
736
737
738
739

    Returns
    -------
    DGLGraph
        A sampled subgraph containing only the sampled neighboring edges.  It is on CPU.
    """
740
    if isinstance(fanout, int):
741
        fanout = F.full_1d(len(g.canonical_etypes), fanout, F.int64, F.cpu())
742
    else:
743
744
745
746
747
748
749
750
751
752
753
        etype_ids = {etype: i for i, etype in enumerate(g.canonical_etypes)}
        fanout_array = [None] * len(g.canonical_etypes)
        for etype, v in fanout.items():
            c_etype = g.to_canonical_etype(etype)
            fanout_array[etype_ids[c_etype]] = v
        assert all(v is not None for v in fanout_array), (
            "Not all etypes have valid fanout. Please make sure passed-in "
            "fanout in dict includes all the etypes in graph. Passed-in "
            f"fanout: {fanout}, graph etypes: {g.canonical_etypes}."
        )
        fanout = F.tensor(fanout_array, dtype=F.int64)
754

755
756
757
758
    gpb = g.get_partition_book()
    if isinstance(nodes, dict):
        homo_nids = []
        for ntype in nodes.keys():
759
760
761
762
763
            assert (
                ntype in g.ntypes
            ), "The sampled node type {} does not exist in the input graph".format(
                ntype
            )
764
765
766
767
768
769
            if F.is_tensor(nodes[ntype]):
                typed_nodes = nodes[ntype]
            else:
                typed_nodes = toindex(nodes[ntype]).tousertensor()
            homo_nids.append(gpb.map_to_homo_nid(typed_nodes, ntype))
        nodes = F.cat(homo_nids, 0)
770

771
    def issue_remote_req(node_ids):
772
773
774
775
776
777
778
779
        if prob is not None:
            # See NOTE 1
            _prob = [
                # NOTE (BarclayII)
                # Currently DistGraph.edges[] does not accept canonical etype.
                g.edges[etype].data[prob].kvstore_key
                if prob in g.edges[etype].data
                else ""
780
                for etype in g.canonical_etypes
781
782
783
            ]
        else:
            _prob = None
784
785
786
787
        return SamplingRequestEtype(
            node_ids,
            fanout,
            edge_dir=edge_dir,
788
            prob=_prob,
789
790
791
792
            replace=replace,
            etype_sorted=etype_sorted,
        )

793
    def local_access(local_g, partition_book, local_nids):
794
795
796
797
798
799
800
801
802
        etype_offset = gpb.local_etype_offset
        # See NOTE 1
        if prob is None:
            _prob = None
        else:
            _prob = [
                g.edges[etype].data[prob].local_partition
                if prob in g.edges[etype].data
                else None
803
                for etype in g.canonical_etypes
804
            ]
805
806
807
808
        return _sample_etype_neighbors(
            local_g,
            partition_book,
            local_nids,
809
            etype_offset,
810
811
            fanout,
            edge_dir,
812
            _prob,
813
814
815
816
            replace,
            etype_sorted=etype_sorted,
        )

817
    frontier = _distributed_access(g, nodes, issue_remote_req, local_access)
818
    if not gpb.is_homogeneous:
819
        return _frontier_to_heterogeneous_graph(g, frontier, gpb)
820
821
822
    else:
        return frontier

823

824
825
826
827
828
829
830
831
832
def sample_neighbors(
    g,
    nodes,
    fanout,
    edge_dir="in",
    prob=None,
    replace=False,
    use_graphbolt=False,
):
833
834
    """Sample from the neighbors of the given nodes from a distributed graph.

835
836
837
    For each node, a number of inbound (or outbound when ``edge_dir == 'out'``) edges
    will be randomly chosen.  The returned graph will contain all the nodes in the
    original graph, but only the sampled edges.
838
839
840

    Node/edge features are not preserved. The original IDs of
    the sampled edges are stored as the `dgl.EID` feature in the returned graph.
Jinjing Zhou's avatar
Jinjing Zhou committed
841

842
843
    For heterogeneous graphs, ``nodes`` is a dictionary whose key is node type
    and the value is type-specific node IDs.
844
845
846
847

    Parameters
    ----------
    g : DistGraph
848
        The distributed graph..
Da Zheng's avatar
Da Zheng committed
849
    nodes : tensor or dict
850
        Node IDs to sample neighbors from. If it's a dict, it should contain only
Da Zheng's avatar
Da Zheng committed
851
        one key-value pair to make this API consistent with dgl.sampling.sample_neighbors.
852
    fanout : int
853
854
855
        The number of edges to be sampled for each node.

        If -1 is given, all of the neighbors will be selected.
856
    edge_dir : str, optional
857
858
859
        Determines whether to sample inbound or outbound edges.

        Can take either ``in`` for inbound edges or ``out`` for outbound edges.
860
    prob : str, optional
861
862
863
864
865
866
867
        Feature name used as the (unnormalized) probabilities associated with each
        neighboring edge of a node.  The feature must have only one element for each
        edge.

        The features must be non-negative floats, and the sum of the features of
        inbound/outbound edges for every node must be positive (though they don't have
        to sum up to one).  Otherwise, the result will be undefined.
868
869
870
    replace : bool, optional
        If True, sample with replacement.

871
872
873
874
        When sampling with replacement, the sampled subgraph could have parallel edges.

        For sampling without replacement, if fanout > the number of neighbors, all the
        neighbors are sampled. If fanout == -1, all neighbors are collected.
875
876
    use_graphbolt : bool, optional
        Whether to use GraphBolt for sampling.
877

878
879
    Returns
    -------
880
881
    DGLGraph
        A sampled subgraph containing only the sampled neighboring edges.  It is on CPU.
882
    """
883
    gpb = g.get_partition_book()
884
    if not gpb.is_homogeneous:
885
        assert isinstance(nodes, dict)
886
887
        homo_nids = []
        for ntype in nodes:
888
889
890
            assert (
                ntype in g.ntypes
            ), "The sampled node type does not exist in the input graph"
891
892
893
894
895
896
            if F.is_tensor(nodes[ntype]):
                typed_nodes = nodes[ntype]
            else:
                typed_nodes = toindex(nodes[ntype]).tousertensor()
            homo_nids.append(gpb.map_to_homo_nid(typed_nodes, ntype))
        nodes = F.cat(homo_nids, 0)
897
898
899
900
    elif isinstance(nodes, dict):
        assert len(nodes) == 1
        nodes = list(nodes.values())[0]

901
    def issue_remote_req(node_ids):
902
903
904
905
906
        if prob is not None:
            # See NOTE 1
            _prob = g.edata[prob].kvstore_key
        else:
            _prob = None
907
        return SamplingRequest(
908
909
910
911
912
913
            node_ids,
            fanout,
            edge_dir=edge_dir,
            prob=_prob,
            replace=replace,
            use_graphbolt=use_graphbolt,
914
915
        )

916
    def local_access(local_g, partition_book, local_nids):
917
        # See NOTE 1
918
        _prob = [g.edata[prob].local_partition] if prob is not None else None
919
920
921
922
923
924
925
926
927
        if use_graphbolt:
            return _sample_neighbors_graphbolt(
                local_g,
                partition_book,
                local_nids,
                fanout,
                prob=_prob,
                replace=replace,
            )
928
        return _sample_neighbors(
929
930
931
932
933
934
935
            local_g,
            partition_book,
            local_nids,
            fanout,
            edge_dir,
            _prob,
            replace,
936
937
        )

938
    frontier = _distributed_access(g, nodes, issue_remote_req, local_access)
939
    if not gpb.is_homogeneous:
940
        return _frontier_to_heterogeneous_graph(g, frontier, gpb)
941
942
    else:
        return frontier
943

944

945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
def _distributed_edge_access(g, edges, issue_remote_req, local_access):
    """A routine that fetches local edges from distributed graph.

    The source and destination nodes of local edges are stored in the local
    machine and others are stored on remote machines. This code will issue
    remote access requests first before fetching data from the local machine.
    In the end, we combine the data from the local machine and remote machines.

    Parameters
    ----------
    g : DistGraph
        The distributed graph
    edges : tensor
        The edges to find their source and destination nodes.
    issue_remote_req : callable
        The function that issues requests to access remote data.
    local_access : callable
        The function that reads data on the local machine.

    Returns
    -------
    tensor
        The source node ID array.
    tensor
        The destination node ID array.
    """
    req_list = []
    partition_book = g.get_partition_book()
    edges = toindex(edges).tousertensor()
    partition_id = partition_book.eid2partid(edges)
    local_eids = None
    reorder_idx = []
    for pid in range(partition_book.num_partitions()):
978
        mask = partition_id == pid
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
        edge_id = F.boolean_mask(edges, mask)
        reorder_idx.append(F.nonzero_1d(mask))
        if pid == partition_book.partid and g.local_partition is not None:
            assert local_eids is None
            local_eids = edge_id
        elif len(edge_id) != 0:
            req = issue_remote_req(edge_id, pid)
            req_list.append((pid, req))

    # send requests to the remote machine.
    msgseq2pos = None
    if len(req_list) > 0:
        msgseq2pos = send_requests_to_machine(req_list)

    # handle edges in local partition.
    src_ids = F.zeros_like(edges)
    dst_ids = F.zeros_like(edges)
    if local_eids is not None:
        src, dst = local_access(g.local_partition, partition_book, local_eids)
998
999
1000
1001
1002
1003
        src_ids = F.scatter_row(
            src_ids, reorder_idx[partition_book.partid], src
        )
        dst_ids = F.scatter_row(
            dst_ids, reorder_idx[partition_book.partid], dst
        )
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014

    # receive responses from remote machines.
    if msgseq2pos is not None:
        results = recv_responses(msgseq2pos)
        for result in results:
            src = result.global_src
            dst = result.global_dst
            src_ids = F.scatter_row(src_ids, reorder_idx[result.order_id], src)
            dst_ids = F.scatter_row(dst_ids, reorder_idx[result.order_id], dst)
    return src_ids, dst_ids

1015

1016
def find_edges(g, edge_ids):
1017
    """Given an edge ID array, return the source and destination
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
    node ID array ``s`` and ``d`` from a distributed graph.
    ``s[i]`` and ``d[i]`` are source and destination node ID for
    edge ``eid[i]``.

    Parameters
    ----------
    g : DistGraph
        The distributed graph.
    edges : tensor
        The edge ID array.

    Returns
    -------
    tensor
        The source node ID array.
    tensor
        The destination node ID array.
    """
1036

1037
    def issue_remote_req(edge_ids, order_id):
1038
        return EdgesRequest(edge_ids, order_id)
1039

1040
1041
    def local_access(local_g, partition_book, edge_ids):
        return _find_edges(local_g, partition_book, edge_ids)
1042

1043
    return _distributed_edge_access(g, edge_ids, issue_remote_req, local_access)
1044

1045

1046
def in_subgraph(g, nodes):
1047
    """Return the subgraph induced on the inbound edges of the given nodes.
1048

1049
1050
1051
1052
    The subgraph keeps the same type schema and all the nodes are preserved regardless
    of whether they have an edge or not.

    Node/edge features are not preserved. The original IDs of
1053
1054
1055
1056
    the extracted edges are stored as the `dgl.EID` feature in the returned graph.

    For now, we only support the input graph with one node type and one edge type.

1057

1058
1059
1060
1061
    Parameters
    ----------
    g : DistGraph
        The distributed graph structure.
1062
    nodes : tensor or dict
1063
1064
1065
1066
        Node ids to sample neighbors from.

    Returns
    -------
1067
    DGLGraph
1068
        The subgraph.
1069
1070
1071

        One can retrieve the mapping from subgraph edge ID to parent
        edge ID via ``dgl.EID`` edge features of the subgraph.
1072
    """
Da Zheng's avatar
Da Zheng committed
1073
    if isinstance(nodes, dict):
1074
1075
1076
        assert (
            len(nodes) == 1
        ), "The distributed in_subgraph only supports one node type for now."
Da Zheng's avatar
Da Zheng committed
1077
        nodes = list(nodes.values())[0]
1078

1079
1080
    def issue_remote_req(node_ids):
        return InSubgraphRequest(node_ids)
1081

1082
1083
    def local_access(local_g, partition_book, local_nids):
        return _in_subgraph(local_g, partition_book, local_nids)
1084

1085
1086
    return _distributed_access(g, nodes, issue_remote_req, local_access)

1087

1088
1089
1090
1091
1092
1093
1094
1095
def _distributed_get_node_property(g, n, issue_remote_req, local_access):
    req_list = []
    partition_book = g.get_partition_book()
    n = toindex(n).tousertensor()
    partition_id = partition_book.nid2partid(n)
    local_nids = None
    reorder_idx = []
    for pid in range(partition_book.num_partitions()):
1096
        mask = partition_id == pid
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
        nid = F.boolean_mask(n, mask)
        reorder_idx.append(F.nonzero_1d(mask))
        if pid == partition_book.partid and g.local_partition is not None:
            assert local_nids is None
            local_nids = nid
        elif len(nid) != 0:
            req = issue_remote_req(nid, pid)
            req_list.append((pid, req))

    # send requests to the remote machine.
    msgseq2pos = None
    if len(req_list) > 0:
        msgseq2pos = send_requests_to_machine(req_list)

    # handle edges in local partition.
    vals = None
    if local_nids is not None:
        local_vals = local_access(g.local_partition, partition_book, local_nids)
        shape = list(F.shape(local_vals))
        shape[0] = len(n)
        vals = F.zeros(shape, F.dtype(local_vals), F.cpu())
1118
1119
1120
        vals = F.scatter_row(
            vals, reorder_idx[partition_book.partid], local_vals
        )
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133

    # receive responses from remote machines.
    if msgseq2pos is not None:
        results = recv_responses(msgseq2pos)
        if len(results) > 0 and vals is None:
            shape = list(F.shape(results[0].val))
            shape[0] = len(n)
            vals = F.zeros(shape, F.dtype(results[0].val), F.cpu())
        for result in results:
            val = result.val
            vals = F.scatter_row(vals, reorder_idx[result.order_id], val)
    return vals

1134

1135
def in_degrees(g, v):
1136
1137
    """Get in-degrees"""

1138
1139
    def issue_remote_req(v, order_id):
        return InDegreeRequest(v, order_id)
1140

1141
1142
    def local_access(local_g, partition_book, v):
        return _in_degrees(local_g, partition_book, v)
1143

1144
1145
    return _distributed_get_node_property(g, v, issue_remote_req, local_access)

1146

1147
def out_degrees(g, u):
1148
1149
    """Get out-degrees"""

1150
1151
    def issue_remote_req(u, order_id):
        return OutDegreeRequest(u, order_id)
1152

1153
1154
    def local_access(local_g, partition_book, u):
        return _out_degrees(local_g, partition_book, u)
1155

1156
1157
    return _distributed_get_node_property(g, u, issue_remote_req, local_access)

1158

1159
register_service(SAMPLING_SERVICE_ID, SamplingRequest, SubgraphResponse)
1160
register_service(EDGES_SERVICE_ID, EdgesRequest, FindEdgeResponse)
1161
register_service(INSUBGRAPH_SERVICE_ID, InSubgraphRequest, SubgraphResponse)
1162
1163
register_service(OUTDEGREE_SERVICE_ID, OutDegreeRequest, OutDegreeResponse)
register_service(INDEGREE_SERVICE_ID, InDegreeRequest, InDegreeResponse)
1164
1165
1166
register_service(
    ETYPE_SAMPLING_SERVICE_ID, SamplingRequestEtype, SubgraphResponse
)