test_subgraph_sampler.py 24.2 KB
Newer Older
1
import unittest
2
3

from enum import Enum
4
5
from functools import partial

6
7
import backend as F

8
import dgl
9
import dgl.graphbolt as gb
10
11
import pytest
import torch
12
from torchdata.datapipes.iter import Mapper
13

14
15
from . import gb_test_utils

16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Skip all tests on GPU.
pytestmark = pytest.mark.skipif(
    F._default_context_str != "cpu",
    reason="GraphBolt sampling tests are only supported on CPU.",
)


class SamplerType(Enum):
    Normal = 0
    Layer = 1
    Temporal = 2


def _get_sampler(sampler_type):
    if sampler_type == SamplerType.Normal:
        return gb.NeighborSampler
    if sampler_type == SamplerType.Layer:
        return gb.LayerNeighborSampler
    return partial(
        gb.TemporalNeighborSampler,
        node_timestamp_attr_name="timestamp",
        edge_timestamp_attr_name="timestamp",
    )


42
43
def test_SubgraphSampler_invoke():
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
44
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
45
46

    # Invoke via class constructor.
47
    datapipe = gb.SubgraphSampler(item_sampler)
48
49
50
51
    with pytest.raises(NotImplementedError):
        next(iter(datapipe))

    # Invokde via functional form.
52
    datapipe = item_sampler.sample_subgraph()
53
54
55
56
57
58
    with pytest.raises(NotImplementedError):
        next(iter(datapipe))


@pytest.mark.parametrize("labor", [False, True])
def test_NeighborSampler_invoke(labor):
59
60
61
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
62
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
63
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
64
65
66
67
68
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    # Invoke via class constructor.
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
69
    datapipe = Sampler(item_sampler, graph, fanouts)
70
71
72
73
    assert len(list(datapipe)) == 5

    # Invokde via functional form.
    if labor:
74
        datapipe = item_sampler.sample_layer_neighbor(graph, fanouts)
75
    else:
76
        datapipe = item_sampler.sample_neighbor(graph, fanouts)
77
78
79
    assert len(list(datapipe)) == 5


80
81
@pytest.mark.parametrize("labor", [False, True])
def test_NeighborSampler_fanouts(labor):
82
83
84
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
85
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
86
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    num_layer = 2

    # `fanouts` is a list of tensors.
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    if labor:
        datapipe = item_sampler.sample_layer_neighbor(graph, fanouts)
    else:
        datapipe = item_sampler.sample_neighbor(graph, fanouts)
    assert len(list(datapipe)) == 5

    # `fanouts` is a list of integers.
    fanouts = [2 for _ in range(num_layer)]
    if labor:
        datapipe = item_sampler.sample_layer_neighbor(graph, fanouts)
    else:
        datapipe = item_sampler.sample_neighbor(graph, fanouts)
    assert len(list(datapipe)) == 5


106
107
108
109
110
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Node(sampler_type):
111
112
113
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
114
115
116
117
118
119
120
121
122
123
    items = torch.arange(10)
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {"timestamp": torch.arange(20).to(F.ctx())}
        graph.edge_attributes = {
            "timestamp": torch.arange(len(graph.indices)).to(F.ctx())
        }
        items = (items, torch.arange(10))
        names = ("seed_nodes", "timestamp")
    itemset = gb.ItemSet(items, names=names)
124
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
125
126
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
127
128
    sampler = _get_sampler(sampler_type)
    sampler_dp = sampler(item_sampler, graph, fanouts)
129
    assert len(list(sampler_dp)) == 5
130
131


132
def to_link_batch(data):
133
    block = gb.MiniBatch(node_pairs=data)
134
    return block
135
136


137
138
139
140
141
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link(sampler_type):
142
143
144
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
145
146
147
148
149
150
151
152
153
154
    items = torch.arange(20).reshape(-1, 2)
    names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {"timestamp": torch.arange(20).to(F.ctx())}
        graph.edge_attributes = {
            "timestamp": torch.arange(len(graph.indices)).to(F.ctx())
        }
        items = (items, torch.arange(10))
        names = ("node_pairs", "timestamp")
    itemset = gb.ItemSet(items, names=names)
155
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
156
157
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
158
159
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
160
161
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
162
163


164
165
166
167
168
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_With_Negative(sampler_type):
169
170
171
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True).to(
        F.ctx()
    )
172
173
174
175
176
177
178
179
180
181
    items = torch.arange(20).reshape(-1, 2)
    names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {"timestamp": torch.arange(20).to(F.ctx())}
        graph.edge_attributes = {
            "timestamp": torch.arange(len(graph.indices)).to(F.ctx())
        }
        items = (items, torch.arange(10))
        names = ("node_pairs", "timestamp")
    itemset = gb.ItemSet(items, names=names)
182
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
183
184
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
185
    datapipe = gb.UniformNegativeSampler(datapipe, graph, 1)
186
187
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
188
189
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
190
191


192
193
194
195
196
197
198
def get_hetero_graph():
    # COO graph:
    # [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
    # [2, 4, 2, 3, 0, 1, 1, 0, 0, 1]
    # [1, 1, 1, 1, 0, 0, 0, 0, 0] - > edge type.
    # num_nodes = 5, num_n1 = 2, num_n2 = 3
    ntypes = {"n1": 0, "n2": 1}
199
    etypes = {"n1:e1:n2": 0, "n2:e2:n1": 1}
200
201
202
203
    indptr = torch.LongTensor([0, 2, 4, 6, 8, 10])
    indices = torch.LongTensor([2, 4, 2, 3, 0, 1, 1, 0, 0, 1])
    type_per_edge = torch.LongTensor([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
    node_type_offset = torch.LongTensor([0, 2, 5])
204
    return gb.fused_csc_sampling_graph(
205
206
207
208
        indptr,
        indices,
        node_type_offset=node_type_offset,
        type_per_edge=type_per_edge,
209
210
        node_type_to_id=ntypes,
        edge_type_to_id=etypes,
211
    )
212
213


214
215
216
217
218
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Node_Hetero(sampler_type):
219
    graph = get_hetero_graph().to(F.ctx())
220
221
222
223
224
225
226
227
228
229
230
231
    items = torch.arange(3)
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        items = (items, torch.randint(0, 10, (3,)))
        names = (names, "timestamp")
    itemset = gb.ItemSetDict({"n2": gb.ItemSet(items, names=names)})
232
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
233
234
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
235
236
    sampler = _get_sampler(sampler_type)
    sampler_dp = sampler(item_sampler, graph, fanouts)
237
238
    assert len(list(sampler_dp)) == 2
    for minibatch in sampler_dp:
peizhou001's avatar
peizhou001 committed
239
        assert len(minibatch.sampled_subgraphs) == num_layer
240
241


242
243
244
245
246
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_Hetero(sampler_type):
247
    graph = get_hetero_graph().to(F.ctx())
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    first_items = torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T
    first_names = "node_pairs"
    second_items = torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T
    second_names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        first_items = (first_items, torch.randint(0, 10, (4,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (6,)))
        second_names = (second_names, "timestamp")
263
264
    itemset = gb.ItemSetDict(
        {
265
            "n1:e1:n2": gb.ItemSet(
266
267
                first_items,
                names=first_names,
268
            ),
269
            "n2:e2:n1": gb.ItemSet(
270
271
                second_items,
                names=second_names,
272
273
274
            ),
        }
    )
275

276
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
277
278
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
279
280
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
281
282
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
283
284


285
286
287
288
289
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Link_Hetero_With_Negative(sampler_type):
290
    graph = get_hetero_graph().to(F.ctx())
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    first_items = torch.LongTensor([[0, 0, 1, 1], [0, 2, 0, 1]]).T
    first_names = "node_pairs"
    second_items = torch.LongTensor([[0, 0, 1, 1, 2, 2], [0, 1, 1, 0, 0, 1]]).T
    second_names = "node_pairs"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.arange(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.arange(graph.indices.numel()).to(F.ctx())
        }
        first_items = (first_items, torch.randint(0, 10, (4,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (6,)))
        second_names = (second_names, "timestamp")
306
307
    itemset = gb.ItemSetDict(
        {
308
            "n1:e1:n2": gb.ItemSet(
309
310
                first_items,
                names=first_names,
311
            ),
312
            "n2:e2:n1": gb.ItemSet(
313
314
                second_items,
                names=second_names,
315
316
317
318
            ),
        }
    )

319
    datapipe = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
320
321
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
322
    datapipe = gb.UniformNegativeSampler(datapipe, graph, 1)
323
324
    sampler = _get_sampler(sampler_type)
    datapipe = sampler(datapipe, graph, fanouts)
325
326
    datapipe = datapipe.transform(partial(gb.exclude_seed_edges))
    assert len(list(datapipe)) == 5
327
328


329
330
331
332
@unittest.skipIf(
    F._default_context_str != "cpu",
    reason="Sampling with replacement not yet supported on GPU.",
)
333
334
335
336
337
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_Random_Hetero_Graph(sampler_type):
338
339
340
341
342
343
344
345
346
    num_nodes = 5
    num_edges = 9
    num_ntypes = 3
    num_etypes = 3
    (
        csc_indptr,
        indices,
        node_type_offset,
        type_per_edge,
347
348
        node_type_to_id,
        edge_type_to_id,
349
350
351
    ) = gb_test_utils.random_hetero_graph(
        num_nodes, num_edges, num_ntypes, num_etypes
    )
352
    node_attributes = {}
353
354
355
356
    edge_attributes = {
        "A1": torch.randn(num_edges),
        "A2": torch.randn(num_edges),
    }
357
358
359
    if sampler_type == SamplerType.Temporal:
        node_attributes["timestamp"] = torch.randint(0, 10, (num_nodes,))
        edge_attributes["timestamp"] = torch.randint(0, 10, (num_edges,))
360
    graph = gb.fused_csc_sampling_graph(
361
362
        csc_indptr,
        indices,
363
364
365
366
        node_type_offset=node_type_offset,
        type_per_edge=type_per_edge,
        node_type_to_id=node_type_to_id,
        edge_type_to_id=edge_type_to_id,
367
        node_attributes=node_attributes,
368
        edge_attributes=edge_attributes,
369
    ).to(F.ctx())
370
371
372
373
374
375
376
377
378
    first_items = torch.tensor([0])
    first_names = "seed_nodes"
    second_items = torch.tensor([0])
    second_names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        first_items = (first_items, torch.randint(0, 10, (1,)))
        first_names = (first_names, "timestamp")
        second_items = (second_items, torch.randint(0, 10, (1,)))
        second_names = (second_names, "timestamp")
379
380
    itemset = gb.ItemSetDict(
        {
381
382
            "n2": gb.ItemSet(first_items, names=first_names),
            "n1": gb.ItemSet(second_items, names=second_names),
383
384
385
        }
    )

386
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
387
388
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
389
    sampler = _get_sampler(sampler_type)
390

391
    sampler_dp = sampler(item_sampler, graph, fanouts, replace=True)
392
393
394

    for data in sampler_dp:
        for sampledsubgraph in data.sampled_subgraphs:
395
            for _, value in sampledsubgraph.sampled_csc.items():
396
                assert torch.equal(
397
398
                    torch.ge(value.indices, torch.zeros(len(value.indices))),
                    torch.ones(len(value.indices)),
399
400
                )
                assert torch.equal(
401
402
                    torch.ge(value.indptr, torch.zeros(len(value.indptr))),
                    torch.ones(len(value.indptr)),
403
404
405
406
407
408
409
410
411
412
413
                )
            for _, value in sampledsubgraph.original_column_node_ids.items():
                assert torch.equal(
                    torch.ge(value, torch.zeros(len(value))),
                    torch.ones(len(value)),
                )
            for _, value in sampledsubgraph.original_row_node_ids.items():
                assert torch.equal(
                    torch.ge(value, torch.zeros(len(value))),
                    torch.ones(len(value)),
                )
414
415


416
417
418
419
@unittest.skipIf(
    F._default_context_str != "cpu",
    reason="Fails due to randomness on the GPU.",
)
420
421
422
423
424
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_without_dedpulication_Homo(sampler_type):
425
426
427
    graph = dgl.graph(
        ([5, 0, 1, 5, 6, 7, 2, 2, 4], [0, 1, 2, 2, 2, 2, 3, 4, 4])
    )
428
    graph = gb.from_dglgraph(graph, True).to(F.ctx())
429
    seed_nodes = torch.LongTensor([0, 3, 4])
430
431
432
433
434
435
436
437
438
439
440
    items = seed_nodes
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.zeros(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.zeros(graph.indices.numel()).to(F.ctx())
        }
        items = (items, torch.randint(0, 10, (3,)))
        names = (names, "timestamp")
441

442
    itemset = gb.ItemSet(items, names=names)
443
444
445
    item_sampler = gb.ItemSampler(itemset, batch_size=len(seed_nodes)).copy_to(
        F.ctx()
    )
446
447
448
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

449
450
451
452
453
    sampler = _get_sampler(sampler_type)
    if sampler_type == SamplerType.Temporal:
        datapipe = sampler(item_sampler, graph, fanouts)
    else:
        datapipe = sampler(item_sampler, graph, fanouts, deduplicate=False)
454
455
456

    length = [17, 7]
    compacted_indices = [
457
458
        (torch.arange(0, 10) + 7).to(F.ctx()),
        (torch.arange(0, 4) + 3).to(F.ctx()),
459
460
    ]
    indptr = [
461
462
463
464
465
466
        torch.tensor([0, 1, 2, 4, 4, 6, 8, 10]).to(F.ctx()),
        torch.tensor([0, 1, 2, 4]).to(F.ctx()),
    ]
    seeds = [
        torch.tensor([0, 3, 4, 5, 2, 2, 4]).to(F.ctx()),
        torch.tensor([0, 3, 4]).to(F.ctx()),
467
468
469
470
471
    ]
    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            assert len(sampled_subgraph.original_row_node_ids) == length[step]
            assert torch.equal(
472
473
474
475
                sampled_subgraph.sampled_csc.indices, compacted_indices[step]
            )
            assert torch.equal(
                sampled_subgraph.sampled_csc.indptr, indptr[step]
476
477
478
479
480
481
            )
            assert torch.equal(
                sampled_subgraph.original_column_node_ids, seeds[step]
            )


482
483
484
485
486
@pytest.mark.parametrize(
    "sampler_type",
    [SamplerType.Normal, SamplerType.Layer, SamplerType.Temporal],
)
def test_SubgraphSampler_without_dedpulication_Hetero(sampler_type):
487
    graph = get_hetero_graph().to(F.ctx())
488
489
490
491
492
493
494
495
496
497
498
499
    items = torch.arange(2)
    names = "seed_nodes"
    if sampler_type == SamplerType.Temporal:
        graph.node_attributes = {
            "timestamp": torch.zeros(graph.csc_indptr.numel() - 1).to(F.ctx())
        }
        graph.edge_attributes = {
            "timestamp": torch.zeros(graph.indices.numel()).to(F.ctx())
        }
        items = (items, torch.randint(0, 10, (2,)))
        names = (names, "timestamp")
    itemset = gb.ItemSetDict({"n2": gb.ItemSet(items, names=names)})
500
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
501
502
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
503
504
505
506
507
    sampler = _get_sampler(sampler_type)
    if sampler_type == SamplerType.Temporal:
        datapipe = sampler(item_sampler, graph, fanouts)
    else:
        datapipe = sampler(item_sampler, graph, fanouts, deduplicate=False)
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    csc_formats = [
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([4, 5, 6, 7]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4, 6, 8]),
                indices=torch.tensor([2, 3, 4, 5, 6, 7, 8, 9]),
            ),
        },
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 1, 2, 3]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0]),
                indices=torch.tensor([], dtype=torch.int64),
            ),
        },
    ]
    original_column_node_ids = [
        {
            "n1": torch.tensor([0, 1, 1, 0]),
            "n2": torch.tensor([0, 1]),
        },
        {
            "n1": torch.tensor([], dtype=torch.int64),
            "n2": torch.tensor([0, 1]),
        },
    ]
    original_row_node_ids = [
        {
            "n1": torch.tensor([0, 1, 1, 0, 0, 1, 1, 0]),
            "n2": torch.tensor([0, 1, 0, 2, 0, 1, 0, 1, 0, 2]),
        },
        {
            "n1": torch.tensor([0, 1, 1, 0]),
            "n2": torch.tensor([0, 1]),
        },
    ]

    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            for ntype in ["n1", "n2"]:
                assert torch.equal(
                    sampled_subgraph.original_row_node_ids[ntype],
556
                    original_row_node_ids[step][ntype].to(F.ctx()),
557
558
559
                )
                assert torch.equal(
                    sampled_subgraph.original_column_node_ids[ntype],
560
                    original_column_node_ids[step][ntype].to(F.ctx()),
561
562
563
                )
            for etype in ["n1:e1:n2", "n2:e2:n1"]:
                assert torch.equal(
564
                    sampled_subgraph.sampled_csc[etype].indices,
565
                    csc_formats[step][etype].indices.to(F.ctx()),
566
567
                )
                assert torch.equal(
568
                    sampled_subgraph.sampled_csc[etype].indptr,
569
                    csc_formats[step][etype].indptr.to(F.ctx()),
570
                )
571
572


573
574
575
576
@unittest.skipIf(
    F._default_context_str != "cpu",
    reason="Fails due to randomness on the GPU.",
)
577
578
579
580
@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_unique_csc_format_Homo(labor):
    torch.manual_seed(1205)
    graph = dgl.graph(([5, 0, 6, 7, 2, 2, 4], [0, 1, 2, 2, 3, 4, 4]))
581
    graph = gb.from_dglgraph(graph, True).to(F.ctx())
582
583
584
    seed_nodes = torch.LongTensor([0, 3, 4])

    itemset = gb.ItemSet(seed_nodes, names="seed_nodes")
585
586
587
    item_sampler = gb.ItemSampler(itemset, batch_size=len(seed_nodes)).copy_to(
        F.ctx()
    )
588
589
590
591
592
593
594
595
596
597
598
599
600
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    datapipe = Sampler(
        item_sampler,
        graph,
        fanouts,
        replace=False,
        deduplicate=True,
    )

    original_row_node_ids = [
601
602
        torch.tensor([0, 3, 4, 5, 2, 6, 7]).to(F.ctx()),
        torch.tensor([0, 3, 4, 5, 2]).to(F.ctx()),
603
604
    ]
    compacted_indices = [
605
606
        torch.tensor([3, 4, 4, 2, 5, 6]).to(F.ctx()),
        torch.tensor([3, 4, 4, 2]).to(F.ctx()),
607
608
    ]
    indptr = [
609
610
611
612
613
614
        torch.tensor([0, 1, 2, 4, 4, 6]).to(F.ctx()),
        torch.tensor([0, 1, 2, 4]).to(F.ctx()),
    ]
    seeds = [
        torch.tensor([0, 3, 4, 5, 2]).to(F.ctx()),
        torch.tensor([0, 3, 4]).to(F.ctx()),
615
616
617
618
619
620
621
622
    ]
    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            assert torch.equal(
                sampled_subgraph.original_row_node_ids,
                original_row_node_ids[step],
            )
            assert torch.equal(
623
624
625
626
                sampled_subgraph.sampled_csc.indices, compacted_indices[step]
            )
            assert torch.equal(
                sampled_subgraph.sampled_csc.indptr, indptr[step]
627
628
629
630
631
632
633
634
            )
            assert torch.equal(
                sampled_subgraph.original_column_node_ids, seeds[step]
            )


@pytest.mark.parametrize("labor", [False, True])
def test_SubgraphSampler_unique_csc_format_Hetero(labor):
635
    graph = get_hetero_graph().to(F.ctx())
636
637
638
    itemset = gb.ItemSetDict(
        {"n2": gb.ItemSet(torch.arange(2), names="seed_nodes")}
    )
639
    item_sampler = gb.ItemSampler(itemset, batch_size=2).copy_to(F.ctx())
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
    Sampler = gb.LayerNeighborSampler if labor else gb.NeighborSampler
    datapipe = Sampler(
        item_sampler,
        graph,
        fanouts,
        deduplicate=True,
    )
    csc_formats = [
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 1, 1, 0]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 2, 0, 1]),
            ),
        },
        {
            "n1:e1:n2": gb.CSCFormatBase(
                indptr=torch.tensor([0, 2, 4]),
                indices=torch.tensor([0, 1, 1, 0]),
            ),
            "n2:e2:n1": gb.CSCFormatBase(
                indptr=torch.tensor([0]),
                indices=torch.tensor([], dtype=torch.int64),
            ),
        },
    ]
    original_column_node_ids = [
        {
            "n1": torch.tensor([0, 1]),
            "n2": torch.tensor([0, 1]),
        },
        {
            "n1": torch.tensor([], dtype=torch.int64),
            "n2": torch.tensor([0, 1]),
        },
    ]
    original_row_node_ids = [
        {
            "n1": torch.tensor([0, 1]),
            "n2": torch.tensor([0, 1, 2]),
        },
        {
            "n1": torch.tensor([0, 1]),
            "n2": torch.tensor([0, 1]),
        },
    ]

    for data in datapipe:
        for step, sampled_subgraph in enumerate(data.sampled_subgraphs):
            for ntype in ["n1", "n2"]:
                assert torch.equal(
                    sampled_subgraph.original_row_node_ids[ntype],
697
                    original_row_node_ids[step][ntype].to(F.ctx()),
698
699
700
                )
                assert torch.equal(
                    sampled_subgraph.original_column_node_ids[ntype],
701
                    original_column_node_ids[step][ntype].to(F.ctx()),
702
703
704
                )
            for etype in ["n1:e1:n2", "n2:e2:n1"]:
                assert torch.equal(
705
                    sampled_subgraph.sampled_csc[etype].indices,
706
                    csc_formats[step][etype].indices.to(F.ctx()),
707
708
                )
                assert torch.equal(
709
                    sampled_subgraph.sampled_csc[etype].indptr,
710
                    csc_formats[step][etype].indptr.to(F.ctx()),
711
                )