test_spspmm.py 1.72 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
2
3
4
5
from itertools import product

import pytest
import torch

Matthias Fey's avatar
Matthias Fey committed
6
7
8
from torch_sparse import SparseTensor, spspmm

from .utils import devices, grad_dtypes, tensor
rusty1s's avatar
rusty1s committed
9
10


rusty1s's avatar
rusty1s committed
11
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
rusty1s's avatar
rusty1s committed
12
def test_spspmm(dtype, device):
Matthias Fey's avatar
Matthias Fey committed
13
14
15
    if device == torch.device('cuda:0') and dtype == torch.bfloat16:
        return  # Not yet implemented.

rusty1s's avatar
rusty1s committed
16
17
18
19
20
21
22
23
    indexA = torch.tensor([[0, 0, 1, 2, 2], [1, 2, 0, 0, 1]], device=device)
    valueA = tensor([1, 2, 3, 4, 5], dtype, device)
    indexB = torch.tensor([[0, 2], [1, 0]], device=device)
    valueB = tensor([2, 4], dtype, device)

    indexC, valueC = spspmm(indexA, valueA, indexB, valueB, 3, 3, 2)
    assert indexC.tolist() == [[0, 1, 2], [0, 1, 1]]
    assert valueC.tolist() == [8, 6, 8]
Mario Geiger's avatar
Mario Geiger committed
24
25
26
27


@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_sparse_tensor_spspmm(dtype, device):
Matthias Fey's avatar
Matthias Fey committed
28
29
30
    if device == torch.device('cuda:0') and dtype == torch.bfloat16:
        return  # Not yet implemented.

Mario Geiger's avatar
Mario Geiger committed
31
32
33
    x = SparseTensor(
        row=torch.tensor(
            [0, 1, 1, 1, 2, 3, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9],
rusty1s's avatar
rusty1s committed
34
            device=device),
Mario Geiger's avatar
Mario Geiger committed
35
36
        col=torch.tensor(
            [0, 5, 10, 15, 1, 2, 3, 7, 13, 6, 9, 5, 10, 15, 11, 14, 5, 15],
rusty1s's avatar
rusty1s committed
37
38
39
40
41
42
            device=device),
        value=torch.tensor([
            1, 3**-0.5, 3**-0.5, 3**-0.5, 1, 1, 1, -2**-0.5, -2**-0.5,
            -2**-0.5, -2**-0.5, 6**-0.5, -6**0.5 / 3, 6**-0.5, -2**-0.5,
            -2**-0.5, 2**-0.5, -2**-0.5
        ], dtype=dtype, device=device),
Mario Geiger's avatar
Mario Geiger committed
43
44
    )

YanbingJiang's avatar
YanbingJiang committed
45
    expected = torch.eye(10, device=device).to(dtype)
Mario Geiger's avatar
Mario Geiger committed
46

rusty1s's avatar
rusty1s committed
47
    out = x @ x.to_dense().t()
rusty1s's avatar
rusty1s committed
48
    assert torch.allclose(out, expected, atol=1e-2)
Mario Geiger's avatar
Mario Geiger committed
49

rusty1s's avatar
rusty1s committed
50
51
    out = x @ x.t()
    out = out.to_dense()
rusty1s's avatar
rusty1s committed
52
    assert torch.allclose(out, expected, atol=1e-2)