test_nn.py 36.5 KB
Newer Older
1
2
3
4
import torch as th
import networkx as nx
import dgl
import dgl.nn.pytorch as nn
5
import dgl.function as fn
6
import backend as F
7
import pytest
8
9
from test_utils.graph_cases import get_cases, random_graph, random_bipartite, random_dglgraph
from test_utils import parametrize_dtype
10
11
from copy import deepcopy

12
13
import scipy as sp

14
15
16
17
18
def _AXWb(A, X, W, b):
    X = th.matmul(X, W)
    Y = th.matmul(A, X.view(X.shape[0], -1)).view_as(X)
    return Y + b

19
20
@pytest.mark.parametrize('out_dim', [1, 2])
def test_graph_conv0(out_dim):
21
    g = dgl.DGLGraph(nx.path_graph(3)).to(F.ctx())
22
    ctx = F.ctx()
23
    adj = g.adjacency_matrix(transpose=False, ctx=ctx)
24

25
    conv = nn.GraphConv(5, out_dim, norm='none', bias=True)
26
    conv = conv.to(ctx)
27
28
    print(conv)
    # test#1: basic
29
    h0 = F.ones((3, 5))
30
    h1 = conv(g, h0)
31
32
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
33
    assert F.allclose(h1, _AXWb(adj, h0, conv.weight, conv.bias))
34
    # test#2: more-dim
35
    h0 = F.ones((3, 5, 5))
36
    h1 = conv(g, h0)
37
38
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
39
    assert F.allclose(h1, _AXWb(adj, h0, conv.weight, conv.bias))
40

41
    conv = nn.GraphConv(5, out_dim)
42
    conv = conv.to(ctx)
43
    # test#3: basic
44
    h0 = F.ones((3, 5))
45
    h1 = conv(g, h0)
46
47
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
48
    # test#4: basic
49
    h0 = F.ones((3, 5, 5))
50
    h1 = conv(g, h0)
51
52
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
53

54
    conv = nn.GraphConv(5, out_dim)
55
    conv = conv.to(ctx)
56
    # test#3: basic
57
    h0 = F.ones((3, 5))
58
    h1 = conv(g, h0)
59
60
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
61
    # test#4: basic
62
    h0 = F.ones((3, 5, 5))
63
    h1 = conv(g, h0)
64
65
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
66
67
68
69
70

    # test rest_parameters
    old_weight = deepcopy(conv.weight.data)
    conv.reset_parameters()
    new_weight = conv.weight.data
71
    assert not F.allclose(old_weight, new_weight)
72

73
74
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo', 'bipartite'], exclude=['zero-degree', 'dglgraph']))
75
76
77
@pytest.mark.parametrize('norm', ['none', 'both', 'right'])
@pytest.mark.parametrize('weight', [True, False])
@pytest.mark.parametrize('bias', [True, False])
78
79
@pytest.mark.parametrize('out_dim', [1, 2])
def test_graph_conv(idtype, g, norm, weight, bias, out_dim):
80
81
    # Test one tensor input
    g = g.astype(idtype).to(F.ctx())
82
83
    conv = nn.GraphConv(5, out_dim, norm=norm, weight=weight, bias=bias).to(F.ctx())
    ext_w = F.randn((5, out_dim)).to(F.ctx())
84
85
    nsrc = g.number_of_src_nodes()
    ndst = g.number_of_dst_nodes()
86
87
    h = F.randn((nsrc, 5)).to(F.ctx())
    if weight:
88
        h_out = conv(g, h)
89
    else:
90
        h_out = conv(g, h, weight=ext_w)
91
    assert h_out.shape == (ndst, out_dim)
92

93
94
95
96
97
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['has_scalar_e_feature'], exclude=['zero-degree', 'dglgraph']))
@pytest.mark.parametrize('norm', ['none', 'both', 'right'])
@pytest.mark.parametrize('weight', [True, False])
@pytest.mark.parametrize('bias', [True, False])
98
99
@pytest.mark.parametrize('out_dim', [1, 2])
def test_graph_conv_e_weight(idtype, g, norm, weight, bias, out_dim):
100
    g = g.astype(idtype).to(F.ctx())
101
102
    conv = nn.GraphConv(5, out_dim, norm=norm, weight=weight, bias=bias).to(F.ctx())
    ext_w = F.randn((5, out_dim)).to(F.ctx())
103
104
105
106
107
108
109
110
    nsrc = g.number_of_src_nodes()
    ndst = g.number_of_dst_nodes()
    h = F.randn((nsrc, 5)).to(F.ctx())
    e_w = g.edata['scalar_w']
    if weight:
        h_out = conv(g, h, edge_weight=e_w)
    else:
        h_out = conv(g, h, weight=ext_w, edge_weight=e_w)
111
    assert h_out.shape == (ndst, out_dim)
112
113
114
115
116
117

@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['has_scalar_e_feature'], exclude=['zero-degree', 'dglgraph']))
@pytest.mark.parametrize('norm', ['none', 'both', 'right'])
@pytest.mark.parametrize('weight', [True, False])
@pytest.mark.parametrize('bias', [True, False])
118
119
@pytest.mark.parametrize('out_dim', [1, 2])
def test_graph_conv_e_weight_norm(idtype, g, norm, weight, bias, out_dim):
120
    g = g.astype(idtype).to(F.ctx())
121
122
    conv = nn.GraphConv(5, out_dim, norm=norm, weight=weight, bias=bias).to(F.ctx())
    ext_w = F.randn((5, out_dim)).to(F.ctx())
123
124
125
126
127
128
129
130
131
    nsrc = g.number_of_src_nodes()
    ndst = g.number_of_dst_nodes()
    h = F.randn((nsrc, 5)).to(F.ctx())
    edgenorm = nn.EdgeWeightNorm(norm=norm)
    norm_weight = edgenorm(g, g.edata['scalar_w'])
    if weight:
        h_out = conv(g, h, edge_weight=norm_weight)
    else:
        h_out = conv(g, h, weight=ext_w, edge_weight=norm_weight)
132
    assert h_out.shape == (ndst, out_dim)
133

134
135
136
137
138
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['bipartite'], exclude=['zero-degree', 'dglgraph']))
@pytest.mark.parametrize('norm', ['none', 'both', 'right'])
@pytest.mark.parametrize('weight', [True, False])
@pytest.mark.parametrize('bias', [True, False])
139
140
@pytest.mark.parametrize('out_dim', [1, 2])
def test_graph_conv_bi(idtype, g, norm, weight, bias, out_dim):
141
142
    # Test a pair of tensor inputs
    g = g.astype(idtype).to(F.ctx())
143
144
    conv = nn.GraphConv(5, out_dim, norm=norm, weight=weight, bias=bias).to(F.ctx())
    ext_w = F.randn((5, out_dim)).to(F.ctx())
145
146
147
    nsrc = g.number_of_src_nodes()
    ndst = g.number_of_dst_nodes()
    h = F.randn((nsrc, 5)).to(F.ctx())
148
    h_dst = F.randn((ndst, out_dim)).to(F.ctx())
149
150
151
152
    if weight:
        h_out = conv(g, (h, h_dst))
    else:
        h_out = conv(g, (h, h_dst), weight=ext_w)
153
    assert h_out.shape == (ndst, out_dim)
154

155
156
157
158
159
160
161
162
163
164
165
166
def _S2AXWb(A, N, X, W, b):
    X1 = X * N
    X1 = th.matmul(A, X1.view(X1.shape[0], -1))
    X1 = X1 * N
    X2 = X1 * N
    X2 = th.matmul(A, X2.view(X2.shape[0], -1))
    X2 = X2 * N
    X = th.cat([X, X1, X2], dim=-1)
    Y = th.matmul(X, W.rot90())

    return Y + b

167
168
@pytest.mark.parametrize('out_dim', [1, 2])
def test_tagconv(out_dim):
169
    g = dgl.DGLGraph(nx.path_graph(3))
170
    g = g.to(F.ctx())
171
    ctx = F.ctx()
172
    adj = g.adjacency_matrix(transpose=False, ctx=ctx)
173
174
    norm = th.pow(g.in_degrees().float(), -0.5)

175
    conv = nn.TAGConv(5, out_dim, bias=True)
176
    conv = conv.to(ctx)
177
178
179
180
    print(conv)

    # test#1: basic
    h0 = F.ones((3, 5))
181
    h1 = conv(g, h0)
182
183
184
185
186
187
188
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
    shp = norm.shape + (1,) * (h0.dim() - 1)
    norm = th.reshape(norm, shp).to(ctx)

    assert F.allclose(h1, _S2AXWb(adj, norm, h0, conv.lin.weight, conv.lin.bias))

189
    conv = nn.TAGConv(5, out_dim)
190
    conv = conv.to(ctx)
191

192
193
    # test#2: basic
    h0 = F.ones((3, 5))
194
    h1 = conv(g, h0)
195
    assert h1.shape[-1] == out_dim
196

197
    # test reset_parameters
198
199
200
201
202
    old_weight = deepcopy(conv.lin.weight.data)
    conv.reset_parameters()
    new_weight = conv.lin.weight.data
    assert not F.allclose(old_weight, new_weight)

203
def test_set2set():
204
    ctx = F.ctx()
205
    g = dgl.DGLGraph(nx.path_graph(10))
206
    g = g.to(F.ctx())
207
208

    s2s = nn.Set2Set(5, 3, 3) # hidden size 5, 3 iters, 3 layers
209
    s2s = s2s.to(ctx)
210
211
212
    print(s2s)

    # test#1: basic
213
    h0 = F.randn((g.number_of_nodes(), 5))
214
    h1 = s2s(g, h0)
215
    assert h1.shape[0] == 1 and h1.shape[1] == 10 and h1.dim() == 2
216
217

    # test#2: batched graph
218
219
    g1 = dgl.DGLGraph(nx.path_graph(11)).to(F.ctx())
    g2 = dgl.DGLGraph(nx.path_graph(5)).to(F.ctx())
220
    bg = dgl.batch([g, g1, g2])
221
    h0 = F.randn((bg.number_of_nodes(), 5))
222
    h1 = s2s(bg, h0)
223
224
225
    assert h1.shape[0] == 3 and h1.shape[1] == 10 and h1.dim() == 2

def test_glob_att_pool():
226
    ctx = F.ctx()
227
    g = dgl.DGLGraph(nx.path_graph(10))
228
    g = g.to(F.ctx())
229
230

    gap = nn.GlobalAttentionPooling(th.nn.Linear(5, 1), th.nn.Linear(5, 10))
231
    gap = gap.to(ctx)
232
233
234
    print(gap)

    # test#1: basic
235
    h0 = F.randn((g.number_of_nodes(), 5))
236
    h1 = gap(g, h0)
237
    assert h1.shape[0] == 1 and h1.shape[1] == 10 and h1.dim() == 2
238
239
240

    # test#2: batched graph
    bg = dgl.batch([g, g, g, g])
241
    h0 = F.randn((bg.number_of_nodes(), 5))
242
    h1 = gap(bg, h0)
243
244
245
    assert h1.shape[0] == 4 and h1.shape[1] == 10 and h1.dim() == 2

def test_simple_pool():
246
    ctx = F.ctx()
247
    g = dgl.DGLGraph(nx.path_graph(15))
248
    g = g.to(F.ctx())
249
250
251
252
253
254
255
256

    sum_pool = nn.SumPooling()
    avg_pool = nn.AvgPooling()
    max_pool = nn.MaxPooling()
    sort_pool = nn.SortPooling(10) # k = 10
    print(sum_pool, avg_pool, max_pool, sort_pool)

    # test#1: basic
257
    h0 = F.randn((g.number_of_nodes(), 5))
258
259
260
261
    sum_pool = sum_pool.to(ctx)
    avg_pool = avg_pool.to(ctx)
    max_pool = max_pool.to(ctx)
    sort_pool = sort_pool.to(ctx)
262
    h1 = sum_pool(g, h0)
263
    assert F.allclose(F.squeeze(h1, 0), F.sum(h0, 0))
264
    h1 = avg_pool(g, h0)
265
    assert F.allclose(F.squeeze(h1, 0), F.mean(h0, 0))
266
    h1 = max_pool(g, h0)
267
    assert F.allclose(F.squeeze(h1, 0), F.max(h0, 0))
268
    h1 = sort_pool(g, h0)
269
    assert h1.shape[0] == 1 and h1.shape[1] == 10 * 5 and h1.dim() == 2
270
271

    # test#2: batched graph
272
    g_ = dgl.DGLGraph(nx.path_graph(5)).to(F.ctx())
273
    bg = dgl.batch([g, g_, g, g_, g])
274
    h0 = F.randn((bg.number_of_nodes(), 5))
275
    h1 = sum_pool(bg, h0)
276
277
278
279
280
281
    truth = th.stack([F.sum(h0[:15], 0),
                      F.sum(h0[15:20], 0),
                      F.sum(h0[20:35], 0),
                      F.sum(h0[35:40], 0),
                      F.sum(h0[40:55], 0)], 0)
    assert F.allclose(h1, truth)
282

283
    h1 = avg_pool(bg, h0)
284
285
286
287
288
289
    truth = th.stack([F.mean(h0[:15], 0),
                      F.mean(h0[15:20], 0),
                      F.mean(h0[20:35], 0),
                      F.mean(h0[35:40], 0),
                      F.mean(h0[40:55], 0)], 0)
    assert F.allclose(h1, truth)
290

291
    h1 = max_pool(bg, h0)
292
293
294
295
296
297
    truth = th.stack([F.max(h0[:15], 0),
                      F.max(h0[15:20], 0),
                      F.max(h0[20:35], 0),
                      F.max(h0[35:40], 0),
                      F.max(h0[40:55], 0)], 0)
    assert F.allclose(h1, truth)
298

299
    h1 = sort_pool(bg, h0)
300
301
302
    assert h1.shape[0] == 5 and h1.shape[1] == 10 * 5 and h1.dim() == 2

def test_set_trans():
303
    ctx = F.ctx()
304
305
306
307
308
    g = dgl.DGLGraph(nx.path_graph(15))

    st_enc_0 = nn.SetTransformerEncoder(50, 5, 10, 100, 2, 'sab')
    st_enc_1 = nn.SetTransformerEncoder(50, 5, 10, 100, 2, 'isab', 3)
    st_dec = nn.SetTransformerDecoder(50, 5, 10, 100, 2, 4)
309
310
311
    st_enc_0 = st_enc_0.to(ctx)
    st_enc_1 = st_enc_1.to(ctx)
    st_dec = st_dec.to(ctx)
312
313
314
    print(st_enc_0, st_enc_1, st_dec)

    # test#1: basic
315
    h0 = F.randn((g.number_of_nodes(), 50))
316
    h1 = st_enc_0(g, h0)
317
    assert h1.shape == h0.shape
318
    h1 = st_enc_1(g, h0)
319
    assert h1.shape == h0.shape
320
    h2 = st_dec(g, h1)
321
    assert h2.shape[0] == 1 and h2.shape[1] == 200 and h2.dim() == 2
322
323
324
325
326

    # test#2: batched graph
    g1 = dgl.DGLGraph(nx.path_graph(5))
    g2 = dgl.DGLGraph(nx.path_graph(10))
    bg = dgl.batch([g, g1, g2])
327
    h0 = F.randn((bg.number_of_nodes(), 50))
328
    h1 = st_enc_0(bg, h0)
329
    assert h1.shape == h0.shape
330
    h1 = st_enc_1(bg, h0)
331
332
    assert h1.shape == h0.shape

333
    h2 = st_dec(bg, h1)
334
335
    assert h2.shape[0] == 3 and h2.shape[1] == 200 and h2.dim() == 2

336
337
@pytest.mark.parametrize('O', [1, 2, 8])
def test_rgcn(O):
Minjie Wang's avatar
Minjie Wang committed
338
339
340
    ctx = F.ctx()
    etype = []
    g = dgl.DGLGraph(sp.sparse.random(100, 100, density=0.1), readonly=True)
341
    g = g.to(F.ctx())
Minjie Wang's avatar
Minjie Wang committed
342
343
344
345
346
347
348
349
    # 5 etypes
    R = 5
    for i in range(g.number_of_edges()):
        etype.append(i % 5)
    B = 2
    I = 10

    rgc_basis = nn.RelGraphConv(I, O, R, "basis", B).to(ctx)
350
351
352
    rgc_basis_low = nn.RelGraphConv(I, O, R, "basis", B, low_mem=True).to(ctx)
    rgc_basis_low.weight = rgc_basis.weight
    rgc_basis_low.w_comp = rgc_basis.w_comp
353
    rgc_basis_low.loop_weight = rgc_basis.loop_weight
Minjie Wang's avatar
Minjie Wang committed
354
355
356
    h = th.randn((100, I)).to(ctx)
    r = th.tensor(etype).to(ctx)
    h_new = rgc_basis(g, h, r)
357
    h_new_low = rgc_basis_low(g, h, r)
Minjie Wang's avatar
Minjie Wang committed
358
    assert list(h_new.shape) == [100, O]
359
360
    assert list(h_new_low.shape) == [100, O]
    assert F.allclose(h_new, h_new_low)
Minjie Wang's avatar
Minjie Wang committed
361

362
363
364
365
366
367
368
369
370
371
372
373
    if O % B == 0:
        rgc_bdd = nn.RelGraphConv(I, O, R, "bdd", B).to(ctx)
        rgc_bdd_low = nn.RelGraphConv(I, O, R, "bdd", B, low_mem=True).to(ctx)
        rgc_bdd_low.weight = rgc_bdd.weight
        rgc_bdd_low.loop_weight = rgc_bdd.loop_weight
        h = th.randn((100, I)).to(ctx)
        r = th.tensor(etype).to(ctx)
        h_new = rgc_bdd(g, h, r)
        h_new_low = rgc_bdd_low(g, h, r)
        assert list(h_new.shape) == [100, O]
        assert list(h_new_low.shape) == [100, O]
        assert F.allclose(h_new, h_new_low)
Minjie Wang's avatar
Minjie Wang committed
374
375

    # with norm
xiang song(charlie.song)'s avatar
xiang song(charlie.song) committed
376
    norm = th.rand((g.number_of_edges(), 1)).to(ctx)
Minjie Wang's avatar
Minjie Wang committed
377
378

    rgc_basis = nn.RelGraphConv(I, O, R, "basis", B).to(ctx)
379
380
381
    rgc_basis_low = nn.RelGraphConv(I, O, R, "basis", B, low_mem=True).to(ctx)
    rgc_basis_low.weight = rgc_basis.weight
    rgc_basis_low.w_comp = rgc_basis.w_comp
382
    rgc_basis_low.loop_weight = rgc_basis.loop_weight
Minjie Wang's avatar
Minjie Wang committed
383
384
385
    h = th.randn((100, I)).to(ctx)
    r = th.tensor(etype).to(ctx)
    h_new = rgc_basis(g, h, r, norm)
386
    h_new_low = rgc_basis_low(g, h, r, norm)
Minjie Wang's avatar
Minjie Wang committed
387
    assert list(h_new.shape) == [100, O]
388
389
    assert list(h_new_low.shape) == [100, O]
    assert F.allclose(h_new, h_new_low)
Minjie Wang's avatar
Minjie Wang committed
390

391
392
393
394
395
396
397
398
399
400
401
402
    if O % B == 0:
        rgc_bdd = nn.RelGraphConv(I, O, R, "bdd", B).to(ctx)
        rgc_bdd_low = nn.RelGraphConv(I, O, R, "bdd", B, low_mem=True).to(ctx)
        rgc_bdd_low.weight = rgc_bdd.weight
        rgc_bdd_low.loop_weight = rgc_bdd.loop_weight
        h = th.randn((100, I)).to(ctx)
        r = th.tensor(etype).to(ctx)
        h_new = rgc_bdd(g, h, r, norm)
        h_new_low = rgc_bdd_low(g, h, r, norm)
        assert list(h_new.shape) == [100, O]
        assert list(h_new_low.shape) == [100, O]
        assert F.allclose(h_new, h_new_low)
Minjie Wang's avatar
Minjie Wang committed
403
404
405

    # id input
    rgc_basis = nn.RelGraphConv(I, O, R, "basis", B).to(ctx)
406
407
408
    rgc_basis_low = nn.RelGraphConv(I, O, R, "basis", B, low_mem=True).to(ctx)
    rgc_basis_low.weight = rgc_basis.weight
    rgc_basis_low.w_comp = rgc_basis.w_comp
409
    rgc_basis_low.loop_weight = rgc_basis.loop_weight
Minjie Wang's avatar
Minjie Wang committed
410
411
412
    h = th.randint(0, I, (100,)).to(ctx)
    r = th.tensor(etype).to(ctx)
    h_new = rgc_basis(g, h, r)
413
    h_new_low = rgc_basis_low(g, h, r)
Minjie Wang's avatar
Minjie Wang committed
414
    assert list(h_new.shape) == [100, O]
415
416
    assert list(h_new_low.shape) == [100, O]
    assert F.allclose(h_new, h_new_low)
417

418

419
420
@pytest.mark.parametrize('O', [1, 2, 8])
def test_rgcn_sorted(O):
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    ctx = F.ctx()
    etype = []
    g = dgl.DGLGraph(sp.sparse.random(100, 100, density=0.1), readonly=True)
    g = g.to(F.ctx())
    # 5 etypes
    R = 5
    etype = [200, 200, 200, 200, 200]
    B = 2
    I = 10

    rgc_basis = nn.RelGraphConv(I, O, R, "basis", B).to(ctx)
    rgc_basis_low = nn.RelGraphConv(I, O, R, "basis", B, low_mem=True).to(ctx)
    rgc_basis_low.weight = rgc_basis.weight
    rgc_basis_low.w_comp = rgc_basis.w_comp
    rgc_basis_low.loop_weight = rgc_basis.loop_weight
    h = th.randn((100, I)).to(ctx)
    r = etype
    h_new = rgc_basis(g, h, r)
    h_new_low = rgc_basis_low(g, h, r)
    assert list(h_new.shape) == [100, O]
    assert list(h_new_low.shape) == [100, O]
    assert F.allclose(h_new, h_new_low)

444
445
446
447
448
449
450
451
452
453
454
455
    if O % B == 0:
        rgc_bdd = nn.RelGraphConv(I, O, R, "bdd", B).to(ctx)
        rgc_bdd_low = nn.RelGraphConv(I, O, R, "bdd", B, low_mem=True).to(ctx)
        rgc_bdd_low.weight = rgc_bdd.weight
        rgc_bdd_low.loop_weight = rgc_bdd.loop_weight
        h = th.randn((100, I)).to(ctx)
        r = etype
        h_new = rgc_bdd(g, h, r)
        h_new_low = rgc_bdd_low(g, h, r)
        assert list(h_new.shape) == [100, O]
        assert list(h_new_low.shape) == [100, O]
        assert F.allclose(h_new, h_new_low)
456
457

    # with norm
xiang song(charlie.song)'s avatar
xiang song(charlie.song) committed
458
    norm = th.rand((g.number_of_edges(), 1)).to(ctx)
459
460
461
462
463
464
465
466
467
468
469
470
471
472

    rgc_basis = nn.RelGraphConv(I, O, R, "basis", B).to(ctx)
    rgc_basis_low = nn.RelGraphConv(I, O, R, "basis", B, low_mem=True).to(ctx)
    rgc_basis_low.weight = rgc_basis.weight
    rgc_basis_low.w_comp = rgc_basis.w_comp
    rgc_basis_low.loop_weight = rgc_basis.loop_weight
    h = th.randn((100, I)).to(ctx)
    r = etype
    h_new = rgc_basis(g, h, r, norm)
    h_new_low = rgc_basis_low(g, h, r, norm)
    assert list(h_new.shape) == [100, O]
    assert list(h_new_low.shape) == [100, O]
    assert F.allclose(h_new, h_new_low)

473
474
475
476
477
478
479
480
481
482
483
484
    if O % B == 0:
        rgc_bdd = nn.RelGraphConv(I, O, R, "bdd", B).to(ctx)
        rgc_bdd_low = nn.RelGraphConv(I, O, R, "bdd", B, low_mem=True).to(ctx)
        rgc_bdd_low.weight = rgc_bdd.weight
        rgc_bdd_low.loop_weight = rgc_bdd.loop_weight
        h = th.randn((100, I)).to(ctx)
        r = etype
        h_new = rgc_bdd(g, h, r, norm)
        h_new_low = rgc_bdd_low(g, h, r, norm)
        assert list(h_new.shape) == [100, O]
        assert list(h_new_low.shape) == [100, O]
        assert F.allclose(h_new, h_new_low)
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

    # id input
    rgc_basis = nn.RelGraphConv(I, O, R, "basis", B).to(ctx)
    rgc_basis_low = nn.RelGraphConv(I, O, R, "basis", B, low_mem=True).to(ctx)
    rgc_basis_low.weight = rgc_basis.weight
    rgc_basis_low.w_comp = rgc_basis.w_comp
    rgc_basis_low.loop_weight = rgc_basis.loop_weight
    h = th.randint(0, I, (100,)).to(ctx)
    r = etype
    h_new = rgc_basis(g, h, r)
    h_new_low = rgc_basis_low(g, h, r)
    assert list(h_new.shape) == [100, O]
    assert list(h_new_low.shape) == [100, O]
    assert F.allclose(h_new, h_new_low)


501
@parametrize_dtype
502
@pytest.mark.parametrize('g', get_cases(['homo', 'block-bipartite'], exclude=['zero-degree']))
503
504
505
@pytest.mark.parametrize('out_dim', [1, 2])
@pytest.mark.parametrize('num_heads', [1, 4])
def test_gat_conv(g, idtype, out_dim, num_heads):
506
    g = g.astype(idtype).to(F.ctx())
507
    ctx = F.ctx()
508
    gat = nn.GATConv(5, out_dim, num_heads)
509
    feat = F.randn((g.number_of_nodes(), 5))
510
    gat = gat.to(ctx)
511
    h = gat(g, feat)
512
    assert h.shape == (g.number_of_nodes(), num_heads, out_dim)
513
    _, a = gat(g, feat, get_attention=True)
514
    assert a.shape == (g.number_of_edges(), num_heads, 1)
515

516
@parametrize_dtype
517
@pytest.mark.parametrize('g', get_cases(['bipartite'], exclude=['zero-degree']))
518
519
520
@pytest.mark.parametrize('out_dim', [1, 2])
@pytest.mark.parametrize('num_heads', [1, 4])
def test_gat_conv_bi(g, idtype, out_dim, num_heads):
521
522
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
523
    gat = nn.GATConv(5, out_dim, num_heads)
524
    feat = (F.randn((g.number_of_src_nodes(), 5)), F.randn((g.number_of_dst_nodes(), 5)))
525
526
    gat = gat.to(ctx)
    h = gat(g, feat)
527
    assert h.shape == (g.number_of_dst_nodes(), num_heads, out_dim)
528
    _, a = gat(g, feat, get_attention=True)
529
    assert a.shape == (g.number_of_edges(), num_heads, 1)
530

531
@parametrize_dtype
532
@pytest.mark.parametrize('g', get_cases(['homo', 'block-bipartite']))
533
@pytest.mark.parametrize('aggre_type', ['mean', 'pool', 'gcn', 'lstm'])
534
535
def test_sage_conv(idtype, g, aggre_type):
    g = g.astype(idtype).to(F.ctx())
536
    sage = nn.SAGEConv(5, 10, aggre_type)
537
538
    feat = F.randn((g.number_of_nodes(), 5))
    sage = sage.to(F.ctx())
539
540
541
    h = sage(g, feat)
    assert h.shape[-1] == 10

542
@parametrize_dtype
543
@pytest.mark.parametrize('g', get_cases(['bipartite']))
544
@pytest.mark.parametrize('aggre_type', ['mean', 'pool', 'gcn', 'lstm'])
545
546
@pytest.mark.parametrize('out_dim', [1, 2])
def test_sage_conv_bi(idtype, g, aggre_type, out_dim):
547
    g = g.astype(idtype).to(F.ctx())
548
    dst_dim = 5 if aggre_type != 'gcn' else 10
549
    sage = nn.SAGEConv((10, dst_dim), out_dim, aggre_type)
550
551
    feat = (F.randn((g.number_of_src_nodes(), 10)), F.randn((g.number_of_dst_nodes(), dst_dim)))
    sage = sage.to(F.ctx())
552
    h = sage(g, feat)
553
    assert h.shape[-1] == out_dim
554
    assert h.shape[0] == g.number_of_dst_nodes()
555

556
@parametrize_dtype
557
558
@pytest.mark.parametrize('out_dim', [1, 2])
def test_sage_conv2(idtype, out_dim):
559
    # TODO: add test for blocks
Mufei Li's avatar
Mufei Li committed
560
    # Test the case for graphs without edges
561
    g = dgl.heterograph({('_U', '_E', '_V'): ([], [])}, {'_U': 5, '_V': 3})
562
563
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
564
    sage = nn.SAGEConv((3, 3), out_dim, 'gcn')
Mufei Li's avatar
Mufei Li committed
565
566
    feat = (F.randn((5, 3)), F.randn((3, 3)))
    sage = sage.to(ctx)
567
    h = sage(g, (F.copy_to(feat[0], F.ctx()), F.copy_to(feat[1], F.ctx())))
568
    assert h.shape[-1] == out_dim
Mufei Li's avatar
Mufei Li committed
569
570
    assert h.shape[0] == 3
    for aggre_type in ['mean', 'pool', 'lstm']:
571
        sage = nn.SAGEConv((3, 1), out_dim, aggre_type)
Mufei Li's avatar
Mufei Li committed
572
573
574
        feat = (F.randn((5, 3)), F.randn((3, 1)))
        sage = sage.to(ctx)
        h = sage(g, feat)
575
        assert h.shape[-1] == out_dim
Mufei Li's avatar
Mufei Li committed
576
577
        assert h.shape[0] == 3

578
579
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo'], exclude=['zero-degree']))
580
581
@pytest.mark.parametrize('out_dim', [1, 2])
def test_sgc_conv(g, idtype, out_dim):
582
    ctx = F.ctx()
583
    g = g.astype(idtype).to(ctx)
584
    # not cached
585
    sgc = nn.SGConv(5, out_dim, 3)
586
    feat = F.randn((g.number_of_nodes(), 5))
587
    sgc = sgc.to(ctx)
588

589
    h = sgc(g, feat)
590
    assert h.shape[-1] == out_dim
591
592

    # cached
593
    sgc = nn.SGConv(5, out_dim, 3, True)
594
    sgc = sgc.to(ctx)
595
596
    h_0 = sgc(g, feat)
    h_1 = sgc(g, feat + 1)
597
    assert F.allclose(h_0, h_1)
598
    assert h_0.shape[-1] == out_dim
599

600
601
602
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo'], exclude=['zero-degree']))
def test_appnp_conv(g, idtype):
603
    ctx = F.ctx()
604
    g = g.astype(idtype).to(ctx)
605
    appnp = nn.APPNPConv(10, 0.1)
606
    feat = F.randn((g.number_of_nodes(), 5))
607
    appnp = appnp.to(ctx)
608

609
    h = appnp(g, feat)
610
611
    assert h.shape[-1] == 5

612
@parametrize_dtype
613
@pytest.mark.parametrize('g', get_cases(['homo', 'block-bipartite'], exclude=['zero-degree']))
614
@pytest.mark.parametrize('aggregator_type', ['mean', 'max', 'sum'])
615
616
def test_gin_conv(g, idtype, aggregator_type):
    g = g.astype(idtype).to(F.ctx())
617
618
619
620
621
    ctx = F.ctx()
    gin = nn.GINConv(
        th.nn.Linear(5, 12),
        aggregator_type
    )
622
    feat = F.randn((g.number_of_nodes(), 5))
623
624
    gin = gin.to(ctx)
    h = gin(g, feat)
625
    assert h.shape == (g.number_of_nodes(), 12)
626

627
@parametrize_dtype
628
@pytest.mark.parametrize('g', get_cases(['bipartite'], exclude=['zero-degree']))
629
630
631
632
@pytest.mark.parametrize('aggregator_type', ['mean', 'max', 'sum'])
def test_gin_conv_bi(g, idtype, aggregator_type):
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
633
634
635
636
    gin = nn.GINConv(
        th.nn.Linear(5, 12),
        aggregator_type
    )
637
    feat = (F.randn((g.number_of_src_nodes(), 5)), F.randn((g.number_of_dst_nodes(), 5)))
638
639
    gin = gin.to(ctx)
    h = gin(g, feat)
640
    assert h.shape == (g.number_of_dst_nodes(), 12)
641

642
@parametrize_dtype
643
@pytest.mark.parametrize('g', get_cases(['homo', 'block-bipartite'], exclude=['zero-degree']))
644
645
def test_agnn_conv(g, idtype):
    g = g.astype(idtype).to(F.ctx())
646
647
    ctx = F.ctx()
    agnn = nn.AGNNConv(1)
648
    feat = F.randn((g.number_of_nodes(), 5))
649
    agnn = agnn.to(ctx)
650
    h = agnn(g, feat)
651
    assert h.shape == (g.number_of_nodes(), 5)
652

653
@parametrize_dtype
654
@pytest.mark.parametrize('g', get_cases(['bipartite'], exclude=['zero-degree']))
655
656
657
def test_agnn_conv_bi(g, idtype):
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
658
    agnn = nn.AGNNConv(1)
659
    feat = (F.randn((g.number_of_src_nodes(), 5)), F.randn((g.number_of_dst_nodes(), 5)))
660
661
    agnn = agnn.to(ctx)
    h = agnn(g, feat)
662
    assert h.shape == (g.number_of_dst_nodes(), 5)
663

664
665
666
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo'], exclude=['zero-degree']))
def test_gated_graph_conv(g, idtype):
667
    ctx = F.ctx()
668
    g = g.astype(idtype).to(ctx)
669
670
    ggconv = nn.GatedGraphConv(5, 10, 5, 3)
    etypes = th.arange(g.number_of_edges()) % 3
671
    feat = F.randn((g.number_of_nodes(), 5))
672
673
    ggconv = ggconv.to(ctx)
    etypes = etypes.to(ctx)
674

675
    h = ggconv(g, feat, etypes)
676
677
678
    # current we only do shape check
    assert h.shape[-1] == 10

679
@parametrize_dtype
680
@pytest.mark.parametrize('g', get_cases(['homo', 'block-bipartite'], exclude=['zero-degree']))
681
682
def test_nn_conv(g, idtype):
    g = g.astype(idtype).to(F.ctx())
683
684
685
    ctx = F.ctx()
    edge_func = th.nn.Linear(4, 5 * 10)
    nnconv = nn.NNConv(5, 10, edge_func, 'mean')
686
    feat = F.randn((g.number_of_nodes(), 5))
687
688
689
690
691
692
    efeat = F.randn((g.number_of_edges(), 4))
    nnconv = nnconv.to(ctx)
    h = nnconv(g, feat, efeat)
    # currently we only do shape check
    assert h.shape[-1] == 10

693
@parametrize_dtype
694
@pytest.mark.parametrize('g', get_cases(['bipartite'], exclude=['zero-degree']))
695
696
697
def test_nn_conv_bi(g, idtype):
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
698
699
    edge_func = th.nn.Linear(4, 5 * 10)
    nnconv = nn.NNConv((5, 2), 10, edge_func, 'mean')
700
701
    feat = F.randn((g.number_of_src_nodes(), 5))
    feat_dst = F.randn((g.number_of_dst_nodes(), 2))
702
703
704
705
706
707
    efeat = F.randn((g.number_of_edges(), 4))
    nnconv = nnconv.to(ctx)
    h = nnconv(g, (feat, feat_dst), efeat)
    # currently we only do shape check
    assert h.shape[-1] == 10

708
@parametrize_dtype
709
@pytest.mark.parametrize('g', get_cases(['homo'], exclude=['zero-degree']))
710
711
def test_gmm_conv(g, idtype):
    g = g.astype(idtype).to(F.ctx())
712
713
    ctx = F.ctx()
    gmmconv = nn.GMMConv(5, 10, 3, 4, 'mean')
714
    feat = F.randn((g.number_of_nodes(), 5))
715
    pseudo = F.randn((g.number_of_edges(), 3))
716
    gmmconv = gmmconv.to(ctx)
717
    h = gmmconv(g, feat, pseudo)
718
719
720
    # currently we only do shape check
    assert h.shape[-1] == 10

721
@parametrize_dtype
722
@pytest.mark.parametrize('g', get_cases(['bipartite', 'block-bipartite'], exclude=['zero-degree']))
723
724
725
def test_gmm_conv_bi(g, idtype):
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
726
    gmmconv = nn.GMMConv((5, 2), 10, 3, 4, 'mean')
727
728
    feat = F.randn((g.number_of_src_nodes(), 5))
    feat_dst = F.randn((g.number_of_dst_nodes(), 2))
729
730
731
732
733
734
    pseudo = F.randn((g.number_of_edges(), 3))
    gmmconv = gmmconv.to(ctx)
    h = gmmconv(g, (feat, feat_dst), pseudo)
    # currently we only do shape check
    assert h.shape[-1] == 10

735
@parametrize_dtype
736
@pytest.mark.parametrize('norm_type', ['both', 'right', 'none'])
737
@pytest.mark.parametrize('g', get_cases(['homo', 'bipartite'], exclude=['zero-degree']))
738
739
@pytest.mark.parametrize('out_dim', [1, 2])
def test_dense_graph_conv(norm_type, g, idtype, out_dim):
740
    g = g.astype(idtype).to(F.ctx())
741
    ctx = F.ctx()
742
    # TODO(minjie): enable the following option after #1385
743
    adj = g.adjacency_matrix(transpose=False, ctx=ctx).to_dense()
744
745
    conv = nn.GraphConv(5, out_dim, norm=norm_type, bias=True)
    dense_conv = nn.DenseGraphConv(5, out_dim, norm=norm_type, bias=True)
746
747
    dense_conv.weight.data = conv.weight.data
    dense_conv.bias.data = conv.bias.data
748
    feat = F.randn((g.number_of_src_nodes(), 5))
749
750
    conv = conv.to(ctx)
    dense_conv = dense_conv.to(ctx)
751
752
    out_conv = conv(g, feat)
    out_dense_conv = dense_conv(adj, feat)
753
754
    assert F.allclose(out_conv, out_dense_conv)

755
@parametrize_dtype
756
@pytest.mark.parametrize('g', get_cases(['homo', 'bipartite']))
757
758
@pytest.mark.parametrize('out_dim', [1, 2])
def test_dense_sage_conv(g, idtype, out_dim):
759
    g = g.astype(idtype).to(F.ctx())
760
    ctx = F.ctx()
761
    adj = g.adjacency_matrix(transpose=False, ctx=ctx).to_dense()
762
763
    sage = nn.SAGEConv(5, out_dim, 'gcn')
    dense_sage = nn.DenseSAGEConv(5, out_dim)
764
765
    dense_sage.fc.weight.data = sage.fc_neigh.weight.data
    dense_sage.fc.bias.data = sage.fc_neigh.bias.data
766
767
768
769
770
771
772
    if len(g.ntypes) == 2:
        feat = (
            F.randn((g.number_of_src_nodes(), 5)),
            F.randn((g.number_of_dst_nodes(), 5))
        )
    else:
        feat = F.randn((g.number_of_nodes(), 5))
773
774
    sage = sage.to(ctx)
    dense_sage = dense_sage.to(ctx)
775
776
    out_sage = sage(g, feat)
    out_dense_sage = dense_sage(adj, feat)
777
778
    assert F.allclose(out_sage, out_dense_sage), g

779
@parametrize_dtype
780
@pytest.mark.parametrize('g', get_cases(['homo', 'block-bipartite'], exclude=['zero-degree']))
781
782
@pytest.mark.parametrize('out_dim', [1, 2])
def test_edge_conv(g, idtype, out_dim):
783
    g = g.astype(idtype).to(F.ctx())
784
    ctx = F.ctx()
785
    edge_conv = nn.EdgeConv(5, out_dim).to(ctx)
786
    print(edge_conv)
787
788
    h0 = F.randn((g.number_of_nodes(), 5))
    h1 = edge_conv(g, h0)
789
    assert h1.shape == (g.number_of_nodes(), out_dim)
790

791
@parametrize_dtype
792
@pytest.mark.parametrize('g', get_cases(['bipartite'], exclude=['zero-degree']))
793
794
@pytest.mark.parametrize('out_dim', [1, 2])
def test_edge_conv_bi(g, idtype, out_dim):
795
796
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
797
    edge_conv = nn.EdgeConv(5, out_dim).to(ctx)
798
    print(edge_conv)
799
    h0 = F.randn((g.number_of_src_nodes(), 5))
800
801
    x0 = F.randn((g.number_of_dst_nodes(), 5))
    h1 = edge_conv(g, (h0, x0))
802
    assert h1.shape == (g.number_of_dst_nodes(), out_dim)
803
804
805
    
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo', 'block-bipartite'], exclude=['zero-degree']))
806
807
808
@pytest.mark.parametrize('out_dim', [1, 2])
@pytest.mark.parametrize('num_heads', [1, 4])
def test_dotgat_conv(g, idtype, out_dim, num_heads):
809
810
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
811
    dotgat = nn.DotGatConv(5, out_dim, num_heads)
812
813
814
    feat = F.randn((g.number_of_nodes(), 5))
    dotgat = dotgat.to(ctx)
    h = dotgat(g, feat)
815
    assert h.shape == (g.number_of_nodes(), num_heads, out_dim)
816
    _, a = dotgat(g, feat, get_attention=True)
817
    assert a.shape == (g.number_of_edges(), num_heads, 1)
818
819
820

@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['bipartite'], exclude=['zero-degree']))
821
822
823
@pytest.mark.parametrize('out_dim', [1, 2])
@pytest.mark.parametrize('num_heads', [1, 4])
def test_dotgat_conv_bi(g, idtype, out_dim, num_heads):
824
825
    g = g.astype(idtype).to(F.ctx())
    ctx = F.ctx()
826
    dotgat = nn.DotGatConv((5, 5), out_dim, num_heads)
827
828
829
    feat = (F.randn((g.number_of_src_nodes(), 5)), F.randn((g.number_of_dst_nodes(), 5)))
    dotgat = dotgat.to(ctx)
    h = dotgat(g, feat)
830
    assert h.shape == (g.number_of_dst_nodes(), num_heads, out_dim)
831
    _, a = dotgat(g, feat, get_attention=True)
832
    assert a.shape == (g.number_of_edges(), num_heads, 1)
833

834
835
@pytest.mark.parametrize('out_dim', [1, 2])
def test_dense_cheb_conv(out_dim):
836
837
838
    for k in range(1, 4):
        ctx = F.ctx()
        g = dgl.DGLGraph(sp.sparse.random(100, 100, density=0.1), readonly=True)
839
        g = g.to(F.ctx())
840
        adj = g.adjacency_matrix(transpose=False, ctx=ctx).to_dense()
841
842
        cheb = nn.ChebConv(5, out_dim, k, None)
        dense_cheb = nn.DenseChebConv(5, out_dim, k)
Axel Nilsson's avatar
Axel Nilsson committed
843
844
        #for i in range(len(cheb.fc)):
        #    dense_cheb.W.data[i] = cheb.fc[i].weight.data.t()
845
        dense_cheb.W.data = cheb.linear.weight.data.transpose(-1, -2).view(k, 5, out_dim)
Axel Nilsson's avatar
Axel Nilsson committed
846
847
        if cheb.linear.bias is not None:
            dense_cheb.bias.data = cheb.linear.bias.data
848
        feat = F.randn((100, 5))
849
850
        cheb = cheb.to(ctx)
        dense_cheb = dense_cheb.to(ctx)
851
852
        out_cheb = cheb(g, feat, [2.0])
        out_dense_cheb = dense_cheb(adj, feat, 2.0)
Axel Nilsson's avatar
Axel Nilsson committed
853
        print(k, out_cheb, out_dense_cheb)
854
855
        assert F.allclose(out_cheb, out_dense_cheb)

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
def test_sequential():
    ctx = F.ctx()
    # Test single graph
    class ExampleLayer(th.nn.Module):
        def __init__(self):
            super().__init__()

        def forward(self, graph, n_feat, e_feat):
            graph = graph.local_var()
            graph.ndata['h'] = n_feat
            graph.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
            n_feat += graph.ndata['h']
            graph.apply_edges(fn.u_add_v('h', 'h', 'e'))
            e_feat += graph.edata['e']
            return n_feat, e_feat

    g = dgl.DGLGraph()
    g.add_nodes(3)
    g.add_edges([0, 1, 2, 0, 1, 2, 0, 1, 2], [0, 0, 0, 1, 1, 1, 2, 2, 2])
875
    g = g.to(F.ctx())
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
    net = nn.Sequential(ExampleLayer(), ExampleLayer(), ExampleLayer())
    n_feat = F.randn((3, 4))
    e_feat = F.randn((9, 4))
    net = net.to(ctx)
    n_feat, e_feat = net(g, n_feat, e_feat)
    assert n_feat.shape == (3, 4)
    assert e_feat.shape == (9, 4)

    # Test multiple graph
    class ExampleLayer(th.nn.Module):
        def __init__(self):
            super().__init__()

        def forward(self, graph, n_feat):
            graph = graph.local_var()
            graph.ndata['h'] = n_feat
            graph.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
            n_feat += graph.ndata['h']
            return n_feat.view(graph.number_of_nodes() // 2, 2, -1).sum(1)

896
897
898
    g1 = dgl.DGLGraph(nx.erdos_renyi_graph(32, 0.05)).to(F.ctx())
    g2 = dgl.DGLGraph(nx.erdos_renyi_graph(16, 0.2)).to(F.ctx())
    g3 = dgl.DGLGraph(nx.erdos_renyi_graph(8, 0.8)).to(F.ctx())
899
900
901
902
903
904
    net = nn.Sequential(ExampleLayer(), ExampleLayer(), ExampleLayer())
    net = net.to(ctx)
    n_feat = F.randn((32, 4))
    n_feat = net([g1, g2, g3], n_feat)
    assert n_feat.shape == (4, 4)

905
906
907
908
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo'], exclude=['zero-degree']))
def test_atomic_conv(g, idtype):
    g = g.astype(idtype).to(F.ctx())
909
910
911
912
913
914
915
916
917
    aconv = nn.AtomicConv(interaction_cutoffs=F.tensor([12.0, 12.0]),
                          rbf_kernel_means=F.tensor([0.0, 2.0]),
                          rbf_kernel_scaling=F.tensor([4.0, 4.0]),
                          features_to_use=F.tensor([6.0, 8.0]))

    ctx = F.ctx()
    if F.gpu_ctx():
        aconv = aconv.to(ctx)

918
    feat = F.randn((g.number_of_nodes(), 1))
919
920
921
922
923
924
    dist = F.randn((g.number_of_edges(), 1))

    h = aconv(g, feat, dist)
    # current we only do shape check
    assert h.shape[-1] == 4

925
926
@parametrize_dtype
@pytest.mark.parametrize('g', get_cases(['homo'], exclude=['zero-degree']))
927
928
@pytest.mark.parametrize('out_dim', [1, 3])
def test_cf_conv(g, idtype, out_dim):
929
    g = g.astype(idtype).to(F.ctx())
930
931
932
    cfconv = nn.CFConv(node_in_feats=2,
                       edge_in_feats=3,
                       hidden_feats=2,
933
                       out_feats=out_dim)
934
935
936
937
938

    ctx = F.ctx()
    if F.gpu_ctx():
        cfconv = cfconv.to(ctx)

939
    node_feats = F.randn((g.number_of_nodes(), 2))
940
941
942
    edge_feats = F.randn((g.number_of_edges(), 3))
    h = cfconv(g, node_feats, edge_feats)
    # current we only do shape check
943
    assert h.shape[-1] == out_dim
944

945
946
947
948
949
950
def myagg(alist, dsttype):
    rst = alist[0]
    for i in range(1, len(alist)):
        rst = rst + (i + 1) * alist[i]
    return rst

951
@parametrize_dtype
952
@pytest.mark.parametrize('agg', ['sum', 'max', 'min', 'mean', 'stack', myagg])
953
def test_hetero_conv(agg, idtype):
954
    g = dgl.heterograph({
955
956
957
        ('user', 'follows', 'user'): ([0, 0, 2, 1], [1, 2, 1, 3]),
        ('user', 'plays', 'game'): ([0, 0, 0, 1, 2], [0, 2, 3, 0, 2]),
        ('store', 'sells', 'game'): ([0, 0, 1, 1], [0, 3, 1, 2])},
958
        idtype=idtype, device=F.ctx())
959
    conv = nn.HeteroGraphConv({
960
961
962
        'follows': nn.GraphConv(2, 3, allow_zero_in_degree=True),
        'plays': nn.GraphConv(2, 4, allow_zero_in_degree=True),
        'sells': nn.GraphConv(3, 4, allow_zero_in_degree=True)},
963
        agg)
964
    conv = conv.to(F.ctx())
965
966
967
968
    uf = F.randn((4, 2))
    gf = F.randn((4, 4))
    sf = F.randn((2, 3))

969
    h = conv(g, {'user': uf, 'game': gf, 'store': sf})
970
971
972
973
974
975
    assert set(h.keys()) == {'user', 'game'}
    if agg != 'stack':
        assert h['user'].shape == (4, 3)
        assert h['game'].shape == (4, 4)
    else:
        assert h['user'].shape == (4, 1, 3)
976
        assert h['game'].shape == (4, 2, 4)
977

978
979
    block = dgl.to_block(g.to(F.cpu()), {'user': [0, 1, 2, 3], 'game': [0, 1, 2, 3], 'store': []}).to(F.ctx())
    h = conv(block, ({'user': uf, 'game': gf, 'store': sf}, {'user': uf, 'game': gf, 'store': sf[0:0]}))
980
981
982
983
984
985
986
987
    assert set(h.keys()) == {'user', 'game'}
    if agg != 'stack':
        assert h['user'].shape == (4, 3)
        assert h['game'].shape == (4, 4)
    else:
        assert h['user'].shape == (4, 1, 3)
        assert h['game'].shape == (4, 2, 4)

988
    h = conv(block, {'user': uf, 'game': gf, 'store': sf})
989
990
991
992
993
994
    assert set(h.keys()) == {'user', 'game'}
    if agg != 'stack':
        assert h['user'].shape == (4, 3)
        assert h['game'].shape == (4, 4)
    else:
        assert h['user'].shape == (4, 1, 3)
995
        assert h['game'].shape == (4, 2, 4)
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018

    # test with mod args
    class MyMod(th.nn.Module):
        def __init__(self, s1, s2):
            super(MyMod, self).__init__()
            self.carg1 = 0
            self.carg2 = 0
            self.s1 = s1
            self.s2 = s2
        def forward(self, g, h, arg1=None, *, arg2=None):
            if arg1 is not None:
                self.carg1 += 1
            if arg2 is not None:
                self.carg2 += 1
            return th.zeros((g.number_of_dst_nodes(), self.s2))
    mod1 = MyMod(2, 3)
    mod2 = MyMod(2, 4)
    mod3 = MyMod(3, 4)
    conv = nn.HeteroGraphConv({
        'follows': mod1,
        'plays': mod2,
        'sells': mod3},
        agg)
1019
    conv = conv.to(F.ctx())
1020
1021
    mod_args = {'follows' : (1,), 'plays' : (1,)}
    mod_kwargs = {'sells' : {'arg2' : 'abc'}}
1022
    h = conv(g, {'user' : uf, 'game': gf, 'store' : sf}, mod_args=mod_args, mod_kwargs=mod_kwargs)
1023
1024
1025
1026
1027
1028
1029
    assert mod1.carg1 == 1
    assert mod1.carg2 == 0
    assert mod2.carg1 == 1
    assert mod2.carg2 == 0
    assert mod3.carg1 == 0
    assert mod3.carg2 == 1

1030
1031
if __name__ == '__main__':
    test_graph_conv()
1032
1033
    test_graph_conv_e_weight()
    test_graph_conv_e_weight_norm()
1034
1035
1036
1037
    test_set2set()
    test_glob_att_pool()
    test_simple_pool()
    test_set_trans()
Minjie Wang's avatar
Minjie Wang committed
1038
    test_rgcn()
xiang song(charlie.song)'s avatar
xiang song(charlie.song) committed
1039
    test_rgcn_sorted()
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
    test_tagconv()
    test_gat_conv()
    test_sage_conv()
    test_sgc_conv()
    test_appnp_conv()
    test_gin_conv()
    test_agnn_conv()
    test_gated_graph_conv()
    test_nn_conv()
    test_gmm_conv()
1050
    test_dotgat_conv()
1051
1052
1053
    test_dense_graph_conv()
    test_dense_sage_conv()
    test_dense_cheb_conv()
1054
    test_sequential()
1055
    test_atomic_conv()
1056
    test_cf_conv()