test_sparse_ops-csr.py 9.45 KB
Newer Older
1
2
import backend as F
import dgl
3
import numpy as np
4
import pytest
5
import scipy.sparse as ssp
nv-dlasalle's avatar
nv-dlasalle committed
6
from test_utils import parametrize_idtype
7

8
if F.backend_name == "pytorch":
9
    import torch
10

11
12
    torch.backends.cuda.matmul.allow_tf32 = False

13
14
15
16

def _random_simple_graph(
    idtype, dtype, ctx, M, N, max_nnz, srctype, dsttype, etype
):
17
18
19
20
21
22
    src = np.random.randint(0, M, (max_nnz,))
    dst = np.random.randint(0, N, (max_nnz,))
    val = np.random.randn(max_nnz)
    a = ssp.csr_matrix((val, (src, dst)), shape=(M, N))
    a.sum_duplicates()
    a = a.tocoo()
23
24
25
26
27
28
29
    # shuffle edges
    perm = np.random.permutation(a.nnz)
    row = a.row[perm]
    col = a.col[perm]
    val = a.data[perm]
    a = ssp.csr_matrix((val, (row, col)), shape=(M, N))

30
    A = dgl.heterograph(
31
32
33
34
35
36
37
38
39
        {
            (srctype, etype, dsttype): (
                F.copy_to(F.tensor(row, dtype=idtype), ctx),
                F.copy_to(F.tensor(col, dtype=idtype), ctx),
            )
        },
        num_nodes_dict={srctype: a.shape[0], dsttype: a.shape[1]},
    )
    A.edata["w"] = F.copy_to(F.tensor(val, dtype=dtype), ctx)
40
41
    return a, A

42

nv-dlasalle's avatar
nv-dlasalle committed
43
@parametrize_idtype
44
@pytest.mark.parametrize("dtype", [F.float32, F.float64])
45
def test_csrmm(idtype, dtype):
46
47
48
49
50
51
52
53
54
55
    a, A = _random_simple_graph(
        idtype, dtype, F.ctx(), 500, 600, 9000, "A", "B", "AB"
    )
    b, B = _random_simple_graph(
        idtype, dtype, F.ctx(), 600, 700, 9000, "B", "C", "BC"
    )
    C, C_weights = dgl._sparse_ops._csrmm(
        A._graph, A.edata["w"], B._graph, B.edata["w"], 2
    )
    C_adj = C.adjacency_matrix_scipy(0, False, "csr")
56
57
58
59
60
    C_adj.data = F.asnumpy(C_weights)
    C_adj = F.tensor(C_adj.todense(), dtype=dtype)
    c = F.tensor((a * b).todense(), dtype=dtype)
    assert F.allclose(C_adj, c)

61

nv-dlasalle's avatar
nv-dlasalle committed
62
@parametrize_idtype
63
64
@pytest.mark.parametrize("dtype", [F.float32, F.float64])
@pytest.mark.parametrize("num_vtypes", [1, 2])
65
def test_csrmm_backward(idtype, dtype, num_vtypes):
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    a, A = _random_simple_graph(idtype, dtype, F.ctx(), 3, 4, 6, "A", "B", "AB")
    b, B = _random_simple_graph(
        idtype,
        dtype,
        F.ctx(),
        4,
        3,
        6,
        "B",
        "A" if num_vtypes == 1 else "C",
        "BA",
    )
    A_row, A_col = A.edges(order="eid")
    B_row, B_col = B.edges(order="eid")
80
81
82
83
84
85
86
    A_row = F.asnumpy(A_row)
    A_col = F.asnumpy(A_col)
    B_row = F.asnumpy(B_row)
    B_col = F.asnumpy(B_col)
    a_dense = F.attach_grad(F.tensor(a.todense(), dtype=dtype))
    b_dense = F.attach_grad(F.tensor(b.todense(), dtype=dtype))

87
88
    A.edata["w"] = F.attach_grad(A.edata["w"])
    B.edata["w"] = F.attach_grad(B.edata["w"])
89
90

    with F.record_grad():
91
        C = dgl.adj_product_graph(A, B, "w")
92
93
94
        assert len(C.ntypes) == num_vtypes
        assert len(C.etypes) == 1
        C_dense = np.zeros((3, 3))
95
        C_row, C_col = C.edges(order="eid")
96
97
        C_row = F.asnumpy(C_row)
        C_col = F.asnumpy(C_col)
98
        C_dense[C_row, C_col] = F.asnumpy(C.edata["w"])
99
100
101
        c_dense = F.matmul(a_dense, b_dense)
        assert np.allclose(C_dense, F.asnumpy(c_dense), rtol=1e-4, atol=1e-4)

102
        F.backward(F.reduce_sum(C.edata["w"]) + F.reduce_sum(c_dense))
103
104
        a_dense_grad = F.asnumpy(F.grad(a_dense))[A_row, A_col]
        b_dense_grad = F.asnumpy(F.grad(b_dense))[B_row, B_col]
105
106
        A_spspmm_grad = F.asnumpy(F.grad(A.edata["w"]))
        B_spspmm_grad = F.asnumpy(F.grad(B.edata["w"]))
107
108
109
        assert np.allclose(a_dense_grad, A_spspmm_grad, rtol=1e-4, atol=1e-4)
        assert np.allclose(b_dense_grad, B_spspmm_grad, rtol=1e-4, atol=1e-4)

110

nv-dlasalle's avatar
nv-dlasalle committed
111
@parametrize_idtype
112
@pytest.mark.parametrize("dtype", [F.float32, F.float64])
113
def test_csrsum(idtype, dtype):
114
115
116
117
118
119
120
121
122
123
    a, A = _random_simple_graph(
        idtype, dtype, F.ctx(), 500, 600, 9000, "A", "B", "AB"
    )
    b, B = _random_simple_graph(
        idtype, dtype, F.ctx(), 500, 600, 9000, "A", "B", "AB"
    )
    C, C_weights = dgl._sparse_ops._csrsum(
        [A._graph, B._graph], [A.edata["w"], B.edata["w"]]
    )
    C_adj = C.adjacency_matrix_scipy(0, False, "csr")
124
125
126
127
128
    C_adj.data = F.asnumpy(C_weights)
    C_adj = F.tensor(C_adj.todense(), dtype=dtype)
    c = F.tensor((a + b).todense(), dtype=dtype)
    assert F.allclose(C_adj, c)

129

nv-dlasalle's avatar
nv-dlasalle committed
130
@parametrize_idtype
131
132
@pytest.mark.parametrize("dtype", [F.float32, F.float64])
@pytest.mark.parametrize("nelems", [1, 2])
133
def test_csrsum_backward(idtype, dtype, nelems):
134
135
136
137
    a, A = _random_simple_graph(idtype, dtype, F.ctx(), 3, 4, 6, "A", "B", "AB")
    b, B = _random_simple_graph(idtype, dtype, F.ctx(), 3, 4, 6, "A", "B", "AB")
    A_row, A_col = A.edges(order="eid")
    B_row, B_col = B.edges(order="eid")
138
139
140
141
142
143
144
    A_row = F.asnumpy(A_row)
    A_col = F.asnumpy(A_col)
    B_row = F.asnumpy(B_row)
    B_col = F.asnumpy(B_col)
    a_dense = F.attach_grad(F.tensor(a.todense(), dtype=dtype))
    b_dense = F.attach_grad(F.tensor(b.todense(), dtype=dtype))

145
146
    A.edata["w"] = F.attach_grad(A.edata["w"])
    B.edata["w"] = F.attach_grad(B.edata["w"])
147
148
149
150

    with F.record_grad():
        if nelems == 2:
            # Test for two element case
151
            C = dgl.adj_sum_graph([A, B], "w")
152
153
            assert C.canonical_etypes == A.canonical_etypes
            C_dense = np.zeros((3, 4))
154
            C_row, C_col = C.edges(order="eid")
155
156
            C_row = F.asnumpy(C_row)
            C_col = F.asnumpy(C_col)
157
            C_dense[C_row, C_col] = F.asnumpy(C.edata["w"])
158
            c_dense = a_dense + b_dense
159
160
161
            assert np.allclose(
                C_dense, F.asnumpy(c_dense), rtol=1e-4, atol=1e-4
            )
162

163
            F.backward(F.reduce_sum(C.edata["w"]) + F.reduce_sum(c_dense))
164
165
            a_dense_grad = F.asnumpy(F.grad(a_dense))[A_row, A_col]
            b_dense_grad = F.asnumpy(F.grad(b_dense))[B_row, B_col]
166
167
168
169
170
171
172
173
            A_spspmm_grad = F.asnumpy(F.grad(A.edata["w"]))
            B_spspmm_grad = F.asnumpy(F.grad(B.edata["w"]))
            assert np.allclose(
                a_dense_grad, A_spspmm_grad, rtol=1e-4, atol=1e-4
            )
            assert np.allclose(
                b_dense_grad, B_spspmm_grad, rtol=1e-4, atol=1e-4
            )
174
175
        elif nelems == 1:
            # Test for single element case
176
            C = dgl.adj_sum_graph([A], "w")
177
178
            assert C.canonical_etypes == A.canonical_etypes
            C_dense = np.zeros((3, 4))
179
            C_row, C_col = C.edges(order="eid")
180
181
            C_row = F.asnumpy(C_row)
            C_col = F.asnumpy(C_col)
182
            C_dense[C_row, C_col] = F.asnumpy(C.edata["w"])
183
            c_dense = a_dense
184
185
186
            assert np.allclose(
                C_dense, F.asnumpy(c_dense), rtol=1e-4, atol=1e-4
            )
187

188
            F.backward(F.reduce_sum(C.edata["w"]) + F.reduce_sum(c_dense))
189
            a_dense_grad = F.asnumpy(F.grad(a_dense))[A_row, A_col]
190
191
192
193
194
            A_spspmm_grad = F.asnumpy(F.grad(A.edata["w"]))
            assert np.allclose(
                a_dense_grad, A_spspmm_grad, rtol=1e-4, atol=1e-4
            )

195

nv-dlasalle's avatar
nv-dlasalle committed
196
@parametrize_idtype
197
198
199
@pytest.mark.parametrize("dtype", [F.float32, F.float64])
@pytest.mark.parametrize("A_nnz", [9000, 0])
@pytest.mark.parametrize("B_nnz", [9000, 0])
200
def test_csrmask(idtype, dtype, A_nnz, B_nnz):
201
202
203
204
205
206
207
208
    a, A = _random_simple_graph(
        idtype, dtype, F.ctx(), 500, 600, A_nnz, "A", "B", "AB"
    )
    b, B = _random_simple_graph(
        idtype, dtype, F.ctx(), 500, 600, B_nnz, "A", "B", "AB"
    )
    C = dgl._sparse_ops._csrmask(A._graph, A.edata["w"], B._graph)
    B_row, B_col = B.edges(order="eid")
209
210
211
212
    B_row = F.asnumpy(B_row)
    B_col = F.asnumpy(B_col)
    c = F.tensor(a.todense()[B_row, B_col], dtype)
    assert F.allclose(C, c)
213

214

nv-dlasalle's avatar
nv-dlasalle committed
215
@parametrize_idtype
216
@pytest.mark.parametrize("dtype", [F.float32, F.float64])
217
def test_csrmask_backward(idtype, dtype):
218
219
220
221
    a, A = _random_simple_graph(idtype, dtype, F.ctx(), 3, 4, 6, "A", "B", "AB")
    b, B = _random_simple_graph(idtype, dtype, F.ctx(), 3, 4, 6, "A", "B", "AB")
    A_row, A_col = A.edges(order="eid")
    B_row, B_col = B.edges(order="eid")
222
223
224
225
226
227
    A_row = F.asnumpy(A_row)
    A_col = F.asnumpy(A_col)
    B_row = F.asnumpy(B_row)
    B_col = F.asnumpy(B_col)
    a_dense = F.attach_grad(F.tensor(a.todense(), dtype=dtype))

228
    A.edata["w"] = F.attach_grad(A.edata["w"])
229
230
231

    with F.record_grad():
        # Test for two element case
232
233
        C1 = F.csrmask(A._graph, A.edata["w"], B._graph)
        if dgl.backend.backend_name == "tensorflow":
234
            import tensorflow as tf
235

236
237
238
239
240
241
242
            C2 = tf.gather_nd(a_dense, tf.stack([B_row, B_col], 1))
        else:
            C2 = a_dense[B_row, B_col]
        assert F.allclose(C1, C2, rtol=1e-4, atol=1e-4)

        F.backward(F.reduce_sum(C1) + F.reduce_sum(C2))
        a_dense_grad = F.asnumpy(F.grad(a_dense))[A_row, A_col]
243
        A_spspmm_grad = F.asnumpy(F.grad(A.edata["w"]))
244
245
        assert np.allclose(a_dense_grad, A_spspmm_grad, rtol=1e-4, atol=1e-4)

246

247
if __name__ == "__main__":
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
    test_csrmm(F.int32, F.float32)
    test_csrmm(F.int64, F.float32)
    test_csrsum(F.int32, F.float32)
    test_csrsum(F.int64, F.float32)
    test_csrmask(F.int32, F.float32, 9000, 9000)
    test_csrmask(F.int64, F.float32, 9000, 0)
    test_csrmask(F.int32, F.float32, 0, 9000)
    test_csrmask(F.int64, F.float32, 0, 0)
    test_csrmm_backward(F.int32, F.float32, 1)
    test_csrmm_backward(F.int64, F.float32, 1)
    test_csrmm_backward(F.int32, F.float32, 2)
    test_csrmm_backward(F.int64, F.float32, 2)
    test_csrsum_backward(F.int32, F.float32, 1)
    test_csrsum_backward(F.int64, F.float32, 1)
    test_csrsum_backward(F.int32, F.float32, 2)
    test_csrsum_backward(F.int64, F.float32, 2)
    test_csrmask_backward(F.int32, F.float32)
    test_csrmask_backward(F.int64, F.float32)