test_mp_dataloader.py 26.8 KB
Newer Older
1
import multiprocessing as mp
Rhett Ying's avatar
Rhett Ying committed
2
3
import os
import tempfile
4
import time
5
import unittest
Rhett Ying's avatar
Rhett Ying committed
6

7
import backend as F
Rhett Ying's avatar
Rhett Ying committed
8
9
10
11
12
13
import dgl
import numpy as np
import pytest
import torch as th
from dgl.data import CitationGraphDataset
from dgl.distributed import (
14
15
    DATA_LOADING_BACKEND_DGL,
    DATA_LOADING_BACKEND_GRAPHBOLT,
Rhett Ying's avatar
Rhett Ying committed
16
17
18
19
20
21
22
23
24
    DistDataLoader,
    DistGraph,
    DistGraphServer,
    load_partition,
    partition_graph,
)
from scipy import sparse as spsp
from utils import generate_ip_config, reset_envs

25
26

class NeighborSampler(object):
27
28
29
30
31
32
33
34
    def __init__(
        self,
        g,
        fanouts,
        sample_neighbors,
        use_graphbolt=False,
        return_eids=False,
    ):
35
36
37
        self.g = g
        self.fanouts = fanouts
        self.sample_neighbors = sample_neighbors
38
39
        self.use_graphbolt = use_graphbolt
        self.return_eids = return_eids
40
41
42

    def sample_blocks(self, seeds):
        import torch as th
Rhett Ying's avatar
Rhett Ying committed
43

44
        seeds = th.tensor(np.asarray(seeds), dtype=self.g.idtype)
45
46
47
48
        blocks = []
        for fanout in self.fanouts:
            # For each seed node, sample ``fanout`` neighbors.
            frontier = self.sample_neighbors(
49
                self.g, seeds, fanout, use_graphbolt=self.use_graphbolt
Rhett Ying's avatar
Rhett Ying committed
50
51
52
            )
            # Then we compact the frontier into a bipartite graph for
            # message passing.
53
54
55
            block = dgl.to_block(frontier, seeds)
            # Obtain the seed nodes for next layer.
            seeds = block.srcdata[dgl.NID]
56
57
58
            if frontier.num_edges() > 0:
                if not self.use_graphbolt or self.return_eids:
                    block.edata[dgl.EID] = frontier.edata[dgl.EID]
59
60
61
62
63

            blocks.insert(0, block)
        return blocks


Rhett Ying's avatar
Rhett Ying committed
64
65
66
67
68
69
def start_server(
    rank,
    ip_config,
    part_config,
    disable_shared_mem,
    num_clients,
70
    use_graphbolt=False,
Rhett Ying's avatar
Rhett Ying committed
71
72
73
74
75
76
77
78
79
80
):
    print("server: #clients=" + str(num_clients))
    g = DistGraphServer(
        rank,
        ip_config,
        1,
        num_clients,
        part_config,
        disable_shared_mem=disable_shared_mem,
        graph_format=["csc", "coo"],
81
        use_graphbolt=use_graphbolt,
Rhett Ying's avatar
Rhett Ying committed
82
    )
83
84
85
    g.start()


Rhett Ying's avatar
Rhett Ying committed
86
87
88
89
90
91
92
93
def start_dist_dataloader(
    rank,
    ip_config,
    part_config,
    num_server,
    drop_last,
    orig_nid,
    orig_eid,
94
95
    use_graphbolt=False,
    return_eids=False,
Rhett Ying's avatar
Rhett Ying committed
96
97
):
    dgl.distributed.initialize(ip_config)
98
    gpb = None
99
    disable_shared_mem = num_server > 1
100
    if disable_shared_mem:
Rhett Ying's avatar
Rhett Ying committed
101
        _, _, _, gpb, _, _, _ = load_partition(part_config, rank)
102
103
104
    num_nodes_to_sample = 202
    batch_size = 32
    train_nid = th.arange(num_nodes_to_sample)
105
106
107
108
109
    dist_graph = DistGraph(
        "test_sampling",
        gpb=gpb,
        part_config=part_config,
    )
110

111
    # Create sampler
Rhett Ying's avatar
Rhett Ying committed
112
    sampler = NeighborSampler(
113
114
115
116
117
        dist_graph,
        [5, 10],
        dgl.distributed.sample_neighbors,
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
Rhett Ying's avatar
Rhett Ying committed
118
    )
119

120
121
122
    # Enable santity check in distributed sampling.
    os.environ["DGL_DIST_DEBUG"] = "1"

123
124
125
126
    # We need to test creating DistDataLoader multiple times.
    for i in range(2):
        # Create DataLoader for constructing blocks
        dataloader = DistDataLoader(
127
            dataset=train_nid,
128
129
130
            batch_size=batch_size,
            collate_fn=sampler.sample_blocks,
            shuffle=False,
Rhett Ying's avatar
Rhett Ying committed
131
132
            drop_last=drop_last,
        )
133
134
135
136

        groundtruth_g = CitationGraphDataset("cora")[0]
        max_nid = []

137
        for _ in range(2):
Rhett Ying's avatar
Rhett Ying committed
138
139
140
            for idx, blocks in zip(
                range(0, num_nodes_to_sample, batch_size), dataloader
            ):
141
                block = blocks[-1]
Rhett Ying's avatar
Rhett Ying committed
142
                o_src, o_dst = block.edges()
143
144
                src_nodes_id = block.srcdata[dgl.NID][o_src]
                dst_nodes_id = block.dstdata[dgl.NID][o_dst]
145
146
147
148
                max_nid.append(np.max(F.asnumpy(dst_nodes_id)))

                src_nodes_id = orig_nid[src_nodes_id]
                dst_nodes_id = orig_nid[dst_nodes_id]
Rhett Ying's avatar
Rhett Ying committed
149
150
151
                has_edges = groundtruth_g.has_edges_between(
                    src_nodes_id, dst_nodes_id
                )
152
                assert np.all(F.asnumpy(has_edges))
153
154
155
156
157
158
159
160
161
162

                if use_graphbolt and not return_eids:
                    continue
                eids = orig_eid[block.edata[dgl.EID]]
                expected_eids = groundtruth_g.edge_ids(
                    src_nodes_id, dst_nodes_id
                )
                assert th.equal(
                    eids, expected_eids
                ), f"{eids} != {expected_eids}"
163
            if drop_last:
Rhett Ying's avatar
Rhett Ying committed
164
165
166
167
168
169
                assert (
                    np.max(max_nid)
                    == num_nodes_to_sample
                    - 1
                    - num_nodes_to_sample % batch_size
                )
170
171
            else:
                assert np.max(max_nid) == num_nodes_to_sample - 1
172
    del dataloader
Rhett Ying's avatar
Rhett Ying committed
173
174
    # this is needed since there's two test here in one process
    dgl.distributed.exit_client()
175
176


Rhett Ying's avatar
Rhett Ying committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def test_standalone():
    reset_envs()
    with tempfile.TemporaryDirectory() as test_dir:
        ip_config = os.path.join(test_dir, "ip_config.txt")
        generate_ip_config(ip_config, 1, 1)

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

        orig_nid, orig_eid = partition_graph(
            g,
            "test_sampling",
            num_parts,
            test_dir,
            num_hops=num_hops,
            part_method="metis",
            return_mapping=True,
        )
        part_config = os.path.join(test_dir, "test_sampling.json")
        os.environ["DGL_DIST_MODE"] = "standalone"
        try:
            start_dist_dataloader(
                0, ip_config, part_config, 1, True, orig_nid, orig_eid
            )
        except Exception as e:
            print(e)


def start_dist_neg_dataloader(
    rank,
    ip_config,
    part_config,
    num_server,
    num_workers,
    orig_nid,
    groundtruth_g,
):
216
217
    import dgl
    import torch as th
Rhett Ying's avatar
Rhett Ying committed
218
219

    dgl.distributed.initialize(ip_config)
220
221
222
    gpb = None
    disable_shared_mem = num_server > 1
    if disable_shared_mem:
Rhett Ying's avatar
Rhett Ying committed
223
        _, _, _, gpb, _, _, _ = load_partition(part_config, rank)
224
225
    num_edges_to_sample = 202
    batch_size = 32
Rhett Ying's avatar
Rhett Ying committed
226
    dist_graph = DistGraph("test_mp", gpb=gpb, part_config=part_config)
227
228
229
230
231
232
233
234
    assert len(dist_graph.ntypes) == len(groundtruth_g.ntypes)
    assert len(dist_graph.etypes) == len(groundtruth_g.etypes)
    if len(dist_graph.etypes) == 1:
        train_eid = th.arange(num_edges_to_sample)
    else:
        train_eid = {dist_graph.etypes[0]: th.arange(num_edges_to_sample)}

    for i in range(num_server):
Rhett Ying's avatar
Rhett Ying committed
235
        part, _, _, _, _, _, _ = load_partition(part_config, i)
236
237

    num_negs = 5
Rhett Ying's avatar
Rhett Ying committed
238
239
240
241
242
243
244
245
246
247
248
249
    sampler = dgl.dataloading.MultiLayerNeighborSampler([5, 10])
    negative_sampler = dgl.dataloading.negative_sampler.Uniform(num_negs)
    dataloader = dgl.dataloading.DistEdgeDataLoader(
        dist_graph,
        train_eid,
        sampler,
        batch_size=batch_size,
        negative_sampler=negative_sampler,
        shuffle=True,
        drop_last=False,
        num_workers=num_workers,
    )
250
    for _ in range(2):
Rhett Ying's avatar
Rhett Ying committed
251
252
253
        for _, (_, pos_graph, neg_graph, blocks) in zip(
            range(0, num_edges_to_sample, batch_size), dataloader
        ):
254
255
            block = blocks[-1]
            for src_type, etype, dst_type in block.canonical_etypes:
Rhett Ying's avatar
Rhett Ying committed
256
                o_src, o_dst = block.edges(etype=etype)
257
258
259
260
                src_nodes_id = block.srcnodes[src_type].data[dgl.NID][o_src]
                dst_nodes_id = block.dstnodes[dst_type].data[dgl.NID][o_dst]
                src_nodes_id = orig_nid[src_type][src_nodes_id]
                dst_nodes_id = orig_nid[dst_type][dst_nodes_id]
Rhett Ying's avatar
Rhett Ying committed
261
262
263
                has_edges = groundtruth_g.has_edges_between(
                    src_nodes_id, dst_nodes_id, etype=etype
                )
264
                assert np.all(F.asnumpy(has_edges))
Rhett Ying's avatar
Rhett Ying committed
265
266
267
268
269
270
271
272
                assert np.all(
                    F.asnumpy(block.dstnodes[dst_type].data[dgl.NID])
                    == F.asnumpy(pos_graph.nodes[dst_type].data[dgl.NID])
                )
                assert np.all(
                    F.asnumpy(block.dstnodes[dst_type].data[dgl.NID])
                    == F.asnumpy(neg_graph.nodes[dst_type].data[dgl.NID])
                )
273
274
275
                assert pos_graph.num_edges() * num_negs == neg_graph.num_edges()

    del dataloader
Rhett Ying's avatar
Rhett Ying committed
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
    # this is needed since there's two test here in one process
    dgl.distributed.exit_client()


def check_neg_dataloader(g, num_server, num_workers):
    with tempfile.TemporaryDirectory() as test_dir:
        ip_config = "ip_config.txt"
        generate_ip_config(ip_config, num_server, num_server)

        num_parts = num_server
        num_hops = 1
        orig_nid, orig_eid = partition_graph(
            g,
            "test_sampling",
            num_parts,
            test_dir,
            num_hops=num_hops,
            part_method="metis",
            return_mapping=True,
        )
        part_config = os.path.join(test_dir, "test_sampling.json")
        if not isinstance(orig_nid, dict):
            orig_nid = {g.ntypes[0]: orig_nid}
        if not isinstance(orig_eid, dict):
            orig_eid = {g.etypes[0]: orig_eid}

        pserver_list = []
        ctx = mp.get_context("spawn")
        for i in range(num_server):
            p = ctx.Process(
                target=start_server,
                args=(
                    i,
                    ip_config,
                    part_config,
                    num_server > 1,
                    num_workers + 1,
                ),
            )
            p.start()
            time.sleep(1)
            pserver_list.append(p)
        os.environ["DGL_DIST_MODE"] = "distributed"
        os.environ["DGL_NUM_SAMPLER"] = str(num_workers)
        ptrainer_list = []

        p = ctx.Process(
            target=start_dist_neg_dataloader,
            args=(
                0,
                ip_config,
                part_config,
                num_server,
                num_workers,
                orig_nid,
                g,
            ),
        )
334
        p.start()
Rhett Ying's avatar
Rhett Ying committed
335
336
337
338
        ptrainer_list.append(p)

        for p in pserver_list:
            p.join()
339
            assert p.exitcode == 0
Rhett Ying's avatar
Rhett Ying committed
340
341
        for p in ptrainer_list:
            p.join()
342
            assert p.exitcode == 0
Rhett Ying's avatar
Rhett Ying committed
343
344


345
@pytest.mark.parametrize("num_server", [1])
346
@pytest.mark.parametrize("num_workers", [0, 1])
347
348
349
350
351
352
@pytest.mark.parametrize("drop_last", [False, True])
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_dist_dataloader(
    num_server, num_workers, drop_last, use_graphbolt, return_eids
):
353
    reset_envs()
354
355
    os.environ["DGL_DIST_MODE"] = "distributed"
    os.environ["DGL_NUM_SAMPLER"] = str(num_workers)
Rhett Ying's avatar
Rhett Ying committed
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    with tempfile.TemporaryDirectory() as test_dir:
        ip_config = "ip_config.txt"
        generate_ip_config(ip_config, num_server, num_server)

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

        orig_nid, orig_eid = partition_graph(
            g,
            "test_sampling",
            num_parts,
            test_dir,
            num_hops=num_hops,
            part_method="metis",
            return_mapping=True,
372
373
            use_graphbolt=use_graphbolt,
            store_eids=return_eids,
Rhett Ying's avatar
Rhett Ying committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
        )

        part_config = os.path.join(test_dir, "test_sampling.json")
        pserver_list = []
        ctx = mp.get_context("spawn")
        for i in range(num_server):
            p = ctx.Process(
                target=start_server,
                args=(
                    i,
                    ip_config,
                    part_config,
                    num_server > 1,
                    num_workers + 1,
388
                    use_graphbolt,
Rhett Ying's avatar
Rhett Ying committed
389
390
                ),
            )
391
            p.start()
Rhett Ying's avatar
Rhett Ying committed
392
393
394
395
396
397
            time.sleep(1)
            pserver_list.append(p)

        ptrainer_list = []
        num_trainers = 1
        for trainer_id in range(num_trainers):
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
            p = ctx.Process(
                target=start_dist_dataloader,
                args=(
                    trainer_id,
                    ip_config,
                    part_config,
                    num_server,
                    drop_last,
                    orig_nid,
                    orig_eid,
                    use_graphbolt,
                    return_eids,
                ),
            )
            p.start()
            time.sleep(1)  # avoid race condition when instantiating DistGraph
            ptrainer_list.append(p)
Rhett Ying's avatar
Rhett Ying committed
415
416
417

        for p in ptrainer_list:
            p.join()
418
            assert p.exitcode == 0
419
        for p in pserver_list:
Rhett Ying's avatar
Rhett Ying committed
420
            p.join()
421
            assert p.exitcode == 0
Rhett Ying's avatar
Rhett Ying committed
422
423
424
425
426
427
428
429
430
431
432


def start_node_dataloader(
    rank,
    ip_config,
    part_config,
    num_server,
    num_workers,
    orig_nid,
    orig_eid,
    groundtruth_g,
433
434
    use_graphbolt=False,
    return_eids=False,
Rhett Ying's avatar
Rhett Ying committed
435
436
):
    dgl.distributed.initialize(ip_config)
437
    gpb = None
438
    disable_shared_mem = num_server > 1
439
    if disable_shared_mem:
Rhett Ying's avatar
Rhett Ying committed
440
        _, _, _, gpb, _, _, _ = load_partition(part_config, rank)
441
442
    num_nodes_to_sample = 202
    batch_size = 32
443
444
445
446
447
    dist_graph = DistGraph(
        "test_sampling",
        gpb=gpb,
        part_config=part_config,
    )
448
449
450
    assert len(dist_graph.ntypes) == len(groundtruth_g.ntypes)
    assert len(dist_graph.etypes) == len(groundtruth_g.etypes)
    if len(dist_graph.etypes) == 1:
451
        train_nid = th.arange(num_nodes_to_sample, dtype=dist_graph.idtype)
452
    else:
453
454
455
        train_nid = {
            "n3": th.arange(num_nodes_to_sample, dtype=dist_graph.idtype)
        }
456

457
    for i in range(num_server):
Rhett Ying's avatar
Rhett Ying committed
458
        part, _, _, _, _, _, _ = load_partition(part_config, i)
459

460
    # Create sampler
Rhett Ying's avatar
Rhett Ying committed
461
462
463
464
465
466
467
468
469
    sampler = dgl.dataloading.MultiLayerNeighborSampler(
        [
            # test dict for hetero
            {etype: 5 for etype in dist_graph.etypes}
            if len(dist_graph.etypes) > 1
            else 5,
            10,
        ]
    )  # test int for hetero
470

471
472
473
    # Enable santity check in distributed sampling.
    os.environ["DGL_DIST_DEBUG"] = "1"

474
475
476
    # We need to test creating DistDataLoader multiple times.
    for i in range(2):
        # Create DataLoader for constructing blocks
477
        dataloader = dgl.dataloading.DistNodeDataLoader(
478
479
480
481
482
483
            dist_graph,
            train_nid,
            sampler,
            batch_size=batch_size,
            shuffle=True,
            drop_last=False,
Rhett Ying's avatar
Rhett Ying committed
484
485
            num_workers=num_workers,
        )
486

487
        for _ in range(2):
Rhett Ying's avatar
Rhett Ying committed
488
489
490
            for idx, (_, _, blocks) in zip(
                range(0, num_nodes_to_sample, batch_size), dataloader
            ):
491
                block = blocks[-1]
492
493
494
                for c_etype in block.canonical_etypes:
                    src_type, _, dst_type = c_etype
                    o_src, o_dst = block.edges(etype=c_etype)
495
496
497
498
                    src_nodes_id = block.srcnodes[src_type].data[dgl.NID][o_src]
                    dst_nodes_id = block.dstnodes[dst_type].data[dgl.NID][o_dst]
                    src_nodes_id = orig_nid[src_type][src_nodes_id]
                    dst_nodes_id = orig_nid[dst_type][dst_nodes_id]
Rhett Ying's avatar
Rhett Ying committed
499
                    has_edges = groundtruth_g.has_edges_between(
500
                        src_nodes_id, dst_nodes_id, etype=c_etype
Rhett Ying's avatar
Rhett Ying committed
501
                    )
502
                    assert np.all(F.asnumpy(has_edges))
503
504
505

                    if use_graphbolt and not return_eids:
                        continue
506
                    eids = orig_eid[c_etype][block.edges[c_etype].data[dgl.EID]]
507
                    expected_eids = groundtruth_g.edge_ids(
508
                        src_nodes_id, dst_nodes_id, etype=c_etype
509
510
511
512
                    )
                    assert th.equal(
                        eids, expected_eids
                    ), f"{eids} != {expected_eids}"
513
    del dataloader
Rhett Ying's avatar
Rhett Ying committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
    # this is needed since there's two test here in one process
    dgl.distributed.exit_client()


def start_edge_dataloader(
    rank,
    ip_config,
    part_config,
    num_server,
    num_workers,
    orig_nid,
    orig_eid,
    groundtruth_g,
):
    dgl.distributed.initialize(ip_config)
529
530
531
    gpb = None
    disable_shared_mem = num_server > 1
    if disable_shared_mem:
Rhett Ying's avatar
Rhett Ying committed
532
        _, _, _, gpb, _, _, _ = load_partition(part_config, rank)
533
534
    num_edges_to_sample = 202
    batch_size = 32
535
    dist_graph = DistGraph("test_sampling", gpb=gpb, part_config=part_config)
536
537
538
539
540
541
542
543
    assert len(dist_graph.ntypes) == len(groundtruth_g.ntypes)
    assert len(dist_graph.etypes) == len(groundtruth_g.etypes)
    if len(dist_graph.etypes) == 1:
        train_eid = th.arange(num_edges_to_sample)
    else:
        train_eid = {dist_graph.etypes[0]: th.arange(num_edges_to_sample)}

    for i in range(num_server):
Rhett Ying's avatar
Rhett Ying committed
544
        part, _, _, _, _, _, _ = load_partition(part_config, i)
545
546
547

    # Create sampler
    sampler = dgl.dataloading.MultiLayerNeighborSampler([5, 10])
548

549
550
551
    # We need to test creating DistDataLoader multiple times.
    for i in range(2):
        # Create DataLoader for constructing blocks
552
        dataloader = dgl.dataloading.DistEdgeDataLoader(
553
554
555
556
557
558
            dist_graph,
            train_eid,
            sampler,
            batch_size=batch_size,
            shuffle=True,
            drop_last=False,
Rhett Ying's avatar
Rhett Ying committed
559
560
            num_workers=num_workers,
        )
561
562

        for epoch in range(2):
Rhett Ying's avatar
Rhett Ying committed
563
564
565
            for idx, (input_nodes, pos_pair_graph, blocks) in zip(
                range(0, num_edges_to_sample, batch_size), dataloader
            ):
566
567
                block = blocks[-1]
                for src_type, etype, dst_type in block.canonical_etypes:
Rhett Ying's avatar
Rhett Ying committed
568
                    o_src, o_dst = block.edges(etype=etype)
569
570
571
572
                    src_nodes_id = block.srcnodes[src_type].data[dgl.NID][o_src]
                    dst_nodes_id = block.dstnodes[dst_type].data[dgl.NID][o_dst]
                    src_nodes_id = orig_nid[src_type][src_nodes_id]
                    dst_nodes_id = orig_nid[dst_type][dst_nodes_id]
Rhett Ying's avatar
Rhett Ying committed
573
574
575
                    has_edges = groundtruth_g.has_edges_between(
                        src_nodes_id, dst_nodes_id, etype=etype
                    )
576
                    assert np.all(F.asnumpy(has_edges))
Rhett Ying's avatar
Rhett Ying committed
577
578
579
580
581
582
                    assert np.all(
                        F.asnumpy(block.dstnodes[dst_type].data[dgl.NID])
                        == F.asnumpy(
                            pos_pair_graph.nodes[dst_type].data[dgl.NID]
                        )
                    )
583
    del dataloader
Rhett Ying's avatar
Rhett Ying committed
584
585
586
    dgl.distributed.exit_client()


587
588
589
590
591
592
593
594
def check_dataloader(
    g,
    num_server,
    num_workers,
    dataloader_type,
    use_graphbolt=False,
    return_eids=False,
):
Rhett Ying's avatar
Rhett Ying committed
595
596
597
598
599
600
601
602
603
604
605
606
607
608
    with tempfile.TemporaryDirectory() as test_dir:
        ip_config = "ip_config.txt"
        generate_ip_config(ip_config, num_server, num_server)

        num_parts = num_server
        num_hops = 1
        orig_nid, orig_eid = partition_graph(
            g,
            "test_sampling",
            num_parts,
            test_dir,
            num_hops=num_hops,
            part_method="metis",
            return_mapping=True,
609
610
            use_graphbolt=use_graphbolt,
            store_eids=return_eids,
Rhett Ying's avatar
Rhett Ying committed
611
612
613
614
615
        )
        part_config = os.path.join(test_dir, "test_sampling.json")
        if not isinstance(orig_nid, dict):
            orig_nid = {g.ntypes[0]: orig_nid}
        if not isinstance(orig_eid, dict):
616
            orig_eid = {g.canonical_etypes[0]: orig_eid}
Rhett Ying's avatar
Rhett Ying committed
617
618
619
620
621
622
623
624
625
626
627
628

        pserver_list = []
        ctx = mp.get_context("spawn")
        for i in range(num_server):
            p = ctx.Process(
                target=start_server,
                args=(
                    i,
                    ip_config,
                    part_config,
                    num_server > 1,
                    num_workers + 1,
629
                    use_graphbolt,
Rhett Ying's avatar
Rhett Ying committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
                ),
            )
            p.start()
            time.sleep(1)
            pserver_list.append(p)

        os.environ["DGL_DIST_MODE"] = "distributed"
        os.environ["DGL_NUM_SAMPLER"] = str(num_workers)
        ptrainer_list = []
        if dataloader_type == "node":
            p = ctx.Process(
                target=start_node_dataloader,
                args=(
                    0,
                    ip_config,
                    part_config,
                    num_server,
                    num_workers,
                    orig_nid,
                    orig_eid,
                    g,
651
652
                    use_graphbolt,
                    return_eids,
Rhett Ying's avatar
Rhett Ying committed
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
                ),
            )
            p.start()
            ptrainer_list.append(p)
        elif dataloader_type == "edge":
            p = ctx.Process(
                target=start_edge_dataloader,
                args=(
                    0,
                    ip_config,
                    part_config,
                    num_server,
                    num_workers,
                    orig_nid,
                    orig_eid,
                    g,
                ),
            )
            p.start()
            ptrainer_list.append(p)
        for p in pserver_list:
            p.join()
675
            assert p.exitcode == 0
Rhett Ying's avatar
Rhett Ying committed
676
677
        for p in ptrainer_list:
            p.join()
678
            assert p.exitcode == 0
Rhett Ying's avatar
Rhett Ying committed
679

680

681
def create_random_hetero():
Rhett Ying's avatar
Rhett Ying committed
682
683
    num_nodes = {"n1": 10000, "n2": 10010, "n3": 10020}
    etypes = [("n1", "r1", "n2"), ("n1", "r2", "n3"), ("n2", "r3", "n3")]
684
685
686
    edges = {}
    for etype in etypes:
        src_ntype, _, dst_ntype = etype
Rhett Ying's avatar
Rhett Ying committed
687
688
689
690
691
692
693
        arr = spsp.random(
            num_nodes[src_ntype],
            num_nodes[dst_ntype],
            density=0.001,
            format="coo",
            random_state=100,
        )
694
695
        edges[etype] = (arr.row, arr.col)
    g = dgl.heterograph(edges, num_nodes)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
696
697
    g.nodes["n1"].data["feat"] = F.unsqueeze(F.arange(0, g.num_nodes("n1")), 1)
    g.edges["r1"].data["feat"] = F.unsqueeze(F.arange(0, g.num_edges("r1")), 1)
698
699
    return g

Rhett Ying's avatar
Rhett Ying committed
700

701
702
@pytest.mark.parametrize("num_server", [1])
@pytest.mark.parametrize("num_workers", [0, 1])
703
@pytest.mark.parametrize("dataloader_type", ["node", "edge"])
704
705
706
707
708
709
710
711
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_dataloader_homograph(
    num_server, num_workers, dataloader_type, use_graphbolt, return_eids
):
    if dataloader_type == "edge" and use_graphbolt:
        # GraphBolt does not support edge dataloader.
        return
712
    reset_envs()
713
    g = CitationGraphDataset("cora")[0]
714
715
716
717
718
719
720
721
722
723
724
725
726
    check_dataloader(
        g,
        num_server,
        num_workers,
        dataloader_type,
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
    )


@pytest.mark.parametrize("num_server", [1])
@pytest.mark.parametrize("num_workers", [0, 1])
@pytest.mark.parametrize("dataloader_type", ["node", "edge"])
727
728
729
730
731
732
733
734
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
def test_dataloader_heterograph(
    num_server, num_workers, dataloader_type, use_graphbolt, return_eids
):
    if dataloader_type == "edge" and use_graphbolt:
        # GraphBolt does not support edge dataloader.
        return
735
    reset_envs()
736
    g = create_random_hetero()
737
738
739
740
741
742
743
744
    check_dataloader(
        g,
        num_server,
        num_workers,
        dataloader_type,
        use_graphbolt=use_graphbolt,
        return_eids=return_eids,
    )
Rhett Ying's avatar
Rhett Ying committed
745

746

747
@unittest.skip(reason="Skip due to glitch in CI")
748
749
@pytest.mark.parametrize("num_server", [3])
@pytest.mark.parametrize("num_workers", [0, 4])
Rhett Ying's avatar
Rhett Ying committed
750
def test_neg_dataloader(num_server, num_workers):
751
    reset_envs()
752
    g = CitationGraphDataset("cora")[0]
Rhett Ying's avatar
Rhett Ying committed
753
    check_neg_dataloader(g, num_server, num_workers)
754
    g = create_random_hetero()
Rhett Ying's avatar
Rhett Ying committed
755
756
757
758
    check_neg_dataloader(g, num_server, num_workers)


def start_multiple_dataloaders(
759
760
761
762
763
764
765
    ip_config,
    part_config,
    graph_name,
    orig_g,
    num_dataloaders,
    dataloader_type,
    use_graphbolt,
Rhett Ying's avatar
Rhett Ying committed
766
767
):
    dgl.distributed.initialize(ip_config)
768
    dist_g = dgl.distributed.DistGraph(graph_name, part_config=part_config)
Rhett Ying's avatar
Rhett Ying committed
769
    if dataloader_type == "node":
770
        train_ids = th.arange(orig_g.num_nodes(), dtype=dist_g.idtype)
Rhett Ying's avatar
Rhett Ying committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
        batch_size = orig_g.num_nodes() // 100
    else:
        train_ids = th.arange(orig_g.num_edges())
        batch_size = orig_g.num_edges() // 100
    sampler = dgl.dataloading.NeighborSampler([-1])
    dataloaders = []
    dl_iters = []
    for _ in range(num_dataloaders):
        if dataloader_type == "node":
            dataloader = dgl.dataloading.DistNodeDataLoader(
                dist_g, train_ids, sampler, batch_size=batch_size
            )
        else:
            dataloader = dgl.dataloading.DistEdgeDataLoader(
                dist_g, train_ids, sampler, batch_size=batch_size
            )
        dataloaders.append(dataloader)
        dl_iters.append(iter(dataloader))

    # iterate on multiple dataloaders randomly
    while len(dl_iters) > 0:
        next_dl = np.random.choice(len(dl_iters), 1)[0]
        try:
            _ = next(dl_iters[next_dl])
        except StopIteration:
            dl_iters.pop(next_dl)
            del dataloaders[next_dl]

    dgl.distributed.exit_client()


@pytest.mark.parametrize("num_dataloaders", [1, 4])
803
@pytest.mark.parametrize("num_workers", [0, 1])
Rhett Ying's avatar
Rhett Ying committed
804
@pytest.mark.parametrize("dataloader_type", ["node", "edge"])
805
806
@pytest.mark.parametrize("use_graphbolt", [False, True])
@pytest.mark.parametrize("return_eids", [False, True])
Rhett Ying's avatar
Rhett Ying committed
807
def test_multiple_dist_dataloaders(
808
    num_dataloaders, num_workers, dataloader_type, use_graphbolt, return_eids
Rhett Ying's avatar
Rhett Ying committed
809
):
810
811
812
    if dataloader_type == "edge" and use_graphbolt:
        # GraphBolt does not support edge dataloader.
        return
Rhett Ying's avatar
Rhett Ying committed
813
814
815
816
817
818
819
820
821
822
    reset_envs()
    os.environ["DGL_DIST_MODE"] = "distributed"
    os.environ["DGL_NUM_SAMPLER"] = str(num_workers)
    num_parts = 1
    num_servers = 1
    with tempfile.TemporaryDirectory() as test_dir:
        ip_config = os.path.join(test_dir, "ip_config.txt")
        generate_ip_config(ip_config, num_parts, num_servers)

        orig_g = dgl.rand_graph(1000, 10000)
823
824
825
826
827
828
829
830
831
        graph_name = "test_multiple_dataloaders"
        partition_graph(
            orig_g,
            graph_name,
            num_parts,
            test_dir,
            use_graphbolt=use_graphbolt,
            store_eids=return_eids,
        )
Rhett Ying's avatar
Rhett Ying committed
832
833
834
835
836
837
838
839
840
841
842
843
844
        part_config = os.path.join(test_dir, f"{graph_name}.json")

        p_servers = []
        ctx = mp.get_context("spawn")
        for i in range(num_servers):
            p = ctx.Process(
                target=start_server,
                args=(
                    i,
                    ip_config,
                    part_config,
                    num_servers > 1,
                    num_workers + 1,
845
                    use_graphbolt,
Rhett Ying's avatar
Rhett Ying committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
                ),
            )
            p.start()
            time.sleep(1)
            p_servers.append(p)

        p_client = ctx.Process(
            target=start_multiple_dataloaders,
            args=(
                ip_config,
                part_config,
                graph_name,
                orig_g,
                num_dataloaders,
                dataloader_type,
861
                use_graphbolt,
Rhett Ying's avatar
Rhett Ying committed
862
863
864
865
866
            ),
        )
        p_client.start()

        p_client.join()
867
        assert p_client.exitcode == 0
Rhett Ying's avatar
Rhett Ying committed
868
869
        for p in p_servers:
            p.join()
870
            assert p.exitcode == 0
Rhett Ying's avatar
Rhett Ying committed
871
    reset_envs()