test_partition.py 39.7 KB
Newer Older
1
import json
2
import os
3
import tempfile
4
5
6

import backend as F
import dgl
7
import numpy as np
8
import pytest
9
import torch as th
10
from dgl import function as fn
11
from dgl.distributed import (
12
    dgl_partition_to_graphbolt,
13
    load_partition,
14
    load_partition_book,
15
16
17
18
    load_partition_feats,
    partition_graph,
)
from dgl.distributed.graph_partition_book import (
19
    _etype_str_to_tuple,
20
    _etype_tuple_to_str,
21
22
23
24
25
26
27
    DEFAULT_ETYPE,
    DEFAULT_NTYPE,
    EdgePartitionPolicy,
    HeteroDataName,
    NodePartitionPolicy,
    RangePartitionBook,
)
28
from dgl.distributed.partition import (
29
    _get_inner_edge_mask,
30
    _get_inner_node_mask,
31
    RESERVED_FIELD_DTYPE,
32
33
)
from scipy import sparse as spsp
34
from utils import reset_envs
35

36
37
38
39
40
41
42

def _verify_partition_data_types(part_g):
    for k, dtype in RESERVED_FIELD_DTYPE.items():
        if k in part_g.ndata:
            assert part_g.ndata[k].dtype == dtype
        if k in part_g.edata:
            assert part_g.edata[k].dtype == dtype
43

44

45
46
47
48
def _verify_partition_formats(part_g, formats):
    # verify saved graph formats
    if formats is None:
        assert "coo" in part_g.formats()["created"]
49
    else:
50
51
        for format in formats:
            assert format in part_g.formats()["created"]
52
53


54
def create_random_graph(n):
55
56
57
    arr = (
        spsp.random(n, n, density=0.001, format="coo", random_state=100) != 0
    ).astype(np.int64)
58
    return dgl.from_scipy(arr)
59

60

61
def create_random_hetero():
62
    num_nodes = {"n1": 1000, "n2": 1010, "n3": 1020}
63
64
65
66
67
68
    etypes = [
        ("n1", "r1", "n2"),
        ("n2", "r1", "n1"),
        ("n1", "r2", "n3"),
        ("n2", "r3", "n3"),
    ]
69
70
71
    edges = {}
    for etype in etypes:
        src_ntype, _, dst_ntype = etype
72
73
74
75
76
77
78
        arr = spsp.random(
            num_nodes[src_ntype],
            num_nodes[dst_ntype],
            density=0.001,
            format="coo",
            random_state=100,
        )
79
80
81
        edges[etype] = (arr.row, arr.col)
    return dgl.heterograph(edges, num_nodes)

82

83
def verify_hetero_graph(g, parts):
84
    num_nodes = {ntype: 0 for ntype in g.ntypes}
85
    num_edges = {etype: 0 for etype in g.canonical_etypes}
86
87
    for part in parts:
        assert len(g.ntypes) == len(F.unique(part.ndata[dgl.NTYPE]))
88
        assert len(g.canonical_etypes) == len(F.unique(part.edata[dgl.ETYPE]))
89
90
91
92
93
        for ntype in g.ntypes:
            ntype_id = g.get_ntype_id(ntype)
            inner_node_mask = _get_inner_node_mask(part, ntype_id)
            num_inner_nodes = F.sum(F.astype(inner_node_mask, F.int64), 0)
            num_nodes[ntype] += num_inner_nodes
94
        for etype in g.canonical_etypes:
95
96
97
98
99
100
            etype_id = g.get_etype_id(etype)
            inner_edge_mask = _get_inner_edge_mask(part, etype_id)
            num_inner_edges = F.sum(F.astype(inner_edge_mask, F.int64), 0)
            num_edges[etype] += num_inner_edges
    # Verify the number of nodes are correct.
    for ntype in g.ntypes:
101
102
        print(
            "node {}: {}, {}".format(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
103
                ntype, g.num_nodes(ntype), num_nodes[ntype]
104
105
            )
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
106
        assert g.num_nodes(ntype) == num_nodes[ntype]
107
    # Verify the number of edges are correct.
108
    for etype in g.canonical_etypes:
109
110
        print(
            "edge {}: {}, {}".format(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
111
                etype, g.num_edges(etype), num_edges[etype]
112
113
            )
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
114
        assert g.num_edges(etype) == num_edges[etype]
115

116
    nids = {ntype: [] for ntype in g.ntypes}
117
    eids = {etype: [] for etype in g.canonical_etypes}
118
    for part in parts:
119
        _, _, eid = part.edges(form="all")
120
121
        etype_arr = F.gather_row(part.edata[dgl.ETYPE], eid)
        eid_type = F.gather_row(part.edata[dgl.EID], eid)
122
        for etype in g.canonical_etypes:
123
124
125
126
            etype_id = g.get_etype_id(etype)
            eids[etype].append(F.boolean_mask(eid_type, etype_arr == etype_id))
            # Make sure edge Ids fall into a range.
            inner_edge_mask = _get_inner_edge_mask(part, etype_id)
127
128
129
130
131
132
            inner_eids = np.sort(
                F.asnumpy(F.boolean_mask(part.edata[dgl.EID], inner_edge_mask))
            )
            assert np.all(
                inner_eids == np.arange(inner_eids[0], inner_eids[-1] + 1)
            )
133
134
135
136
137
138

        for ntype in g.ntypes:
            ntype_id = g.get_ntype_id(ntype)
            # Make sure inner nodes have Ids fall into a range.
            inner_node_mask = _get_inner_node_mask(part, ntype_id)
            inner_nids = F.boolean_mask(part.ndata[dgl.NID], inner_node_mask)
139
140
141
142
143
144
145
146
147
            assert np.all(
                F.asnumpy(
                    inner_nids
                    == F.arange(
                        F.as_scalar(inner_nids[0]),
                        F.as_scalar(inner_nids[-1]) + 1,
                    )
                )
            )
148
149
150
151
152
153
            nids[ntype].append(inner_nids)

    for ntype in nids:
        nids_type = F.cat(nids[ntype], 0)
        uniq_ids = F.unique(nids_type)
        # We should get all nodes.
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
154
        assert len(uniq_ids) == g.num_nodes(ntype)
155
156
157
    for etype in eids:
        eids_type = F.cat(eids[etype], 0)
        uniq_ids = F.unique(eids_type)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
158
        assert len(uniq_ids) == g.num_edges(etype)
159
160
    # TODO(zhengda) this doesn't check 'part_id'

161
162
163
164

def verify_graph_feats(
    g, gpb, part, node_feats, edge_feats, orig_nids, orig_eids
):
165
166
    for ntype in g.ntypes:
        ntype_id = g.get_ntype_id(ntype)
167
        inner_node_mask = _get_inner_node_mask(part, ntype_id)
168
        inner_nids = F.boolean_mask(part.ndata[dgl.NID], inner_node_mask)
169
170
171
172
173
        ntype_ids, inner_type_nids = gpb.map_to_per_ntype(inner_nids)
        partid = gpb.nid2partid(inner_type_nids, ntype)
        assert np.all(F.asnumpy(ntype_ids) == ntype_id)
        assert np.all(F.asnumpy(partid) == gpb.partid)

174
        orig_id = orig_nids[ntype][inner_type_nids]
175
176
        local_nids = gpb.nid2localnid(inner_type_nids, gpb.partid, ntype)

177
        for name in g.nodes[ntype].data:
178
            if name in [dgl.NID, "inner_node"]:
179
180
                continue
            true_feats = F.gather_row(g.nodes[ntype].data[name], orig_id)
181
            ndata = F.gather_row(node_feats[ntype + "/" + name], local_nids)
182
183
            assert np.all(F.asnumpy(ndata == true_feats))

184
    for etype in g.canonical_etypes:
185
186
        etype_id = g.get_etype_id(etype)
        inner_edge_mask = _get_inner_edge_mask(part, etype_id)
187
        inner_eids = F.boolean_mask(part.edata[dgl.EID], inner_edge_mask)
188
189
190
191
192
        etype_ids, inner_type_eids = gpb.map_to_per_etype(inner_eids)
        partid = gpb.eid2partid(inner_type_eids, etype)
        assert np.all(F.asnumpy(etype_ids) == etype_id)
        assert np.all(F.asnumpy(partid) == gpb.partid)

193
        orig_id = orig_eids[etype][inner_type_eids]
194
195
196
        local_eids = gpb.eid2localeid(inner_type_eids, gpb.partid, etype)

        for name in g.edges[etype].data:
197
            if name in [dgl.EID, "inner_edge"]:
198
199
                continue
            true_feats = F.gather_row(g.edges[etype].data[name], orig_id)
200
201
202
            edata = F.gather_row(
                edge_feats[_etype_tuple_to_str(etype) + "/" + name], local_eids
            )
203
204
            assert np.all(F.asnumpy(edata == true_feats))

205
206
207
208
209
210
211
212
213

def check_hetero_partition(
    hg,
    part_method,
    num_parts=4,
    num_trainers_per_machine=1,
    load_feats=True,
    graph_formats=None,
):
214
215
216
217
218
    test_ntype = "n1"
    test_etype = ("n1", "r1", "n2")
    hg.nodes[test_ntype].data["labels"] = F.arange(0, hg.num_nodes(test_ntype))
    hg.nodes[test_ntype].data["feats"] = F.tensor(
        np.random.randn(hg.num_nodes(test_ntype), 10), F.float32
219
    )
220
221
    hg.edges[test_etype].data["feats"] = F.tensor(
        np.random.randn(hg.num_edges(test_etype), 10), F.float32
222
    )
223
    hg.edges[test_etype].data["labels"] = F.arange(0, hg.num_edges(test_etype))
224
225
    num_hops = 1

226
227
228
229
230
231
232
233
234
235
236
    orig_nids, orig_eids = partition_graph(
        hg,
        "test",
        num_parts,
        "/tmp/partition",
        num_hops=num_hops,
        part_method=part_method,
        return_mapping=True,
        num_trainers_per_machine=num_trainers_per_machine,
        graph_formats=graph_formats,
    )
237
    assert len(orig_nids) == len(hg.ntypes)
238
    assert len(orig_eids) == len(hg.canonical_etypes)
239
    for ntype in hg.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
240
        assert len(orig_nids[ntype]) == hg.num_nodes(ntype)
241
    for etype in hg.canonical_etypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
242
        assert len(orig_eids[etype]) == hg.num_edges(etype)
243
    parts = []
244
245
    shuffled_labels = []
    shuffled_elabels = []
246
    for i in range(num_parts):
247
        part_g, node_feats, edge_feats, gpb, _, ntypes, etypes = load_partition(
248
249
            "/tmp/partition/test.json", i, load_feats=load_feats
        )
250
        _verify_partition_data_types(part_g)
251
        _verify_partition_formats(part_g, graph_formats)
252
253
254
        if not load_feats:
            assert not node_feats
            assert not edge_feats
255
256
257
            node_feats, edge_feats = load_partition_feats(
                "/tmp/partition/test.json", i
            )
258
259
        if num_trainers_per_machine > 1:
            for ntype in hg.ntypes:
260
                name = ntype + "/trainer_id"
261
                assert name in node_feats
262
263
264
                part_ids = F.floor_div(
                    node_feats[name], num_trainers_per_machine
                )
265
266
                assert np.all(F.asnumpy(part_ids) == i)

267
268
            for etype in hg.canonical_etypes:
                name = _etype_tuple_to_str(etype) + "/trainer_id"
269
                assert name in edge_feats
270
271
272
                part_ids = F.floor_div(
                    edge_feats[name], num_trainers_per_machine
                )
273
                assert np.all(F.asnumpy(part_ids) == i)
274
275
276
277
278
279
280
281
282
283
284
285
        # Verify the mapping between the reshuffled IDs and the original IDs.
        # These are partition-local IDs.
        part_src_ids, part_dst_ids = part_g.edges()
        # These are reshuffled global homogeneous IDs.
        part_src_ids = F.gather_row(part_g.ndata[dgl.NID], part_src_ids)
        part_dst_ids = F.gather_row(part_g.ndata[dgl.NID], part_dst_ids)
        part_eids = part_g.edata[dgl.EID]
        # These are reshuffled per-type IDs.
        src_ntype_ids, part_src_ids = gpb.map_to_per_ntype(part_src_ids)
        dst_ntype_ids, part_dst_ids = gpb.map_to_per_ntype(part_dst_ids)
        etype_ids, part_eids = gpb.map_to_per_etype(part_eids)
        # These are original per-type IDs.
286
        for etype_id, etype in enumerate(hg.canonical_etypes):
287
            part_src_ids1 = F.boolean_mask(part_src_ids, etype_ids == etype_id)
288
289
290
            src_ntype_ids1 = F.boolean_mask(
                src_ntype_ids, etype_ids == etype_id
            )
291
            part_dst_ids1 = F.boolean_mask(part_dst_ids, etype_ids == etype_id)
292
293
294
            dst_ntype_ids1 = F.boolean_mask(
                dst_ntype_ids, etype_ids == etype_id
            )
295
296
297
298
299
300
301
302
303
304
305
            part_eids1 = F.boolean_mask(part_eids, etype_ids == etype_id)
            assert np.all(F.asnumpy(src_ntype_ids1 == src_ntype_ids1[0]))
            assert np.all(F.asnumpy(dst_ntype_ids1 == dst_ntype_ids1[0]))
            src_ntype = hg.ntypes[F.as_scalar(src_ntype_ids1[0])]
            dst_ntype = hg.ntypes[F.as_scalar(dst_ntype_ids1[0])]
            orig_src_ids1 = F.gather_row(orig_nids[src_ntype], part_src_ids1)
            orig_dst_ids1 = F.gather_row(orig_nids[dst_ntype], part_dst_ids1)
            orig_eids1 = F.gather_row(orig_eids[etype], part_eids1)
            orig_eids2 = hg.edge_ids(orig_src_ids1, orig_dst_ids1, etype=etype)
            assert len(orig_eids1) == len(orig_eids2)
            assert np.all(F.asnumpy(orig_eids1) == F.asnumpy(orig_eids2))
306
        parts.append(part_g)
307
308
309
        verify_graph_feats(
            hg, gpb, part_g, node_feats, edge_feats, orig_nids, orig_eids
        )
310

311
312
313
314
        shuffled_labels.append(node_feats[test_ntype + "/labels"])
        shuffled_elabels.append(
            edge_feats[_etype_tuple_to_str(test_etype) + "/labels"]
        )
315
316
    verify_hetero_graph(hg, parts)

317
318
319
    shuffled_labels = F.asnumpy(F.cat(shuffled_labels, 0))
    shuffled_elabels = F.asnumpy(F.cat(shuffled_elabels, 0))
    orig_labels = np.zeros(shuffled_labels.shape, dtype=shuffled_labels.dtype)
320
321
322
    orig_elabels = np.zeros(
        shuffled_elabels.shape, dtype=shuffled_elabels.dtype
    )
323
324
325
326
327
328
    orig_labels[F.asnumpy(orig_nids[test_ntype])] = shuffled_labels
    orig_elabels[F.asnumpy(orig_eids[test_etype])] = shuffled_elabels
    assert np.all(orig_labels == F.asnumpy(hg.nodes[test_ntype].data["labels"]))
    assert np.all(
        orig_elabels == F.asnumpy(hg.edges[test_etype].data["labels"])
    )
329
330
331
332
333
334
335
336
337
338


def check_partition(
    g,
    part_method,
    num_parts=4,
    num_trainers_per_machine=1,
    load_feats=True,
    graph_formats=None,
):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
339
340
341
    g.ndata["labels"] = F.arange(0, g.num_nodes())
    g.ndata["feats"] = F.tensor(np.random.randn(g.num_nodes(), 10), F.float32)
    g.edata["feats"] = F.tensor(np.random.randn(g.num_edges(), 10), F.float32)
342
343
    g.update_all(fn.copy_u("feats", "msg"), fn.sum("msg", "h"))
    g.update_all(fn.copy_e("feats", "msg"), fn.sum("msg", "eh"))
344
    num_hops = 2
Da Zheng's avatar
Da Zheng committed
345

346
347
348
349
350
351
352
353
354
355
356
    orig_nids, orig_eids = partition_graph(
        g,
        "test",
        num_parts,
        "/tmp/partition",
        num_hops=num_hops,
        part_method=part_method,
        return_mapping=True,
        num_trainers_per_machine=num_trainers_per_machine,
        graph_formats=graph_formats,
    )
Da Zheng's avatar
Da Zheng committed
357
    part_sizes = []
358
359
    shuffled_labels = []
    shuffled_edata = []
360
    for i in range(num_parts):
361
        part_g, node_feats, edge_feats, gpb, _, _, _ = load_partition(
362
363
            "/tmp/partition/test.json", i, load_feats=load_feats
        )
364
        _verify_partition_data_types(part_g)
365
        _verify_partition_formats(part_g, graph_formats)
366
367
368
        if not load_feats:
            assert not node_feats
            assert not edge_feats
369
370
371
            node_feats, edge_feats = load_partition_feats(
                "/tmp/partition/test.json", i
            )
372
373
        if num_trainers_per_machine > 1:
            for ntype in g.ntypes:
374
                name = ntype + "/trainer_id"
375
                assert name in node_feats
376
377
378
                part_ids = F.floor_div(
                    node_feats[name], num_trainers_per_machine
                )
379
380
                assert np.all(F.asnumpy(part_ids) == i)

381
382
            for etype in g.canonical_etypes:
                name = _etype_tuple_to_str(etype) + "/trainer_id"
383
                assert name in edge_feats
384
385
386
                part_ids = F.floor_div(
                    edge_feats[name], num_trainers_per_machine
                )
387
                assert np.all(F.asnumpy(part_ids) == i)
388
389

        # Check the metadata
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
390
391
        assert gpb._num_nodes() == g.num_nodes()
        assert gpb._num_edges() == g.num_edges()
Da Zheng's avatar
Da Zheng committed
392
393
394
395

        assert gpb.num_partitions() == num_parts
        gpb_meta = gpb.metadata()
        assert len(gpb_meta) == num_parts
396
397
398
        assert len(gpb.partid2nids(i)) == gpb_meta[i]["num_nodes"]
        assert len(gpb.partid2eids(i)) == gpb_meta[i]["num_edges"]
        part_sizes.append((gpb_meta[i]["num_nodes"], gpb_meta[i]["num_edges"]))
Da Zheng's avatar
Da Zheng committed
399

400
        nid = F.boolean_mask(part_g.ndata[dgl.NID], part_g.ndata["inner_node"])
401
        local_nid = gpb.nid2localnid(nid, i)
402
        assert F.dtype(local_nid) in (F.int64, F.int32)
Da Zheng's avatar
Da Zheng committed
403
        assert np.all(F.asnumpy(local_nid) == np.arange(0, len(local_nid)))
404
        eid = F.boolean_mask(part_g.edata[dgl.EID], part_g.edata["inner_edge"])
405
        local_eid = gpb.eid2localeid(eid, i)
406
        assert F.dtype(local_eid) in (F.int64, F.int32)
Da Zheng's avatar
Da Zheng committed
407
        assert np.all(F.asnumpy(local_eid) == np.arange(0, len(local_eid)))
408
409

        # Check the node map.
410
411
412
413
        local_nodes = F.boolean_mask(
            part_g.ndata[dgl.NID], part_g.ndata["inner_node"]
        )
        llocal_nodes = F.nonzero_1d(part_g.ndata["inner_node"])
414
        local_nodes1 = gpb.partid2nids(i)
415
        assert F.dtype(local_nodes1) in (F.int32, F.int64)
416
417
418
        assert np.all(
            np.sort(F.asnumpy(local_nodes)) == np.sort(F.asnumpy(local_nodes1))
        )
419
        assert np.all(F.asnumpy(llocal_nodes) == np.arange(len(llocal_nodes)))
420
421

        # Check the edge map.
422
423
424
425
        local_edges = F.boolean_mask(
            part_g.edata[dgl.EID], part_g.edata["inner_edge"]
        )
        llocal_edges = F.nonzero_1d(part_g.edata["inner_edge"])
426
        local_edges1 = gpb.partid2eids(i)
427
        assert F.dtype(local_edges1) in (F.int32, F.int64)
428
429
430
        assert np.all(
            np.sort(F.asnumpy(local_edges)) == np.sort(F.asnumpy(local_edges1))
        )
431
        assert np.all(F.asnumpy(llocal_edges) == np.arange(len(llocal_edges)))
432

433
434
435
436
437
438
439
440
441
442
443
444
        # Verify the mapping between the reshuffled IDs and the original IDs.
        part_src_ids, part_dst_ids = part_g.edges()
        part_src_ids = F.gather_row(part_g.ndata[dgl.NID], part_src_ids)
        part_dst_ids = F.gather_row(part_g.ndata[dgl.NID], part_dst_ids)
        part_eids = part_g.edata[dgl.EID]
        orig_src_ids = F.gather_row(orig_nids, part_src_ids)
        orig_dst_ids = F.gather_row(orig_nids, part_dst_ids)
        orig_eids1 = F.gather_row(orig_eids, part_eids)
        orig_eids2 = g.edge_ids(orig_src_ids, orig_dst_ids)
        assert F.shape(orig_eids1)[0] == F.shape(orig_eids2)[0]
        assert np.all(F.asnumpy(orig_eids1) == F.asnumpy(orig_eids2))

445
446
        local_orig_nids = orig_nids[part_g.ndata[dgl.NID]]
        local_orig_eids = orig_eids[part_g.edata[dgl.EID]]
447
448
        part_g.ndata["feats"] = F.gather_row(g.ndata["feats"], local_orig_nids)
        part_g.edata["feats"] = F.gather_row(g.edata["feats"], local_orig_eids)
449
450
        local_nodes = orig_nids[local_nodes]
        local_edges = orig_eids[local_edges]
451

452
453
        part_g.update_all(fn.copy_u("feats", "msg"), fn.sum("msg", "h"))
        part_g.update_all(fn.copy_e("feats", "msg"), fn.sum("msg", "eh"))
454
455
456
457
458
459
460
461
462
463
464
465
        assert F.allclose(
            F.gather_row(g.ndata["h"], local_nodes),
            F.gather_row(part_g.ndata["h"], llocal_nodes),
        )
        assert F.allclose(
            F.gather_row(g.ndata["eh"], local_nodes),
            F.gather_row(part_g.ndata["eh"], llocal_nodes),
        )

        for name in ["labels", "feats"]:
            assert "_N/" + name in node_feats
            assert node_feats["_N/" + name].shape[0] == len(local_nodes)
466
            true_feats = F.gather_row(g.ndata[name], local_nodes)
467
            ndata = F.gather_row(node_feats["_N/" + name], local_nid)
468
            assert np.all(F.asnumpy(true_feats) == F.asnumpy(ndata))
469
        for name in ["feats"]:
470
471
472
            efeat_name = _etype_tuple_to_str(DEFAULT_ETYPE) + "/" + name
            assert efeat_name in edge_feats
            assert edge_feats[efeat_name].shape[0] == len(local_edges)
473
            true_feats = F.gather_row(g.edata[name], local_edges)
474
            edata = F.gather_row(edge_feats[efeat_name], local_eid)
475
476
477
            assert np.all(F.asnumpy(true_feats) == F.asnumpy(edata))

        # This only works if node/edge IDs are shuffled.
478
479
        shuffled_labels.append(node_feats["_N/labels"])
        shuffled_edata.append(edge_feats["_N:_E:_N/feats"])
480
481

    # Verify that we can reconstruct node/edge data for original IDs.
482
483
    shuffled_labels = F.asnumpy(F.cat(shuffled_labels, 0))
    shuffled_edata = F.asnumpy(F.cat(shuffled_edata, 0))
484
    orig_labels = np.zeros(shuffled_labels.shape, dtype=shuffled_labels.dtype)
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
    orig_edata = np.zeros(shuffled_edata.shape, dtype=shuffled_edata.dtype)
    orig_labels[F.asnumpy(orig_nids)] = shuffled_labels
    orig_edata[F.asnumpy(orig_eids)] = shuffled_edata
    assert np.all(orig_labels == F.asnumpy(g.ndata["labels"]))
    assert np.all(orig_edata == F.asnumpy(g.edata["feats"]))

    node_map = []
    edge_map = []
    for i, (num_nodes, num_edges) in enumerate(part_sizes):
        node_map.append(np.ones(num_nodes) * i)
        edge_map.append(np.ones(num_edges) * i)
    node_map = np.concatenate(node_map)
    edge_map = np.concatenate(edge_map)
    nid2pid = gpb.nid2partid(F.arange(0, len(node_map)))
    assert F.dtype(nid2pid) in (F.int32, F.int64)
    assert np.all(F.asnumpy(nid2pid) == node_map)
    eid2pid = gpb.eid2partid(F.arange(0, len(edge_map)))
    assert F.dtype(eid2pid) in (F.int32, F.int64)
    assert np.all(F.asnumpy(eid2pid) == edge_map)
Da Zheng's avatar
Da Zheng committed
504

505

506
507
@pytest.mark.parametrize("part_method", ["metis", "random"])
@pytest.mark.parametrize("num_parts", [1, 4])
508
@pytest.mark.parametrize("num_trainers_per_machine", [1])
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
@pytest.mark.parametrize("load_feats", [True, False])
@pytest.mark.parametrize(
    "graph_formats", [None, ["csc"], ["coo", "csc"], ["coo", "csc", "csr"]]
)
def test_partition(
    part_method,
    num_parts,
    num_trainers_per_machine,
    load_feats,
    graph_formats,
):
    os.environ["DGL_DIST_DEBUG"] = "1"
    if part_method == "random" and num_parts > 1:
        num_trainers_per_machine = 1
    g = create_random_graph(1000)
    check_partition(
        g,
        part_method,
        num_parts,
        num_trainers_per_machine,
        load_feats,
        graph_formats,
    )
532
    hg = create_random_hetero()
533
534
535
536
537
538
539
540
    check_hetero_partition(
        hg,
        part_method,
        num_parts,
        num_trainers_per_machine,
        load_feats,
        graph_formats,
    )
541
    reset_envs()
Da Zheng's avatar
Da Zheng committed
542

543

544
def test_RangePartitionBook():
545
    part_id = 1
546
    num_parts = 2
547

548
    # homogeneous
549
550
551
552
    node_map = {DEFAULT_NTYPE: F.tensor([[0, 1000], [1000, 2000]])}
    edge_map = {DEFAULT_ETYPE: F.tensor([[0, 5000], [5000, 10000]])}
    ntypes = {DEFAULT_NTYPE: 0}
    etypes = {DEFAULT_ETYPE: 0}
553
    gpb = RangePartitionBook(
554
555
        part_id, num_parts, node_map, edge_map, ntypes, etypes
    )
556
557
558
    assert gpb.etypes == [DEFAULT_ETYPE[1]]
    assert gpb.canonical_etypes == [DEFAULT_ETYPE]
    assert gpb.to_canonical_etype(DEFAULT_ETYPE[1]) == DEFAULT_ETYPE
559

560
561
562
563
    node_policy = NodePartitionPolicy(gpb, DEFAULT_NTYPE)
    assert node_policy.type_name == DEFAULT_NTYPE
    edge_policy = EdgePartitionPolicy(gpb, DEFAULT_ETYPE)
    assert edge_policy.type_name == DEFAULT_ETYPE
564

565
    # Init via etype is not supported
566
567
568
569
570
571
572
    node_map = {
        "node1": F.tensor([[0, 1000], [1000, 2000]]),
        "node2": F.tensor([[0, 1000], [1000, 2000]]),
    }
    edge_map = {"edge1": F.tensor([[0, 5000], [5000, 10000]])}
    ntypes = {"node1": 0, "node2": 1}
    etypes = {"edge1": 0}
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    expect_except = False
    try:
        RangePartitionBook(
            part_id, num_parts, node_map, edge_map, ntypes, etypes
        )
    except AssertionError:
        expect_except = True
    assert expect_except
    expect_except = False
    try:
        EdgePartitionPolicy(gpb, "edge1")
    except AssertionError:
        expect_except = True
    assert expect_except
587
588

    # heterogeneous, init via canonical etype
589
590
591
592
593
594
595
596
597
    node_map = {
        "node1": F.tensor([[0, 1000], [1000, 2000]]),
        "node2": F.tensor([[0, 1000], [1000, 2000]]),
    }
    edge_map = {
        ("node1", "edge1", "node2"): F.tensor([[0, 5000], [5000, 10000]])
    }
    ntypes = {"node1": 0, "node2": 1}
    etypes = {("node1", "edge1", "node2"): 0}
598
599
    c_etype = list(etypes.keys())[0]
    gpb = RangePartitionBook(
600
601
602
        part_id, num_parts, node_map, edge_map, ntypes, etypes
    )
    assert gpb.etypes == ["edge1"]
603
    assert gpb.canonical_etypes == [c_etype]
604
605
    assert gpb.to_canonical_etype("edge1") == c_etype
    assert gpb.to_canonical_etype(c_etype) == c_etype
606
607
    expect_except = False
    try:
608
        gpb.to_canonical_etype(("node1", "edge2", "node2"))
609
    except BaseException:
610
611
612
613
        expect_except = True
    assert expect_except
    expect_except = False
    try:
614
        gpb.to_canonical_etype("edge2")
615
    except BaseException:
616
617
618
        expect_except = True
    assert expect_except

619
    # NodePartitionPolicy
620
621
    node_policy = NodePartitionPolicy(gpb, "node1")
    assert node_policy.type_name == "node1"
622
623
624
    assert node_policy.policy_str == "node~node1"
    assert node_policy.part_id == part_id
    assert node_policy.is_node
625
    assert node_policy.get_data_name("x").is_node()
626
627
628
629
630
631
632
633
    local_ids = th.arange(0, 1000)
    global_ids = local_ids + 1000
    assert th.equal(node_policy.to_local(global_ids), local_ids)
    assert th.all(node_policy.to_partid(global_ids) == part_id)
    assert node_policy.get_part_size() == 1000
    assert node_policy.get_size() == 2000

    # EdgePartitionPolicy
634
635
    edge_policy = EdgePartitionPolicy(gpb, c_etype)
    assert edge_policy.type_name == c_etype
636
637
638
    assert edge_policy.policy_str == "edge~node1:edge1:node2"
    assert edge_policy.part_id == part_id
    assert not edge_policy.is_node
639
    assert not edge_policy.get_data_name("x").is_node()
640
641
642
643
644
645
    local_ids = th.arange(0, 5000)
    global_ids = local_ids + 5000
    assert th.equal(edge_policy.to_local(global_ids), local_ids)
    assert th.all(edge_policy.to_partid(global_ids) == part_id)
    assert edge_policy.get_part_size() == 5000
    assert edge_policy.get_size() == 10000
646

647
648
649
    expect_except = False
    try:
        HeteroDataName(False, "edge1", "feat")
650
    except BaseException:
651
652
653
        expect_except = True
    assert expect_except
    data_name = HeteroDataName(False, c_etype, "feat")
654
    assert data_name.get_type() == c_etype
655
656
657


def test_UnknownPartitionBook():
658
659
    node_map = {"_N": {0: 0, 1: 1, 2: 2}}
    edge_map = {"_N:_E:_N": {0: 0, 1: 1, 2: 2}}
660
661
662
663
664
665
666

    part_metadata = {
        "num_parts": 1,
        "num_nodes": len(node_map),
        "num_edges": len(edge_map),
        "node_map": node_map,
        "edge_map": edge_map,
667
        "graph_name": "test_graph",
668
669
670
671
672
    }

    with tempfile.TemporaryDirectory() as test_dir:
        part_config = os.path.join(test_dir, "test_graph.json")
        with open(part_config, "w") as file:
673
            json.dump(part_metadata, file, indent=4)
674
675
676
677
678
        try:
            load_partition_book(part_config, 0)
        except Exception as e:
            if not isinstance(e, TypeError):
                raise e
679
680
681
682


@pytest.mark.parametrize("part_method", ["metis", "random"])
@pytest.mark.parametrize("num_parts", [1, 4])
683
684
685
686
687
688
689
690
691
692
693
@pytest.mark.parametrize("store_eids", [True, False])
@pytest.mark.parametrize("store_inner_node", [True, False])
@pytest.mark.parametrize("store_inner_edge", [True, False])
@pytest.mark.parametrize("debug_mode", [True, False])
def test_dgl_partition_to_graphbolt_homo(
    part_method,
    num_parts,
    store_eids,
    store_inner_node,
    store_inner_edge,
    debug_mode,
694
):
695
696
697
    reset_envs()
    if debug_mode:
        os.environ["DGL_DIST_DEBUG"] = "1"
698
699
700
701
702
703
704
    with tempfile.TemporaryDirectory() as test_dir:
        g = create_random_graph(1000)
        graph_name = "test"
        partition_graph(
            g, graph_name, num_parts, test_dir, part_method=part_method
        )
        part_config = os.path.join(test_dir, f"{graph_name}.json")
705
706
707
708
709
710
        dgl_partition_to_graphbolt(
            part_config,
            store_eids=store_eids,
            store_inner_node=store_inner_node,
            store_inner_edge=store_inner_edge,
        )
711
712
713
714
        for part_id in range(num_parts):
            orig_g = dgl.load_graphs(
                os.path.join(test_dir, f"part{part_id}/graph.dgl")
            )[0][0]
715
716
717
            new_g = load_partition(
                part_config, part_id, load_feats=False, use_graphbolt=True
            )[0]
718
            orig_indptr, orig_indices, orig_eids = orig_g.adj().csc()
719
720
721
            assert th.equal(orig_indptr, new_g.csc_indptr)
            assert th.equal(orig_indices, new_g.indices)
            assert new_g.node_type_offset is None
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
            assert th.equal(
                orig_g.ndata[dgl.NID], new_g.node_attributes[dgl.NID]
            )
            if store_inner_node or debug_mode:
                assert th.equal(
                    orig_g.ndata["inner_node"],
                    new_g.node_attributes["inner_node"],
                )
            else:
                assert "inner_node" not in new_g.node_attributes
            if store_eids or debug_mode:
                assert th.equal(
                    orig_g.edata[dgl.EID][orig_eids],
                    new_g.edge_attributes[dgl.EID],
                )
            else:
                assert dgl.EID not in new_g.edge_attributes
            if store_inner_edge or debug_mode:
                assert th.equal(
                    orig_g.edata["inner_edge"][orig_eids],
                    new_g.edge_attributes["inner_edge"],
                )
            else:
                assert "inner_edge" not in new_g.edge_attributes
            assert new_g.type_per_edge is None
            assert new_g.node_type_to_id is None
            assert new_g.edge_type_to_id is None
749
750
751
752


@pytest.mark.parametrize("part_method", ["metis", "random"])
@pytest.mark.parametrize("num_parts", [1, 4])
753
754
755
756
757
758
759
760
761
762
763
@pytest.mark.parametrize("store_eids", [True, False])
@pytest.mark.parametrize("store_inner_node", [True, False])
@pytest.mark.parametrize("store_inner_edge", [True, False])
@pytest.mark.parametrize("debug_mode", [True, False])
def test_dgl_partition_to_graphbolt_hetero(
    part_method,
    num_parts,
    store_eids,
    store_inner_node,
    store_inner_edge,
    debug_mode,
764
):
765
766
767
    reset_envs()
    if debug_mode:
        os.environ["DGL_DIST_DEBUG"] = "1"
768
769
770
771
772
773
774
    with tempfile.TemporaryDirectory() as test_dir:
        g = create_random_hetero()
        graph_name = "test"
        partition_graph(
            g, graph_name, num_parts, test_dir, part_method=part_method
        )
        part_config = os.path.join(test_dir, f"{graph_name}.json")
775
776
777
778
779
780
        dgl_partition_to_graphbolt(
            part_config,
            store_eids=store_eids,
            store_inner_node=store_inner_node,
            store_inner_edge=store_inner_edge,
        )
781
782
783
784
        for part_id in range(num_parts):
            orig_g = dgl.load_graphs(
                os.path.join(test_dir, f"part{part_id}/graph.dgl")
            )[0][0]
785
786
787
            new_g = load_partition(
                part_config, part_id, load_feats=False, use_graphbolt=True
            )[0]
788
            orig_indptr, orig_indices, orig_eids = orig_g.adj().csc()
789
790
            assert th.equal(orig_indptr, new_g.csc_indptr)
            assert th.equal(orig_indices, new_g.indices)
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
            assert th.equal(
                orig_g.ndata[dgl.NID], new_g.node_attributes[dgl.NID]
            )
            if store_inner_node or debug_mode:
                assert th.equal(
                    orig_g.ndata["inner_node"],
                    new_g.node_attributes["inner_node"],
                )
            else:
                assert "inner_node" not in new_g.node_attributes
            if debug_mode:
                assert th.equal(
                    orig_g.ndata[dgl.NTYPE], new_g.node_attributes[dgl.NTYPE]
                )
            else:
                assert dgl.NTYPE not in new_g.node_attributes
            if store_eids or debug_mode:
                assert th.equal(
                    orig_g.edata[dgl.EID][orig_eids],
                    new_g.edge_attributes[dgl.EID],
                )
            else:
                assert dgl.EID not in new_g.edge_attributes
            if store_inner_edge or debug_mode:
                assert th.equal(
                    orig_g.edata["inner_edge"],
                    new_g.edge_attributes["inner_edge"],
                )
            else:
                assert "inner_edge" not in new_g.edge_attributes
            if debug_mode:
                assert th.equal(
                    orig_g.edata[dgl.ETYPE][orig_eids],
                    new_g.edge_attributes[dgl.ETYPE],
                )
            else:
                assert dgl.ETYPE not in new_g.edge_attributes
            assert th.equal(
                orig_g.edata[dgl.ETYPE][orig_eids], new_g.type_per_edge
            )

832
            for node_type, type_id in new_g.node_type_to_id.items():
833
                assert g.get_ntype_id(node_type) == type_id
834
            for edge_type, type_id in new_g.edge_type_to_id.items():
835
                assert g.get_etype_id(_etype_str_to_tuple(edge_type)) == type_id
836
            assert new_g.node_type_offset is None
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946


def test_not_sorted_node_edge_map():
    # Partition configure file which includes not sorted node/edge map.
    part_config_str = """
{
    "edge_map": {
        "item:likes-rev:user": [
            [
                0,
                100
            ],
            [
                1000,
                1500
            ]
        ],
        "user:follows-rev:user": [
            [
                300,
                600
            ],
            [
                2100,
                2800
            ]
        ],
        "user:follows:user": [
            [
                100,
                300
            ],
            [
                1500,
                2100
            ]
        ],
        "user:likes:item": [
            [
                600,
                1000
            ],
            [
                2800,
                3600
            ]
        ]
    },
    "etypes": {
        "item:likes-rev:user": 0,
        "user:follows-rev:user": 2,
        "user:follows:user": 1,
        "user:likes:item": 3
    },
    "graph_name": "test_graph",
    "halo_hops": 1,
    "node_map": {
        "user": [
            [
                100,
                300
            ],
            [
                600,
                1000
            ]
        ],
        "item": [
            [
                0,
                100
            ],
            [
                300,
                600
            ]
        ]
    },
    "ntypes": {
        "user": 1,
        "item": 0
    },
    "num_edges": 3600,
    "num_nodes": 1000,
    "num_parts": 2,
    "part-0": {
        "edge_feats": "part0/edge_feat.dgl",
        "node_feats": "part0/node_feat.dgl",
        "part_graph": "part0/graph.dgl"
    },
    "part-1": {
        "edge_feats": "part1/edge_feat.dgl",
        "node_feats": "part1/node_feat.dgl",
        "part_graph": "part1/graph.dgl"
    },
    "part_method": "metis"
}
    """
    with tempfile.TemporaryDirectory() as test_dir:
        part_config = os.path.join(test_dir, "test_graph.json")
        with open(part_config, "w") as file:
            file.write(part_config_str)
        # Part 0.
        gpb, _, _, _ = load_partition_book(part_config, 0)
        assert gpb.local_ntype_offset == [0, 100, 300]
        assert gpb.local_etype_offset == [0, 100, 300, 600, 1000]
        # Patr 1.
        gpb, _, _, _ = load_partition_book(part_config, 1)
        assert gpb.local_ntype_offset == [0, 300, 700]
        assert gpb.local_etype_offset == [0, 500, 1100, 1800, 2600]
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108


@pytest.mark.parametrize("part_method", ["metis", "random"])
@pytest.mark.parametrize("num_parts", [1, 4])
@pytest.mark.parametrize("store_eids", [True, False])
@pytest.mark.parametrize("store_inner_node", [True, False])
@pytest.mark.parametrize("store_inner_edge", [True, False])
@pytest.mark.parametrize("debug_mode", [True, False])
def test_partition_graph_graphbolt_homo(
    part_method,
    num_parts,
    store_eids,
    store_inner_node,
    store_inner_edge,
    debug_mode,
):
    reset_envs()
    if debug_mode:
        os.environ["DGL_DIST_DEBUG"] = "1"
    with tempfile.TemporaryDirectory() as test_dir:
        g = create_random_graph(1000)
        graph_name = "test"
        partition_graph(
            g,
            graph_name,
            num_parts,
            test_dir,
            part_method=part_method,
            use_graphbolt=True,
            store_eids=store_eids,
            store_inner_node=store_inner_node,
            store_inner_edge=store_inner_edge,
        )
        part_config = os.path.join(test_dir, f"{graph_name}.json")
        for part_id in range(num_parts):
            orig_g = dgl.load_graphs(
                os.path.join(test_dir, f"part{part_id}/graph.dgl")
            )[0][0]
            new_g = load_partition(
                part_config, part_id, load_feats=False, use_graphbolt=True
            )[0]
            orig_indptr, orig_indices, orig_eids = orig_g.adj().csc()
            assert th.equal(orig_indptr, new_g.csc_indptr)
            assert th.equal(orig_indices, new_g.indices)
            assert new_g.node_type_offset is None
            assert th.equal(
                orig_g.ndata[dgl.NID], new_g.node_attributes[dgl.NID]
            )
            if store_inner_node or debug_mode:
                assert th.equal(
                    orig_g.ndata["inner_node"],
                    new_g.node_attributes["inner_node"],
                )
            else:
                assert "inner_node" not in new_g.node_attributes
            if store_eids or debug_mode:
                assert th.equal(
                    orig_g.edata[dgl.EID][orig_eids],
                    new_g.edge_attributes[dgl.EID],
                )
            else:
                assert dgl.EID not in new_g.edge_attributes
            if store_inner_edge or debug_mode:
                assert th.equal(
                    orig_g.edata["inner_edge"][orig_eids],
                    new_g.edge_attributes["inner_edge"],
                )
            else:
                assert "inner_edge" not in new_g.edge_attributes
            assert new_g.type_per_edge is None
            assert new_g.node_type_to_id is None
            assert new_g.edge_type_to_id is None


@pytest.mark.parametrize("part_method", ["metis", "random"])
@pytest.mark.parametrize("num_parts", [1, 4])
@pytest.mark.parametrize("store_eids", [True, False])
@pytest.mark.parametrize("store_inner_node", [True, False])
@pytest.mark.parametrize("store_inner_edge", [True, False])
@pytest.mark.parametrize("debug_mode", [True, False])
def test_partition_graph_graphbolt_hetero(
    part_method,
    num_parts,
    store_eids,
    store_inner_node,
    store_inner_edge,
    debug_mode,
):
    reset_envs()
    if debug_mode:
        os.environ["DGL_DIST_DEBUG"] = "1"
    with tempfile.TemporaryDirectory() as test_dir:
        g = create_random_hetero()
        graph_name = "test"
        partition_graph(
            g,
            graph_name,
            num_parts,
            test_dir,
            part_method=part_method,
            use_graphbolt=True,
            store_eids=store_eids,
            store_inner_node=store_inner_node,
            store_inner_edge=store_inner_edge,
        )
        part_config = os.path.join(test_dir, f"{graph_name}.json")
        for part_id in range(num_parts):
            orig_g = dgl.load_graphs(
                os.path.join(test_dir, f"part{part_id}/graph.dgl")
            )[0][0]
            new_g = load_partition(
                part_config, part_id, load_feats=False, use_graphbolt=True
            )[0]
            orig_indptr, orig_indices, orig_eids = orig_g.adj().csc()
            assert th.equal(orig_indptr, new_g.csc_indptr)
            assert th.equal(orig_indices, new_g.indices)
            assert th.equal(
                orig_g.ndata[dgl.NID], new_g.node_attributes[dgl.NID]
            )
            if store_inner_node or debug_mode:
                assert th.equal(
                    orig_g.ndata["inner_node"],
                    new_g.node_attributes["inner_node"],
                )
            else:
                assert "inner_node" not in new_g.node_attributes
            if debug_mode:
                assert th.equal(
                    orig_g.ndata[dgl.NTYPE], new_g.node_attributes[dgl.NTYPE]
                )
            else:
                assert dgl.NTYPE not in new_g.node_attributes
            if store_eids or debug_mode:
                assert th.equal(
                    orig_g.edata[dgl.EID][orig_eids],
                    new_g.edge_attributes[dgl.EID],
                )
            else:
                assert dgl.EID not in new_g.edge_attributes
            if store_inner_edge or debug_mode:
                assert th.equal(
                    orig_g.edata["inner_edge"],
                    new_g.edge_attributes["inner_edge"],
                )
            else:
                assert "inner_edge" not in new_g.edge_attributes
            if debug_mode:
                assert th.equal(
                    orig_g.edata[dgl.ETYPE][orig_eids],
                    new_g.edge_attributes[dgl.ETYPE],
                )
            else:
                assert dgl.ETYPE not in new_g.edge_attributes
            assert th.equal(
                orig_g.edata[dgl.ETYPE][orig_eids], new_g.type_per_edge
            )

            for node_type, type_id in new_g.node_type_to_id.items():
                assert g.get_ntype_id(node_type) == type_id
            for edge_type, type_id in new_g.edge_type_to_id.items():
                assert g.get_etype_id(_etype_str_to_tuple(edge_type)) == type_id
            assert new_g.node_type_offset is None