-
Notifications
You must be signed in to change notification settings - Fork 7
/
spd_net_util.py
512 lines (398 loc) · 16.3 KB
/
spd_net_util.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import torch
from torch.autograd import Function
from torch.autograd import Variable
import numpy as np
from torch.nn.modules.module import Module
class SVD_opt(Function):
def forward(self, input):
Us = torch.zeros_like(input)
Ss = torch.zeros((input.shape[0], input.shape[1])).double()
for i in range(input.shape[0]):
U, S, V = torch.svd(input[i, :, :])
Ss[i, :] = S
Us[i, :, :] = U
self.Us = Us
self.Ss = Ss
# self.save_for_backward(input)
return Us, Ss
def backward(self, dLdV, dLdS):
Ut = torch.transpose(self.Us, 1, 2)
Ks = torch.zeros_like(dLdV)
diag_dLdS = torch.zeros_like(dLdV)
for i in range(dLdV.shape[0]):
diagS = self.Ss[i, :]
diagS = diagS.contiguous()
vs_1 = diagS.view([diagS.shape[0], 1])
vs_2 = diagS.view([1, diagS.shape[0]])
K = 1.0 / (vs_1 - vs_2)
# K.masked_fill(mask_diag, 0.0)
K[K >= float("Inf")] = 0.0
Ks[i, :, :] = K
# diag_dLdS[i, :, :] = torch.diag(torch.diag(dLdS[i, :, :]))
diag_dLdS[i, :, :] = torch.diag(dLdS[i, :])
tmp = torch.transpose(Ks, 1, 2) * torch.matmul(Ut, dLdV)
tmp = 0.5 * (tmp + torch.transpose(tmp, 1, 2)) + diag_dLdS
grad = torch.matmul(self.Us, torch.matmul(tmp, Ut)) # checked
return grad
class RecFunction_v2(Function):
def forward(self, input):
Us = torch.zeros_like(input)
Ss = torch.zeros((input.shape[0], input.shape[1])).double()
max_Ss = torch.zeros_like(input)
max_Ids = torch.zeros_like(input)
for i in range(input.shape[0]):
U, S, V = torch.svd(input[i, :, :])
eps = 0.0001
max_S = torch.clamp(S, min=eps)
max_Id = torch.ge(S, eps)
# res = torch.matmul(U, torch.matmul(torch.diag(max_S), torch.transpose(U, 0, 1)))
# result[i, :, :] = res
Ss[i, :]=S
Us[i, :, :] = U
max_Ss[i, :, :] = torch.diag(max_S)
max_Ids[i, :, :] = torch.diag(max_Id)
result = torch.matmul(Us, torch.matmul(max_Ss, torch.transpose(Us, 1, 2)))
self.Us = Us
self.Ss = Ss
self.max_Ss = max_Ss
self.max_Ids = max_Ids
self.save_for_backward(input)
return result
def backward(self, grad_output):
Ks = torch.zeros_like(grad_output)
dLdC = grad_output
dLdC = 0.5 * (dLdC + torch.transpose(dLdC, 1, 2)) # checked
Ut = torch.transpose(self.Us, 1, 2)
dLdV = 2 * torch.matmul(torch.matmul(dLdC, self.Us), self.max_Ss)
dLdS_1 = torch.matmul(torch.matmul(Ut, dLdC), self.Us)
dLdS = torch.matmul(self.max_Ids, dLdS_1) # checked
diag_dLdS = torch.zeros_like(grad_output)
for i in range(grad_output.shape[0]):
diagS = self.Ss[i, :]
diagS = diagS.contiguous()
vs_1 = diagS.view([diagS.shape[0], 1])
vs_2 = diagS.view([1, diagS.shape[0]])
K = 1.0 / (vs_1 - vs_2)
# K.masked_fill(mask_diag, 0.0)
K[K >= float("Inf")] = 0.0
Ks[i, :, :] = K
diag_dLdS[i, :, :] = torch.diag(torch.diag(dLdS[i, :, :]))
tmp = torch.transpose(Ks, 1, 2) * torch.matmul(Ut, dLdV)
tmp = 0.5 * (tmp + torch.transpose(tmp, 1, 2)) + diag_dLdS
grad = torch.matmul(self.Us, torch.matmul(tmp, Ut)) # checked
return grad
class LogFunction_v2(Function):
def forward(self, input):
Us = torch.zeros_like(input)
Ss = torch.zeros((input.shape[0], input.shape[1])).double()
logSs = torch.zeros_like(input)
invSs = torch.zeros_like(input)
for i in range(input.shape[0]):
U, S, V = torch.svd(input[i, :, :])
Ss[i, :] = S
Us[i, :, :] = U
logSs[i, :, :] = torch.diag(torch.log(S))
invSs[i, :, :] = torch.diag(1.0/S)
result = torch.matmul(Us, torch.matmul(logSs, torch.transpose(Us, 1, 2)))
self.Us = Us
self.Ss = Ss
self.logSs = logSs
self.invSs = invSs
self.save_for_backward(input)
return result
def backward(self, grad_output):
grad_output = grad_output.double()
Ks = torch.zeros_like(grad_output)
dLdC = grad_output
dLdC = 0.5 * (dLdC + torch.transpose(dLdC, 1, 2)) # checked
Ut = torch.transpose(self.Us, 1, 2)
dLdV = 2 * torch.matmul(dLdC, torch.matmul(self.Us, self.logSs)) # [d, ind]
dLdS_1 = torch.matmul(torch.matmul(Ut, dLdC), self.Us) # [ind, ind]
dLdS = torch.matmul(self.invSs, dLdS_1)
diag_dLdS = torch.zeros_like(grad_output)
for i in range(grad_output.shape[0]):
diagS = self.Ss[i, :]
diagS = diagS.contiguous()
vs_1 = diagS.view([diagS.shape[0], 1])
vs_2 = diagS.view([1, diagS.shape[0]])
K = 1.0 / (vs_1 - vs_2)
# K.masked_fill(mask_diag, 0.0)
K[K >= float("Inf")] = 0.0
Ks[i, :, :] = K
diag_dLdS[i, :, :] = torch.diag(torch.diag(dLdS[i, :, :]))
tmp = torch.transpose(Ks, 1, 2) * torch.matmul(Ut, dLdV)
tmp = 0.5 * (tmp + torch.transpose(tmp, 1, 2)) + diag_dLdS
grad = torch.matmul(self.Us, torch.matmul(tmp, Ut)) # checked
# print('log_mat_v2 backward')
return grad
class LogFunction_v0(Function):
def forward(self, input):
Us = torch.zeros_like(input)
Ss = torch.zeros((input.shape[0], input.shape[1])).double()
mSs = torch.zeros_like(input)
for i in range(input.shape[0]):
U, S, V = torch.svd(input[i, :, :])
Ss[i, :] = S
Us[i, :, :] = U
mSs[i, :, :] = torch.diag(torch.log(S))
result = torch.matmul(Us, torch.matmul(mSs, torch.transpose(Us, 1, 2)))
self.Us = Us
self.Ss = Ss
self.save_for_backward(input)
return result
def backward(self, grad_output):
grad_output = grad_output.double()
grad = torch.zeros_like(grad_output)
d = grad_output.shape[1]
# mask_diag = torch.ByteTensor(torch.eye(d).byte())
for i in range(grad_output.shape[0]):
dLdC = grad_output[i, :, :]
dLdC = 0.5 * (dLdC + torch.transpose(dLdC, 0, 1)) # checked
diagS = self.Ss[i, :]
diagS = diagS.contiguous()
U = self.Us[i, :, :]
Ut = torch.transpose(U, 0, 1)
diagLogS = torch.diag(torch.log(diagS)) # matrix
diagInvS = torch.diag(1.0 / diagS) # matrix
dLdV = 2 * torch.matmul(dLdC, torch.matmul(U, diagLogS)) # [d, ind]
dLdS_1 = torch.matmul(torch.matmul(Ut, dLdC), U) # [ind, ind]
dLdS = torch.matmul(diagInvS, dLdS_1)
vs_1 = diagS.view([diagS.shape[0], 1])
vs_2 = diagS.view([1, diagS.shape[0]])
K = 1.0 / (vs_1 - vs_2)
# K.masked_fill(mask_diag, 0.0)
K[K >= float("Inf")] = 0.0
tmp = torch.transpose(K, 0, 1) * torch.matmul(Ut, dLdV)
tmp = 0.5 * (tmp + torch.transpose(tmp, 0, 1)) + torch.diag(torch.diag(dLdS))
dzdx = torch.matmul(U, torch.matmul(tmp, Ut)) # checked
grad[i, :, :] = dzdx
# print('log_mat_v2 backward')
return grad
class LogFunction(Function):
def forward(ctx, input):
numpy_input = input.numpy()
if numpy_input.dtype != np.float64:
numpy_input = numpy_input.astype(np.float64)
u, s, v = np.linalg.svd(numpy_input)
diag = np.zeros(numpy_input.shape, dtype=np.float64)
n = numpy_input.shape[0]
for i in range(n):
diag[i, :, :] = np.diag(np.log(s[i, :]))
result = np.matmul(u, np.matmul(diag, np.transpose(u, axes=[0, 2, 1]))) # checked
ctx.save_for_backward(input)
return torch.DoubleTensor(result)
def backward(ctx, grad_output):
np_grad_output = grad_output.numpy()
numpy_input, = ctx.saved_tensors
numpy_input = numpy_input.numpy()
if numpy_input.dtype != np.float64:
numpy_input = numpy_input.astype(np.float64)
if np_grad_output.dtype != np.float64:
np_grad_output = np_grad_output.astype(np.float64)
grad = np.zeros(np_grad_output.shape, dtype=np.float64)
u, s, v = np.linalg.svd(numpy_input)
for i in range(np_grad_output.shape[0]):
dLdC = np_grad_output[i, :, :]
dLdC = dLdC.astype(dtype=np.float64)
dLdC = 0.5 * (dLdC + np.transpose(dLdC)) # checked
diagS = s[i, :]
U = u[i, :, :] #
# thr = dLdC.shape[-1] * np.spacing(np.max(diagS))
# ind = np.greater(diagS, thr)
# diagS = diagS[ind]
# U = U[:, ind] # checked [d, ind]
diagLogS = np.diag(np.log(diagS)) # matrix
diagInvS = np.diag(1.0 / diagS) # matrix
dLdV = 2 * np.matmul(dLdC, np.matmul(U, diagLogS)) # [d, ind]
dLdS_1 = np.matmul(np.matmul(np.transpose(U), dLdC), U) # [ind, ind]
dLdS = np.matmul(diagInvS, dLdS_1)
# if np.sum(ind) == 1:
# # K = 1. / (S(1) * ones(1, Dmin) - (S(1) * ones(1, Dmin))');
# # K(eye(size(K, 1)) > 0)=0;
# print('rank is one!')
# K is [ind, ind]
K = 1.0 / (np.expand_dims(diagS, axis=-1) - np.expand_dims(diagS, axis=0))
np.fill_diagonal(K, 0.0)
K[np.isinf(K)] = 0.0
tmp = np.transpose(K) * np.matmul(np.transpose(U), dLdV)
tmp = 0.5 * (tmp + np.transpose(tmp)) + np.diag(np.diag(dLdS))
dzdx = np.matmul(U, np.matmul(tmp, np.transpose(U)))
grad[i, :, :] = dzdx # checked
return torch.DoubleTensor(grad)
class RecFunction_v0(Function):
def forward(self, input):
Us = torch.zeros_like(input)
Ss = torch.zeros((input.shape[0], input.shape[1])).double()
max_Ss = torch.zeros_like(input)
max_Ids = torch.zeros_like(input)
for i in range(input.shape[0]):
U, S, V = torch.svd(input[i, :, :])
eps = 0.0001
max_S = torch.clamp(S, min=eps)
max_Id = torch.ge(S, eps)
# res = torch.matmul(U, torch.matmul(torch.diag(max_S), torch.transpose(U, 0, 1)))
# result[i, :, :] = res
Ss[i, :]=S
Us[i, :, :] = U
max_Ss[i, :, :] = torch.diag(max_S)
max_Ids[i, :, :] = torch.diag(max_Id)
result = torch.matmul(Us, torch.matmul(max_Ss, torch.transpose(Us, 1, 2)))
self.Us = Us
self.Ss = Ss
self.max_Ss = max_Ss
self.max_Ids = max_Ids
self.save_for_backward(input)
return result
def backward(self, grad_output):
grad = torch.zeros_like(grad_output)
d = grad_output[1]
# mask_diag = torch.ByteTensor(torch.eye(d).byte())
for i in range(grad_output.shape[0]):
dLdC = grad_output[i, :, :]
dLdC = 0.5 * (dLdC + torch.transpose(dLdC, 0, 1)) # checked
rec_s = self.max_Ss[i, :, :]
rec_id = self.max_Ids[i, :, :]
U = self.Us[i, :, :]
Ut = torch.transpose(U, 0, 1)
diagS = self.Ss[i, :]
diagS = diagS.contiguous()
dLdV = 2 * torch.matmul(torch.matmul(dLdC, U), rec_s)
dLdS_1 = torch.matmul(torch.matmul(Ut, dLdC), U)
dLdS = torch.matmul(rec_id, dLdS_1) # checked
vs_1 = diagS.view([diagS.shape[0], 1])
vs_2 = diagS.view([1, diagS.shape[0]])
K = 1.0 / (vs_1 - vs_2)
# K.masked_fill(mask_diag, 0.0)
K[K >= float("Inf")] = 0.0
tmp = torch.transpose(K, 0, 1) * torch.matmul(Ut, dLdV)
tmp = 0.5 * (tmp + torch.transpose(tmp, 0, 1)) + torch.diag(torch.diag(dLdS))
dzdx = torch.matmul(U, torch.matmul(tmp, Ut)) # checked
grad[i, :, :] = dzdx
# print('rec_mat_v2 backward')
return grad
def SVD_customed(input):
return SVD_opt()(input)
def rec_mat_v2(input):
return RecFunction_v2()(input)
def log_mat_v2(input):
return LogFunction_v2()(input)
class RecFunction(Function):
# @staticmethod
def forward(ctx, input):
numpy_input = input.numpy()
if numpy_input.dtype != np.float64:
numpy_input = numpy_input.astype(np.float64)
u, s, v = np.linalg.svd(numpy_input)
eps = 0.0001
max_s = np.maximum(s, eps)
n = numpy_input.shape[0]
diag = np.zeros(numpy_input.shape, dtype=np.float64)
# max_s = s
for i in range(n):
diag[i, :, :] = np.diag(max_s[i, :])
result = np.matmul(u, np.matmul(diag, np.transpose(u, axes=[0, 2, 1]))) # checked
ctx.save_for_backward(input)
return torch.DoubleTensor(result)
# @staticmethod
def backward(ctx, grad_output):
np_grad_output = grad_output.numpy()
numpy_input, = ctx.saved_tensors
numpy_input = numpy_input.numpy()
if numpy_input.dtype != np.float64:
numpy_input = numpy_input.astype(np.float64)
if np_grad_output.dtype != np.float64:
np_grad_output = np_grad_output.astype(np.float64)
u, s, v = np.linalg.svd(numpy_input)
eps = 0.0001
max_s = np.maximum(s, eps)
max_id = np.greater(s, eps).astype(dtype=np.float32)
grad = np.zeros(np_grad_output.shape)
for i in range(np_grad_output.shape[0]):
dLdC = np_grad_output[i, :, :]
dLdC = 0.5 * (dLdC + np.transpose(dLdC)) # checked
rec_s = np.diag(max_s[i, :]) # checked
rec_id = np.diag(max_id[i, :])
U = u[i, :, :]
dLdV = 2 * np.matmul(np.matmul(dLdC, U), rec_s)
dLdS_1 = np.matmul(np.matmul(np.transpose(U), dLdC), U)
dLdS = np.matmul(rec_id, dLdS_1) # checked
K = 1.0 / (np.expand_dims(s[i, :], axis=-1) - np.expand_dims(s[i, :], axis=0))
np.fill_diagonal(K, 0.0)
K[np.isinf(K)] = 0.0 # checked
tmp = np.transpose(K) * np.matmul(np.transpose(U), dLdV)
tmp = 0.5 * (tmp + np.transpose(tmp)) + np.diag(np.diag(dLdS))
dzdx = np.matmul(U, np.matmul(tmp, np.transpose(U))) # checked
grad[i, :, :] = dzdx
return torch.DoubleTensor(grad)
def rec_mat(input):
return RecFunction()(input)
def log_mat(input):
return LogFunction()(input)
def cal_riemann_grad_torch(X, U):
'''
:param X: the parameter
:param U: the eculidean gradient
:return: the riemann gradient
'''
#-- Matlab code
# XtU = X'*U;
# symXtU = 0.5 * (XtU + XtU');
# Up = U - X * symXtU;
#-- numpy code
# XtU = np.matmul(np.transpose(X), U)
# symXtU = 0.5*(XtU + np.transpose(XtU))
# Up = U - np.matmul(X, symXtU)
XtU = torch.matmul(torch.transpose(X, 0, 1), U)
symXtU = 0.5*(XtU + torch.transpose(XtU, 0, 1))
Up = U - torch.matmul(X, symXtU)
return Up
def cal_retraction_torch(X, rU, t):
"""
:param X: the parameter
:param rU: the riemann gradient
:param t: the learning rate
:return: the retraction:
"""
# matlab code
# Y = X + t * U;
# [Q, R] = qr(Y, 0);
# Y = Q * diag(sign(diag(R)));
# python code
# Y = X - t*rU
# Q, R = np.linalg.qr(Y, mode='reduced')
# sR = np.diag(np.sign(np.diag(R)))
# Y = np.matmul(Q, sR)
Y = X - t*rU
return Y
def update_para_riemann(X, U, t):
Up = cal_riemann_grad(X, U)
new_X = cal_retraction(X, Up, t)
return new_X
def cal_riemann_grad(X, U):
'''
:param X: the parameter
:param U: the eculidean gradient
:return: the riemann gradient
'''
# XtU = X'*U;
# symXtU = 0.5 * (XtU + XtU');
# Up = U - X * symXtU;
XtU = np.matmul(np.transpose(X), U)
symXtU = 0.5*(XtU + np.transpose(XtU))
Up = U - np.matmul(X, symXtU)
return Up
def cal_retraction(X, rU, t):
"""
:param X: the parameter
:param rU: the riemann gradient
:param t: the learning rate
:return: the retraction:
"""
# Y = X + t * U;
# [Q, R] = qr(Y, 0);
# Y = Q * diag(sign(diag(R)));
Y = X - t*rU
Q, R = np.linalg.qr(Y, mode='reduced')
sR = np.diag(np.sign(np.diag(R)))
Y = np.matmul(Q, sR)
return Y