|
| 1 | +from itertools import product |
| 2 | + |
| 3 | +import pytest |
| 4 | +import torch |
| 5 | +from torch_scatter.composite import scatter_log_softmax, scatter_softmax |
| 6 | + |
| 7 | +from test.utils import devices, tensor, grad_dtypes |
| 8 | + |
| 9 | + |
| 10 | +@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices)) |
| 11 | +def test_softmax(dtype, device): |
| 12 | + src = tensor([0.2, 0, 0.2, -2.1, 3.2, 7, -1, float('-inf')], dtype, device) |
| 13 | + index = tensor([0, 1, 0, 1, 1, 2, 4, 4], torch.long, device) |
| 14 | + |
| 15 | + out = scatter_softmax(src, index) |
| 16 | + |
| 17 | + out0 = torch.softmax(torch.tensor([0.2, 0.2], dtype=dtype), dim=-1) |
| 18 | + out1 = torch.softmax(torch.tensor([0, -2.1, 3.2], dtype=dtype), dim=-1) |
| 19 | + out2 = torch.softmax(torch.tensor([7], dtype=dtype), dim=-1) |
| 20 | + out4 = torch.softmax(torch.tensor([-1, float('-inf')], dtype=dtype), |
| 21 | + dim=-1) |
| 22 | + |
| 23 | + expected = torch.stack([ |
| 24 | + out0[0], out1[0], out0[1], out1[1], out1[2], out2[0], out4[0], out4[1] |
| 25 | + ], dim=0) |
| 26 | + |
| 27 | + assert torch.allclose(out, expected) |
| 28 | + |
| 29 | + |
| 30 | +@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices)) |
| 31 | +def test_log_softmax(dtype, device): |
| 32 | + src = tensor([0.2, 0, 0.2, -2.1, 3.2, 7, -1, float('-inf')], dtype, device) |
| 33 | + index = tensor([0, 1, 0, 1, 1, 2, 4, 4], torch.long, device) |
| 34 | + |
| 35 | + out = scatter_log_softmax(src, index) |
| 36 | + |
| 37 | + out0 = torch.log_softmax(torch.tensor([0.2, 0.2], dtype=dtype), dim=-1) |
| 38 | + out1 = torch.log_softmax(torch.tensor([0, -2.1, 3.2], dtype=dtype), dim=-1) |
| 39 | + out2 = torch.log_softmax(torch.tensor([7], dtype=dtype), dim=-1) |
| 40 | + out4 = torch.log_softmax(torch.tensor([-1, float('-inf')], dtype=dtype), |
| 41 | + dim=-1) |
| 42 | + |
| 43 | + expected = torch.stack([ |
| 44 | + out0[0], out1[0], out0[1], out1[1], out1[2], out2[0], out4[0], out4[1] |
| 45 | + ], dim=0) |
| 46 | + |
| 47 | + assert torch.allclose(out, expected) |
0 commit comments