test_feature_fetcher.py 7.84 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
            range_tensor = torch.arange(10)
84
            subgraphs.append(
85
                gb.FusedSampledSubgraphImpl(
86
                    sampled_csc=(range_tensor, range_tensor),
87
88
                    original_column_node_ids=range_tensor,
                    original_row_node_ids=range_tensor,
89
90
91
                    original_edge_ids=torch.randint(
                        0, graph.total_num_edges, (10,)
                    ),
92
93
                )
            )
94
        data = gb.MiniBatch(input_nodes=seeds, sampled_subgraphs=subgraphs)
95
96
97
98
99
100
101
102
103
        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))
104
105
    item_sampler_dp = gb.ItemSampler(itemset, batch_size=2)
    converter_dp = Mapper(item_sampler_dp, add_node_and_edge_ids)
106
    fetcher_dp = gb.FeatureFetcher(converter_dp, feature_store, ["a"], ["b"])
107
108
109

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


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


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

143
144
145
146
147
    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)
148

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

163
164
165
    assert len(list(fetcher_dp)) == 3


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

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

205
206
207
208
209
    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)
210

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

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