-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathsemirings.py
426 lines (330 loc) · 11 KB
/
semirings.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import torch
has_genbmm = False
try:
import genbmm
has_genbmm = True
except ImportError:
pass
def matmul(cls, a, b):
dims = 1
act_on = -(dims + 1)
a = a.unsqueeze(-1)
b = b.unsqueeze(act_on - 1)
c = cls.times(a, b)
for d in range(act_on, -1, 1):
c = cls.sum(c.transpose(-2, -1))
return c
class Semiring:
"""
Base semiring class.
Based on description in:
* Semiring parsing :cite:`goodman1999semiring`
"""
@classmethod
def matmul(cls, a, b):
"Generalized tensordot. Classes should override."
return matmul(cls, a, b)
@classmethod
def size(cls):
"Additional *ssize* first dimension needed."
return 1
@classmethod
def dot(cls, a, b):
"Dot product along last dim."
a = a.unsqueeze(-2)
b = b.unsqueeze(-1)
return cls.matmul(a, b).squeeze(-1).squeeze(-1)
@staticmethod
def fill(c, mask, v):
return torch.where(
mask, v.type_as(c).view((-1,) + (1,) * (len(c.shape) - 1)), c
)
@classmethod
def times(cls, *ls):
"Multiply a list of tensors together"
cur = ls[0]
for l in ls[1:]:
cur = cls.mul(cur, l)
return cur
@classmethod
def convert(cls, potentials):
"Convert to semiring by adding an extra first dimension."
return potentials.unsqueeze(0)
@classmethod
def unconvert(cls, potentials):
"Unconvert from semiring by removing extra first dimension."
return potentials.squeeze(0)
@staticmethod
def sum(xs, dim=-1):
"Sum over *dim* of tensor."
raise NotImplementedError()
@classmethod
def plus(cls, a, b):
return cls.sum(torch.stack([a, b], dim=-1))
class _Base(Semiring):
zero = torch.tensor(0.0)
one = torch.tensor(1.0)
@staticmethod
def mul(a, b):
return torch.mul(a, b)
@staticmethod
def prod(a, dim=-1):
return torch.prod(a, dim=dim)
class _BaseLog(Semiring):
zero = torch.tensor(-1e5)
one = torch.tensor(-0.0)
@staticmethod
def sum(xs, dim=-1):
return torch.logsumexp(xs, dim=dim)
@staticmethod
def mul(a, b):
return a + b
@staticmethod
def prod(a, dim=-1):
return torch.sum(a, dim=dim)
# @classmethod
# def matmul(cls, a, b):
# return super(cls).matmul(a, b)
class StdSemiring(_Base):
"""
Implements the counting semiring (+, *, 0, 1).
"""
@staticmethod
def sum(xs, dim=-1):
return torch.sum(xs, dim=dim)
@classmethod
def matmul(cls, a, b):
"Dot product along last dim"
if has_genbmm and isinstance(a, genbmm.BandedMatrix):
return b.multiply(a.transpose())
else:
return torch.matmul(a, b)
class LogSemiring(_BaseLog):
"""
Implements the log-space semiring (logsumexp, +, -inf, 0).
Gradients give marginals.
"""
@classmethod
def matmul(cls, a, b):
if has_genbmm and a.device != "cpu":
if isinstance(a, genbmm.BandedMatrix):
return b.multiply_log(a.transpose())
return genbmm.logbmm(
a.contiguous(),#.view(-1, a.size(-1), a.size(-1)),
b.contiguous()#.view(-1, b.size(-1), b.size(-1))
)#.view(*a.shape)
else:
return _BaseLog.matmul(a, b)
class MaxSemiring(_BaseLog):
"""
Implements the max semiring (max, +, -inf, 0).
Gradients give argmax.
"""
@classmethod
def matmul(cls, a, b):
if has_genbmm and isinstance(a, genbmm.BandedMatrix):
return b.multiply_max(a.transpose())
else:
return matmul(cls, a, b)
@staticmethod
def sum(xs, dim=-1):
return torch.max(xs, dim=dim)[0]
@staticmethod
def sparse_sum(xs, dim=-1):
m, a = torch.max(xs, dim=dim)
return m, (torch.zeros(a.shape).long(), a)
def KMaxSemiring(k):
"Implements the k-max semiring (kmax, +, [-inf, -inf..], [0, -inf, ...])."
class KMaxSemiring(_BaseLog):
zero = torch.tensor([-1e5 for i in range(k)])
one = torch.tensor([0 if i == 0 else -1e5 for i in range(k)])
@staticmethod
def size():
return k
@classmethod
def convert(cls, orig_potentials):
potentials = torch.zeros(
(k,) + orig_potentials.shape,
dtype=orig_potentials.dtype,
device=orig_potentials.device,
)
potentials = cls.fill(potentials, torch.tensor(True), cls.zero)
potentials[0] = orig_potentials
return potentials
@staticmethod
def unconvert(potentials):
return potentials[0]
@staticmethod
def sum(xs, dim=-1):
if dim == -1:
xs = xs.permute(tuple(range(1, xs.dim())) + (0,))
xs = xs.contiguous().view(xs.shape[:-2] + (-1,))
xs = torch.topk(xs, k, dim=-1)[0]
xs = xs.permute((xs.dim() - 1,) + tuple(range(0, xs.dim() - 1)))
assert xs.shape[0] == k
return xs
assert False
@staticmethod
def sparse_sum(xs, dim=-1):
if dim == -1:
xs = xs.permute(tuple(range(1, xs.dim())) + (0,))
xs = xs.contiguous().view(xs.shape[:-2] + (-1,))
xs, xs2 = torch.topk(xs, k, dim=-1)
xs = xs.permute((xs.dim() - 1,) + tuple(range(0, xs.dim() - 1)))
xs2 = xs2.permute((xs.dim() - 1,) + tuple(range(0, xs.dim() - 1)))
assert xs.shape[0] == k
return xs, (xs2 % k, xs2 // k)
assert False
@staticmethod
def mul(a, b):
a = a.view((k, 1) + a.shape[1:])
b = b.view((1, k) + b.shape[1:])
c = a + b
c = c.contiguous().view((k * k,) + c.shape[2:])
ret = torch.topk(c, k, 0)[0]
assert ret.shape[0] == k
return ret
return KMaxSemiring
class KLDivergenceSemiring(Semiring):
"""
Implements an KL-divergence semiring.
Computes both the log-values of two distributions and the running KL divergence between two distributions.
Based on descriptions in:
* Parameter estimation for probabilistic finite-state
transducers :cite:`eisner2002parameter`
* First-and second-order expectation semirings with applications to
minimumrisk training on translation forests :cite:`li2009first`
* Sample Selection for Statistical Grammar Induction :cite:`hwa2000samplesf`
"""
zero = torch.tensor([-1e5, -1e5, 0.0])
one = torch.tensor([0.0, 0.0, 0.0])
@staticmethod
def size():
return 3
@staticmethod
def convert(xs):
values = torch.zeros((3,) + xs[0].shape).type_as(xs[0])
values[0] = xs[0]
values[1] = xs[1]
values[2] = 0
return values
@staticmethod
def unconvert(xs):
return xs[-1]
@staticmethod
def sum(xs, dim=-1):
assert dim != 0
d = dim - 1 if dim > 0 else dim
part_p = torch.logsumexp(xs[0], dim=d)
part_q = torch.logsumexp(xs[1], dim=d)
log_sm_p = xs[0] - part_p.unsqueeze(d)
log_sm_q = xs[1] - part_q.unsqueeze(d)
sm_p = log_sm_p.exp()
return torch.stack(
(
part_p,
part_q,
torch.sum(
xs[2].mul(sm_p) - log_sm_q.mul(sm_p) + log_sm_p.mul(sm_p), dim=d
),
)
)
@staticmethod
def mul(a, b):
return torch.stack((a[0] + b[0], a[1] + b[1], a[2] + b[2]))
@classmethod
def prod(cls, xs, dim=-1):
return xs.sum(dim)
class CrossEntropySemiring(Semiring):
"""
Implements an cross-entropy expectation semiring.
Computes both the log-values of two distributions and the running cross entropy between two distributions.
Based on descriptions in:
* Parameter estimation for probabilistic finite-state transducers :cite:`eisner2002parameter`
* First-and second-order expectation semirings with applications to minimum-risk training on translation forests :cite:`li2009first`
* Sample Selection for Statistical Grammar Induction :cite:`hwa2000samplesf`
"""
zero = torch.tensor([-1e5, -1e5, 0.0])
one = torch.tensor([0.0, 0.0, 0.0])
@staticmethod
def size():
return 3
@staticmethod
def convert(xs):
values = torch.zeros((3,) + xs[0].shape).type_as(xs[0])
values[0] = xs[0]
values[1] = xs[1]
values[2] = 0
return values
@staticmethod
def unconvert(xs):
return xs[-1]
@staticmethod
def sum(xs, dim=-1):
assert dim != 0
d = dim - 1 if dim > 0 else dim
part_p = torch.logsumexp(xs[0], dim=d)
part_q = torch.logsumexp(xs[1], dim=d)
log_sm_p = xs[0] - part_p.unsqueeze(d)
log_sm_q = xs[1] - part_q.unsqueeze(d)
sm_p = log_sm_p.exp()
return torch.stack(
(part_p, part_q, torch.sum(xs[2].mul(sm_p) - log_sm_q.mul(sm_p), dim=d))
)
@staticmethod
def mul(a, b):
return torch.stack((a[0] + b[0], a[1] + b[1], a[2] + b[2]))
@classmethod
def prod(cls, xs, dim=-1):
return xs.sum(dim)
class EntropySemiring(Semiring):
"""
Implements an entropy expectation semiring.
Computes both the log-values and the running distributional entropy.
Based on descriptions in:
* Parameter estimation for probabilistic finite-state transducers :cite:`eisner2002parameter`
* First-and second-order expectation semirings with applications to minimum-risk training on translation forests :cite:`li2009first`
* Sample Selection for Statistical Grammar Induction :cite:`hwa2000samplesf`
"""
zero = torch.tensor([-1e5, 0.0])
one = torch.tensor([0.0, 0.0])
@staticmethod
def size():
return 2
@staticmethod
def convert(xs):
values = torch.zeros((2,) + xs.shape).type_as(xs)
values[0] = xs
values[1] = 0
return values
@staticmethod
def unconvert(xs):
return xs[1]
@staticmethod
def sum(xs, dim=-1):
assert dim != 0
d = dim - 1 if dim > 0 else dim
part = torch.logsumexp(xs[0], dim=d)
log_sm = xs[0] - part.unsqueeze(d)
sm = log_sm.exp()
return torch.stack((part, torch.sum(xs[1].mul(sm) - log_sm.mul(sm), dim=d)))
@staticmethod
def mul(a, b):
return torch.stack((a[0] + b[0], a[1] + b[1]))
@classmethod
def prod(cls, xs, dim=-1):
return xs.sum(dim)
def TempMax(alpha):
class _TempMax(_BaseLog):
"""
Implements a max forward, hot softmax backward.
"""
@staticmethod
def sum(xs, dim=-1):
pass
@staticmethod
def sparse_sum(xs, dim=-1):
m, _ = torch.max(xs, dim=dim)
a = torch.softmax(alpha * xs, dim)
return m, (torch.zeros(a.shape[:-1]).long(), a)
return _TempMax