test_feature_fetcher.py 7.97 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
def test_FeatureFetcher_invoke():
13
    # Prepare graph and required datapipes.
14
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
15
16
17
18
19
20
    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)]
    )
21
22
23
24
25
26
27
28

    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")
29
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
30
31
32
33
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]

    # Invoke FeatureFetcher via class constructor.
34
    datapipe = gb.NeighborSampler(item_sampler, graph, fanouts)
35

36
37
38
39
    datapipe = gb.FeatureFetcher(datapipe, feature_store, ["a"], ["b"])
    assert len(list(datapipe)) == 5

    # Invoke FeatureFetcher via functional form.
40
    datapipe = item_sampler.sample_neighbor(graph, fanouts).fetch_feature(
41
42
43
44
45
        feature_store, ["a"], ["b"]
    )
    assert len(list(datapipe)) == 5


46
def test_FeatureFetcher_homo():
47
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
48
49
50
51
52
53
    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)]
    )
54

55
56
57
58
59
60
    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)

61
62
    itemset = gb.ItemSet(torch.arange(10), names="seed_nodes")
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
63
64
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
65
    sampler_dp = gb.NeighborSampler(item_sampler, graph, fanouts)
66
    fetcher_dp = gb.FeatureFetcher(sampler_dp, feature_store, ["a"], ["b"])
67
68
69
70

    assert len(list(fetcher_dp)) == 5


71
def test_FeatureFetcher_with_edges_homo():
72
    graph = gb_test_utils.rand_csc_graph(20, 0.15, bidirection_edge=True)
73
74
75
76
77
78
    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)]
    )
79
80
81
82

    def add_node_and_edge_ids(seeds):
        subgraphs = []
        for _ in range(3):
83
84
85
86
            sampled_csc = gb.CSCFormatBase(
                indptr=torch.arange(11),
                indices=torch.arange(10),
            )
87
            subgraphs.append(
88
89
90
91
                gb.SampledSubgraphImpl(
                    sampled_csc=sampled_csc,
                    original_column_node_ids=torch.arange(10),
                    original_row_node_ids=torch.arange(10),
92
93
94
                    original_edge_ids=torch.randint(
                        0, graph.total_num_edges, (10,)
                    ),
95
96
                )
            )
97
        data = gb.MiniBatch(input_nodes=seeds, sampled_subgraphs=subgraphs)
98
99
100
101
102
103
104
105
106
        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))
107
108
    item_sampler_dp = gb.ItemSampler(itemset, batch_size=2)
    converter_dp = Mapper(item_sampler_dp, add_node_and_edge_ids)
109
    fetcher_dp = gb.FeatureFetcher(converter_dp, feature_store, ["a"], ["b"])
110
111
112

    assert len(list(fetcher_dp)) == 5
    for data in fetcher_dp:
113
114
115
116
        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
117
118
119
120
121
122
123
124
125


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}
126
    etypes = {"n1:e1:n2": 0, "n2:e2:n1": 1}
127
128
129
130
    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])
131
    return gb.fused_csc_sampling_graph(
132
133
134
135
        indptr,
        indices,
        node_type_offset=node_type_offset,
        type_per_edge=type_per_edge,
136
137
        node_type_to_id=ntypes,
        edge_type_to_id=etypes,
138
    )
139
140


141
def test_FeatureFetcher_hetero():
142
    graph = get_hetero_graph()
143
144
    a = torch.tensor([[random.randint(0, 10)] for _ in range(2)])
    b = torch.tensor([[random.randint(0, 10)] for _ in range(3)])
145

146
147
148
149
150
    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)
151

152
153
    itemset = gb.ItemSetDict(
        {
154
155
            "n1": gb.ItemSet(torch.LongTensor([0, 1]), names="seed_nodes"),
            "n2": gb.ItemSet(torch.LongTensor([0, 1, 2]), names="seed_nodes"),
156
157
        }
    )
158
    item_sampler = gb.ItemSampler(itemset, batch_size=2)
159
160
    num_layer = 2
    fanouts = [torch.LongTensor([2]) for _ in range(num_layer)]
161
    sampler_dp = gb.NeighborSampler(item_sampler, graph, fanouts)
162
163
164
    fetcher_dp = gb.FeatureFetcher(
        sampler_dp, feature_store, {"n1": ["a"], "n2": ["a"]}
    )
165

166
167
168
    assert len(list(fetcher_dp)) == 3


169
def test_FeatureFetcher_with_edges_hetero():
170
171
    a = torch.tensor([[random.randint(0, 10)] for _ in range(20)])
    b = torch.tensor([[random.randint(0, 10)] for _ in range(50)])
172
173
174

    def add_node_and_edge_ids(seeds):
        subgraphs = []
175
        original_edge_ids = {
176
177
            "n1:e1:n2": torch.randint(0, 50, (10,)),
            "n2:e2:n1": torch.randint(0, 50, (10,)),
178
        }
179
180
181
182
183
184
185
186
        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,)),
        }
187
188
        for _ in range(3):
            subgraphs.append(
189
                gb.SampledSubgraphImpl(
190
                    sampled_csc={
191
192
193
                        "n1:e1:n2": gb.CSCFormatBase(
                            indptr=torch.arange(11),
                            indices=torch.arange(10),
194
                        ),
195
196
197
                        "n2:e2:n1": gb.CSCFormatBase(
                            indptr=torch.arange(11),
                            indices=torch.arange(10),
198
199
200
201
                        ),
                    },
                    original_column_node_ids=original_column_node_ids,
                    original_row_node_ids=original_row_node_ids,
202
                    original_edge_ids=original_edge_ids,
203
204
                )
            )
205
        data = gb.MiniBatch(input_nodes=seeds, sampled_subgraphs=subgraphs)
206
        return data
207

208
209
210
211
212
    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)
213

214
215
216
217
218
    itemset = gb.ItemSetDict(
        {
            "n1": gb.ItemSet(torch.randint(0, 20, (10,))),
        }
    )
219
220
    item_sampler_dp = gb.ItemSampler(itemset, batch_size=2)
    converter_dp = Mapper(item_sampler_dp, add_node_and_edge_ids)
221
222
223
    fetcher_dp = gb.FeatureFetcher(
        converter_dp, feature_store, {"n1": ["a"]}, {"n1:e1:n2": ["a"]}
    )
224
225

    assert len(list(fetcher_dp)) == 5
226
    for data in fetcher_dp:
227
228
229
        assert data.node_features[("n1", "a")].size(0) == 2
        assert len(data.edge_features) == 3
        for edge_feature in data.edge_features:
230
            assert edge_feature[("n1:e1:n2", "a")].size(0) == 10