test_backward.py 1.47 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
2
3
4
from itertools import product

import pytest
import torch
rusty1s's avatar
rusty1s committed
5
from torch.autograd import gradcheck
rusty1s's avatar
rusty1s committed
6
7
import torch_scatter

rusty1s's avatar
rusty1s committed
8
from .utils import dtypes, devices, tensor
rusty1s's avatar
rusty1s committed
9

rusty1s's avatar
rusty1s committed
10
funcs = ['add', 'sub', 'mul', 'div', 'mean']
rusty1s's avatar
rusty1s committed
11
indices = [2, 0, 1, 1, 0]
rusty1s's avatar
rusty1s committed
12
13


rusty1s's avatar
rusty1s committed
14
15
16
17
18
@pytest.mark.parametrize('func,device', product(funcs, devices))
def test_backward(func, device):
    index = torch.tensor(indices, dtype=torch.long, device=device)
    src = torch.rand(index.size(), dtype=torch.double, device=device)
    src.requires_grad_()
rusty1s's avatar
rusty1s committed
19

rusty1s's avatar
rusty1s committed
20
21
22
    op = getattr(torch_scatter, 'scatter_{}'.format(func))
    data = (src, index)
    assert gradcheck(op, data, eps=1e-6, atol=1e-4) is True
rusty1s's avatar
rusty1s committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54


tests = [{
    'name': 'max',
    'src': [1, 2, 3, 4, 5],
    'index': [2, 0, 1, 1, 0],
    'dim': 0,
    'fill_value': 0,
    'grad': [4, 8, 6],
    'expected': [6, 0, 0, 8, 4]
}, {
    'name': 'min',
    'src': [1, 2, 3, 4, 5],
    'index': [2, 0, 1, 1, 0],
    'dim': 0,
    'fill_value': 3,
    'grad': [4, 8, 6],
    'expected': [6, 4, 8, 0, 0]
}]


@pytest.mark.parametrize('test,dtype,device', product(tests, dtypes, devices))
def test_arg_backward(test, dtype, device):
    src = tensor(test['src'], dtype, device)
    src.requires_grad_()
    index = tensor(test['index'], torch.long, device)
    grad = tensor(test['grad'], dtype, device)

    op = getattr(torch_scatter, 'scatter_{}'.format(test['name']))
    out, _ = op(src, index, test['dim'], fill_value=test['fill_value'])
    out.backward(grad)
    assert src.grad.tolist() == test['expected']