-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
337 lines (261 loc) · 9.9 KB
/
utils.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
# author: vlad niculae and andre f. t. martins
# license: simplified bsd
import math
import torch
import torch.nn as nn
from torch.autograd import Function
from entmax import sparsemax, entmax15, normmax_bisect
# from lpsmap import TorchFactorGraph, Budget, SequenceBudget
class Flatten(object):
def __call__(self, tensor):
return torch.flatten(tensor)
def __repr__(self):
return self.__class__.__name__ + '()'
def entmax(Z, alpha, dim):
"""only exact cases; raise otherwise; for toy experiments"""
if alpha == 1:
return torch.softmax(Z, dim=dim)
elif alpha == 1.5:
return entmax15(Z, dim=dim)
elif alpha == 2:
return sparsemax(Z, dim=dim)
else:
raise NotImplementedError()
def SparseMAP_exactly_k(scores, k=2):
marginals = torch.zeros_like(scores)
for j in range(scores.shape[1]):
fg = TorchFactorGraph()
u = fg.variable_from(scores[:, j])
fg.add(Budget(u, k, force_budget=True))
fg.solve(verbose=0)
marginals[:, j] = u.value[:]
return marginals
def SparseMAP_sequence_exactly_k(scores, edge_score, k=2):
n = scores.shape[0]
transition = torch.zeros((n+1,2,2))
transition.data[1:n, 0, 0] = edge_score
# Only one state in the beginning and in the end for start / stop symbol.
transition = transition.reshape(-1)[2:-2]
marginals = torch.zeros_like(scores)
for j in range(scores.shape[1]):
s = torch.zeros((n, 2))
s[:, 0] = scores[:, j]
fg = TorchFactorGraph()
u = fg.variable_from(s)
fg.add(SequenceBudget(u, transition, k, force_budget=True))
fg.solve(verbose=0)
marginals[:, j] = u.value[:, 0]
return marginals
class NormmaxBisectFunction(Function):
@classmethod
def _gp(cls, x, alpha):
return x ** (alpha - 1)
@classmethod
def _gp_inv(cls, y, alpha):
return y ** (1 / (alpha - 1))
@classmethod
def _p(cls, X, alpha):
return cls._gp_inv(torch.clamp(X, min=0), alpha)
@classmethod
def forward(cls, ctx, X, alpha=2, dim=-1, n_iter=50):
if not isinstance(alpha, torch.Tensor):
alpha = torch.tensor(alpha, dtype=X.dtype, device=X.device)
alpha_shape = list(X.shape)
alpha_shape[dim] = 1
alpha = alpha.expand(*alpha_shape)
ctx.alpha = alpha
ctx.dim = dim
d = X.shape[dim]
max_val, _ = X.max(dim=dim, keepdim=True)
# Note: when alpha < 1, tau_lo > tau_hi. This still works since dm < 0.
# With alpha >= 1, ||p||_alpha <= 1 and ||p||_alpha >= d**((1-alpha)/alpha), therefore
# pi = (si - tau)**(1/(alpha-1)) ||p||_alpha
# tau = si - (pi / ||p||_\alpha) ** (alpha-1)
# tau = smax - (pmax / ||p||_\alpha) ** (alpha-1)
# pmax / ||p||_\alpha <= 1 / (d**(1-alpha)/alpha) = d**((alpha-1)/alpha)
# Also pmax / ||p||_\alpha <= 1 (since pmax = ||p||_inf)
# pmax / ||p||_\alpha >= (1/d) / 1 = d**(-1)
# Therefore
# tau_min = smax - 1 ** (alpha-1)
# tau_max = smax - (1/d) ** (alpha-1)
# Same as entmax!!
tau_lo = max_val - cls._gp(1, alpha) # 1
tau_hi = max_val - cls._gp(1 / d, alpha) # (1/d)**(alpha-1)
f_lo = (cls._p(X - tau_lo, alpha) ** alpha).sum(dim) - 1
dm = tau_hi - tau_lo
for it in range(n_iter):
dm /= 2
tau_m = tau_lo + dm
p_m = cls._p(X - tau_m, alpha) # [X - tau]_+ ** (1/(alpha-1))
f_m = (p_m ** alpha).sum(dim) - 1
mask = (f_m >= 0).unsqueeze(dim)
tau_lo = torch.where(mask, tau_m, tau_lo)
#p_m = p_m + 1e-12
p_m /= p_m.sum(dim=dim).unsqueeze(dim=dim)
ctx.save_for_backward(p_m)
return p_m
@classmethod
def backward(cls, ctx, dY):
Y, = ctx.saved_tensors
a = torch.where(Y > 0, Y, Y.new_zeros(1))
b = torch.where(Y > 0, Y ** (2 - ctx.alpha), Y.new_zeros(1))
dX = dY * b
q = dX.sum(ctx.dim).unsqueeze(ctx.dim)
dX -= q * a
q = (dY * a).sum(ctx.dim).unsqueeze(ctx.dim)
dX -= q * (b - b.sum(ctx.dim).unsqueeze(ctx.dim) * a)
dX *= ((a ** ctx.alpha).sum(ctx.dim).unsqueeze(ctx.dim) ** ((ctx.alpha - 1) / ctx.alpha))
dX /= (ctx.alpha - 1)
return dX, None, None, None, None
def normmax_bisect(X, alpha=2, dim=-1):
"""alpha-normmax: normalizing sparse transform (a la softmax and entmax).
Solves the optimization problem:
max_p <x, p> - ||p||_alpha s.t. p >= 0, sum(p) == 1.
where ||.||_alpha is the alpha-norm, with custom alpha >= 1,
using a bisection (root finding, binary search) algorithm.
This function is differentiable with respect to X.
Parameters
----------
X : torch.Tensor
The input tensor.
alpha : float or torch.Tensor
Tensor of alpha parameters (> 1) to use. If scalar
or python float, the same value is used for all rows, otherwise,
it must have shape (or be expandable to)
alpha.shape[j] == (X.shape[j] if j != dim else 1).
dim : int
The dimension along which to apply alpha-normmax.
n_iter : int
Number of bisection iterations. For float32, 24 iterations should
suffice for machine precision.
Returns
-------
P : torch tensor, same shape as X
The projection result, such that P.sum(dim=dim) == 1 elementwise.
"""
return normmax_bisect(X, alpha=alpha, dim=dim)
def tsallis_unif(n, alpha, dtype=torch.double):
if alpha == 1:
return math.log(n)
return (1 - n**(1-alpha)) / (alpha * (alpha-1))
def tsallis(p, alpha, dim=-1):
if alpha == 1:
return torch.special.entr(p).sum(dim)
else:
return ((p - p ** alpha) / (alpha * (alpha-1))).sum(dim=dim)
def normmaxentropy(p, alpha, dim=-1):
return 1 - torch.sqrt((p**2).sum(dim=-1))
def normmax_unif(n, alpha, dim=-1):
return 1 - math.sqrt(n)/n
def energy(Q, X, alpha=1.0, beta=1.0, normmax = False):
# Q: tensor dim (m, d)
# X: tensor dim (n, d)
n = X.shape[0]
# m is batch dim, so bXQ[i] = bXq_i
bXQ = beta * Q @ X.T
if normmax:
phat = normmax_bisect(bXQ, alpha, -1)
fy_term_gold = -normmax_unif(n, alpha) - bXQ.mean(dim=-1)
fy_term_pred = -normmaxentropy(phat, alpha) - (bXQ * phat).sum(dim=-1)
else:
phat = entmax(bXQ, alpha, dim = -1)
fy_term_gold = -tsallis_unif(n, alpha) - bXQ.mean(dim=-1)
fy_term_pred = -tsallis(phat, alpha) - (bXQ * phat).sum(dim=-1)
fy = fy_term_gold - fy_term_pred
mx = X.mean(dim=0)
q_nrmsq = (Q**2).sum(dim=-1)
Msq = (X ** 2).sum(dim=-1).max()
return -fy/beta - Q @ mx + q_nrmsq/2 + Msq/2
class UHopfieldNet(nn.Module):
def __init__(self,
in_features,
alpha=1.0,
beta=1.0,
max_iter=128,
sparsemap = False,
normmax = False,
factor = "budget",
k = 2,
return_p = False):
super(UHopfieldNet, self).__init__()
self.sparsemap = sparsemap
self.normmax = normmax
self.X = in_features
self.max_iter = max_iter
self.alpha = alpha
self.beta = beta
self.k = k
self.return_p = return_p
self.factor = factor
self.feature_map = nn.Linear(in_features.size(0))
def _energy(self, Q):
return energy(Q, self.X, self.alpha, self.beta)
def _run(self, Q, eps=1e-6):
"""Synchronousl update
Args:
x (torch.Tensor): inputs
eps (float): Defaults to 1e-6.
"""
for _ in range(self.max_iter):
if self.sparsemap:
if self.factor == "budget":
p = SparseMAP_exactly_k(self.beta * self.X.mm(Q), self.k)
else:
p = SparseMAP_sequence_exactly_k(self.beta * self.X.mm(Q), 100, self.k)
elif self.normmax:
p = normmax_bisect(self.beta * self.X.mm(Q), alpha=self.alpha, dim=0)
else:
p = entmax(self.beta * self.X.mm(Q), self.alpha, dim=0)
Q = self.X.T @ p
if self.return_p:
return Q, p
else:
return Q
def forward(self, Q):
return self._run(Q)
class HopfieldNet(nn.Module):
def __init__(self,
in_features,
alpha=1.0,
beta=1.0,
max_iter=128,
sparsemap = False,
normmax = False,
factor = "budget",
k = 2,
return_p = False):
super(HopfieldNet, self).__init__()
self.sparsemap = sparsemap
self.normmax = normmax
self.X = in_features
self.max_iter = max_iter
self.alpha = alpha
self.beta = beta
self.k = k
self.return_p = return_p
self.factor = factor
def _energy(self, Q):
return energy(Q, self.X, self.alpha, self.beta)
def _run(self, Q, eps=1e-6):
"""Synchronousl update
Args:
x (torch.Tensor): inputs
eps (float): Defaults to 1e-6.
"""
for _ in range(self.max_iter):
if self.sparsemap:
if self.factor == "budget":
p = SparseMAP_exactly_k(self.beta * self.X.mm(Q), self.k)
else:
p = SparseMAP_sequence_exactly_k(self.beta * self.X.mm(Q), 100, self.k)
elif self.normmax:
p = normmax_bisect(self.beta * self.X.mm(Q), alpha=self.alpha, dim=0)
else:
p = entmax(self.beta * self.X.mm(Q), self.alpha, dim=0)
Q = self.X.T @ p
if self.return_p:
return Q, p
else:
return Q
def forward(self, Q):
return self._run(Q)