-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
2441 lines (1140 loc) · 45 KB
/
functions.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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import re
import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
import importlib
import copy
import argparse
from torchvision import transforms, datasets
from matplotlib import pyplot as plt
import torch.nn.functional as F
from scipy.sparse.linalg import LinearOperator
from scipy.sparse.linalg import eigsh
from torch.autograd import Variable, grad
from numpy.linalg import eig as eig
from torch.distributions.multivariate_normal import MultivariateNormal
from utils import *
from models.fc import Network
import scipy
from scipy.linalg import eigh_tridiagonal
from dataset import create_dataset
from torch.optim.lr_scheduler import CosineAnnealingLR
from models.wide_resnet_1 import WideResNet
import time
from backpack import extend, backpack
from backpack.extensions import (
GGNMP,
HMP,
KFAC,
KFLR,
KFRA,
PCHMP,
BatchDiagGGNExact,
BatchDiagGGNMC,
BatchDiagHessian,
BatchGrad,
BatchL2Grad,
DiagGGNExact,
DiagGGNMC,
DiagHessian,
SumGradSquared,
Variance,
)
# mode = 'none'
# 'train': train and save models
# 'lanczo': use lanczo method to calculate the eigen spectrum of hessian.
# 'scipy': use scipy.sparse.linalg.eigsh to calculate the eigen spectrum of fisher
# 'fisher': eigen spectrum of FIM
# 'trad': calculate full hessian then do eigen value decomposition
# 'eva_posterior': estimate the first term of PAC-Bayes bound (both for CE loss and for 0-1 loss) by sampling from the posterior calculated in bound_1.py.
def train(model, device, train_loader, criterion, optimizer, epoch):
sum_loss, sum_correct = 0, 0
model.train()
for i, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
output = model(data)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# def diff_norm(u_list, v_list):
# '''
# u_list, v_list: lists of tensors
# return: difference of u_list and v_list
# '''
# diff = []
# for (u, v) in zip(u_list, v_list):
# diff.append(u-v)
# diff_norm = norm_2_list(diff)
# return(diff_norm)
def train_decay(model, model_init, decay, device, train_loader, criterion, optimizer, epoch):
sum_loss, sum_correct = 0, 0
model.train()
for i, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
output = model(data)
loss = criterion(output, target)
diff = diff_norm(list(model.parameters()), list(model_init.parameters()))
loss = loss + decay * diff**2
optimizer.zero_grad()
loss.backward()
optimizer.step()
print((diff**2).item())
def train_LBFGS(model, device, train_loader, criterion, optimizer, epoch):
model.train()
for i, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
def closure():
output = model(data)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
return loss
optimizer.step(closure)
def val(model, device, val_loader, criterion):
sum_loss, sum_correct = 0, 0
model.eval()
# with torch.no_grad():
for i, (data, target) in enumerate(val_loader):
data, target = data.to(device), target.to(device)
output = model(data)
# print(output)
pred = output.max(1)[1]
sum_correct += pred.eq(target).sum().item()
sum_loss += len(data) * criterion(output, target).item()
return 1 - (sum_correct / len(val_loader.dataset)), sum_loss / len(val_loader.dataset)
def val_grad(model, device, val_loader, criterion):
sum_loss, sum_correct = 0, 0
margin = torch.tensor([]).to(device)
model.eval()
for i, (data, target) in enumerate(val_loader):
data, target = data.to(device), target.to(device)
output = model(data)
pred = output.max(1)[1]
sum_loss += len(data) * criterion(output, target)
return sum_loss / len(val_loader.dataset)
def KLdiv(pbar,p):
return pbar * np.log(pbar/p) + (1-pbar) * np.log((1-pbar)/(1-p))
def KLdiv_prime(pbar,p):
return (1-pbar)/(1-p) - pbar/p
def Newt(p,q,c):
newp = p - (KLdiv(q,p) - c)/KLdiv_prime(q,p)
return newp
def approximate_BPAC_bound(train_accur, B_init, niter=5):
'''
train_accur : training accuracy
B_init: the second term of pac-bayes bound
return: approximated pac bayes bound using inverse of kl
eg: err = approximate_BPAC_bound(0.9716, 0.2292)
'''
B_RE = 2* B_init **2
A = 1-train_accur
B_next = B_init+A
if B_next>1.0:
return 1.0
for i in range(niter):
B_next = Newt(B_next,A,B_RE)
return B_next
def FIM(model, criterion, loader, num_params, device):
'''
empirical fisher using the data in loader
'''
grad_all = torch.empty((len(loader), num_params))
for i, (data, target) in enumerate(loader):
data, target = data.to(device), target.to(device)
output = model(data)
loss = criterion(output, target)
loss.backward()
grad_list = []
for param in model.parameters():
m = param.grad.clone().detach()
m = torch.reshape(m, (-1,))
grad_list.append(m)
for param in model.parameters():
param.grad.data.zero_()
grad = torch.cat(grad_list)
grad_all[i] = grad
# print(grad_all.shape)
# print(len(loader))
FIM = (grad_all@grad_all.T)/len(loader)
L, _ = torch.eig(FIM)
return FIM, L
def FIM2(model, criterion, loader, device, k):
'''
calculates the empirical fisher using the data in loader
model should be trained, fisher is calculated at the param in model.
k: number of eigen values
loader: the data loader used for FIM calculation, should have batch size 1, use train_loader_FIM. Use 'cpu if the model is large'
return: torch.tensor of FIM (num_data, num_data), L (k, ), v (num_params, u)
'''
model = model.to(device)
criterion = criterion.to(device)
num_params = sum(param.numel() for param in model.parameters())
grad_all = torch.empty((len(loader), num_params)).to(device)
# check this
model.eval()
for i, (data, target) in enumerate(loader):
# print(i)
data, target = data.to(device), target.to(device)
output = model(data)
loss = criterion(output, target)
loss.backward()
grad_list = []
for param in model.parameters():
m = param.grad.clone().detach()
m = torch.reshape(m, (-1,))
grad_list.append(m)
for param in model.parameters():
param.grad.data.zero_()
grad = torch.cat(grad_list)
grad_all[i] = grad
FIM = (grad_all@grad_all.T)/len(loader)
FIM = FIM.cpu().detach().numpy()
L, v = scipy.linalg.eigh(FIM, driver = 'evx', subset_by_index = [len(loader)-k, len(loader)-1])
L = torch.tensor(L)
v = torch.tensor(v)
u = (grad_all.T / np.sqrt(len(loader))) @ v
u = u * torch.sqrt(1/L)
idx = list(np.flip(L.numpy().argsort()))
L = L[idx]
u = (u.T[idx]).T
return FIM, L, u
def FIM_true(model, criterion, loader, device, k):
'''
calculates the true fisher using the data in loader
model should be trained, fisher is calculated at the param in model.
k: number of eigen values
loader: the data loader used for FIM calculation, should have batch size 1, use train_loader_FIM. Use 'cpu if the model is large'
return: torch.tensor of FIM (num_data, num_data), L (k, ), v (num_params, u)
'''
model = model.to(device)
criterion = criterion.to(device)
num_params = sum(param.numel() for param in model.parameters())
grad_all = torch.empty((len(loader), num_params)).to(device)
# check this
model.eval()
for i, (data, target) in enumerate(loader):
# print(i)
data, target = data.to(device), target.to(device)
output = model(data)
pr = F.softmax(output, dim=1)
y = torch.multinomial(pr, num_samples=1)
y = y.reshape(target.shape)
loss = criterion(output, y)
loss.backward()
grad_list = []
for param in model.parameters():
m = param.grad.clone().detach()
m = torch.reshape(m, (-1,))
grad_list.append(m)
for param in model.parameters():
param.grad.data.zero_()
grad = torch.cat(grad_list)
grad_all[i] = grad
FIM = (grad_all@grad_all.T)/len(loader)
FIM = FIM.cpu().detach().numpy()
# FIM = (FIM + FIM.T) / 2
L, v = scipy.linalg.eigh(FIM, driver = 'evx', subset_by_index = [len(loader)-k, len(loader)-1])
L = torch.tensor(L)
v = torch.tensor(v)
u = (grad_all.T / np.sqrt(len(loader))) @ v
u = u * torch.sqrt(1/L)
idx = list(np.flip(L.numpy().argsort()))
L = L[idx]
u = (u.T[idx]).T
return FIM, L, u
def logit_jacobian(model, cl, criterion, loader, device, k):
'''
calculates the logit jacobian of a certain class cl
logit jacobian is calculated at the param in model.
k: number of eigen values
loader: the data loader used for FIM calculation, should have batch size 1, use train_loader_FIM. Use 'cpu if the model is large'
return: torch.tensor of FIM (num_data, num_data), L (k, ), v (num_params, u)
'''
model = model.to(device)
criterion = criterion.to(device)
num_params = sum(param.numel() for param in model.parameters())
grad_all = torch.empty((len(loader), num_params)).to(device)
# check this
model.eval()
for i, (data, target) in enumerate(loader):
# print(i)
data, target = data.to(device), target.to(device)
output = model(data)
logit = output[0, cl]
logit.backward()
grad_list = []
for param in model.parameters():
m = param.grad.clone().detach()
m = torch.reshape(m, (-1,))
grad_list.append(m)
for param in model.parameters():
param.grad.data.zero_()
grad = torch.cat(grad_list)
grad_all[i] = grad
FIM = (grad_all@grad_all.T)/len(loader)
FIM = FIM.cpu().detach().numpy()
L, v = scipy.linalg.eigh(FIM, driver = 'evx', subset_by_index = [len(loader)-k, len(loader)-1])
L = torch.tensor(L)
v = torch.tensor(v)
u = (grad_all.T / np.sqrt(len(loader))) @ v
u = u * torch.sqrt(1/L)
idx = list(np.flip(L.numpy().argsort()))
L = L[idx]
u = (u.T[idx]).T
return FIM, L, u
def FIM_kfac(model, loader, device, mc, mode = "kfra", empirical = True):
model_kf = model.classifier.to(device)
criterion1 = nn.CrossEntropyLoss().to(device)
for (p1, p2) in zip(model_kf.parameters(), model.parameters()):
p1.data = p2.data
criterion1 = extend(criterion1)
model_kf = extend(model_kf)
sum_loss = 0
for data, targets in loader:
data, targets = data.to(device), targets.to(device)
data = data.view(data.size(0), -1)
output = model_kf(data)
if empirical == True:
loss = criterion1(output, targets)
else:
pr = F.softmax(output, dim=1)
y = torch.multinomial(pr, num_samples=1)
y = y.reshape(targets.shape)
loss = criterion1(output, y)
sum_loss += loss
with backpack(KFAC(mc_samples=mc), KFLR(), KFRA()):
sum_loss.backward()
kfac_list = []
for n, p in model_kf.named_parameters():
d = dict({"kfac":p.kfac, "kflr":p.kflr, "kfra":p.kfra})
kfac_list.append(d[mode])
return kfac_list
def FIM2x(model, criterion, loader, device):
'''
calculates the empirical fisher using the data in loader
model should be trained, fisher is calculated at the param in model.
k: number of eigen values
loader: the data loader used for FIM calculation, should have batch size 1, use train_loader_FIM. Use 'cpu if the model is large'
return: torch.tensor of FIM (num_data, num_data), L (k, ), v (num_params, u)
'''
model = model.to(device)
criterion = criterion.to(device)
num_params = sum(param.numel() for param in model.parameters())
grad_all = torch.empty((len(loader), num_params)).to(device)
# check this
model.eval()
for i, (data, target) in enumerate(loader):
# print(i)
data, target = data.to(device), target.to(device)
output = model(data)
loss = criterion(output, target)
loss.backward()
grad_list = []
for param in model.parameters():
m = param.grad.clone().detach()
m = torch.reshape(m, (-1,))
grad_list.append(m)
for param in model.parameters():
param.grad.data.zero_()
grad = torch.cat(grad_list)
grad_all[i] = grad
FIM = (grad_all@grad_all.T)/len(loader)
FIM = FIM.cpu().detach().numpy()
L = np.linalg.eigvalsh(FIM)
L = L[::-1]
return L
def FIM_truex(model, criterion, loader, device):
'''
calculates the true fisher using the data in loader
model should be trained, fisher is calculated at the param in model.
k: number of eigen values
loader: the data loader used for FIM calculation, should have batch size 1, use train_loader_FIM. Use 'cpu if the model is large'
return: torch.tensor of FIM (num_data, num_data), L (k, ), v (num_params, u)
'''
model = model.to(device)
criterion = criterion.to(device)
num_params = sum(param.numel() for param in model.parameters())
grad_all = torch.empty((len(loader), num_params)).to(device)
# check this
model.eval()
for i, (data, target) in enumerate(loader):
# print(i)
data, target = data.to(device), target.to(device)
output = model(data)
pr = F.softmax(output, dim=1)
y = torch.multinomial(pr, num_samples=1)
y = y.reshape(target.shape)
loss = criterion(output, y)
loss.backward()
grad_list = []
for param in model.parameters():
m = param.grad.clone().detach()
m = torch.reshape(m, (-1,))
grad_list.append(m)
for param in model.parameters():
param.grad.data.zero_()
grad = torch.cat(grad_list)
grad_all[i] = grad
FIM = (grad_all@grad_all.T)/len(loader)
FIM = FIM.cpu().detach().numpy()
L = np.linalg.eigvalsh(FIM)
L = L[::-1]
return L
def logit_jacobianx(model, cl, criterion, loader, device):
'''
calculates the logit jacobian of a certain class cl
logit jacobian is calculated at the param in model.
k: number of eigen values
loader: the data loader used for FIM calculation, should have batch size 1, use train_loader_FIM. Use 'cpu if the model is large'
return: torch.tensor of FIM (num_data, num_data), L (k, ), v (num_params, u)
'''
model = model.to(device)
criterion = criterion.to(device)
num_params = sum(param.numel() for param in model.parameters())
grad_all = torch.empty((len(loader), num_params)).to(device)
# check this
model.eval()
for i, (data, target) in enumerate(loader):
# print(i)
data, target = data.to(device), target.to(device)
output = model(data)
logit = output[0, cl]
logit.backward()
grad_list = []
for param in model.parameters():
m = param.grad.clone().detach()
m = torch.reshape(m, (-1,))
grad_list.append(m)
for param in model.parameters():
param.grad.data.zero_()
grad = torch.cat(grad_list)
grad_all[i] = grad
FIM = (grad_all@grad_all.T)/len(loader)
FIM = FIM.cpu().detach().numpy()
L = np.linalg.eigvalsh(FIM)
L = L[::-1]
return L
def eigspace_FIM_kron(kfac_list):
eigspace_list =[]
eigval_list = []
for kfac in kfac_list:
if len(kfac) == 2:
outmat, inmat = kfac
outmat = (outmat + outmat.T) / 2
inmat = (inmat + inmat.T) / 2
outmat, inmat = outmat.detach().cpu(), inmat.detach().cpu()
eo, vo = np.linalg.eig(outmat)
ei, vi = np.linalg.eig(inmat)
eo, vo = torch.tensor(np.real(eo)), torch.tensor(np.real(vo))
ei, vi = torch.tensor(np.real(ei)), torch.tensor(np.real(vi))
# e = (torch.kron(eo.contiguous(), ei.contiguous())).reshape(len(outmat), len(inmat))
eigspace_list.append((vo, vi))
eigval_list.append((eo, ei))
if len(kfac) == 1:
mat = kfac[0]
mat = (mat + mat.T) / 2
mat = mat.detach().cpu()
e, v = np.linalg.eig(mat)
e, v = torch.tensor(np.real(e)), torch.tensor(np.real(v))
eigspace_list.append((v,))
eigval_list.append((e,))
return eigspace_list, eigval_list
def trans_eigval(eigval_list):
eigval_true_list = []
for fac in eigval_list:
if len(fac) == 2:
eigval_true = torch.outer(fac[0], fac[1])
if len(fac) == 1:
eigval_true = fac[0]
eigval_true_list.append(eigval_true)
return eigval_true_list
def kfac_top_eigvec(kfac_list, model, k):
num_params = sum(p.numel() for p in model.parameters())
eigspace_list, eigval_list = eigspace_FIM_kron(kfac_list)
eigval_true_list = trans_eigval(eigval_list)
tag1 = list_to_vec([torch.ones(p.shape)*i for i, p in enumerate(model.parameters())])
tag2 = list_to_vec([torch.arange(p.numel()) for p in model.parameters()])
eigval = list_to_vec(eigval_true_list)
idx = list(np.flip(eigval.numpy().argsort()))
eigval, tag1, tag2 = eigval[idx], tag1[idx], tag2[idx]
eig_vec_list = []
for i in range(k):
vec_list = [torch.zeros(p.shape) for p in model.parameters()]
pos_list, pos_vec = int(tag1[i]), int(tag2[i])
es = eigspace_list[pos_list]
if len(es) == 2:
vo, vi = es
p = list(model.parameters())[pos_list].detach().cpu()
h = torch.zeros(p.numel())
h[pos_vec] = 1
h = h.reshape(p.shape)
vec = vo@h@vi.T
if len(es) == 1:
v = es[0]
p = list(model.parameters())[pos_list].detach().cpu()
h = torch.zeros(p.numel())
h[pos_vec] = 1
h = h.reshape(p.shape)
vec = v@h
vec_list[pos_list].data = vec
eig_vec = list_to_vec(vec_list)
eig_vec = eig_vec.reshape(len(eig_vec), 1)
eig_vec_list.append(eig_vec)
eig_vec = torch.cat(eig_vec_list, dim=1)
eig_val = eigval[:k]
return eig_val, eig_vec
def diag_hess(model, loader, device):
model_kf = model.classifier.to(device)
criterion1 = nn.CrossEntropyLoss().to(device)
for (p1, p2) in zip(model_kf.parameters(), model.parameters()):
p1.data = p2.data
criterion1 = extend(criterion1)
model_kf = extend(model_kf)
sum_loss = 0
for data, targets in loader:
data, targets = data.to(device), targets.to(device)
data = data.view(data.size(0), -1)
output = model_kf(data)
sum_loss += criterion1(output, targets)
with backpack(DiagHessian()):
sum_loss.backward()
hess_diag_list = []
for p in model_kf.parameters():
hess_diag_list.append(p.diag_h)
return hess_diag_list
def overlap(A, B, k, device):
A, B = torch.tensor(A).to(device), torch.tensor(B).to(device)
over = torch.zeros(k).to(device)
for i in range(k):
print(i)
a = A[:, :i+1]
b = B[:, :i+1]
# print(a.shape)
overlap = torch.norm(a.T@b, p='fro')**2 / (i+1)
# print(overlap)
over[i] = overlap
return over.detach().cpu()
def proj(vec, spa, k, device):
vec = torch.tensor(vec).to(device)
spa = torch.tensor(spa).to(device)
frac_all = torch.zeros(k).to(device)
for i in range(k):
i=i+1
print(i)
normp = torch.norm(spa[:, :i].T@vec, p=2)**2
norm = torch.norm(vec, p=2)**2
frac = normp / norm
frac_all[i-1] = frac
return frac_all
def proj_single(vec, spa, k, device):
vec = torch.tensor(vec).to(device)
spa = torch.tensor(spa).to(device)
frac_all = torch.zeros(k).to(device)
for i in range(k):
print(i)
normp = torch.sum(spa[:, i]*vec)**2
norm = torch.norm(vec, p=2)**2
frac = normp / norm
frac_all[i] = frac
return frac_all
def fnc_2(model, loader, param_list, criterion, device):
'''
param_list: list of tensors of parameters in model
return: averaged loss of model
'''
sum_loss = 0
for i, (data, target) in enumerate(loader):
data, target = data.to(device), target.to(device)
output = data.view(data.size(0), -1)
output = F.linear(output, param_list[0], param_list[1])
output = F.relu(output)
output = F.linear(output, param_list[2], param_list[3])
loss = criterion(output, target)
sum_loss += len(data) * loss