"research/syntaxnet/dragnn/runtime/alignment_test.cc" did not exist on "dea7ecf6492b02e2ced3fbba858942b2b43d3029"
softmax.py 1.61 KB
Newer Older
1
2
import torch

rusty1s's avatar
rusty1s committed
3
from torch_scatter import scatter_sum, scatter_max
4
from torch_scatter.utils import broadcast
5

6

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

rusty1s's avatar
rusty1s committed
13
14
15
    index = broadcast(index, src, dim)

    max_value_per_index = scatter_max(src, index, dim=dim)[0]
16
    max_per_src_element = max_value_per_index.gather(dim, index)
17

18
    recentered_scores = src - max_per_src_element
rusty1s's avatar
rusty1s committed
19
    recentered_scores_exp = recentered_scores.exp()
20

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

rusty1s's avatar
rusty1s committed
24
    return recentered_scores_exp.div(normalizing_constants)
25

26

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

rusty1s's avatar
rusty1s committed
33
34
35
    index = broadcast(index, src, dim)

    max_value_per_index = scatter_max(src, index, dim=dim)[0]
36
37
38
    max_per_src_element = max_value_per_index.gather(dim, index)

    recentered_scores = src - max_per_src_element
39

rusty1s's avatar
rusty1s committed
40
41
    sum_per_index = scatter_sum(recentered_scores.exp(), index, dim)
    normalizing_constants = sum_per_index.add_(eps).log_().gather(dim, index)
42

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