test_base.py 7.46 KB
Newer Older
1
2
import re
import unittest
3
from collections.abc import Iterable, Mapping
4
5
6
7
8
9
10

import backend as F

import dgl.graphbolt as gb
import pytest
import torch

11
12
from . import gb_test_utils

13
14
15

@unittest.skipIf(F._default_context_str == "cpu", "CopyTo needs GPU to test")
def test_CopyTo():
16
    item_sampler = gb.ItemSampler(gb.ItemSet(torch.randn(20)), 4)
17
18

    # Invoke CopyTo via class constructor.
19
    dp = gb.CopyTo(item_sampler, "cuda")
20
21
    for data in dp:
        assert data.device.type == "cuda"
22

23
    # Invoke CopyTo via functional form.
24
    dp = item_sampler.copy_to("cuda")
25
26
27
28
    for data in dp:
        assert data.device.type == "cuda"


29
30
31
32
33
34
35
36
37
38
@pytest.mark.parametrize(
    "task",
    [
        "node_classification",
        "node_inference",
        "link_prediction",
        "edge_classification",
        "other",
    ],
)
39
@unittest.skipIf(F._default_context_str == "cpu", "CopyTo needs GPU to test")
40
def test_CopyToWithMiniBatches(task):
41
42
    N = 16
    B = 2
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    if task == "node_classification":
        itemset = gb.ItemSet(
            (torch.arange(N), torch.arange(N)), names=("seed_nodes", "labels")
        )
    elif task == "node_inference":
        itemset = gb.ItemSet(torch.arange(N), names="seed_nodes")
    elif task == "link_prediction":
        itemset = gb.ItemSet(
            (
                torch.arange(2 * N).reshape(-1, 2),
                torch.arange(3 * N).reshape(-1, 3),
            ),
            names=("node_pairs", "negative_dsts"),
        )
    elif task == "edge_classification":
        itemset = gb.ItemSet(
            (torch.arange(2 * N).reshape(-1, 2), torch.arange(N)),
            names=("node_pairs", "labels"),
        )
    else:
        itemset = gb.ItemSet(
            (torch.arange(2 * N).reshape(-1, 2), torch.arange(N)),
            names=("node_pairs", "seed_nodes"),
        )
67
    graph = gb_test_utils.rand_csc_graph(100, 0.15, bidirection_edge=True)
68
69
70
71
72
73
74
75
76
77
78
79
80

    features = {}
    keys = [("node", None, "a"), ("node", None, "b")]
    features[keys[0]] = gb.TorchBasedFeature(torch.randn(200, 4))
    features[keys[1]] = gb.TorchBasedFeature(torch.randn(200, 4))
    feature_store = gb.BasicFeatureStore(features)

    datapipe = gb.ItemSampler(itemset, batch_size=B)
    datapipe = gb.NeighborSampler(
        datapipe,
        graph,
        fanouts=[torch.LongTensor([2]) for _ in range(2)],
    )
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
    if task != "node_inference":
        datapipe = gb.FeatureFetcher(
            datapipe,
            feature_store,
            ["a"],
        )

    if task == "node_classification":
        copied_attrs = [
            "node_features",
            "edge_features",
            "sampled_subgraphs",
            "labels",
            "blocks",
        ]
    elif task == "node_inference":
        copied_attrs = [
            "seed_nodes",
            "sampled_subgraphs",
            "blocks",
            "labels",
        ]
    elif task == "link_prediction":
        copied_attrs = [
            "compacted_node_pairs",
            "node_features",
            "edge_features",
            "sampled_subgraphs",
            "compacted_negative_srcs",
            "compacted_negative_dsts",
            "blocks",
            "positive_node_pairs",
            "negative_node_pairs",
            "node_pairs_with_labels",
        ]
    elif task == "edge_classification":
        copied_attrs = [
            "compacted_node_pairs",
            "node_features",
            "edge_features",
            "sampled_subgraphs",
            "labels",
            "blocks",
            "positive_node_pairs",
            "negative_node_pairs",
            "node_pairs_with_labels",
        ]
128
129
130
131
132

    def test_data_device(datapipe):
        for data in datapipe:
            for attr in dir(data):
                var = getattr(data, attr)
133
134
135
136
                if isinstance(var, Mapping):
                    var = var[next(iter(var))]
                elif isinstance(var, Iterable):
                    var = next(iter(var))
137
138
139
140
                if (
                    not callable(var)
                    and not attr.startswith("__")
                    and hasattr(var, "device")
141
                    and var is not None
142
                ):
143
144
145
146
147
148
149
                    if task == "other":
                        assert var.device.type == "cuda"
                    else:
                        if attr in copied_attrs:
                            assert var.device.type == "cuda"
                        else:
                            assert var.device.type == "cpu"
150
151
152
153
154
155
156
157

    # Invoke CopyTo via class constructor.
    test_data_device(gb.CopyTo(datapipe, "cuda"))

    # Invoke CopyTo via functional form.
    test_data_device(datapipe.copy_to("cuda"))


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
195
196
197
198
199
200
201
202
203
204
def test_etype_tuple_to_str():
    """Convert etype from tuple to string."""
    # Test for expected input.
    c_etype = ("user", "like", "item")
    c_etype_str = gb.etype_tuple_to_str(c_etype)
    assert c_etype_str == "user:like:item"

    # Test for unexpected input: not a tuple.
    c_etype = "user:like:item"
    with pytest.raises(
        AssertionError,
        match=re.escape(
            "Passed-in canonical etype should be in format of (str, str, str). "
            "But got user:like:item."
        ),
    ):
        _ = gb.etype_tuple_to_str(c_etype)

    # Test for unexpected input: tuple with wrong length.
    c_etype = ("user", "like")
    with pytest.raises(
        AssertionError,
        match=re.escape(
            "Passed-in canonical etype should be in format of (str, str, str). "
            "But got ('user', 'like')."
        ),
    ):
        _ = gb.etype_tuple_to_str(c_etype)


def test_etype_str_to_tuple():
    """Convert etype from string to tuple."""
    # Test for expected input.
    c_etype_str = "user:like:item"
    c_etype = gb.etype_str_to_tuple(c_etype_str)
    assert c_etype == ("user", "like", "item")

    # Test for unexpected input: string with wrong format.
    c_etype_str = "user:like"
    with pytest.raises(
        AssertionError,
        match=re.escape(
            "Passed-in canonical etype should be in format of 'str:str:str'. "
            "But got user:like."
        ),
    ):
        _ = gb.etype_str_to_tuple(c_etype_str)
205
206
207


def test_isin():
208
209
    elements = torch.tensor([2, 3, 5, 5, 20, 13, 11], device=F.ctx())
    test_elements = torch.tensor([2, 5], device=F.ctx())
210
    res = gb.isin(elements, test_elements)
211
212
213
    expected = torch.tensor(
        [True, False, True, True, False, False, False], device=F.ctx()
    )
214
215
216
217
    assert torch.equal(res, expected)


def test_isin_big_data():
218
219
    elements = torch.randint(0, 10000, (10000000,), device=F.ctx())
    test_elements = torch.randint(0, 10000, (500000,), device=F.ctx())
220
221
222
223
224
225
    res = gb.isin(elements, test_elements)
    expected = torch.isin(elements, test_elements)
    assert torch.equal(res, expected)


def test_isin_non_1D_dim():
226
227
    elements = torch.tensor([[2, 3], [5, 5], [20, 13]], device=F.ctx())
    test_elements = torch.tensor([2, 5], device=F.ctx())
228
229
    with pytest.raises(Exception):
        gb.isin(elements, test_elements)
230
231
    elements = torch.tensor([2, 3, 5, 5, 20, 13], device=F.ctx())
    test_elements = torch.tensor([[2, 5]], device=F.ctx())
232
233
    with pytest.raises(Exception):
        gb.isin(elements, test_elements)
234
235
236
237
238
239
240
241
242
243
244
245
246


def test_csc_format_base_representation():
    csc_format_base = gb.CSCFormatBase(
        indptr=torch.tensor([0, 2, 4]),
        indices=torch.tensor([4, 5, 6, 7]),
    )
    expected_result = str(
        """CSCFormatBase(indptr=tensor([0, 2, 4]),
              indices=tensor([4, 5, 6, 7]),
)"""
    )
    assert str(csc_format_base) == expected_result, print(csc_format_base)