test_distributed_sampling.py 41.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
79
):
    os.environ["DGL_GROUP_ID"] = str(group_id)
80
81
    gpb = None
    if disable_shared_mem:
82
83
84
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_sampling.json", rank
        )
85
    dgl.distributed.initialize("rpc_ip_config.txt")
86
87
88
89
90
91
    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
    )
92
93
94
95

    src, dst = sampled_graph.edges()
    src = orig_nid[src]
    dst = orig_nid[dst]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
96
    assert sampled_graph.num_nodes() == g.num_nodes()
97
    assert np.all(F.asnumpy(g.has_edges_between(src, dst)))
98
99
100
101
102
103
104
105
    if use_graphbolt:
        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))
106

107

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

124

125
126
127
def start_get_degrees_client(rank, tmpdir, disable_shared_mem, nids=None):
    gpb = None
    if disable_shared_mem:
128
129
130
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_get_degrees.json", rank
        )
131
    dgl.distributed.initialize("rpc_ip_config.txt")
132
133
134
135
136
137
138
    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:
139
        print(traceback.format_exc())
140
141
142
143
        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

144

145
def check_rpc_sampling(tmpdir, num_server):
146
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
Jinjing Zhou's avatar
Jinjing Zhou committed
147
148
149
150
151
152

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

153
154
155
156
157
158
159
160
    partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )
Jinjing Zhou's avatar
Jinjing Zhou committed
161
162

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

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

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

Jinjing Zhou's avatar
Jinjing Zhou committed
187

188
def check_rpc_find_edges_shuffle(tmpdir, num_server):
189
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
190
191
192
193

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

194
195
196
197
198
199
200
201
202
    orig_nid, orig_eid = partition_graph(
        g,
        "test_find_edges",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
203
204

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

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

223

224
def create_random_hetero(dense=False, empty=False):
225
226
227
228
229
230
    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")]
231
    edges = {}
232
    random.seed(42)
233
234
    for etype in etypes:
        src_ntype, _, dst_ntype = etype
235
236
237
238
239
240
241
        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,
        )
242
        edges[etype] = (arr.row, arr.col)
243
    g = dgl.heterograph(edges, num_nodes)
244
    g.nodes["n1"].data["feat"] = F.ones(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
245
        (g.num_nodes("n1"), 10), F.float32, F.cpu()
246
    )
247
    return g
248

249

250
def check_rpc_hetero_find_edges_shuffle(tmpdir, num_server):
251
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
252
253
254
255

    g = create_random_hetero()
    num_parts = num_server

256
257
258
259
260
261
262
263
264
    orig_nid, orig_eid = partition_graph(
        g,
        "test_find_edges",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
265
266

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

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

297

298
# Wait non shared memory graph store
299
300
301
302
303
304
305
306
@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"
)
307
@pytest.mark.parametrize("num_server", [1])
308
def test_rpc_find_edges_shuffle(num_server):
309
    reset_envs()
310
    import tempfile
311
312

    os.environ["DGL_DIST_MODE"] = "distributed"
313
    with tempfile.TemporaryDirectory() as tmpdirname:
314
        check_rpc_hetero_find_edges_shuffle(Path(tmpdirname), num_server)
315
316
        check_rpc_find_edges_shuffle(Path(tmpdirname), num_server)

317

318
def check_rpc_get_degree_shuffle(tmpdir, num_server):
319
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
320
321
322
323

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

324
325
326
327
328
329
330
331
332
    orig_nid, _ = partition_graph(
        g,
        "test_get_degrees",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
333
334

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

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

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

355
    print("check results")
356
357
358
359
360
    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)

361

362
# Wait non shared memory graph store
363
364
365
366
367
368
369
370
@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"
)
371
@pytest.mark.parametrize("num_server", [1])
372
def test_rpc_get_degree_shuffle(num_server):
373
    reset_envs()
374
    import tempfile
375
376

    os.environ["DGL_DIST_MODE"] = "distributed"
377
378
379
    with tempfile.TemporaryDirectory() as tmpdirname:
        check_rpc_get_degree_shuffle(Path(tmpdirname), num_server)

380
381
382
383

# @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
384
def test_rpc_sampling():
385
    reset_envs()
Jinjing Zhou's avatar
Jinjing Zhou committed
386
    import tempfile
387
388

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

392

393
394
395
def check_rpc_sampling_shuffle(
    tmpdir, num_server, num_groups=1, use_graphbolt=False
):
396
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
397

Jinjing Zhou's avatar
Jinjing Zhou committed
398
399
400
401
    g = CitationGraphDataset("cora")[0]
    num_parts = num_server
    num_hops = 1

402
403
404
405
406
407
408
409
    orig_nids, orig_eids = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
410
        use_graphbolt=use_graphbolt,
411
    )
Jinjing Zhou's avatar
Jinjing Zhou committed
412
413

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

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

459

460
def start_hetero_sample_client(rank, tmpdir, disable_shared_mem, nodes):
461
462
    gpb = None
    if disable_shared_mem:
463
464
465
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_sampling.json", rank
        )
466
    dgl.distributed.initialize("rpc_ip_config.txt")
467
    dist_graph = DistGraph("test_sampling", gpb=gpb)
468
469
470
    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
471
472
473
474
475
476
477
    if gpb is None:
        gpb = dist_graph.get_partition_book()
    try:
        sampled_graph = sample_neighbors(dist_graph, nodes, 3)
        block = dgl.to_block(sampled_graph, nodes)
        block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
    except Exception as e:
478
        print(traceback.format_exc())
479
480
481
482
        block = None
    dgl.distributed.exit_client()
    return block, gpb

483
484
485
486
487
488
489
490
491

def start_hetero_etype_sample_client(
    rank,
    tmpdir,
    disable_shared_mem,
    fanout=3,
    nodes={"n3": [0, 10, 99, 66, 124, 208]},
    etype_sorted=False,
):
492
493
    gpb = None
    if disable_shared_mem:
494
495
496
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_sampling.json", rank
        )
497
498
    dgl.distributed.initialize("rpc_ip_config.txt")
    dist_graph = DistGraph("test_sampling", gpb=gpb)
499
500
501
    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
502
503
504
505
506
507

    if dist_graph.local_partition is not None:
        # 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:
508
            leids = local_g.in_edges(lnid, form="eid")
509
510
511
512
            letids = F.asnumpy(local_g.edata[dgl.ETYPE][leids])
            _, idices = np.unique(letids, return_index=True)
            assert np.all(idices[:-1] <= idices[1:])

513
514
515
    if gpb is None:
        gpb = dist_graph.get_partition_book()
    try:
516
        sampled_graph = sample_etype_neighbors(
517
518
            dist_graph, nodes, fanout, etype_sorted=etype_sorted
        )
519
520
521
        block = dgl.to_block(sampled_graph, nodes)
        block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
    except Exception as e:
522
        print(traceback.format_exc())
523
524
525
526
        block = None
    dgl.distributed.exit_client()
    return block, gpb

527

528
def check_rpc_hetero_sampling_shuffle(tmpdir, num_server):
529
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
530
531
532
533
534

    g = create_random_hetero()
    num_parts = num_server
    num_hops = 1

535
536
537
538
539
540
541
542
543
    orig_nid_map, orig_eid_map = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
    )
544
545

    pserver_list = []
546
    ctx = mp.get_context("spawn")
547
    for i in range(num_server):
548
549
550
551
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
552
553
554
555
        p.start()
        time.sleep(1)
        pserver_list.append(p)

556
557
558
    block, gpb = start_hetero_sample_client(
        0, tmpdir, num_server > 1, nodes={"n3": [0, 10, 99, 66, 124, 208]}
    )
559
560
561
    print("Done sampling")
    for p in pserver_list:
        p.join()
562
        assert p.exitcode == 0
563

564
565
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
566
567
568
569
570
571
572
573
        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)
        shuffled_eid = block.edges[etype].data[dgl.EID]

        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))
574
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
575
576

        # Check the node Ids and edge Ids.
577
578
579
        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)
580

581

582
583
584
585
586
587
588
589
590
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

591

592
def check_rpc_hetero_sampling_empty_shuffle(tmpdir, num_server):
593
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
594
595
596
597
598

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

599
600
601
602
603
604
605
606
607
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
    )
608
609

    pserver_list = []
610
    ctx = mp.get_context("spawn")
611
    for i in range(num_server):
612
613
614
615
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
616
617
618
619
        p.start()
        time.sleep(1)
        pserver_list.append(p)

620
    deg = get_degrees(g, orig_nids["n3"], "n3")
621
    empty_nids = F.nonzero_1d(deg == 0)
622
623
624
    block, gpb = start_hetero_sample_client(
        0, tmpdir, num_server > 1, nodes={"n3": empty_nids}
    )
625
626
627
    print("Done sampling")
    for p in pserver_list:
        p.join()
628
        assert p.exitcode == 0
629

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
630
    assert block.num_edges() == 0
631
632
    assert len(block.etypes) == len(g.etypes)

633
634
635
636

def check_rpc_hetero_etype_sampling_shuffle(
    tmpdir, num_server, graph_formats=None
):
637
638
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

639
640
641
642
    g = create_random_hetero(dense=True)
    num_parts = num_server
    num_hops = 1

643
644
645
646
647
648
649
650
651
652
    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,
    )
653
654

    pserver_list = []
655
    ctx = mp.get_context("spawn")
656
    for i in range(num_server):
657
658
659
660
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling", ["csc", "coo"]),
        )
661
662
663
664
        p.start()
        time.sleep(1)
        pserver_list.append(p)

665
    fanout = {etype: 3 for etype in g.canonical_etypes}
666
667
    etype_sorted = False
    if graph_formats is not None:
668
669
670
671
672
673
674
675
676
        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,
    )
677
678
679
    print("Done sampling")
    for p in pserver_list:
        p.join()
680
        assert p.exitcode == 0
681

682
    src, dst = block.edges(etype=("n1", "r13", "n3"))
683
    assert len(src) == 18
684
    src, dst = block.edges(etype=("n2", "r23", "n3"))
685
686
    assert len(src) == 18

687
688
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
689
690
691
692
693
694
695
696
        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)
        shuffled_eid = block.edges[etype].data[dgl.EID]

        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))
697
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
698
699
700
701
702
703

        # 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)

704

705
def check_rpc_hetero_etype_sampling_empty_shuffle(tmpdir, num_server):
706
707
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)

708
709
710
711
    g = create_random_hetero(dense=True, empty=True)
    num_parts = num_server
    num_hops = 1

712
713
714
715
716
717
718
719
720
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
    )
721
722

    pserver_list = []
723
    ctx = mp.get_context("spawn")
724
    for i in range(num_server):
725
726
727
728
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
729
730
731
732
733
        p.start()
        time.sleep(1)
        pserver_list.append(p)

    fanout = 3
734
    deg = get_degrees(g, orig_nids["n3"], "n3")
735
    empty_nids = F.nonzero_1d(deg == 0)
736
737
738
    block, gpb = start_hetero_etype_sample_client(
        0, tmpdir, num_server > 1, fanout, nodes={"n3": empty_nids}
    )
739
740
741
    print("Done sampling")
    for p in pserver_list:
        p.join()
742
        assert p.exitcode == 0
743

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
744
    assert block.num_edges() == 0
745
746
    assert len(block.etypes) == len(g.etypes)

747
748

def create_random_bipartite():
749
750
751
752
753
754
755
    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()
    )
756
757
758
759
760
761
762
    return g


def start_bipartite_sample_client(rank, tmpdir, disable_shared_mem, nodes):
    gpb = None
    if disable_shared_mem:
        _, _, _, gpb, _, _, _ = load_partition(
763
764
            tmpdir / "test_sampling.json", rank
        )
765
766
    dgl.distributed.initialize("rpc_ip_config.txt")
    dist_graph = DistGraph("test_sampling", gpb=gpb)
767
768
    assert "feat" in dist_graph.nodes["user"].data
    assert "feat" in dist_graph.nodes["game"].data
769
770
771
772
773
774
775
776
777
778
    if gpb is None:
        gpb = dist_graph.get_partition_book()
    sampled_graph = sample_neighbors(dist_graph, nodes, 3)
    block = dgl.to_block(sampled_graph, nodes)
    if sampled_graph.num_edges() > 0:
        block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
    dgl.distributed.exit_client()
    return block, gpb


779
780
781
def start_bipartite_etype_sample_client(
    rank, tmpdir, disable_shared_mem, fanout=3, nodes={}
):
782
783
784
    gpb = None
    if disable_shared_mem:
        _, _, _, gpb, _, _, _ = load_partition(
785
786
            tmpdir / "test_sampling.json", rank
        )
787
788
    dgl.distributed.initialize("rpc_ip_config.txt")
    dist_graph = DistGraph("test_sampling", gpb=gpb)
789
790
    assert "feat" in dist_graph.nodes["user"].data
    assert "feat" in dist_graph.nodes["game"].data
791
792
793
794
795
796

    if dist_graph.local_partition is not None:
        # 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:
797
            leids = local_g.in_edges(lnid, form="eid")
798
799
800
801
802
803
            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()
804
    sampled_graph = sample_etype_neighbors(dist_graph, nodes, fanout)
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
    block = dgl.to_block(sampled_graph, nodes)
    if sampled_graph.num_edges() > 0:
        block.edata[dgl.EID] = sampled_graph.edata[dgl.EID]
    dgl.distributed.exit_client()
    return block, gpb


def check_rpc_bipartite_sampling_empty(tmpdir, num_server):
    """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

820
821
822
823
824
825
826
827
828
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
    )
829
830

    pserver_list = []
831
    ctx = mp.get_context("spawn")
832
    for i in range(num_server):
833
834
835
836
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
837
838
839
840
        p.start()
        time.sleep(1)
        pserver_list.append(p)

841
    deg = get_degrees(g, orig_nids["game"], "game")
842
    empty_nids = F.nonzero_1d(deg == 0)
843
844
845
    block, _ = start_bipartite_sample_client(
        0, tmpdir, num_server > 1, nodes={"game": empty_nids, "user": [1]}
    )
846
847
848
849

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

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
852
    assert block.num_edges() == 0
853
854
855
856
857
858
859
860
861
862
863
    assert len(block.etypes) == len(g.etypes)


def check_rpc_bipartite_sampling_shuffle(tmpdir, num_server):
    """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

864
865
866
867
868
869
870
871
872
    orig_nid_map, orig_eid_map = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
    )
873
874

    pserver_list = []
875
    ctx = mp.get_context("spawn")
876
    for i in range(num_server):
877
878
879
880
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
881
882
883
884
        p.start()
        time.sleep(1)
        pserver_list.append(p)

885
    deg = get_degrees(g, orig_nid_map["game"], "game")
886
    nids = F.nonzero_1d(deg > 0)
887
888
889
    block, gpb = start_bipartite_sample_client(
        0, tmpdir, num_server > 1, nodes={"game": nids, "user": [0]}
    )
890
891
892
    print("Done sampling")
    for p in pserver_list:
        p.join()
893
        assert p.exitcode == 0
894

895
896
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
897
898
        src, dst = block.edges(etype=etype)
        # These are global Ids after shuffling.
899
900
        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)
901
902
        shuffled_eid = block.edges[etype].data[dgl.EID]

903
904
        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))
905
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920

        # 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)


def check_rpc_bipartite_etype_sampling_empty(tmpdir, num_server):
    """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

921
922
923
924
925
926
927
928
929
    orig_nids, _ = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
    )
930
931

    pserver_list = []
932
    ctx = mp.get_context("spawn")
933
    for i in range(num_server):
934
935
936
937
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
938
939
940
941
        p.start()
        time.sleep(1)
        pserver_list.append(p)

942
    deg = get_degrees(g, orig_nids["game"], "game")
943
    empty_nids = F.nonzero_1d(deg == 0)
944
945
946
    block, gpb = start_bipartite_etype_sample_client(
        0, tmpdir, num_server > 1, nodes={"game": empty_nids, "user": [1]}
    )
947
948
949
950

    print("Done sampling")
    for p in pserver_list:
        p.join()
951
        assert p.exitcode == 0
952
953

    assert block is not None
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
954
    assert block.num_edges() == 0
955
956
957
958
959
960
961
962
963
964
965
    assert len(block.etypes) == len(g.etypes)


def check_rpc_bipartite_etype_sampling_shuffle(tmpdir, num_server):
    """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

966
967
968
969
970
971
972
973
974
    orig_nid_map, orig_eid_map = partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
        return_mapping=True,
    )
975
976

    pserver_list = []
977
    ctx = mp.get_context("spawn")
978
    for i in range(num_server):
979
980
981
982
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_sampling"),
        )
983
984
985
986
987
        p.start()
        time.sleep(1)
        pserver_list.append(p)

    fanout = 3
988
    deg = get_degrees(g, orig_nid_map["game"], "game")
989
    nids = F.nonzero_1d(deg > 0)
990
991
992
    block, gpb = start_bipartite_etype_sample_client(
        0, tmpdir, num_server > 1, fanout, nodes={"game": nids, "user": [0]}
    )
993
994
995
    print("Done sampling")
    for p in pserver_list:
        p.join()
996
        assert p.exitcode == 0
997

998
999
    for c_etype in block.canonical_etypes:
        src_type, etype, dst_type = c_etype
1000
1001
        src, dst = block.edges(etype=etype)
        # These are global Ids after shuffling.
1002
1003
        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)
1004
1005
        shuffled_eid = block.edges[etype].data[dgl.EID]

1006
1007
        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))
1008
        orig_eid = F.asnumpy(F.gather_row(orig_eid_map[c_etype], shuffled_eid))
1009
1010
1011
1012
1013
1014

        # 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)

1015

1016
@pytest.mark.parametrize("num_server", [1])
1017
1018
@pytest.mark.parametrize("use_graphbolt", [False, True])
def test_rpc_sampling_shuffle(num_server, use_graphbolt):
1019
    reset_envs()
1020
    os.environ["DGL_DIST_MODE"] = "distributed"
Jinjing Zhou's avatar
Jinjing Zhou committed
1021
    with tempfile.TemporaryDirectory() as tmpdirname:
1022
        check_rpc_sampling_shuffle(
1023
            Path(tmpdirname), num_server, use_graphbolt=use_graphbolt
1024
        )
1025
1026
1027
1028
1029
1030
1031


@pytest.mark.parametrize("num_server", [1])
def test_rpc_hetero_sampling_shuffle(num_server):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1032
        check_rpc_hetero_sampling_shuffle(Path(tmpdirname), num_server)
1033
1034
1035
1036
1037
1038
1039


@pytest.mark.parametrize("num_server", [1])
def test_rpc_hetero_sampling_empty_shuffle(num_server):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1040
        check_rpc_hetero_sampling_empty_shuffle(Path(tmpdirname), num_server)
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050


@pytest.mark.parametrize("num_server", [1])
@pytest.mark.parametrize(
    "graph_formats", [None, ["csc"], ["csr"], ["csc", "coo"]]
)
def test_rpc_hetero_etype_sampling_shuffle(num_server, graph_formats):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1051
        check_rpc_hetero_etype_sampling_shuffle(
1052
            Path(tmpdirname), num_server, graph_formats=graph_formats
1053
        )
1054
1055
1056
1057
1058
1059
1060


@pytest.mark.parametrize("num_server", [1])
def test_rpc_hetero_etype_sampling_empty_shuffle(num_server):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1061
1062
1063
        check_rpc_hetero_etype_sampling_empty_shuffle(
            Path(tmpdirname), num_server
        )
1064
1065
1066
1067
1068
1069
1070


@pytest.mark.parametrize("num_server", [1])
def test_rpc_bipartite_sampling_empty_shuffle(num_server):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1071
        check_rpc_bipartite_sampling_empty(Path(tmpdirname), num_server)
1072
1073
1074
1075
1076
1077
1078


@pytest.mark.parametrize("num_server", [1])
def test_rpc_bipartite_sampling_shuffle(num_server):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1079
        check_rpc_bipartite_sampling_shuffle(Path(tmpdirname), num_server)
1080
1081
1082
1083
1084
1085
1086


@pytest.mark.parametrize("num_server", [1])
def test_rpc_bipartite_etype_sampling_empty_shuffle(num_server):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1087
        check_rpc_bipartite_etype_sampling_empty(Path(tmpdirname), num_server)
1088
1089
1090
1091
1092
1093
1094


@pytest.mark.parametrize("num_server", [1])
def test_rpc_bipartite_etype_sampling_shuffle(num_server):
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    with tempfile.TemporaryDirectory() as tmpdirname:
1095
        check_rpc_bipartite_etype_sampling_shuffle(Path(tmpdirname), num_server)
Jinjing Zhou's avatar
Jinjing Zhou committed
1096

1097

1098
def check_standalone_sampling(tmpdir):
1099
    g = CitationGraphDataset("cora")[0]
1100
    prob = np.maximum(np.random.randn(g.num_edges()), 0)
1101
1102
1103
    mask = prob > 0
    g.edata["prob"] = F.tensor(prob)
    g.edata["mask"] = F.tensor(mask)
1104
1105
    num_parts = 1
    num_hops = 1
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
    partition_graph(
        g,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )

    os.environ["DGL_DIST_MODE"] = "standalone"
1116
    dgl.distributed.initialize("rpc_ip_config.txt")
1117
1118
1119
    dist_graph = DistGraph(
        "test_sampling", part_config=tmpdir / "test_sampling.json"
    )
1120
1121
1122
    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
1123
    assert sampled_graph.num_nodes() == g.num_nodes()
1124
1125
1126
    assert np.all(F.asnumpy(g.has_edges_between(src, dst)))
    eids = g.edge_ids(src, dst)
    assert np.array_equal(
1127
1128
        F.asnumpy(sampled_graph.edata[dgl.EID]), F.asnumpy(eids)
    )
1129
1130

    sampled_graph = sample_neighbors(
1131
1132
        dist_graph, [0, 10, 99, 66, 1024, 2008], 3, prob="mask"
    )
1133
1134
1135
1136
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert mask[eid].all()

    sampled_graph = sample_neighbors(
1137
1138
        dist_graph, [0, 10, 99, 66, 1024, 2008], 3, prob="prob"
    )
1139
1140
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert (prob[eid] > 0).all()
1141
    dgl.distributed.exit_client()
1142

1143

1144
def check_standalone_etype_sampling(tmpdir):
1145
    hg = CitationGraphDataset("cora")[0]
1146
    prob = np.maximum(np.random.randn(hg.num_edges()), 0)
1147
1148
1149
    mask = prob > 0
    hg.edata["prob"] = F.tensor(prob)
    hg.edata["mask"] = F.tensor(mask)
1150
1151
1152
    num_parts = 1
    num_hops = 1

1153
1154
1155
1156
1157
1158
1159
1160
1161
    partition_graph(
        hg,
        "test_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )
    os.environ["DGL_DIST_MODE"] = "standalone"
1162
    dgl.distributed.initialize("rpc_ip_config.txt")
1163
1164
1165
    dist_graph = DistGraph(
        "test_sampling", part_config=tmpdir / "test_sampling.json"
    )
1166
    sampled_graph = sample_etype_neighbors(dist_graph, [0, 10, 99, 66, 1023], 3)
1167
1168

    src, dst = sampled_graph.edges()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1169
    assert sampled_graph.num_nodes() == hg.num_nodes()
1170
1171
1172
    assert np.all(F.asnumpy(hg.has_edges_between(src, dst)))
    eids = hg.edge_ids(src, dst)
    assert np.array_equal(
1173
1174
        F.asnumpy(sampled_graph.edata[dgl.EID]), F.asnumpy(eids)
    )
1175
1176

    sampled_graph = sample_etype_neighbors(
1177
1178
        dist_graph, [0, 10, 99, 66, 1023], 3, prob="mask"
    )
1179
1180
1181
1182
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert mask[eid].all()

    sampled_graph = sample_etype_neighbors(
1183
1184
        dist_graph, [0, 10, 99, 66, 1023], 3, prob="prob"
    )
1185
1186
    eid = F.asnumpy(sampled_graph.edata[dgl.EID])
    assert (prob[eid] > 0).all()
1187
1188
    dgl.distributed.exit_client()

1189

1190
def check_standalone_etype_sampling_heterograph(tmpdir):
1191
    hg = CitationGraphDataset("cora")[0]
1192
1193
1194
    num_parts = 1
    num_hops = 1
    src, dst = hg.edges()
1195
1196
1197
1198
1199
    new_hg = dgl.heterograph(
        {
            ("paper", "cite", "paper"): (src, dst),
            ("paper", "cite-by", "paper"): (dst, src),
        },
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1200
        {"paper": hg.num_nodes()},
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
    )
    partition_graph(
        new_hg,
        "test_hetero_sampling",
        num_parts,
        tmpdir,
        num_hops=num_hops,
        part_method="metis",
    )
    os.environ["DGL_DIST_MODE"] = "standalone"
1211
    dgl.distributed.initialize("rpc_ip_config.txt")
1212
1213
1214
    dist_graph = DistGraph(
        "test_hetero_sampling", part_config=tmpdir / "test_hetero_sampling.json"
    )
1215
    sampled_graph = sample_etype_neighbors(
1216
1217
1218
        dist_graph, [0, 1, 2, 10, 99, 66, 1023, 1024, 2700, 2701], 1
    )
    src, dst = sampled_graph.edges(etype=("paper", "cite", "paper"))
1219
    assert len(src) == 10
1220
    src, dst = sampled_graph.edges(etype=("paper", "cite-by", "paper"))
1221
    assert len(src) == 10
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1222
    assert sampled_graph.num_nodes() == new_hg.num_nodes()
1223
1224
    dgl.distributed.exit_client()

1225
1226
1227
1228
1229
1230

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="Not support tensorflow for now",
)
1231
def test_standalone_sampling():
1232
    reset_envs()
1233
    import tempfile
1234
1235

    os.environ["DGL_DIST_MODE"] = "standalone"
1236
    with tempfile.TemporaryDirectory() as tmpdirname:
1237
        check_standalone_sampling(Path(tmpdirname))
1238

1239

1240
1241
def start_in_subgraph_client(rank, tmpdir, disable_shared_mem, nodes):
    gpb = None
1242
    dgl.distributed.initialize("rpc_ip_config.txt")
1243
    if disable_shared_mem:
1244
1245
1246
        _, _, _, gpb, _, _, _ = load_partition(
            tmpdir / "test_in_subgraph.json", rank
        )
1247
    dist_graph = DistGraph("test_in_subgraph", gpb=gpb)
1248
1249
1250
    try:
        sampled_graph = dgl.distributed.in_subgraph(dist_graph, nodes)
    except Exception as e:
1251
        print(traceback.format_exc())
1252
        sampled_graph = None
1253
    dgl.distributed.exit_client()
1254
1255
1256
    return sampled_graph


1257
def check_rpc_in_subgraph_shuffle(tmpdir, num_server):
1258
    generate_ip_config("rpc_ip_config.txt", num_server, num_server)
1259
1260
1261
1262

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

1263
1264
1265
1266
1267
1268
1269
1270
1271
    orig_nid, orig_eid = partition_graph(
        g,
        "test_in_subgraph",
        num_parts,
        tmpdir,
        num_hops=1,
        part_method="metis",
        return_mapping=True,
    )
1272
1273

    pserver_list = []
1274
    ctx = mp.get_context("spawn")
1275
    for i in range(num_server):
1276
1277
1278
1279
        p = ctx.Process(
            target=start_server,
            args=(i, tmpdir, num_server > 1, "test_in_subgraph"),
        )
1280
1281
1282
1283
1284
1285
1286
1287
        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()
1288
        assert p.exitcode == 0
1289
1290

    src, dst = sampled_graph.edges()
1291
1292
    src = orig_nid[src]
    dst = orig_nid[dst]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1293
    assert sampled_graph.num_nodes() == g.num_nodes()
1294
1295
1296
    assert np.all(F.asnumpy(g.has_edges_between(src, dst)))

    subg1 = dgl.in_subgraph(g, orig_nid[nodes])
1297
1298
1299
1300
    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)
1301
1302
    eids1 = orig_eid[sampled_graph.edata[dgl.EID]]
    assert np.array_equal(F.asnumpy(eids1), F.asnumpy(eids))
1303

1304
1305
1306
1307
1308
1309

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="Not support tensorflow for now",
)
1310
def test_rpc_in_subgraph():
1311
    reset_envs()
1312
    import tempfile
1313
1314

    os.environ["DGL_DIST_MODE"] = "distributed"
1315
    with tempfile.TemporaryDirectory() as tmpdirname:
1316
        check_rpc_in_subgraph_shuffle(Path(tmpdirname), 1)
1317

1318
1319
1320
1321
1322
1323
1324
1325
1326

@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"
)
1327
def test_standalone_etype_sampling():
1328
    reset_envs()
1329
    import tempfile
1330

1331
    with tempfile.TemporaryDirectory() as tmpdirname:
1332
        os.environ["DGL_DIST_MODE"] = "standalone"
1333
        check_standalone_etype_sampling_heterograph(Path(tmpdirname))
1334
    with tempfile.TemporaryDirectory() as tmpdirname:
1335
        os.environ["DGL_DIST_MODE"] = "standalone"
1336
        check_standalone_etype_sampling(Path(tmpdirname))
1337

1338

Jinjing Zhou's avatar
Jinjing Zhou committed
1339
1340
if __name__ == "__main__":
    import tempfile
1341

Jinjing Zhou's avatar
Jinjing Zhou committed
1342
    with tempfile.TemporaryDirectory() as tmpdirname:
1343
        os.environ["DGL_DIST_MODE"] = "standalone"
1344
        check_standalone_etype_sampling_heterograph(Path(tmpdirname))
1345
1346

    with tempfile.TemporaryDirectory() as tmpdirname:
1347
        os.environ["DGL_DIST_MODE"] = "standalone"
1348
1349
        check_standalone_etype_sampling(Path(tmpdirname))
        check_standalone_sampling(Path(tmpdirname))
1350
        os.environ["DGL_DIST_MODE"] = "distributed"
1351
1352
        check_rpc_sampling(Path(tmpdirname), 2)
        check_rpc_sampling(Path(tmpdirname), 1)
1353
1354
        check_rpc_get_degree_shuffle(Path(tmpdirname), 1)
        check_rpc_get_degree_shuffle(Path(tmpdirname), 2)
1355
1356
        check_rpc_find_edges_shuffle(Path(tmpdirname), 2)
        check_rpc_find_edges_shuffle(Path(tmpdirname), 1)
1357
1358
        check_rpc_hetero_find_edges_shuffle(Path(tmpdirname), 1)
        check_rpc_hetero_find_edges_shuffle(Path(tmpdirname), 2)
1359
1360
1361
1362
        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)
1363
1364
1365
1366
        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)