-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsemiring.py
83 lines (72 loc) · 1.5 KB
/
semiring.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import torch
def identity(x):
return x
def zero(data, *size):
return data.new(*size).zero_()
def one(data, *size):
return data.new(*size).zero_() + 1.
def neg_infinity(data, *size):
return -100 * one(data, *size)
class Semiring:
def __init__(self,
type,
zero,
one,
plus,
times,
from_float,
to_float):
self.type = type
self.zero = zero
self.one = one
self.plus = plus
self.times = times
self.from_float = from_float
self.to_float = to_float
# element-wise plus, times
PlusTimesSemiring = \
Semiring(
0,
zero,
one,
torch.add,
torch.mul,
identity,
identity
)
# element-wise max, plus
MaxPlusSemiring = \
Semiring(
1,
neg_infinity,
zero,
torch.max,
torch.add,
identity,
identity
)
# element-wise max, times. in log-space
MaxTimesSemiring = \
Semiring(
2,
neg_infinity,
zero,
torch.max,
torch.mul,
identity,
identity
)
def LogSum(x, y):
return torch.log(torch.exp(x) + torch.exp(y))
# element-wise max, times. in log-space
LogSemiring = \
Semiring(
3,
neg_infinity,
zero,
# lambda x, y: torch.log(torch.exp(x) + torch.exp(y)),
LogSum,
torch.add,
identity,
identity
)