| 1 |
import torch |
| 2 |
from torch_scatter import scatter_log_softmax, scatter_softmax |
| 3 |
|
| 4 |
|
| 5 |
def test_softmax(): |
| 6 |
src = torch.tensor([0.2, 0, 0.2, -2.1, 3.2, 7, -1, float('-inf')]) |
| 7 |
src.requires_grad_() |
| 8 |
index = torch.tensor([0, 1, 0, 1, 1, 2, 4, 4]) |
| 9 |
|
| 10 |
out = scatter_softmax(src, index) |
| 11 |
|
| 12 |
out0 = torch.softmax(torch.tensor([0.2, 0.2]), dim=-1) |
| 13 |
out1 = torch.softmax(torch.tensor([0, -2.1, 3.2]), dim=-1) |
| 14 |
out2 = torch.softmax(torch.tensor([7], dtype=torch.float), dim=-1) |
| 15 |
out4 = torch.softmax(torch.tensor([-1, float('-inf')]), dim=-1) |
| 16 |
|
| 17 |
expected = torch.stack([ |
| 18 |
out0[0], out1[0], out0[1], out1[1], out1[2], out2[0], out4[0], out4[1] |
| 19 |
], dim=0) |
| 20 |
|
| 21 |
assert torch.allclose(out, expected) |
| 22 |
|
| 23 |
out.backward(torch.randn_like(out)) |
| 24 |
|
| 25 |
jit = torch.jit.script(scatter_softmax) |
| 26 |
assert jit(src, index).tolist() == out.tolist() |
| 27 |
|
| 28 |
|
| 29 |
def test_log_softmax(): |
| 30 |
src = torch.tensor([0.2, 0, 0.2, -2.1, 3.2, 7, -1, float('-inf')]) |
| 31 |
src.requires_grad_() |
| 32 |
index = torch.tensor([0, 1, 0, 1, 1, 2, 4, 4]) |
| 33 |
|
| 34 |
out = scatter_log_softmax(src, index) |
| 35 |
|
| 36 |
out0 = torch.log_softmax(torch.tensor([0.2, 0.2]), dim=-1) |
| 37 |
out1 = torch.log_softmax(torch.tensor([0, -2.1, 3.2]), dim=-1) |
| 38 |
out2 = torch.log_softmax(torch.tensor([7], dtype=torch.float), dim=-1) |
| 39 |
out4 = torch.log_softmax(torch.tensor([-1, float('-inf')]), dim=-1) |
| 40 |
|
| 41 |
expected = torch.stack([ |
| 42 |
out0[0], out1[0], out0[1], out1[1], out1[2], out2[0], out4[0], out4[1] |
| 43 |
], dim=0) |
| 44 |
|
| 45 |
assert torch.allclose(out, expected) |
| 46 |
|
| 47 |
out.backward(torch.randn_like(out)) |
| 48 |
|
| 49 |
jit = torch.jit.script(scatter_log_softmax) |
| 50 |
assert jit(src, index).tolist() == out.tolist() |