test_geometry.py 6.37 KB
Newer Older
1
import backend as F
2
3
import dgl.nn
import dgl
4
import numpy as np
5
6
import pytest
import torch as th
7
8
from dgl import DGLError
from dgl.base import DGLWarning
9
10
11
12
13
from dgl.geometry.pytorch import FarthestPointSampler
from dgl.geometry import neighbor_matching
from test_utils import parametrize_dtype
from test_utils.graph_cases import get_cases

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

def test_fps():
    N = 1000
    batch_size = 5
    sample_points = 10
    x = th.tensor(np.random.uniform(size=(batch_size, int(N/batch_size), 3)))
    ctx = F.ctx()
    if F.gpu_ctx():
        x = x.to(ctx)
    fps = FarthestPointSampler(sample_points)
    res = fps(x)
    assert res.shape[0] == batch_size
    assert res.shape[1] == sample_points
    assert res.sum() > 0

29

30
31
32
33
@pytest.mark.parametrize('algorithm', ['bruteforce-blas', 'bruteforce', 'kd-tree'])
@pytest.mark.parametrize('dist', ['euclidean', 'cosine'])
def test_knn_cpu(algorithm, dist):
    x = th.randn(8, 3).to(F.cpu())
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
34
    kg = dgl.nn.KNNGraph(3)
35
36
37
38
39
40
    if dist == 'euclidean':
        d = th.cdist(x, x).to(F.cpu())
    else:
        x = x + th.randn(1).item()
        tmp_x = x / (1e-5 + F.sqrt(F.sum(x * x, dim=1, keepdims=True)))
        d = 1 - F.matmul(tmp_x, tmp_x.T).to(F.cpu())
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
41

42
43
    def check_knn(g, x, start, end, k):
        assert g.device == x.device
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
44
45
46
47
        for v in range(start, end):
            src, _ = g.in_edges(v)
            src = set(src.numpy())
            i = v - start
48
            src_ans = set(th.topk(d[start:end, start:end][i], k, largest=False)[1].numpy() + start)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
49
50
            assert src == src_ans

51
52
53
    # check knn with 2d input
    g = kg(x, algorithm, dist)
    check_knn(g, x, 0, 8, 3)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
54

55
56
57
58
    # check knn with 3d input
    g = kg(x.view(2, 4, 3), algorithm, dist)
    check_knn(g, x, 0, 4, 3)
    check_knn(g, x, 4, 8, 3)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
59

60
    # check segmented knn
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
61
    kg = dgl.nn.SegmentedKNNGraph(3)
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
    g = kg(x, [3, 5], algorithm, dist)
    check_knn(g, x, 0, 3, 3)
    check_knn(g, x, 3, 8, 3)

    # check k > num_points
    kg = dgl.nn.KNNGraph(10)
    with pytest.warns(DGLWarning):
        g = kg(x, algorithm, dist)
    check_knn(g, x, 0, 8, 8)

    with pytest.warns(DGLWarning):
        g = kg(x.view(2, 4, 3), algorithm, dist)
    check_knn(g, x, 0, 4, 4)
    check_knn(g, x, 4, 8, 4)

    kg = dgl.nn.SegmentedKNNGraph(5)
    with pytest.warns(DGLWarning):
        g = kg(x, [3, 5], algorithm, dist)
    check_knn(g, x, 0, 3, 3)
    check_knn(g, x, 3, 8, 3)

    # check k == 0
    kg = dgl.nn.KNNGraph(0)
    with pytest.raises(DGLError):
        g = kg(x, algorithm, dist)
    kg = dgl.nn.SegmentedKNNGraph(0)
    with pytest.raises(DGLError):
        g = kg(x, [3, 5], algorithm, dist)

    # check empty
    x_empty = th.tensor([])
    kg = dgl.nn.KNNGraph(3)
    with pytest.raises(DGLError):
        g = kg(x_empty, algorithm, dist)
    kg = dgl.nn.SegmentedKNNGraph(3)
    with pytest.raises(DGLError):
        g = kg(x_empty, [3, 5], algorithm, dist)

@pytest.mark.parametrize('algorithm', ['bruteforce-blas', 'bruteforce', 'bruteforce-sharemem'])
@pytest.mark.parametrize('dist', ['euclidean', 'cosine'])
def test_knn_cuda(algorithm, dist):
    if not th.cuda.is_available():
        return
    x = th.randn(8, 3).to(F.cuda())
    kg = dgl.nn.KNNGraph(3)
    if dist == 'euclidean':
        d = th.cdist(x, x).to(F.cpu())
    else:
        x = x + th.randn(1).item()
        tmp_x = x / (1e-5 + F.sqrt(F.sum(x * x, dim=1, keepdims=True)))
        d = 1 - F.matmul(tmp_x, tmp_x.T).to(F.cpu())

    def check_knn(g, x, start, end, k):
        assert g.device == x.device
        g = g.to(F.cpu())
        for v in range(start, end):
            src, _ = g.in_edges(v)
            src = set(src.numpy())
            i = v - start
            src_ans = set(th.topk(d[start:end, start:end][i], k, largest=False)[1].numpy() + start)
            assert src == src_ans

    # check knn with 2d input
    g = kg(x, algorithm, dist)
    check_knn(g, x, 0, 8, 3)

    # check knn with 3d input
    g = kg(x.view(2, 4, 3), algorithm, dist)
    check_knn(g, x, 0, 4, 3)
    check_knn(g, x, 4, 8, 3)

    # check segmented knn
    kg = dgl.nn.SegmentedKNNGraph(3)
    g = kg(x, [3, 5], algorithm, dist)
    check_knn(g, x, 0, 3, 3)
    check_knn(g, x, 3, 8, 3)

    # check k > num_points
    kg = dgl.nn.KNNGraph(10)
    with pytest.warns(DGLWarning):
        g = kg(x, algorithm, dist)
    check_knn(g, x, 0, 8, 8)

    with pytest.warns(DGLWarning):
        g = kg(x.view(2, 4, 3), algorithm, dist)
    check_knn(g, x, 0, 4, 4)
    check_knn(g, x, 4, 8, 4)

    kg = dgl.nn.SegmentedKNNGraph(5)
    with pytest.warns(DGLWarning):
        g = kg(x, [3, 5], algorithm, dist)
    check_knn(g, x, 0, 3, 3)
    check_knn(g, x, 3, 8, 3)

    # check k == 0
    kg = dgl.nn.KNNGraph(0)
    with pytest.raises(DGLError):
        g = kg(x, algorithm, dist)
    kg = dgl.nn.SegmentedKNNGraph(0)
    with pytest.raises(DGLError):
        g = kg(x, [3, 5], algorithm, dist)

    # check empty
    x_empty = th.tensor([])
    kg = dgl.nn.KNNGraph(3)
    with pytest.raises(DGLError):
        g = kg(x_empty, algorithm, dist)
    kg = dgl.nn.SegmentedKNNGraph(3)
    with pytest.raises(DGLError):
        g = kg(x_empty, [3, 5], algorithm, dist)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
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
205
206
207
208
209
210

@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo'], exclude=['dglgraph']))
@pytest.mark.parametrize('weight', [True, False])
@pytest.mark.parametrize('relabel', [True, False])
def test_edge_coarsening(idtype, g, weight, relabel):
    num_nodes = g.num_nodes()
    g = dgl.to_bidirected(g)
    g = g.astype(idtype).to(F.ctx())
    edge_weight = None
    if weight:
        edge_weight = F.abs(F.randn((g.num_edges(),))).to(F.ctx())
    node_labels = neighbor_matching(g, edge_weight, relabel_idx=relabel)
    unique_ids, counts = th.unique(node_labels, return_counts=True)
    num_result_ids = unique_ids.size(0)

    # shape correct
    assert node_labels.shape == (g.num_nodes(),)

    # all nodes marked
    assert F.reduce_sum(node_labels < 0).item() == 0

    # number of unique node ids correct.
    assert num_result_ids >= num_nodes // 2 and num_result_ids <= num_nodes

    # each unique id has <= 2 nodes
    assert F.reduce_sum(counts > 2).item() == 0

    # if two nodes have the same id, they must be neighbors
    idxs = F.arange(0, num_nodes, idtype)
    for l in unique_ids:
        l = l.item()
        idx = idxs[(node_labels == l)]
        if idx.size(0) == 2:
            u, v = idx[0].item(), idx[1].item()
            assert g.has_edges_between(u, v)


211
212
if __name__ == '__main__':
    test_fps()
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
213
    test_knn()