test_feature_fetcher.py 8.94 KB
Newer Older
1
import random
2
from enum import Enum
3

4
import dgl.graphbolt as gb
5
import pytest
6
import torch
7
from torchdata.datapipes.iter import Mapper
8

9
10
from . import gb_test_utils

11

12
13
14
15
16
17
18
19
20
class MiniBatchType(Enum):
    MiniBatch = 1
    DGLMiniBatch = 2


@pytest.mark.parametrize(
    "minibatch_type", [MiniBatchType.MiniBatch, MiniBatchType.DGLMiniBatch]
)
def test_FeatureFetcher_invoke(minibatch_type):
21
    # Prepare graph and required datapipes.
22
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
23
24
25
26
27
28
    a = torch.tensor(
        [[random.randint(0, 10)] for _ in range(graph.total_num_nodes)]
    )
    b = torch.tensor(
        [[random.randint(0, 10)] for _ in range(graph.total_num_edges)]
    )
29
30
31
32
33
34
35
36

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

    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
37
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
38
39
40
41
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    # Invoke FeatureFetcher via class constructor.
42
    datapipe = gb.NeighborSampler(item_sampler, graph, fanouts)
43
44
45
    if minibatch_type == MiniBatchType.DGLMiniBatch:
        datapipe = datapipe.to_dgl()

46
47
48
49
    datapipe = gb.FeatureFetcher(datapipe, feature_store, ["a"], ["b"])
    assert len(list(datapipe)) == 5

    # Invoke FeatureFetcher via functional form.
50
    datapipe = item_sampler.sample_neighbor(graph, fanouts).fetch_feature(
51
52
53
54
55
        feature_store, ["a"], ["b"]
    )
    assert len(list(datapipe)) == 5


56
57
58
59
@pytest.mark.parametrize(
    "minibatch_type", [MiniBatchType.MiniBatch, MiniBatchType.DGLMiniBatch]
)
def test_FeatureFetcher_homo(minibatch_type):
60
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
61
62
63
64
65
66
    a = torch.tensor(
        [[random.randint(0, 10)] for _ in range(graph.total_num_nodes)]
    )
    b = torch.tensor(
        [[random.randint(0, 10)] for _ in range(graph.total_num_edges)]
    )
67

68
69
70
71
72
73
    features = {}
    keys = [("node", None, "a"), ("edge", None, "b")]
    features[keys[0]] = gb.TorchBasedFeature(a)
    features[keys[1]] = gb.TorchBasedFeature(b)
    feature_store = gb.BasicFeatureStore(features)

74
75
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
76
77
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
78
    sampler_dp = gb.NeighborSampler(item_sampler, graph, fanouts)
79
80
    if minibatch_type == MiniBatchType.DGLMiniBatch:
        sampler_dp = sampler_dp.to_dgl()
81
    fetcher_dp = gb.FeatureFetcher(sampler_dp, feature_store, ["a"], ["b"])
82
83
84
85

    assert len(list(fetcher_dp)) == 5


86
87
88
89
@pytest.mark.parametrize(
    "minibatch_type", [MiniBatchType.MiniBatch, MiniBatchType.DGLMiniBatch]
)
def test_FeatureFetcher_with_edges_homo(minibatch_type):
90
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
91
92
93
94
95
96
    a = torch.tensor(
        [[random.randint(0, 10)] for _ in range(graph.total_num_nodes)]
    )
    b = torch.tensor(
        [[random.randint(0, 10)] for _ in range(graph.total_num_edges)]
    )
97
98
99
100

    def add_node_and_edge_ids(seeds):
        subgraphs = []
        for _ in range(3):
101
            range_tensor = torch.arange(10)
102
            subgraphs.append(
103
                gb.FusedSampledSubgraphImpl(
104
105
106
                    node_pairs=(range_tensor, range_tensor),
                    original_column_node_ids=range_tensor,
                    original_row_node_ids=range_tensor,
107
108
109
                    original_edge_ids=torch.randint(
                        0, graph.total_num_edges, (10,)
                    ),
110
111
                )
            )
112
        data = gb.MiniBatch(input_nodes=seeds, sampled_subgraphs=subgraphs)
113
114
115
116
117
118
119
120
121
        return data

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

    itemset = gb.ItemSet(torch.arange(10))
122
123
    item_sampler_dp = gb.ItemSampler(itemset, batch_size=2)
    converter_dp = Mapper(item_sampler_dp, add_node_and_edge_ids)
124
125
    if minibatch_type == MiniBatchType.DGLMiniBatch:
        converter_dp = converter_dp.to_dgl()
126
    fetcher_dp = gb.FeatureFetcher(converter_dp, feature_store, ["a"], ["b"])
127
128
129

    assert len(list(fetcher_dp)) == 5
    for data in fetcher_dp:
130
131
132
133
        assert data.node_features["a"].size(0) == 2
        assert len(data.edge_features) == 3
        for edge_feature in data.edge_features:
            assert edge_feature["b"].size(0) == 10
134
135
136
137
138
139
140
141
142


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}
143
    etypes = {"n1:e1:n2": 0, "n2:e2:n1": 1}
144
145
146
147
    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])
148
    return gb.fused_csc_sampling_graph(
149
150
151
152
        indptr,
        indices,
        node_type_offset=node_type_offset,
        type_per_edge=type_per_edge,
153
154
        node_type_to_id=ntypes,
        edge_type_to_id=etypes,
155
    )
156
157


158
159
160
161
@pytest.mark.parametrize(
    "minibatch_type", [MiniBatchType.MiniBatch, MiniBatchType.DGLMiniBatch]
)
def test_FeatureFetcher_hetero(minibatch_type):
162
    graph = get_hetero_graph()
163
164
    a = torch.tensor([[random.randint(0, 10)] for _ in range(2)])
    b = torch.tensor([[random.randint(0, 10)] for _ in range(3)])
165

166
167
168
169
170
    features = {}
    keys = [("node", "n1", "a"), ("node", "n2", "a")]
    features[keys[0]] = gb.TorchBasedFeature(a)
    features[keys[1]] = gb.TorchBasedFeature(b)
    feature_store = gb.BasicFeatureStore(features)
171

172
173
    itemset = gb.ItemSetDict(
        {
174
175
            "n1": gb.ItemSet(torch.LongTensor([0, 1]), names="seed_nodes"),
            "n2": gb.ItemSet(torch.LongTensor([0, 1, 2]), names="seed_nodes"),
176
177
        }
    )
178
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
179
180
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
181
    sampler_dp = gb.NeighborSampler(item_sampler, graph, fanouts)
182
183
    if minibatch_type == MiniBatchType.DGLMiniBatch:
        sampler_dp = sampler_dp.to_dgl()
184
185
186
    fetcher_dp = gb.FeatureFetcher(
        sampler_dp, feature_store, {"n1": ["a"], "n2": ["a"]}
    )
187

188
189
190
    assert len(list(fetcher_dp)) == 3


191
192
193
194
@pytest.mark.parametrize(
    "minibatch_type", [MiniBatchType.MiniBatch, MiniBatchType.DGLMiniBatch]
)
def test_FeatureFetcher_with_edges_hetero(minibatch_type):
195
196
    a = torch.tensor([[random.randint(0, 10)] for _ in range(20)])
    b = torch.tensor([[random.randint(0, 10)] for _ in range(50)])
197
198
199

    def add_node_and_edge_ids(seeds):
        subgraphs = []
200
        original_edge_ids = {
201
202
            "n1:e1:n2": torch.randint(0, 50, (10,)),
            "n2:e2:n1": torch.randint(0, 50, (10,)),
203
        }
204
205
206
207
208
209
210
211
        original_column_node_ids = {
            "n1": torch.randint(0, 20, (10,)),
            "n2": torch.randint(0, 20, (10,)),
        }
        original_row_node_ids = {
            "n1": torch.randint(0, 20, (10,)),
            "n2": torch.randint(0, 20, (10,)),
        }
212
213
        for _ in range(3):
            subgraphs.append(
214
                gb.FusedSampledSubgraphImpl(
215
216
217
218
219
220
221
222
223
224
225
226
                    node_pairs={
                        "n1:e1:n2": (
                            torch.arange(10),
                            torch.arange(10),
                        ),
                        "n2:e2:n1": (
                            torch.arange(10),
                            torch.arange(10),
                        ),
                    },
                    original_column_node_ids=original_column_node_ids,
                    original_row_node_ids=original_row_node_ids,
227
                    original_edge_ids=original_edge_ids,
228
229
                )
            )
230
        data = gb.MiniBatch(input_nodes=seeds, sampled_subgraphs=subgraphs)
231
        return data
232

233
234
235
236
237
    features = {}
    keys = [("node", "n1", "a"), ("edge", "n1:e1:n2", "a")]
    features[keys[0]] = gb.TorchBasedFeature(a)
    features[keys[1]] = gb.TorchBasedFeature(b)
    feature_store = gb.BasicFeatureStore(features)
238

239
240
241
242
243
    itemset = gb.ItemSetDict(
        {
            "n1": gb.ItemSet(torch.randint(0, 20, (10,))),
        }
    )
244
245
    item_sampler_dp = gb.ItemSampler(itemset, batch_size=2)
    converter_dp = Mapper(item_sampler_dp, add_node_and_edge_ids)
246
247
    if minibatch_type == MiniBatchType.DGLMiniBatch:
        converter_dp = converter_dp.to_dgl()
248
249
250
    fetcher_dp = gb.FeatureFetcher(
        converter_dp, feature_store, {"n1": ["a"]}, {"n1:e1:n2": ["a"]}
    )
251
252

    assert len(list(fetcher_dp)) == 5
253
    for data in fetcher_dp:
254
255
256
        assert data.node_features[("n1", "a")].size(0) == 2
        assert len(data.edge_features) == 3
        for edge_feature in data.edge_features:
257
            assert edge_feature[("n1:e1:n2", "a")].size(0) == 10