"tests/compute/test_subgraph.py" did not exist on "2ecd2b23ec7e8f48c0e7286dad306d7265e17a29"
test_distributed_sampling.py 48.9 KB
Newer Older
1
import multiprocessing as mp
Jinjing Zhou's avatar
Jinjing Zhou committed
2
import os
3
import random
4
import tempfile
Jinjing Zhou's avatar
Jinjing Zhou committed
5
import time
6
7
import traceback
import unittest
Jinjing Zhou's avatar
Jinjing Zhou committed
8
from pathlib import Path
9
10
11
12

import backend as F
import dgl
import numpy as np
13
import pytest
14
15
16
17
18
19
20
21
22
23
from dgl.data import CitationGraphDataset, WN18Dataset
from dgl.distributed import (
    DistGraph,
    DistGraphServer,
    load_partition,
    load_partition_book,
    partition_graph,
    sample_etype_neighbors,
    sample_neighbors,
)
24
from scipy import sparse as spsp
25
from utils import generate_ip_config, reset_envs
Jinjing Zhou's avatar
Jinjing Zhou committed
26
27


28
29
30
31
32
33
def start_server(
    rank,
    tmpdir,
    disable_shared_mem,
    graph_name,
    graph_format=["csc", "coo"],
34
    use_graphbolt=False,
35
36
37
38
39
40
41
42
43
):
    g = DistGraphServer(
        rank,
        "rpc_ip_config.txt",
        1,
        1,
        tmpdir / (graph_name + ".json"),
        disable_shared_mem=disable_shared_mem,
        graph_format=graph_format,
44
        use_graphbolt=use_graphbolt,
45
    )
Jinjing Zhou's avatar
Jinjing Zhou committed
46
47
48
    g.start()


49
def start_sample_client(rank, tmpdir, disable_shared_mem):
50
51
    gpb = None
    if disable_shared_mem:
52
53
54
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_sampling.json", rank
        )
55
    dgl.distributed.initialize("rpc_ip_config.txt")
56
    dist_graph = DistGraph("test_sampling", gpb=gpb)
57
    try:
58
59
60
        sampled_graph = sample_neighbors(
            dist_graph, [0, 10, 99, 66, 1024, 2008], 3
        )
61
    except Exception as e:
62
        print(traceback.format_exc())
63
        sampled_graph = None
64
    dgl.distributed.exit_client()
Jinjing Zhou's avatar
Jinjing Zhou committed
65
66
    return sampled_graph

67

68
69
70
71
72
73
74
75
76
def start_sample_client_shuffle(
    rank,
    tmpdir,
    disable_shared_mem,
    g,
    num_servers,
    group_id,
    orig_nid,
    orig_eid,
77
    use_graphbolt=False,
78
    return_eids=False,
79
80
):
    os.environ["DGL_GROUP_ID"] = str(group_id)
81
82
    gpb = None
    if disable_shared_mem:
83
84
85
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_sampling.json", rank
        )
86
    dgl.distributed.initialize("rpc_ip_config.txt")
87
88
89
90
91
92
    dist_graph = DistGraph(
        "test_sampling", gpb=gpb, use_graphbolt=use_graphbolt
    )
    sampled_graph = sample_neighbors(
        dist_graph, [0, 10, 99, 66, 1024, 2008], 3, use_graphbolt=use_graphbolt
    )
93

94
95
96
    assert (
        dgl.ETYPE not in sampled_graph.edata
    ), "Etype should not be in homogeneous sampled graph."
97
98
99
    src, dst = sampled_graph.edges()
    src = orig_nid[src]
    dst = orig_nid[dst]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
100
    assert sampled_graph.num_nodes() == g.num_nodes()
101
    assert np.all(F.asnumpy(g.has_edges_between(src, dst)))
102
    if use_graphbolt and not return_eids:
103
104
105
106
107
108
109
        assert (
            dgl.EID not in sampled_graph.edata
        ), "EID should not be in sampled graph if use_graphbolt=True."
    else:
        eids = g.edge_ids(src, dst)
        eids1 = orig_eid[sampled_graph.edata[dgl.EID]]
        assert np.array_equal(F.asnumpy(eids1), F.asnumpy(eids))
110

111

112
def start_find_edges_client(rank, tmpdir, disable_shared_mem, eids, etype=None):
113
114
    gpb = None
    if disable_shared_mem:
115
116
117
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_find_edges.json", rank
        )
118
    dgl.distributed.initialize("rpc_ip_config.txt")
119
    dist_graph = DistGraph("test_find_edges", gpb=gpb)
120
    try:
121
        u, v = dist_graph.find_edges(eids, etype=etype)
122
    except Exception as e:
123
        print(traceback.format_exc())
124
        u, v = None, None
125
126
    dgl.distributed.exit_client()
    return u, v
Jinjing Zhou's avatar
Jinjing Zhou committed
127

128

129
130
131
def start_get_degrees_client(rank, tmpdir, disable_shared_mem, nids=None):
    gpb = None
    if disable_shared_mem:
132
133
134
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_get_degrees.json", rank
        )
135
    dgl.distributed.initialize("rpc_ip_config.txt")
136
137
138
139
140
141
142
    dist_graph = DistGraph("test_get_degrees", gpb=gpb)
    try:
        in_deg = dist_graph.in_degrees(nids)
        all_in_deg = dist_graph.in_degrees()
        out_deg = dist_graph.out_degrees(nids)
        all_out_deg = dist_graph.out_degrees()
    except Exception as e:
143
        print(traceback.format_exc())
144
145
146
147
        in_deg, out_deg, all_in_deg, all_out_deg = None, None, None, None
    dgl.distributed.exit_client()
    return in_deg, out_deg, all_in_deg, all_out_deg

148

149
def check_rpc_sampling(tmpdir, num_server):
150
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
Jinjing Zhou's avatar
Jinjing Zhou committed
151
152
153
154
155
156

    g = CitationGraphDataset("cora")[0]
    print(g.idtype)
    num_parts = num_server
    num_hops = 1

157
158
159
160
161
162
163
164
    partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )
Jinjing Zhou's avatar
Jinjing Zhou committed
165
166

    pserver_list = []
167
    ctx = mp.get_context("spawn")
Jinjing Zhou's avatar
Jinjing Zhou committed
168
    for i in range(num_server):
169
170
171
172
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
Jinjing Zhou's avatar
Jinjing Zhou committed
173
174
175
176
        p.start()
        time.sleep(1)
        pserver_list.append(p)

177
    sampled_graph = start_sample_client(0, tmpdir, num_server > 1)
Jinjing Zhou's avatar
Jinjing Zhou committed
178
179
180
    print("Done sampling")
    for p in pserver_list:
        p.join()
181
        assert p.exitcode == 0
Jinjing Zhou's avatar
Jinjing Zhou committed
182
183

    src, dst = sampled_graph.edges()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
184
    assert sampled_graph.num_nodes() == g.num_nodes()
Jinjing Zhou's avatar
Jinjing Zhou committed
185
186
187
    assert np.all(F.asnumpy(g.has_edges_between(src, dst)))
    eids = g.edge_ids(src, dst)
    assert np.array_equal(
188
189
190
        F.asnumpy(sampled_graph.edata[dgl.EID]), F.asnumpy(eids)
    )

Jinjing Zhou's avatar
Jinjing Zhou committed
191

192
def check_rpc_find_edges_shuffle(tmpdir, num_server):
193
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
194
195
196
197

    g = CitationGraphDataset("cora")[0]
    num_parts = num_server

198
199
200
201
202
203
204
205
206
    orig_nid, orig_eid = partition_graph(
        g,
        "test_find_edges",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
207
208

    pserver_list = []
209
    ctx = mp.get_context("spawn")
210
    for i in range(num_server):
211
212
213
214
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_find_edges", ["csr", "coo"]),
        )
215
216
217
218
        p.start()
        time.sleep(1)
        pserver_list.append(p)

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
219
    eids = F.tensor(np.random.randint(g.num_edges(), size=100))
220
    u, v = g.find_edges(orig_eid[eids])
221
    du, dv = start_find_edges_client(0, tmpdir, num_server > 1, eids)
222
223
    du = orig_nid[du]
    dv = orig_nid[dv]
224
225
226
    assert F.array_equal(u, du)
    assert F.array_equal(v, dv)

227

228
def create_random_hetero(dense=False, empty=False):
229
230
231
232
233
234
    num_nodes = (
        {"n1": 210, "n2": 200, "n3": 220}
        if dense
        else {"n1": 1010, "n2": 1000, "n3": 1020}
    )
    etypes = [("n1", "r12", "n2"), ("n1", "r13", "n3"), ("n2", "r23", "n3")]
235
    edges = {}
236
    random.seed(42)
237
238
    for etype in etypes:
        src_ntype, _, dst_ntype = etype
239
240
241
242
243
244
245
        arr = spsp.random(
            num_nodes[src_ntype] - 10 if empty else num_nodes[src_ntype],
            num_nodes[dst_ntype] - 10 if empty else num_nodes[dst_ntype],
            density=0.1 if dense else 0.001,
            format="coo",
            random_state=100,
        )
246
        edges[etype] = (arr.row, arr.col)
247
    g = dgl.heterograph(edges, num_nodes)
248
    g.nodes["n1"].data["feat"] = F.ones(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
249
        (g.num_nodes("n1"), 10), F.float32, F.cpu()
250
    )
251
    return g
252

253

254
def check_rpc_hetero_find_edges_shuffle(tmpdir, num_server):
255
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
256
257
258
259

    g = create_random_hetero()
    num_parts = num_server

260
261
262
263
264
265
266
267
268
    orig_nid, orig_eid = partition_graph(
        g,
        "test_find_edges",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
269
270

    pserver_list = []
271
    ctx = mp.get_context("spawn")
272
    for i in range(num_server):
273
274
275
276
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_find_edges", ["csr", "coo"]),
        )
277
278
279
280
        p.start()
        time.sleep(1)
        pserver_list.append(p)

281
    test_etype = g.to_canonical_etype("r12")
282
    eids = F.tensor(np.random.randint(g.num_edges(test_etype), size=100))
283
284
    expect_except = False
    try:
285
        _, _ = g.find_edges(orig_eid[test_etype][eids], etype=("n1", "r12"))
286
287
288
    except:
        expect_except = True
    assert expect_except
289
290
    u, v = g.find_edges(orig_eid[test_etype][eids], etype="r12")
    u1, v1 = g.find_edges(orig_eid[test_etype][eids], etype=("n1", "r12", "n2"))
291
292
    assert F.array_equal(u, u1)
    assert F.array_equal(v, v1)
293
294
295
296
297
    du, dv = start_find_edges_client(
        0, tmpdir, num_server > 1, eids, etype="r12"
    )
    du = orig_nid["n1"][du]
    dv = orig_nid["n2"][dv]
298
299
300
    assert F.array_equal(u, du)
    assert F.array_equal(v, dv)

301

302
# Wait non shared memory graph store
303
304
305
306
307
308
309
310
@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="Not support tensorflow for now",
)
@unittest.skipIf(
    dgl.backend.backend_name == "mxnet", reason="Turn off Mxnet support"
)
311
@pytest.mark.parametrize("num_server", [1])
312
def test_rpc_find_edges_shuffle(num_server):
313
    reset_envs()
314
    import tempfile
315
316

    os.environ["DGL_DIST_MODE"] = "distributed"
317
    with tempfile.TemporaryDirectory() as tmpdirname:
318
        check_rpc_hetero_find_edges_shuffle(Path(tmpdirname), num_server)
319
320
        check_rpc_find_edges_shuffle(Path(tmpdirname), num_server)

321

322
def check_rpc_get_degree_shuffle(tmpdir, num_server):
323
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
324
325
326
327

    g = CitationGraphDataset("cora")[0]
    num_parts = num_server

328
329
330
331
332
333
334
335
336
    orig_nid, _ = partition_graph(
        g,
        "test_get_degrees",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
337
338

    pserver_list = []
339
    ctx = mp.get_context("spawn")
340
    for i in range(num_server):
341
342
343
344
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_get_degrees"),
        )
345
346
347
348
        p.start()
        time.sleep(1)
        pserver_list.append(p)

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
349
    nids = F.tensor(np.random.randint(g.num_nodes(), size=100))
350
351
352
    in_degs, out_degs, all_in_degs, all_out_degs = start_get_degrees_client(
        0, tmpdir, num_server > 1, nids
    )
353
354
355
356

    print("Done get_degree")
    for p in pserver_list:
        p.join()
357
        assert p.exitcode == 0
358

359
    print("check results")
360
361
362
363
364
    assert F.array_equal(g.in_degrees(orig_nid[nids]), in_degs)
    assert F.array_equal(g.in_degrees(orig_nid), all_in_degs)
    assert F.array_equal(g.out_degrees(orig_nid[nids]), out_degs)
    assert F.array_equal(g.out_degrees(orig_nid), all_out_degs)

365

366
# Wait non shared memory graph store
367
368
369
370
371
372
373
374
@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="Not support tensorflow for now",
)
@unittest.skipIf(
    dgl.backend.backend_name == "mxnet", reason="Turn off Mxnet support"
)
375
@pytest.mark.parametrize("num_server", [1])
376
def test_rpc_get_degree_shuffle(num_server):
377
    reset_envs()
378
    import tempfile
379
380

    os.environ["DGL_DIST_MODE"] = "distributed"
381
382
383
    with tempfile.TemporaryDirectory() as tmpdirname:
        check_rpc_get_degree_shuffle(Path(tmpdirname), num_server)

384
385
386
387

# @unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
# @unittest.skipIf(dgl.backend.backend_name == 'tensorflow', reason='Not support tensorflow for now')
@unittest.skip("Only support partition with shuffle")
Jinjing Zhou's avatar
Jinjing Zhou committed
388
def test_rpc_sampling():
389
    reset_envs()
Jinjing Zhou's avatar
Jinjing Zhou committed
390
    import tempfile
391
392

    os.environ["DGL_DIST_MODE"] = "distributed"
Jinjing Zhou's avatar
Jinjing Zhou committed
393
    with tempfile.TemporaryDirectory() as tmpdirname:
394
        check_rpc_sampling(Path(tmpdirname), 1)
Jinjing Zhou's avatar
Jinjing Zhou committed
395

396

397
def check_rpc_sampling_shuffle(
398
    tmpdir, num_server, num_groups=1, use_graphbolt=False, return_eids=False
399
):
400
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
401

Jinjing Zhou's avatar
Jinjing Zhou committed
402
403
404
405
    g = CitationGraphDataset("cora")[0]
    num_parts = num_server
    num_hops = 1

406
407
408
409
410
411
412
413
    orig_nids, orig_eids = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
414
        use_graphbolt=use_graphbolt,
415
        store_eids=return_eids,
416
    )
Jinjing Zhou's avatar
Jinjing Zhou committed
417
418

    pserver_list = []
419
    ctx = mp.get_context("spawn")
Jinjing Zhou's avatar
Jinjing Zhou committed
420
    for i in range(num_server):
421
422
423
424
425
426
427
428
        p = ctx.Process(
            target=start_server,
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
429
                use_graphbolt,
430
431
            ),
        )
Jinjing Zhou's avatar
Jinjing Zhou committed
432
433
434
435
        p.start()
        time.sleep(1)
        pserver_list.append(p)

436
437
438
439
    pclient_list = []
    num_clients = 1
    for client_id in range(num_clients):
        for group_id in range(num_groups):
440
441
442
443
444
445
446
447
448
449
450
            p = ctx.Process(
                target=start_sample_client_shuffle,
                args=(
                    client_id,
                    tmpdir,
                    num_server > 1,
                    g,
                    num_server,
                    group_id,
                    orig_nids,
                    orig_eids,
451
                    use_graphbolt,
452
                    return_eids,
453
454
                ),
            )
455
            p.start()
456
            time.sleep(1)  # avoid race condition when instantiating DistGraph
457
458
459
            pclient_list.append(p)
    for p in pclient_list:
        p.join()
460
        assert p.exitcode == 0
Jinjing Zhou's avatar
Jinjing Zhou committed
461
462
    for p in pserver_list:
        p.join()
463
        assert p.exitcode == 0
Jinjing Zhou's avatar
Jinjing Zhou committed
464

465

466
467
468
469
470
471
472
473
def start_hetero_sample_client(
    rank,
    tmpdir,
    disable_shared_mem,
    nodes,
    use_graphbolt=False,
    return_eids=False,
):
474
475
    gpb = None
    if disable_shared_mem:
476
477
478
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_sampling.json", rank
        )
479
    dgl.distributed.initialize("rpc_ip_config.txt")
480
481
482
    dist_graph = DistGraph(
        "test_sampling", gpb=gpb, use_graphbolt=use_graphbolt
    )
483
484
485
    assert "feat" in dist_graph.nodes["n1"].data
    assert "feat" not in dist_graph.nodes["n2"].data
    assert "feat" not in dist_graph.nodes["n3"].data
486
487
488
    if gpb is None:
        gpb = dist_graph.get_partition_book()
    try:
489
490
491
492
493
        # Enable santity check in distributed sampling.
        os.environ["DGL_DIST_DEBUG"] = "1"
        sampled_graph = sample_neighbors(
            dist_graph, nodes, 3, use_graphbolt=use_graphbolt
        )
494
        block = dgl.to_block(sampled_graph, nodes)
495
496
        if not use_graphbolt or return_eids:
            block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
497
    except Exception as e:
498
        print(traceback.format_exc())
499
500
501
502
        block = None
    dgl.distributed.exit_client()
    return block, gpb

503
504
505
506
507
508
509
510

def start_hetero_etype_sample_client(
    rank,
    tmpdir,
    disable_shared_mem,
    fanout=3,
    nodes={"n3": [0, 10, 99, 66, 124, 208]},
    etype_sorted=False,
511
512
    use_graphbolt=False,
    return_eids=False,
513
):
514
515
    gpb = None
    if disable_shared_mem:
516
517
518
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_sampling.json", rank
        )
519
    dgl.distributed.initialize("rpc_ip_config.txt")
520
521
522
    dist_graph = DistGraph(
        "test_sampling", gpb=gpb, use_graphbolt=use_graphbolt
    )
523
524
525
    assert "feat" in dist_graph.nodes["n1"].data
    assert "feat" not in dist_graph.nodes["n2"].data
    assert "feat" not in dist_graph.nodes["n3"].data
526

527
    if (not use_graphbolt) and dist_graph.local_partition is not None:
528
529
530
531
        # Check whether etypes are sorted in dist_graph
        local_g = dist_graph.local_partition
        local_nids = np.arange(local_g.num_nodes())
        for lnid in local_nids:
532
            leids = local_g.in_edges(lnid, form="eid")
533
534
535
536
            letids = F.asnumpy(local_g.edata[dgl.ETYPE][leids])
            _, idices = np.unique(letids, return_index=True)
            assert np.all(idices[:-1] <= idices[1:])

537
538
539
    if gpb is None:
        gpb = dist_graph.get_partition_book()
    try:
540
541
        # Enable santity check in distributed sampling.
        os.environ["DGL_DIST_DEBUG"] = "1"
542
        sampled_graph = sample_etype_neighbors(
543
544
545
546
547
            dist_graph,
            nodes,
            fanout,
            etype_sorted=etype_sorted,
            use_graphbolt=use_graphbolt,
548
        )
549
        block = dgl.to_block(sampled_graph, nodes)
550
551
552
        if sampled_graph.num_edges() > 0:
            if not use_graphbolt or return_eids:
                block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
553
    except Exception as e:
554
        print(traceback.format_exc())
555
556
557
558
        block = None
    dgl.distributed.exit_client()
    return block, gpb

559

560
561
562
def check_rpc_hetero_sampling_shuffle(
    tmpdir, num_server, use_graphbolt=False, return_eids=False
):
563
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
564
565
566
567
568

    g = create_random_hetero()
    num_parts = num_server
    num_hops = 1

569
570
571
572
573
574
575
576
    orig_nid_map, orig_eid_map = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
577
578
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
579
    )
580
581

    pserver_list = []
582
    ctx = mp.get_context("spawn")
583
    for i in range(num_server):
584
585
        p = ctx.Process(
            target=start_server,
586
587
588
589
590
591
592
593
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
594
        )
595
596
597
598
        p.start()
        time.sleep(1)
        pserver_list.append(p)

599
    block, gpb = start_hetero_sample_client(
600
601
602
603
604
605
        0,
        tmpdir,
        num_server > 1,
        nodes={"n3": [0, 10, 99, 66, 124, 208]},
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
606
    )
607
608
    for p in pserver_list:
        p.join()
609
        assert p.exitcode == 0
610

611
612
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
613
614
615
616
617
618
        src, dst = block.edges(etype=etype)
        # These are global Ids after shuffling.
        shuffled_src = F.gather_row(block.srcnodes[src_type].data[dgl.NID], src)
        shuffled_dst = F.gather_row(block.dstnodes[dst_type].data[dgl.NID], dst)
        orig_src = F.asnumpy(F.gather_row(orig_nid_map[src_type], shuffled_src))
        orig_dst = F.asnumpy(F.gather_row(orig_nid_map[dst_type], shuffled_dst))
619
620
621
622
623
624
625
626
627

        assert np.all(
            F.asnumpy(g.has_edges_between(orig_src, orig_dst, etype=etype))
        )

        if use_graphbolt and not return_eids:
            continue

        shuffled_eid = block.edges[etype].data[dgl.EID]
628
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
629
630

        # Check the node Ids and edge Ids.
631
632
633
        orig_src1, orig_dst1 = g.find_edges(orig_eid, etype=etype)
        assert np.all(F.asnumpy(orig_src1) == orig_src)
        assert np.all(F.asnumpy(orig_dst1) == orig_dst)
634

635

636
637
638
639
640
641
642
643
644
def get_degrees(g, nids, ntype):
    deg = F.zeros((len(nids),), dtype=F.int64)
    for srctype, etype, dsttype in g.canonical_etypes:
        if srctype == ntype:
            deg += g.out_degrees(u=nids, etype=etype)
        elif dsttype == ntype:
            deg += g.in_degrees(v=nids, etype=etype)
    return deg

645

646
647
648
def check_rpc_hetero_sampling_empty_shuffle(
    tmpdir, num_server, use_graphbolt=False, return_eids=False
):
649
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
650
651
652
653
654

    g = create_random_hetero(empty=True)
    num_parts = num_server
    num_hops = 1

655
656
657
658
659
660
661
662
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
663
664
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
665
    )
666
667

    pserver_list = []
668
    ctx = mp.get_context("spawn")
669
    for i in range(num_server):
670
671
        p = ctx.Process(
            target=start_server,
672
673
674
675
676
677
678
679
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
680
        )
681
682
683
684
        p.start()
        time.sleep(1)
        pserver_list.append(p)

685
    deg = get_degrees(g, orig_nids["n3"], "n3")
686
    empty_nids = F.nonzero_1d(deg == 0)
687
    block, gpb = start_hetero_sample_client(
688
689
690
691
692
693
        0,
        tmpdir,
        num_server > 1,
        nodes={"n3": empty_nids},
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
694
    )
695
696
    for p in pserver_list:
        p.join()
697
        assert p.exitcode == 0
698

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
699
    assert block.num_edges() == 0
700
701
    assert len(block.etypes) == len(g.etypes)

702
703

def check_rpc_hetero_etype_sampling_shuffle(
704
705
706
707
708
    tmpdir,
    num_server,
    graph_formats=None,
    use_graphbolt=False,
    return_eids=False,
709
):
710
711
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

712
713
714
715
    g = create_random_hetero(dense=True)
    num_parts = num_server
    num_hops = 1

716
717
718
719
720
721
722
723
724
    orig_nid_map, orig_eid_map = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
        graph_formats=graph_formats,
725
726
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
727
    )
728
729

    pserver_list = []
730
    ctx = mp.get_context("spawn")
731
    for i in range(num_server):
732
733
        p = ctx.Process(
            target=start_server,
734
735
736
737
738
739
740
741
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
742
        )
743
744
745
746
        p.start()
        time.sleep(1)
        pserver_list.append(p)

747
    fanout = {etype: 3 for etype in g.canonical_etypes}
748
749
    etype_sorted = False
    if graph_formats is not None:
750
751
752
753
754
755
756
757
        etype_sorted = "csc" in graph_formats or "csr" in graph_formats
    block, gpb = start_hetero_etype_sample_client(
        0,
        tmpdir,
        num_server > 1,
        fanout,
        nodes={"n3": [0, 10, 99, 66, 124, 208]},
        etype_sorted=etype_sorted,
758
759
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
760
    )
761
762
763
    print("Done sampling")
    for p in pserver_list:
        p.join()
764
        assert p.exitcode == 0
765

766
    src, dst = block.edges(etype=("n1", "r13", "n3"))
767
    assert len(src) == 18
768
    src, dst = block.edges(etype=("n2", "r23", "n3"))
769
770
    assert len(src) == 18

771
772
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
773
774
775
776
777
778
        src, dst = block.edges(etype=etype)
        # These are global Ids after shuffling.
        shuffled_src = F.gather_row(block.srcnodes[src_type].data[dgl.NID], src)
        shuffled_dst = F.gather_row(block.dstnodes[dst_type].data[dgl.NID], dst)
        orig_src = F.asnumpy(F.gather_row(orig_nid_map[src_type], shuffled_src))
        orig_dst = F.asnumpy(F.gather_row(orig_nid_map[dst_type], shuffled_dst))
779
780
781
782
783
784
        assert np.all(
            F.asnumpy(g.has_edges_between(orig_src, orig_dst, etype=etype))
        )

        if use_graphbolt and not return_eids:
            continue
785
786

        # Check the node Ids and edge Ids.
787
788
        shuffled_eid = block.edges[etype].data[dgl.EID]
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
789
790
791
792
        orig_src1, orig_dst1 = g.find_edges(orig_eid, etype=etype)
        assert np.all(F.asnumpy(orig_src1) == orig_src)
        assert np.all(F.asnumpy(orig_dst1) == orig_dst)

793

794
795
796
def check_rpc_hetero_etype_sampling_empty_shuffle(
    tmpdir, num_server, use_graphbolt=False, return_eids=False
):
797
798
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

799
800
801
802
    g = create_random_hetero(dense=True, empty=True)
    num_parts = num_server
    num_hops = 1

803
804
805
806
807
808
809
810
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
811
812
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
813
    )
814
815

    pserver_list = []
816
    ctx = mp.get_context("spawn")
817
    for i in range(num_server):
818
819
        p = ctx.Process(
            target=start_server,
820
821
822
823
824
825
826
827
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
828
        )
829
830
831
832
833
        p.start()
        time.sleep(1)
        pserver_list.append(p)

    fanout = 3
834
    deg = get_degrees(g, orig_nids["n3"], "n3")
835
    empty_nids = F.nonzero_1d(deg == 0)
836
    block, gpb = start_hetero_etype_sample_client(
837
838
839
840
841
842
843
        0,
        tmpdir,
        num_server > 1,
        fanout,
        nodes={"n3": empty_nids},
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
844
    )
845
846
847
    print("Done sampling")
    for p in pserver_list:
        p.join()
848
        assert p.exitcode == 0
849

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
850
    assert block.num_edges() == 0
851
852
    assert len(block.etypes) == len(g.etypes)

853
854

def create_random_bipartite():
855
856
857
858
859
860
861
    g = dgl.rand_bipartite("user", "buys", "game", 500, 1000, 1000)
    g.nodes["user"].data["feat"] = F.ones(
        (g.num_nodes("user"), 10), F.float32, F.cpu()
    )
    g.nodes["game"].data["feat"] = F.ones(
        (g.num_nodes("game"), 10), F.float32, F.cpu()
    )
862
863
864
    return g


865
866
867
868
869
870
871
872
def start_bipartite_sample_client(
    rank,
    tmpdir,
    disable_shared_mem,
    nodes,
    use_graphbolt=False,
    return_eids=False,
):
873
874
875
    gpb = None
    if disable_shared_mem:
        _, _, _, gpb, _, _, _ = load_partition(
876
877
            tmpdir / "test_sampling.json", rank
        )
878
    dgl.distributed.initialize("rpc_ip_config.txt")
879
880
881
    dist_graph = DistGraph(
        "test_sampling", gpb=gpb, use_graphbolt=use_graphbolt
    )
882
883
    assert "feat" in dist_graph.nodes["user"].data
    assert "feat" in dist_graph.nodes["game"].data
884
885
    if gpb is None:
        gpb = dist_graph.get_partition_book()
886
887
888
889
890
    # Enable santity check in distributed sampling.
    os.environ["DGL_DIST_DEBUG"] = "1"
    sampled_graph = sample_neighbors(
        dist_graph, nodes, 3, use_graphbolt=use_graphbolt
    )
891
892
    block = dgl.to_block(sampled_graph, nodes)
    if sampled_graph.num_edges() > 0:
893
894
        if not use_graphbolt or return_eids:
            block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
895
896
897
898
    dgl.distributed.exit_client()
    return block, gpb


899
def start_bipartite_etype_sample_client(
900
901
902
903
904
905
906
    rank,
    tmpdir,
    disable_shared_mem,
    fanout=3,
    nodes={},
    use_graphbolt=False,
    return_eids=False,
907
):
908
909
910
    gpb = None
    if disable_shared_mem:
        _, _, _, gpb, _, _, _ = load_partition(
911
912
            tmpdir / "test_sampling.json", rank
        )
913
    dgl.distributed.initialize("rpc_ip_config.txt")
914
915
916
    dist_graph = DistGraph(
        "test_sampling", gpb=gpb, use_graphbolt=use_graphbolt
    )
917
918
    assert "feat" in dist_graph.nodes["user"].data
    assert "feat" in dist_graph.nodes["game"].data
919

920
    if not use_graphbolt and dist_graph.local_partition is not None:
921
922
923
924
        # Check whether etypes are sorted in dist_graph
        local_g = dist_graph.local_partition
        local_nids = np.arange(local_g.num_nodes())
        for lnid in local_nids:
925
            leids = local_g.in_edges(lnid, form="eid")
926
927
928
929
930
931
            letids = F.asnumpy(local_g.edata[dgl.ETYPE][leids])
            _, idices = np.unique(letids, return_index=True)
            assert np.all(idices[:-1] <= idices[1:])

    if gpb is None:
        gpb = dist_graph.get_partition_book()
932
933
934
    sampled_graph = sample_etype_neighbors(
        dist_graph, nodes, fanout, use_graphbolt=use_graphbolt
    )
935
936
    block = dgl.to_block(sampled_graph, nodes)
    if sampled_graph.num_edges() > 0:
937
938
        if not use_graphbolt or return_eids:
            block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
939
940
941
942
    dgl.distributed.exit_client()
    return block, gpb


943
944
945
def check_rpc_bipartite_sampling_empty(
    tmpdir, num_server, use_graphbolt=False, return_eids=False
):
946
947
948
949
950
951
952
    """sample on bipartite via sample_neighbors() which yields empty sample results"""
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

    g = create_random_bipartite()
    num_parts = num_server
    num_hops = 1

953
954
955
956
957
958
959
960
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
961
962
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
963
    )
964
965

    pserver_list = []
966
    ctx = mp.get_context("spawn")
967
    for i in range(num_server):
968
969
        p = ctx.Process(
            target=start_server,
970
971
972
973
974
975
976
977
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
978
        )
979
980
981
982
        p.start()
        time.sleep(1)
        pserver_list.append(p)

983
    deg = get_degrees(g, orig_nids["game"], "game")
984
    empty_nids = F.nonzero_1d(deg == 0)
985
    block, _ = start_bipartite_sample_client(
986
987
988
989
990
991
        0,
        tmpdir,
        num_server > 1,
        nodes={"game": empty_nids, "user": [1]},
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
992
    )
993
994
995
996

    print("Done sampling")
    for p in pserver_list:
        p.join()
997
        assert p.exitcode == 0
998

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
999
    assert block.num_edges() == 0
1000
1001
1002
    assert len(block.etypes) == len(g.etypes)


1003
1004
1005
def check_rpc_bipartite_sampling_shuffle(
    tmpdir, num_server, use_graphbolt=False, return_eids=False
):
1006
1007
1008
1009
1010
1011
1012
    """sample on bipartite via sample_neighbors() which yields non-empty sample results"""
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

    g = create_random_bipartite()
    num_parts = num_server
    num_hops = 1

1013
1014
1015
1016
1017
1018
1019
1020
    orig_nid_map, orig_eid_map = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
1021
1022
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
1023
    )
1024
1025

    pserver_list = []
1026
    ctx = mp.get_context("spawn")
1027
    for i in range(num_server):
1028
1029
        p = ctx.Process(
            target=start_server,
1030
1031
1032
1033
1034
1035
1036
1037
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
1038
        )
1039
1040
1041
1042
        p.start()
        time.sleep(1)
        pserver_list.append(p)

1043
    deg = get_degrees(g, orig_nid_map["game"], "game")
1044
    nids = F.nonzero_1d(deg > 0)
1045
    block, gpb = start_bipartite_sample_client(
1046
1047
1048
1049
1050
1051
        0,
        tmpdir,
        num_server > 1,
        nodes={"game": nids, "user": [0]},
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
1052
    )
1053
1054
1055
    print("Done sampling")
    for p in pserver_list:
        p.join()
1056
        assert p.exitcode == 0
1057

1058
1059
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
1060
1061
        src, dst = block.edges(etype=etype)
        # These are global Ids after shuffling.
1062
1063
1064
1065
        shuffled_src = F.gather_row(block.srcnodes[src_type].data[dgl.NID], src)
        shuffled_dst = F.gather_row(block.dstnodes[dst_type].data[dgl.NID], dst)
        orig_src = F.asnumpy(F.gather_row(orig_nid_map[src_type], shuffled_src))
        orig_dst = F.asnumpy(F.gather_row(orig_nid_map[dst_type], shuffled_dst))
1066
1067
1068
1069
1070
1071
1072
1073
        assert np.all(
            F.asnumpy(g.has_edges_between(orig_src, orig_dst, etype=etype))
        )

        if use_graphbolt and not return_eids:
            continue

        shuffled_eid = block.edges[etype].data[dgl.EID]
1074
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
1075
1076
1077
1078
1079
1080
1081

        # Check the node Ids and edge Ids.
        orig_src1, orig_dst1 = g.find_edges(orig_eid, etype=etype)
        assert np.all(F.asnumpy(orig_src1) == orig_src)
        assert np.all(F.asnumpy(orig_dst1) == orig_dst)


1082
1083
1084
def check_rpc_bipartite_etype_sampling_empty(
    tmpdir, num_server, use_graphbolt=False, return_eids=False
):
1085
1086
1087
1088
1089
1090
1091
    """sample on bipartite via sample_etype_neighbors() which yields empty sample results"""
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

    g = create_random_bipartite()
    num_parts = num_server
    num_hops = 1

1092
1093
1094
1095
1096
1097
1098
1099
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
1100
1101
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
1102
    )
1103
1104

    pserver_list = []
1105
    ctx = mp.get_context("spawn")
1106
    for i in range(num_server):
1107
1108
        p = ctx.Process(
            target=start_server,
1109
1110
1111
1112
1113
1114
1115
1116
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
1117
        )
1118
1119
1120
1121
        p.start()
        time.sleep(1)
        pserver_list.append(p)

1122
    deg = get_degrees(g, orig_nids["game"], "game")
1123
    empty_nids = F.nonzero_1d(deg == 0)
1124
1125
1126
1127
1128
1129
1130
    block, _ = start_bipartite_etype_sample_client(
        0,
        tmpdir,
        num_server > 1,
        nodes={"game": empty_nids, "user": [1]},
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
1131
    )
1132
1133
1134
1135

    print("Done sampling")
    for p in pserver_list:
        p.join()
1136
        assert p.exitcode == 0
1137
1138

    assert block is not None
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1139
    assert block.num_edges() == 0
1140
1141
1142
    assert len(block.etypes) == len(g.etypes)


1143
1144
1145
def check_rpc_bipartite_etype_sampling_shuffle(
    tmpdir, num_server, use_graphbolt=False, return_eids=False
):
1146
1147
1148
1149
1150
1151
1152
    """sample on bipartite via sample_etype_neighbors() which yields non-empty sample results"""
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

    g = create_random_bipartite()
    num_parts = num_server
    num_hops = 1

1153
1154
1155
1156
1157
1158
1159
1160
    orig_nid_map, orig_eid_map = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
1161
1162
        use_graphbolt=use_graphbolt,
        store_eids=return_eids,
1163
    )
1164
1165

    pserver_list = []
1166
    ctx = mp.get_context("spawn")
1167
    for i in range(num_server):
1168
1169
        p = ctx.Process(
            target=start_server,
1170
1171
1172
1173
1174
1175
1176
1177
            args=(
                i,
                tmpdir,
                num_server > 1,
                "test_sampling",
                ["csc", "coo"],
                use_graphbolt,
            ),
1178
        )
1179
1180
1181
1182
1183
        p.start()
        time.sleep(1)
        pserver_list.append(p)

    fanout = 3
1184
    deg = get_degrees(g, orig_nid_map["game"], "game")
1185
    nids = F.nonzero_1d(deg > 0)
1186
    block, gpb = start_bipartite_etype_sample_client(
1187
1188
1189
1190
1191
1192
1193
        0,
        tmpdir,
        num_server > 1,
        fanout,
        nodes={"game": nids, "user": [0]},
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
1194
    )
1195
1196
1197
    print("Done sampling")
    for p in pserver_list:
        p.join()
1198
        assert p.exitcode == 0
1199

1200
1201
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
1202
1203
        src, dst = block.edges(etype=etype)
        # These are global Ids after shuffling.
1204
1205
1206
1207
        shuffled_src = F.gather_row(block.srcnodes[src_type].data[dgl.NID], src)
        shuffled_dst = F.gather_row(block.dstnodes[dst_type].data[dgl.NID], dst)
        orig_src = F.asnumpy(F.gather_row(orig_nid_map[src_type], shuffled_src))
        orig_dst = F.asnumpy(F.gather_row(orig_nid_map[dst_type], shuffled_dst))
1208
1209
1210
1211
1212
1213
        assert np.all(
            F.asnumpy(g.has_edges_between(orig_src, orig_dst, etype=etype))
        )

        if use_graphbolt and not return_eids:
            continue
1214
1215

        # Check the node Ids and edge Ids.
1216
1217
        shuffled_eid = block.edges[etype].data[dgl.EID]
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
1218
1219
1220
1221
        orig_src1, orig_dst1 = g.find_edges(orig_eid, etype=etype)
        assert np.all(F.asnumpy(orig_src1) == orig_src)
        assert np.all(F.asnumpy(orig_dst1) == orig_dst)

1222

1223
@pytest.mark.parametrize("num_server", [1])
1224
@pytest.mark.parametrize("use_graphbolt", [False, True])
1225
1226
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_sampling_shuffle(num_server, use_graphbolt, return_eids):
1227
    reset_envs()
1228
    os.environ["DGL_DIST_MODE"] = "distributed"
Jinjing Zhou's avatar
Jinjing Zhou committed
1229
    with tempfile.TemporaryDirectory() as tmpdirname:
1230
        check_rpc_sampling_shuffle(
1231
1232
1233
1234
            Path(tmpdirname),
            num_server,
            use_graphbolt=use_graphbolt,
            return_eids=return_eids,
1235
        )
1236
1237
1238


@pytest.mark.parametrize("num_server", [1])
1239
1240
1241
@pytest.mark.parametrize("use_graphbolt,", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_hetero_sampling_shuffle(num_server, use_graphbolt, return_eids):
1242
1243
1244
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1245
1246
1247
1248
1249
1250
        check_rpc_hetero_sampling_shuffle(
            Path(tmpdirname),
            num_server,
            use_graphbolt=use_graphbolt,
            return_eids=return_eids,
        )
1251
1252
1253


@pytest.mark.parametrize("num_server", [1])
1254
1255
1256
1257
1258
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_hetero_sampling_empty_shuffle(
    num_server, use_graphbolt, return_eids
):
1259
1260
1261
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1262
1263
1264
1265
1266
1267
        check_rpc_hetero_sampling_empty_shuffle(
            Path(tmpdirname),
            num_server,
            use_graphbolt=use_graphbolt,
            return_eids=return_eids,
        )
1268
1269
1270
1271
1272
1273


@pytest.mark.parametrize("num_server", [1])
@pytest.mark.parametrize(
    "graph_formats", [None, ["csc"], ["csr"], ["csc", "coo"]]
)
1274
def test_rpc_hetero_etype_sampling_shuffle_dgl(num_server, graph_formats):
1275
1276
1277
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1278
        check_rpc_hetero_etype_sampling_shuffle(
1279
            Path(tmpdirname), num_server, graph_formats=graph_formats
1280
        )
1281
1282
1283


@pytest.mark.parametrize("num_server", [1])
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_hetero_etype_sampling_shuffle_graphbolt(num_server, return_eids):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
        check_rpc_hetero_etype_sampling_shuffle(
            Path(tmpdirname),
            num_server,
            use_graphbolt=True,
            return_eids=return_eids,
        )


@pytest.mark.parametrize("num_server", [1])
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_hetero_etype_sampling_empty_shuffle(
    num_server, use_graphbolt, return_eids
):
1303
1304
1305
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1306
        check_rpc_hetero_etype_sampling_empty_shuffle(
1307
1308
1309
1310
            Path(tmpdirname),
            num_server,
            use_graphbolt=use_graphbolt,
            return_eids=return_eids,
1311
        )
1312
1313
1314


@pytest.mark.parametrize("num_server", [1])
1315
1316
1317
1318
1319
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_bipartite_sampling_empty_shuffle(
    num_server, use_graphbolt, return_eids
):
1320
1321
1322
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1323
1324
1325
        check_rpc_bipartite_sampling_empty(
            Path(tmpdirname), num_server, use_graphbolt, return_eids
        )
1326
1327
1328


@pytest.mark.parametrize("num_server", [1])
1329
1330
1331
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_bipartite_sampling_shuffle(num_server, use_graphbolt, return_eids):
1332
1333
1334
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1335
1336
1337
        check_rpc_bipartite_sampling_shuffle(
            Path(tmpdirname), num_server, use_graphbolt, return_eids
        )
1338
1339
1340


@pytest.mark.parametrize("num_server", [1])
1341
1342
1343
1344
1345
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_bipartite_etype_sampling_empty_shuffle(
    num_server, use_graphbolt, return_eids
):
1346
1347
1348
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1349
1350
1351
1352
1353
1354
        check_rpc_bipartite_etype_sampling_empty(
            Path(tmpdirname),
            num_server,
            use_graphbolt=use_graphbolt,
            return_eids=return_eids,
        )
1355
1356
1357


@pytest.mark.parametrize("num_server", [1])
1358
1359
1360
1361
1362
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_rpc_bipartite_etype_sampling_shuffle(
    num_server, use_graphbolt, return_eids
):
1363
1364
1365
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1366
1367
1368
1369
1370
1371
        check_rpc_bipartite_etype_sampling_shuffle(
            Path(tmpdirname),
            num_server,
            use_graphbolt=use_graphbolt,
            return_eids=return_eids,
        )
Jinjing Zhou's avatar
Jinjing Zhou committed
1372

1373

1374
def check_standalone_sampling(tmpdir):
1375
    g = CitationGraphDataset("cora")[0]
1376
    prob = np.maximum(np.random.randn(g.num_edges()), 0)
1377
1378
1379
    mask = prob > 0
    g.edata["prob"] = F.tensor(prob)
    g.edata["mask"] = F.tensor(mask)
1380
1381
    num_parts = 1
    num_hops = 1
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
    partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )

    os.environ["DGL_DIST_MODE"] = "standalone"
1392
    dgl.distributed.initialize("rpc_ip_config.txt")
1393
1394
1395
    dist_graph = DistGraph(
        "test_sampling", part_config=tmpdir / "test_sampling.json"
    )
1396
1397
1398
    sampled_graph = sample_neighbors(dist_graph, [0, 10, 99, 66, 1024, 2008], 3)

    src, dst = sampled_graph.edges()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1399
    assert sampled_graph.num_nodes() == g.num_nodes()
1400
1401
1402
    assert np.all(F.asnumpy(g.has_edges_between(src, dst)))
    eids = g.edge_ids(src, dst)
    assert np.array_equal(
1403
1404
        F.asnumpy(sampled_graph.edata[dgl.EID]), F.asnumpy(eids)
    )
1405
1406

    sampled_graph = sample_neighbors(
1407
1408
        dist_graph, [0, 10, 99, 66, 1024, 2008], 3, prob="mask"
    )
1409
1410
1411
1412
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert mask[eid].all()

    sampled_graph = sample_neighbors(
1413
1414
        dist_graph, [0, 10, 99, 66, 1024, 2008], 3, prob="prob"
    )
1415
1416
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert (prob[eid] > 0).all()
1417
    dgl.distributed.exit_client()
1418

1419

1420
def check_standalone_etype_sampling(tmpdir):
1421
    hg = CitationGraphDataset("cora")[0]
1422
    prob = np.maximum(np.random.randn(hg.num_edges()), 0)
1423
1424
1425
    mask = prob > 0
    hg.edata["prob"] = F.tensor(prob)
    hg.edata["mask"] = F.tensor(mask)
1426
1427
1428
    num_parts = 1
    num_hops = 1

1429
1430
1431
1432
1433
1434
1435
1436
1437
    partition_graph(
        hg,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )
    os.environ["DGL_DIST_MODE"] = "standalone"
1438
    dgl.distributed.initialize("rpc_ip_config.txt")
1439
1440
1441
    dist_graph = DistGraph(
        "test_sampling", part_config=tmpdir / "test_sampling.json"
    )
1442
    sampled_graph = sample_etype_neighbors(dist_graph, [0, 10, 99, 66, 1023], 3)
1443
1444

    src, dst = sampled_graph.edges()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1445
    assert sampled_graph.num_nodes() == hg.num_nodes()
1446
1447
1448
    assert np.all(F.asnumpy(hg.has_edges_between(src, dst)))
    eids = hg.edge_ids(src, dst)
    assert np.array_equal(
1449
1450
        F.asnumpy(sampled_graph.edata[dgl.EID]), F.asnumpy(eids)
    )
1451
1452

    sampled_graph = sample_etype_neighbors(
1453
1454
        dist_graph, [0, 10, 99, 66, 1023], 3, prob="mask"
    )
1455
1456
1457
1458
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert mask[eid].all()

    sampled_graph = sample_etype_neighbors(
1459
1460
        dist_graph, [0, 10, 99, 66, 1023], 3, prob="prob"
    )
1461
1462
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert (prob[eid] > 0).all()
1463
1464
    dgl.distributed.exit_client()

1465

1466
def check_standalone_etype_sampling_heterograph(tmpdir):
1467
    hg = CitationGraphDataset("cora")[0]
1468
1469
1470
    num_parts = 1
    num_hops = 1
    src, dst = hg.edges()
1471
1472
1473
1474
1475
    new_hg = dgl.heterograph(
        {
            ("paper", "cite", "paper"): (src, dst),
            ("paper", "cite-by", "paper"): (dst, src),
        },
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1476
        {"paper": hg.num_nodes()},
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
    )
    partition_graph(
        new_hg,
        "test_hetero_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )
    os.environ["DGL_DIST_MODE"] = "standalone"
1487
    dgl.distributed.initialize("rpc_ip_config.txt")
1488
1489
1490
    dist_graph = DistGraph(
        "test_hetero_sampling", part_config=tmpdir / "test_hetero_sampling.json"
    )
1491
    sampled_graph = sample_etype_neighbors(
1492
1493
1494
        dist_graph, [0, 1, 2, 10, 99, 66, 1023, 1024, 2700, 2701], 1
    )
    src, dst = sampled_graph.edges(etype=("paper", "cite", "paper"))
1495
    assert len(src) == 10
1496
    src, dst = sampled_graph.edges(etype=("paper", "cite-by", "paper"))
1497
    assert len(src) == 10
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1498
    assert sampled_graph.num_nodes() == new_hg.num_nodes()
1499
1500
    dgl.distributed.exit_client()

1501
1502
1503
1504
1505
1506

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="Not support tensorflow for now",
)
1507
def test_standalone_sampling():
1508
    reset_envs()
1509
    import tempfile
1510
1511

    os.environ["DGL_DIST_MODE"] = "standalone"
1512
    with tempfile.TemporaryDirectory() as tmpdirname:
1513
        check_standalone_sampling(Path(tmpdirname))
1514

1515

1516
1517
def start_in_subgraph_client(rank, tmpdir, disable_shared_mem, nodes):
    gpb = None
1518
    dgl.distributed.initialize("rpc_ip_config.txt")
1519
    if disable_shared_mem:
1520
1521
1522
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_in_subgraph.json", rank
        )
1523
    dist_graph = DistGraph("test_in_subgraph", gpb=gpb)
1524
1525
1526
    try:
        sampled_graph = dgl.distributed.in_subgraph(dist_graph, nodes)
    except Exception as e:
1527
        print(traceback.format_exc())
1528
        sampled_graph = None
1529
    dgl.distributed.exit_client()
1530
1531
1532
    return sampled_graph


1533
def check_rpc_in_subgraph_shuffle(tmpdir, num_server):
1534
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
1535
1536
1537
1538

    g = CitationGraphDataset("cora")[0]
    num_parts = num_server

1539
1540
1541
1542
1543
1544
1545
1546
1547
    orig_nid, orig_eid = partition_graph(
        g,
        "test_in_subgraph",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
1548
1549

    pserver_list = []
1550
    ctx = mp.get_context("spawn")
1551
    for i in range(num_server):
1552
1553
1554
1555
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_in_subgraph"),
        )
1556
1557
1558
1559
1560
1561
1562
1563
        p.start()
        time.sleep(1)
        pserver_list.append(p)

    nodes = [0, 10, 99, 66, 1024, 2008]
    sampled_graph = start_in_subgraph_client(0, tmpdir, num_server > 1, nodes)
    for p in pserver_list:
        p.join()
1564
        assert p.exitcode == 0
1565
1566

    src, dst = sampled_graph.edges()
1567
1568
    src = orig_nid[src]
    dst = orig_nid[dst]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1569
    assert sampled_graph.num_nodes() == g.num_nodes()
1570
1571
1572
    assert np.all(F.asnumpy(g.has_edges_between(src, dst)))

    subg1 = dgl.in_subgraph(g, orig_nid[nodes])
1573
1574
1575
1576
    src1, dst1 = subg1.edges()
    assert np.all(np.sort(F.asnumpy(src)) == np.sort(F.asnumpy(src1)))
    assert np.all(np.sort(F.asnumpy(dst)) == np.sort(F.asnumpy(dst1)))
    eids = g.edge_ids(src, dst)
1577
1578
    eids1 = orig_eid[sampled_graph.edata[dgl.EID]]
    assert np.array_equal(F.asnumpy(eids1), F.asnumpy(eids))
1579

1580
1581
1582
1583
1584
1585

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="Not support tensorflow for now",
)
1586
def test_rpc_in_subgraph():
1587
    reset_envs()
1588
    import tempfile
1589
1590

    os.environ["DGL_DIST_MODE"] = "distributed"
1591
    with tempfile.TemporaryDirectory() as tmpdirname:
1592
        check_rpc_in_subgraph_shuffle(Path(tmpdirname), 1)
1593

1594
1595
1596
1597
1598
1599
1600
1601
1602

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="Not support tensorflow for now",
)
@unittest.skipIf(
    dgl.backend.backend_name == "mxnet", reason="Turn off Mxnet support"
)
1603
def test_standalone_etype_sampling():
1604
    reset_envs()
1605
    import tempfile
1606

1607
    with tempfile.TemporaryDirectory() as tmpdirname:
1608
        os.environ["DGL_DIST_MODE"] = "standalone"
1609
        check_standalone_etype_sampling_heterograph(Path(tmpdirname))
1610
    with tempfile.TemporaryDirectory() as tmpdirname:
1611
        os.environ["DGL_DIST_MODE"] = "standalone"
1612
        check_standalone_etype_sampling(Path(tmpdirname))
1613

1614

Jinjing Zhou's avatar
Jinjing Zhou committed
1615
1616
if __name__ == "__main__":
    import tempfile
1617

Jinjing Zhou's avatar
Jinjing Zhou committed
1618
    with tempfile.TemporaryDirectory() as tmpdirname:
1619
        os.environ["DGL_DIST_MODE"] = "standalone"
1620
        check_standalone_etype_sampling_heterograph(Path(tmpdirname))
1621
1622

    with tempfile.TemporaryDirectory() as tmpdirname:
1623
        os.environ["DGL_DIST_MODE"] = "standalone"
1624
1625
        check_standalone_etype_sampling(Path(tmpdirname))
        check_standalone_sampling(Path(tmpdirname))
1626
        os.environ["DGL_DIST_MODE"] = "distributed"
1627
1628
        check_rpc_sampling(Path(tmpdirname), 2)
        check_rpc_sampling(Path(tmpdirname), 1)
1629
1630
        check_rpc_get_degree_shuffle(Path(tmpdirname), 1)
        check_rpc_get_degree_shuffle(Path(tmpdirname), 2)
1631
1632
        check_rpc_find_edges_shuffle(Path(tmpdirname), 2)
        check_rpc_find_edges_shuffle(Path(tmpdirname), 1)
1633
1634
        check_rpc_hetero_find_edges_shuffle(Path(tmpdirname), 1)
        check_rpc_hetero_find_edges_shuffle(Path(tmpdirname), 2)
1635
1636
1637
1638
        check_rpc_in_subgraph_shuffle(Path(tmpdirname), 2)
        check_rpc_sampling_shuffle(Path(tmpdirname), 1)
        check_rpc_hetero_sampling_shuffle(Path(tmpdirname), 1)
        check_rpc_hetero_sampling_shuffle(Path(tmpdirname), 2)
1639
1640
1641
1642
        check_rpc_hetero_sampling_empty_shuffle(Path(tmpdirname), 1)
        check_rpc_hetero_etype_sampling_shuffle(Path(tmpdirname), 1)
        check_rpc_hetero_etype_sampling_shuffle(Path(tmpdirname), 2)
        check_rpc_hetero_etype_sampling_empty_shuffle(Path(tmpdirname), 1)