test_minibatch.py 17.3 KB
Newer Older
1
2
import dgl
import dgl.graphbolt as gb
peizhou001's avatar
peizhou001 committed
3
import pytest
4
5
6
import torch


peizhou001's avatar
peizhou001 committed
7
8
9
10
11
relation = "A:r:B"
reverse_relation = "B:rr:A"


def create_homo_minibatch():
12
    node_pairs = [
peizhou001's avatar
peizhou001 committed
13
14
15
16
17
18
19
20
        (
            torch.tensor([0, 1, 2, 2, 2, 1]),
            torch.tensor([0, 1, 1, 2, 3, 2]),
        ),
        (
            torch.tensor([0, 1, 2]),
            torch.tensor([1, 0, 0]),
        ),
21
    ]
22
    original_column_node_ids = [
peizhou001's avatar
peizhou001 committed
23
24
        torch.tensor([10, 11, 12, 13]),
        torch.tensor([10, 11]),
25
    ]
26
    original_row_node_ids = [
peizhou001's avatar
peizhou001 committed
27
28
        torch.tensor([10, 11, 12, 13]),
        torch.tensor([10, 11, 12]),
29
    ]
30
    original_edge_ids = [
peizhou001's avatar
peizhou001 committed
31
32
        torch.tensor([19, 20, 21, 22, 25, 30]),
        torch.tensor([10, 15, 17]),
33
    ]
peizhou001's avatar
peizhou001 committed
34
    node_features = {"x": torch.randint(0, 10, (4,))}
35
    edge_features = [
peizhou001's avatar
peizhou001 committed
36
37
        {"x": torch.randint(0, 10, (6,))},
        {"x": torch.randint(0, 10, (3,))},
38
39
40
41
42
43
    ]
    subgraphs = []
    for i in range(2):
        subgraphs.append(
            gb.SampledSubgraphImpl(
                node_pairs=node_pairs[i],
44
45
46
                original_column_node_ids=original_column_node_ids[i],
                original_row_node_ids=original_row_node_ids[i],
                original_edge_ids=original_edge_ids[i],
47
48
            )
        )
peizhou001's avatar
peizhou001 committed
49
    return gb.MiniBatch(
50
51
52
        sampled_subgraphs=subgraphs,
        node_features=node_features,
        edge_features=edge_features,
53
        input_nodes=torch.tensor([10, 11, 12, 13]),
54
55
56
    )


peizhou001's avatar
peizhou001 committed
57
def create_hetero_minibatch():
58
    node_pairs = [
peizhou001's avatar
peizhou001 committed
59
60
61
62
63
        {
            relation: (torch.tensor([0, 1, 1]), torch.tensor([0, 1, 2])),
            reverse_relation: (torch.tensor([1, 0]), torch.tensor([2, 3])),
        },
        {relation: (torch.tensor([0, 1]), torch.tensor([1, 0]))},
64
    ]
65
    original_column_node_ids = [
peizhou001's avatar
peizhou001 committed
66
67
        {"B": torch.tensor([10, 11, 12]), "A": torch.tensor([5, 7, 9, 11])},
        {"B": torch.tensor([10, 11])},
68
    ]
69
    original_row_node_ids = [
peizhou001's avatar
peizhou001 committed
70
71
72
73
74
75
76
77
        {
            "A": torch.tensor([5, 7, 9, 11]),
            "B": torch.tensor([10, 11, 12]),
        },
        {
            "A": torch.tensor([5, 7]),
            "B": torch.tensor([10, 11]),
        },
78
    ]
79
    original_edge_ids = [
peizhou001's avatar
peizhou001 committed
80
81
82
83
84
        {
            relation: torch.tensor([19, 20, 21]),
            reverse_relation: torch.tensor([23, 26]),
        },
        {relation: torch.tensor([10, 12])},
85
    ]
peizhou001's avatar
peizhou001 committed
86
87
88
    node_features = {
        ("A", "x"): torch.randint(0, 10, (4,)),
    }
89
    edge_features = [
peizhou001's avatar
peizhou001 committed
90
91
        {(relation, "x"): torch.randint(0, 10, (3,))},
        {(relation, "x"): torch.randint(0, 10, (2,))},
92
93
94
95
96
97
    ]
    subgraphs = []
    for i in range(2):
        subgraphs.append(
            gb.SampledSubgraphImpl(
                node_pairs=node_pairs[i],
98
99
100
                original_column_node_ids=original_column_node_ids[i],
                original_row_node_ids=original_row_node_ids[i],
                original_edge_ids=original_edge_ids[i],
101
102
            )
        )
peizhou001's avatar
peizhou001 committed
103
    return gb.MiniBatch(
104
105
106
        sampled_subgraphs=subgraphs,
        node_features=node_features,
        edge_features=edge_features,
107
108
109
110
        input_nodes={
            "A": torch.tensor([5, 7, 9, 11]),
            "B": torch.tensor([10, 11, 12]),
        },
peizhou001's avatar
peizhou001 committed
111
    )
112
113


114
def test_minibatch_representation():
115
116
117
118
119
120
121
122
123
124
    node_pairs = [
        (
            torch.tensor([0, 1, 2, 2, 2, 1]),
            torch.tensor([0, 1, 1, 2, 3, 2]),
        ),
        (
            torch.tensor([0, 1, 2]),
            torch.tensor([1, 0, 0]),
        ),
    ]
125
    original_column_node_ids = [
126
127
128
        torch.tensor([10, 11, 12, 13]),
        torch.tensor([10, 11]),
    ]
129
    original_row_node_ids = [
130
131
132
        torch.tensor([10, 11, 12, 13]),
        torch.tensor([10, 11, 12]),
    ]
133
    original_edge_ids = [
134
135
136
137
138
139
140
141
142
143
144
145
146
        torch.tensor([19, 20, 21, 22, 25, 30]),
        torch.tensor([10, 15, 17]),
    ]
    node_features = {"x": torch.tensor([7, 6, 2, 2])}
    edge_features = [
        {"x": torch.tensor([[8], [1], [6]])},
        {"x": torch.tensor([[2], [8], [8]])},
    ]
    subgraphs = []
    for i in range(2):
        subgraphs.append(
            gb.SampledSubgraphImpl(
                node_pairs=node_pairs[i],
147
148
149
                original_column_node_ids=original_column_node_ids[i],
                original_row_node_ids=original_row_node_ids[i],
                original_edge_ids=original_edge_ids[i],
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
            )
        )
    negative_srcs = torch.tensor([[8], [1], [6]])
    negative_dsts = torch.tensor([[2], [8], [8]])
    input_nodes = torch.tensor([8, 1, 6, 5, 9, 0, 2, 4])
    compacted_node_pairs = (torch.tensor([0, 1, 2]), torch.tensor([3, 4, 5]))
    compacted_negative_srcs = torch.tensor([0, 1, 2])
    compacted_negative_dsts = torch.tensor([6, 0, 0])
    labels = torch.tensor([0.0, 1.0, 2.0])
    # Test minibatch without data.
    minibatch = gb.MiniBatch()
    expect_result = str(
        """MiniBatch(seed_nodes=None,
          sampled_subgraphs=None,
          node_pairs=None,
          node_features=None,
          negative_srcs=None,
          negative_dsts=None,
          labels=None,
          input_nodes=None,
          edge_features=None,
          compacted_node_pairs=None,
          compacted_negative_srcs=None,
          compacted_negative_dsts=None,
       )"""
    )
    result = str(minibatch)
    assert result == expect_result, print(len(expect_result), len(result))
    # Test minibatch with all attributes.
    minibatch = gb.MiniBatch(
        node_pairs=node_pairs,
        sampled_subgraphs=subgraphs,
        labels=labels,
        node_features=node_features,
        edge_features=edge_features,
        negative_srcs=negative_srcs,
        negative_dsts=negative_dsts,
        compacted_node_pairs=compacted_node_pairs,
        input_nodes=input_nodes,
        compacted_negative_srcs=compacted_negative_srcs,
        compacted_negative_dsts=compacted_negative_dsts,
    )
    expect_result = str(
        """MiniBatch(seed_nodes=None,
          sampled_subgraphs=[SampledSubgraphImpl(node_pairs=(tensor([0, 1, 2, 2, 2, 1]), tensor([0, 1, 1, 2, 3, 2])),
195
196
197
                                                original_column_node_ids=tensor([10, 11, 12, 13]),
                                                original_edge_ids=tensor([19, 20, 21, 22, 25, 30]),
                                                original_row_node_ids=tensor([10, 11, 12, 13]),),
198
                            SampledSubgraphImpl(node_pairs=(tensor([0, 1, 2]), tensor([1, 0, 0])),
199
200
201
                                                original_column_node_ids=tensor([10, 11]),
                                                original_edge_ids=tensor([10, 15, 17]),
                                                original_row_node_ids=tensor([10, 11, 12]),)],
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
          node_pairs=[(tensor([0, 1, 2, 2, 2, 1]), tensor([0, 1, 1, 2, 3, 2])),
                     (tensor([0, 1, 2]), tensor([1, 0, 0]))],
          node_features={'x': tensor([7, 6, 2, 2])},
          negative_srcs=tensor([[8],
                                [1],
                                [6]]),
          negative_dsts=tensor([[2],
                                [8],
                                [8]]),
          labels=tensor([0., 1., 2.]),
          input_nodes=tensor([8, 1, 6, 5, 9, 0, 2, 4]),
          edge_features=[{'x': tensor([[8],
                                       [1],
                                       [6]])},
                        {'x': tensor([[2],
                                       [8],
                                       [8]])}],
          compacted_node_pairs=(tensor([0, 1, 2]), tensor([3, 4, 5])),
          compacted_negative_srcs=tensor([0, 1, 2]),
          compacted_negative_dsts=tensor([6, 0, 0]),
       )"""
    )
    result = str(minibatch)
    assert result == expect_result, print(expect_result, result)
peizhou001's avatar
peizhou001 committed
226
227


228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def test_dgl_minibatch_representation():
    node_pairs = [
        (
            torch.tensor([0, 1, 2, 2, 2, 1]),
            torch.tensor([0, 1, 1, 2, 3, 2]),
        ),
        (
            torch.tensor([0, 1, 2]),
            torch.tensor([1, 0, 0]),
        ),
    ]
    original_column_node_ids = [
        torch.tensor([10, 11, 12, 13]),
        torch.tensor([10, 11]),
    ]
    original_row_node_ids = [
        torch.tensor([10, 11, 12, 13]),
        torch.tensor([10, 11, 12]),
    ]
    original_edge_ids = [
        torch.tensor([19, 20, 21, 22, 25, 30]),
        torch.tensor([10, 15, 17]),
    ]
    node_features = {"x": torch.tensor([7, 6, 2, 2])}
    edge_features = [
        {"x": torch.tensor([[8], [1], [6]])},
        {"x": torch.tensor([[2], [8], [8]])},
    ]
    subgraphs = []
    for i in range(2):
        subgraphs.append(
            gb.SampledSubgraphImpl(
                node_pairs=node_pairs[i],
                original_column_node_ids=original_column_node_ids[i],
                original_row_node_ids=original_row_node_ids[i],
                original_edge_ids=original_edge_ids[i],
            )
        )
    negative_srcs = torch.tensor([[8], [1], [6]])
    negative_dsts = torch.tensor([[2], [8], [8]])
    input_nodes = torch.tensor([8, 1, 6, 5, 9, 0, 2, 4])
    compacted_node_pairs = (torch.tensor([0, 1, 2]), torch.tensor([3, 4, 5]))
    compacted_negative_srcs = torch.tensor([0, 1, 2])
    compacted_negative_dsts = torch.tensor([6, 0, 0])
    labels = torch.tensor([0.0, 1.0, 2.0])
    # Test dglminibatch with all attributes.
    minibatch = gb.MiniBatch(
        node_pairs=node_pairs,
        sampled_subgraphs=subgraphs,
        labels=labels,
        node_features=node_features,
        edge_features=edge_features,
        negative_srcs=negative_srcs,
        negative_dsts=negative_dsts,
        compacted_node_pairs=compacted_node_pairs,
        input_nodes=input_nodes,
        compacted_negative_srcs=compacted_negative_srcs,
        compacted_negative_dsts=compacted_negative_dsts,
    )
    dgl_minibatch = minibatch.to_dgl()
    expect_result = str(
        """DGLMiniBatch(positive_node_pairs=(tensor([0, 1, 2]), tensor([3, 4, 5])),
             output_nodes=None,
             node_features={'x': tensor([7, 6, 2, 2])},
             negative_node_pairs=(tensor([0, 1, 2]), tensor([6, 0, 0])),
             labels=tensor([0., 1., 2.]),
294
             input_nodes=None,
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
             edge_features=[{'x': tensor([[8],
                                          [1],
                                          [6]])},
                            {'x': tensor([[2],
                                          [8],
                                          [8]])}],
             blocks=[Block(num_src_nodes=4,
                           num_dst_nodes=4,
                           num_edges=6),
                     Block(num_src_nodes=3,
                           num_dst_nodes=2,
                           num_edges=3)],
          )"""
    )
    result = str(dgl_minibatch)
    assert result == expect_result, print(result)


peizhou001's avatar
peizhou001 committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def check_dgl_blocks_hetero(minibatch, blocks):
    etype = gb.etype_str_to_tuple(relation)
    node_pairs = [
        subgraph.node_pairs for subgraph in minibatch.sampled_subgraphs
    ]
    original_edge_ids = [
        subgraph.original_edge_ids for subgraph in minibatch.sampled_subgraphs
    ]
    original_row_node_ids = [
        subgraph.original_row_node_ids
        for subgraph in minibatch.sampled_subgraphs
    ]

    for i, block in enumerate(blocks):
        edges = block.edges(etype=etype)
        assert torch.equal(edges[0], node_pairs[i][relation][0])
        assert torch.equal(edges[1], node_pairs[i][relation][1])
        assert torch.equal(
            block.edges[etype].data[dgl.EID], original_edge_ids[i][relation]
        )
    edges = blocks[0].edges(etype=gb.etype_str_to_tuple(reverse_relation))
    assert torch.equal(edges[0], node_pairs[0][reverse_relation][0])
    assert torch.equal(edges[1], node_pairs[0][reverse_relation][1])
    assert torch.equal(
        blocks[0].srcdata[dgl.NID]["A"], original_row_node_ids[0]["A"]
    )
    assert torch.equal(
        blocks[0].srcdata[dgl.NID]["B"], original_row_node_ids[0]["B"]
    )


def check_dgl_blocks_homo(minibatch, blocks):
    node_pairs = [
        subgraph.node_pairs for subgraph in minibatch.sampled_subgraphs
    ]
    original_edge_ids = [
        subgraph.original_edge_ids for subgraph in minibatch.sampled_subgraphs
    ]
    original_row_node_ids = [
        subgraph.original_row_node_ids
        for subgraph in minibatch.sampled_subgraphs
    ]
    for i, block in enumerate(blocks):
        assert torch.equal(block.edges()[0], node_pairs[i][0])
        assert torch.equal(block.edges()[1], node_pairs[i][1])
        assert torch.equal(block.edata[dgl.EID], original_edge_ids[i])
    assert torch.equal(blocks[0].srcdata[dgl.NID], original_row_node_ids[0])


362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def test_to_dgl_node_classification_without_feature():
    # Arrange
    minibatch = create_homo_minibatch()
    minibatch.node_features = None
    minibatch.labels = None
    minibatch.seed_nodes = torch.tensor([10, 15])
    # Act
    dgl_minibatch = minibatch.to_dgl()

    # Assert
    assert len(dgl_minibatch.blocks) == 2
    assert dgl_minibatch.node_features is None
    assert minibatch.edge_features is dgl_minibatch.edge_features
    assert dgl_minibatch.labels is None
    assert minibatch.input_nodes is dgl_minibatch.input_nodes
    assert minibatch.seed_nodes is dgl_minibatch.output_nodes
    check_dgl_blocks_homo(minibatch, dgl_minibatch.blocks)


peizhou001's avatar
peizhou001 committed
381
382
383
384
385
386
387
388
389
390
391
392
393
def test_to_dgl_node_classification_homo():
    # Arrange
    minibatch = create_homo_minibatch()
    minibatch.seed_nodes = torch.tensor([10, 15])
    minibatch.labels = torch.tensor([2, 5])
    # Act
    dgl_minibatch = minibatch.to_dgl()

    # Assert
    assert len(dgl_minibatch.blocks) == 2
    assert minibatch.node_features is dgl_minibatch.node_features
    assert minibatch.edge_features is dgl_minibatch.edge_features
    assert minibatch.labels is dgl_minibatch.labels
394
395
    assert dgl_minibatch.input_nodes is None
    assert dgl_minibatch.output_nodes is None
peizhou001's avatar
peizhou001 committed
396
397
398
399
400
401
402
403
404
405
406
407
408
409
    check_dgl_blocks_homo(minibatch, dgl_minibatch.blocks)


def test_to_dgl_node_classification_hetero():
    minibatch = create_hetero_minibatch()
    minibatch.labels = {"B": torch.tensor([2, 5])}
    minibatch.seed_nodes = {"B": torch.tensor([10, 15])}
    dgl_minibatch = minibatch.to_dgl()

    # Assert
    assert len(dgl_minibatch.blocks) == 2
    assert minibatch.node_features is dgl_minibatch.node_features
    assert minibatch.edge_features is dgl_minibatch.edge_features
    assert minibatch.labels is dgl_minibatch.labels
410
411
    assert dgl_minibatch.input_nodes is None
    assert dgl_minibatch.output_nodes is None
peizhou001's avatar
peizhou001 committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
    check_dgl_blocks_hetero(minibatch, dgl_minibatch.blocks)


@pytest.mark.parametrize("mode", ["neg_graph", "neg_src", "neg_dst"])
def test_to_dgl_link_predication_homo(mode):
    # Arrange
    minibatch = create_homo_minibatch()
    minibatch.compacted_node_pairs = (
        torch.tensor([0, 1]),
        torch.tensor([1, 0]),
    )
    if mode == "neg_graph" or mode == "neg_src":
        minibatch.compacted_negative_srcs = torch.tensor([[0, 0], [1, 1]])
    if mode == "neg_graph" or mode == "neg_dst":
        minibatch.compacted_negative_dsts = torch.tensor([[1, 0], [0, 1]])
    # Act
    dgl_minibatch = minibatch.to_dgl()

    # Assert
    assert len(dgl_minibatch.blocks) == 2
    assert minibatch.node_features is dgl_minibatch.node_features
    assert minibatch.edge_features is dgl_minibatch.edge_features
    assert minibatch.compacted_node_pairs is dgl_minibatch.positive_node_pairs
    check_dgl_blocks_homo(minibatch, dgl_minibatch.blocks)
    if mode == "neg_graph" or mode == "neg_src":
        assert torch.equal(
            dgl_minibatch.negative_node_pairs[0],
            minibatch.compacted_negative_srcs.view(-1),
        )
    if mode == "neg_graph" or mode == "neg_dst":
        assert torch.equal(
            dgl_minibatch.negative_node_pairs[1],
            minibatch.compacted_negative_dsts.view(-1),
        )


@pytest.mark.parametrize("mode", ["neg_graph", "neg_src", "neg_dst"])
def test_to_dgl_link_predication_hetero(mode):
    # Arrange
    minibatch = create_hetero_minibatch()
    minibatch.compacted_node_pairs = {
        relation: (
            torch.tensor([1, 1]),
            torch.tensor([1, 0]),
        ),
        reverse_relation: (
            torch.tensor([0, 1]),
            torch.tensor([1, 0]),
        ),
    }
    if mode == "neg_graph" or mode == "neg_src":
        minibatch.compacted_negative_srcs = {
            relation: torch.tensor([[2, 0], [1, 2]]),
            reverse_relation: torch.tensor([[1, 2], [0, 2]]),
        }
    if mode == "neg_graph" or mode == "neg_dst":
        minibatch.compacted_negative_dsts = {
            relation: torch.tensor([[1, 3], [2, 1]]),
            reverse_relation: torch.tensor([[2, 1], [3, 1]]),
        }
    # Act
    dgl_minibatch = minibatch.to_dgl()

    # Assert
    assert len(dgl_minibatch.blocks) == 2
    assert minibatch.node_features is dgl_minibatch.node_features
    assert minibatch.edge_features is dgl_minibatch.edge_features
    assert minibatch.compacted_node_pairs is dgl_minibatch.positive_node_pairs
    check_dgl_blocks_hetero(minibatch, dgl_minibatch.blocks)
    if mode == "neg_graph" or mode == "neg_src":
        for etype, src in minibatch.compacted_negative_srcs.items():
            assert torch.equal(
                dgl_minibatch.negative_node_pairs[etype][0],
                src.view(-1),
            )
    if mode == "neg_graph" or mode == "neg_dst":
        for etype, dst in minibatch.compacted_negative_dsts.items():
            assert torch.equal(
                dgl_minibatch.negative_node_pairs[etype][1],
                minibatch.compacted_negative_dsts[etype].view(-1),
            )