softmax.py 1.63 KB
Newer Older
1
2
import torch

rusty1s's avatar
rusty1s committed
3
from torch_scatter import scatter_sum, scatter_max
4

rusty1s's avatar
rusty1s committed
5
from .utils import broadcast
6

7

rusty1s's avatar
rusty1s committed
8
9
10
@torch.jit.script
def scatter_softmax(src: torch.Tensor, index: torch.Tensor, dim: int = -1,
                    eps: float = 1e-12) -> torch.Tensor:
11
    if not torch.is_floating_point(src):
12
13
        raise ValueError('`scatter_softmax` can only be computed over tensors '
                         'with floating point data types.')
14

rusty1s's avatar
rusty1s committed
15
16
17
    index = broadcast(index, src, dim)

    max_value_per_index = scatter_max(src, index, dim=dim)[0]
18
    max_per_src_element = max_value_per_index.gather(dim, index)
19

20
    recentered_scores = src - max_per_src_element
rusty1s's avatar
rusty1s committed
21
    recentered_scores_exp = recentered_scores.exp_()
22

rusty1s's avatar
rusty1s committed
23
24
    sum_per_index = scatter_sum(recentered_scores_exp, index, dim)
    normalizing_constants = sum_per_index.add_(eps).gather(dim, index)
25

rusty1s's avatar
rusty1s committed
26
    return recentered_scores_exp.div_(normalizing_constants)
27

28

rusty1s's avatar
rusty1s committed
29
30
31
@torch.jit.script
def scatter_log_softmax(src: torch.Tensor, index: torch.Tensor, dim: int = -1,
                        eps: float = 1e-12) -> torch.Tensor:
32
    if not torch.is_floating_point(src):
33
        raise ValueError('`scatter_log_softmax` can only be computed over '
34
                         'tensors with floating point data types.')
35

rusty1s's avatar
rusty1s committed
36
37
38
    index = broadcast(index, src, dim)

    max_value_per_index = scatter_max(src, index, dim=dim)[0]
39
40
41
    max_per_src_element = max_value_per_index.gather(dim, index)

    recentered_scores = src - max_per_src_element
42

rusty1s's avatar
rusty1s committed
43
44
    sum_per_index = scatter_sum(recentered_scores.exp(), index, dim)
    normalizing_constants = sum_per_index.add_(eps).log_().gather(dim, index)
45

rusty1s's avatar
rusty1s committed
46
    return recentered_scores.sub_(normalizing_constants)