-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpair_influence.py
1328 lines (1124 loc) · 51.8 KB
/
pair_influence.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 random
import pickle
import math
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
#from tqdm.notebook import tqdm
from tqdm import tqdm
import scipy
import sklearn
sns.set(color_codes=True)
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, Subset
import torch.optim as optim
from torch import autograd
import sys
# try:
# from apex.parallel import DistributedDataParallel as DDP
# from apex.fp16_utils import *
# from apex import amp, optimizers
# from apex.multi_tensor_apply import multi_tensor_applier
# except ImportError:
# raise ImportError("Please install apex from https://www.github.com/nvidia/apex to run this example.")
# my influence "package"
#from influence.influence_lib import get_influence_on_test_loss
#from influence.influence_lib import params_to_list
#from influence.utils import save, load
#from config_my import NR_EPOCHS, DAMPING, TRAIN_DIR, MODEL_NAME, DATA_PATH
import time
from scipy.optimize import fmin_ncg
import cProfile
import os.path
from collections import defaultdict
from model.RankNet import *
from model.load_mslr import get_time, NaverLoader, MQ2008semiLoader, NaverClickLoader
from model.metrics import NDCG
from model.utils import (
eval_cross_entropy_loss,
eval_ndcg_at_k,
get_device,
get_ckptdir,
init_weights,
load_train_vali_data,
get_args_parser,
save_to_ckpt,
)
np.random.seed(42)
USE_AMP = False
def save(model, path):
try:
torch.save(model.module.state_dict(), path)
except AttributeError:
torch.save(model.state_dict(), path)
def load(ModelClass, path, **kwargs):
model = ModelClass(**kwargs)
model.load_state_dict(torch.load(path))
return model
# load dataset
def load_naver_data(drop_high_rel=False):
train_loader = NaverLoader(data_type='train', drop_high_rel=drop_high_rel)
valid_loader = NaverLoader(data_type='valid', drop_high_rel=drop_high_rel)
test_loader = NaverLoader(data_type='test', drop_high_rel=drop_high_rel)
return train_loader, train_loader.df, valid_loader, valid_loader.df, test_loader, test_loader.df
def load_mq2008semi_data(device):
train_loader = MQ2008semiLoader(data_type='train', device=device)
valid_loader = MQ2008semiLoader(data_type='vali', device=device)
test_loader = MQ2008semiLoader(data_type='test', device=device)
return train_loader, train_loader.df, valid_loader, valid_loader.df, test_loader, test_loader.df
def load_naver_click_data(device):
train_loader = NaverClickLoader(data_type='train', device=device)
valid_loader = NaverClickLoader(data_type='valid', device=device)
test_loader = NaverClickLoader(data_type='test', device=device)
return train_loader, train_loader.df, valid_loader, valid_loader.df, test_loader, test_loader.df
def load_data(standardize=True, device=1, dataset_type='mslr-web30k', drop_high_rel=False):
if dataset_type in ['mslr-web30k', 'mslr-web10k']:
data_fold = 'Fold1'
data_dir = 'model/data/'+dataset_type+'/'
pkl_name = '/standardized.pkl'
if device == 0:
pkl_name = '/standardized_cuda0.pkl'
if standardize and os.path.exists(data_dir+data_fold+pkl_name):
with open(data_dir+data_fold+pkl_name, 'rb') as fp:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = pickle.load(fp)
else:
train_loader, df_train, valid_loader, df_valid = load_train_vali_data(data_fold, small_dataset=False,
data_type=dataset_type)
_, _, test_loader, df_test = load_train_vali_data(data_fold, small_dataset=True, data_type=dataset_type)
if standardize:
df_train, scaler = train_loader.train_scaler_and_transform()
df_valid = valid_loader.apply_scaler(scaler)
df_test = test_loader.apply_scaler(scaler)
with open(data_dir+data_fold+pkl_name, 'wb') as fp:
pickle.dump((train_loader, df_train, valid_loader, df_valid, test_loader, df_test), fp, pickle.HIGHEST_PROTOCOL)
elif dataset_type == 'naver':
data_fold = ''
data_dir = 'model/data/naver/'
if drop_high_rel:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = load_naver_data(drop_high_rel)
else:
pkl_name = '/cuda1.pkl'
if device == 0:
pkl_name = '/cuda0.pkl'
if os.path.exists(data_dir+data_fold+pkl_name):
with open(data_dir+data_fold+pkl_name, 'rb') as fp:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = pickle.load(fp)
else:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = load_naver_data()
with open(data_dir+data_fold+pkl_name, 'wb') as fp:
pickle.dump((train_loader, df_train, valid_loader, df_valid, test_loader, df_test),
fp, pickle.HIGHEST_PROTOCOL)
elif dataset_type == 'mq2008-semi':
data_fold = ''
data_dir = 'model/data/MQ2008-semi/'
pkl_name = '/cuda1.pkl'
if device == 0:
pkl_name = '/cuda0.pkl'
if os.path.exists(data_dir+data_fold+pkl_name):
with open(data_dir+data_fold+pkl_name, 'rb') as fp:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = pickle.load(fp)
else:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = load_mq2008semi_data(device)
with open(data_dir+data_fold+pkl_name, 'wb') as fp:
pickle.dump((train_loader, df_train, valid_loader, df_valid, test_loader, df_test),
fp, pickle.HIGHEST_PROTOCOL)
elif dataset_type == 'naver_click':
data_fold = ''
data_dir = 'model/data/naver_click/'
pkl_name = '/cuda1.pkl'
if device == 0:
pkl_name = '/cuda0.pkl'
if os.path.exists(data_dir+data_fold+pkl_name):
with open(data_dir+data_fold+pkl_name, 'rb') as fp:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = pickle.load(fp)
else:
train_loader, df_train, valid_loader, df_valid, test_loader, df_test = load_naver_click_data(device)
with open(data_dir+data_fold+pkl_name, 'wb') as fp:
pickle.dump((train_loader, df_train, valid_loader, df_valid, test_loader, df_test),
fp, pickle.HIGHEST_PROTOCOL)
else:
raise NotImplementedError
return train_loader, df_train, valid_loader, df_valid, test_loader, df_test
args = {}
args["start_epoch"] = 0
args['additional_epoch'] = 50
args['lr'] = 0.01
args['optim'] = 'adam'
args['train_algo'] = SUM_SESSION
args['double_precision'] = False
args['standardize'] = True
args['small_dataset'] = False
args['debug'] = False#True
args['output_dir'] = '/model/ranknet/ranking_output/'
def train_rank_net(
train_loader, valid_loader, df_valid,
start_epoch=0, additional_epoch=100, lr=0.0001, optim="adam",
train_algo=SUM_SESSION,
double_precision=False, standardize=False,
small_dataset=False, debug=False,
output_dir="/tmp/ranking_output/",
opt=None,
log=True,
device=0,
seed=7777):
"""
:param start_epoch: int
:param additional_epoch: int
:param lr: float
:param optim: str
:param train_algo: str
:param double_precision: boolean
:param standardize: boolean
:param small_dataset: boolean
:param debug: boolean
:return:
"""
print("start_epoch:{}, additional_epoch:{}, lr:{}".format(start_epoch, additional_epoch, lr))
writer = SummaryWriter(output_dir)
precision = torch.float64 if double_precision else torch.float32
# get training and validation data:
data_fold = 'Fold1'
net, _, ckptfile = get_train_inference_net(
train_algo, train_loader.num_features, start_epoch, double_precision, opt, log
)
net.cuda(device)
net_inference = net
torch.backends.cudnn.benchmark=False
# initialize to make training faster
clear_seed_all(seed)
net.apply(init_weights)
if train_loader.dataset_type == 'naver':
lr = 1e-2
wd = 0.
elif train_loader.dataset_type == 'mq2008-semi':
lr = 5e-3
wd = 0.
elif train_loader.dataset_type == 'naver_click':
lr = 1e-2
wd = 0.
else:
lr = 1e-2
wd = 0.
if optim == "adam":
optimizer = torch.optim.Adam(net.parameters(), lr=lr, weight_decay=wd)
elif optim == "sgd":
optimizer = torch.optim.SGD(net.parameters(), lr=lr, momentum=0.9)
else:
raise ValueError("Optimization method {} not implemented".format(optim))
print(optimizer)
# if USE_AMP:
# net, optimizer = amp.initialize(net, optimizer)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.75)
loss_func = None
if train_algo == BASELINE:
loss_func = torch.nn.BCELoss()
loss_func.cuda()
losses = []
best_ndcg_result = 0.
best_epoch = 0
for i in range(start_epoch, start_epoch + additional_epoch):
scheduler.step()
net.zero_grad()
net.train()
if train_algo == BASELINE:
epoch_loss = baseline_pairwise_training_loop(
i, net, loss_func, optimizer,
train_loader,
precision=precision, device='cuda:'+str(device), debug=debug
)
elif train_algo in [SUM_SESSION, ACC_GRADIENT]:
epoch_loss = factorized_training_loop(
i, net, None, optimizer,
train_loader,
training_algo=train_algo,
precision=precision, device='cuda:'+str(device), debug=debug
)
losses.append(epoch_loss)
print('=' * 20 + '\n', get_time(), 'Epoch{}, loss : {}'.format(i, losses[-1]), '\n' + '=' * 20)
# save to checkpoint every 5 step, and run eval
if i % 5 == 0 and i != start_epoch:
save_to_ckpt(ckptfile, i, net, optimizer, scheduler)
net_inference.load_state_dict(net.state_dict())
ndcg_result = eval_model(net_inference, device, df_valid, valid_loader, i, writer)
if best_ndcg_result < ndcg_result[10]:
best_ndcg_result = ndcg_result[10]
best_epoch = i
# save the last ckpt
save_to_ckpt(ckptfile, start_epoch + additional_epoch, net, optimizer, scheduler)
# final evaluation
net_inference.load_state_dict(net.state_dict())
ndcg_result = eval_model(
net_inference, device, df_valid, valid_loader, start_epoch + additional_epoch, writer)
if best_ndcg_result < ndcg_result[10]:
best_ndcg_result = ndcg_result[10]
best_epoch = start_epoch + additional_epoch
# save the final model
torch.save(net.state_dict(), ckptfile)
print(
get_time(),
"finish training " + ", ".join(
["NDCG@{}: {:.5f}".format(k, ndcg_result[k]) for k in ndcg_result]
),
'\n\n'
)
return best_ndcg_result, best_epoch
def eval_model(inference_model, device, df_valid, valid_loader, epoch, writer=None):
"""
:param torch.nn.Module inference_model:
:param str device: cpu or cuda:id
:param pandas.DataFrame df_valid:
:param valid_loader:
:param int epoch:
:return:
"""
inference_model.eval() # Set model to evaluate mode
batch_size = 1000000
with torch.no_grad():
#eval_cross_entropy_loss(inference_model, device, valid_loader, epoch, writer)
ndcg_result, _ = eval_ndcg_at_k(
inference_model, device, df_valid, valid_loader, [10, 30], batch_size)
return ndcg_result
def eval_ndcg_at_k(inference_model, device, df_valid, valid_loader, k_list=[5, 10, 30], batch_size=1000000, phase="Eval"):
ndcg_metrics = {k: NDCG(k) for k in k_list}
qids, rels, scores = [], [], []
inference_model.eval()
session_ndcgs = defaultdict(list)
with torch.no_grad():
for i, (X, Y) in enumerate(valid_loader.generate_batch_per_query()):
if X is None or X.size()[0] < 2:
continue
y_tensor = inference_model.forward(X.to(torch.float32))
score = y_tensor.cpu().numpy().squeeze()
rel = Y.cpu().numpy()
if valid_loader.dataset_type in ['naver'] or \
(valid_loader.dataset_type == 'naver_click' and valid_loader.data_type == 'test'):
rel = rel + 1
result_qid = sorted([(s, r) for s, r in zip(score, rel)], key=lambda x: x[0], reverse=True)
rel_rank = [s[1] for s in result_qid]
for k, ndcg in ndcg_metrics.items():
if ndcg.maxDCG(rel_rank) == 0:
continue
ndcg_k = ndcg.evaluate(rel_rank)
if not np.isnan(ndcg_k):
session_ndcgs[k].append(ndcg_k)
scores.append(score)
rels.append(rel)
ndcg_result = {k: np.mean(session_ndcgs[k]) for k in k_list}
ndcg_result_print = ", ".join(["NDCG@{}: {:.5f}".format(k, ndcg_result[k]) for k in k_list])
print(get_time(), "{} Phase evaluate {}".format(phase, ndcg_result_print))
return ndcg_result, (scores, rels)
def get_train_inference_net(train_algo, num_features, start_epoch, double_precision, opt=None, log=True):
ranknet_structure = [num_features, 64, 16]
if train_algo == BASELINE:
net = RankNetPairs(ranknet_structure, double_precision)
net_inference = RankNet(ranknet_structure) # inference always use single precision
ckptfile = get_ckptdir('ranknet', ranknet_structure, opt=opt, log=log)
elif train_algo in [SUM_SESSION, ACC_GRADIENT]:
net = RankNet(ranknet_structure, double_precision)
net_inference = net
ckptfile = get_ckptdir('ranknet-factorize', ranknet_structure, opt=opt, log=log)
else:
raise ValueError("train algo {} not implemented".format(train_algo))
if start_epoch != 0:
load_from_ckpt(ckptfile, start_epoch, net, log)
return net, net_inference, ckptfile
def get_ckptdir(net_name, net_structure, sigma=None, opt=None, log=True):
net_name = '{}-{}'.format(net_name, '-'.join([str(x) for x in net_structure]))
if sigma:
net_name += '-scale-{}'.format(sigma)
ckptdir = os.path.join('model', 'ckptdir')
if opt is not None:
ckptdir = os.path.join(ckptdir, opt)
if not os.path.exists(ckptdir):
os.makedirs(ckptdir)
ckptfile = os.path.join(ckptdir, net_name)
if log:
print("checkpoint dir:", ckptfile)
return ckptfile
# load model with checkpoint
def get_model(train_loader, ckpt_epoch=50, train_algo=SUM_SESSION, double_precision=False, opt=None, device=0):
net, net_inference, ckptfile = get_train_inference_net(
train_algo, train_loader.num_features, ckpt_epoch, double_precision, opt
)
# device = "cuda:1"#get_device('RankNet')
# net.to(device)
# net_inference.to(device)
net.cuda(device)
return net, net
def clear_mislabel(data_loader):
data_loader.mislabeled_on = False
data_loader.mislabeled_dict = None
def build_mislabeled_dataset(data_loader, error_query_ratio, error_doc_ratio, error_type):
clear_mislabel(data_loader)
assert 0 <= error_query_ratio and error_query_ratio <= 100
# doc ratio is % based
assert 0 <= error_doc_ratio and error_doc_ratio <= 100
assert error_type in ['RAND', 'FN', 'FP', 'CE', 'CE2', 'RAND2', 'SW', 'SWO', \
'CE3', 'SW2', 'SW3', 'CE2v3pn', 'CE2v3np', 'SWDIST', 'SWDIST2']
if error_type == 'SWDIST2':
error_type = 'SWDIST'
if error_query_ratio == 0 or error_doc_ratio == 0:
print('Error query ratio:', str(error_query_ratio)+'%',\
'\tError doc ratio:', str(error_doc_ratio)+'%')
return
else:
print('Error query ratio:', str(error_query_ratio)+'%',\
'\tError doc ratio:', str(error_doc_ratio)+'%',\
'\tError type:', error_type)
data_loader.get_qids()
data_loader.get_cached_batch_per_query(data_loader.df, data_loader.qids)
index_list = list(range(data_loader.num_sessions))
clear_seed_all()
random.shuffle(index_list)
#if error_type == 'CE2' or error_type == 'SW2':
if error_type == 'SW2':
error_query_index = []
for i in index_list:
if 3 in data_loader.Y[i] or 4 in data_loader.Y[i]:
error_query_index.append(i)
error_query_index = error_query_index[:int(data_loader.num_sessions * error_query_ratio // 100)]
elif error_type == 'CE2' or error_type == 'SW3' or error_type == 'CE2v3pn' or error_type == 'CE2v3np':
error_query_index = []
for i in index_list:
if 4 in data_loader.Y[i]:
error_query_index.append(i)
error_query_index = error_query_index[:int(data_loader.num_sessions * error_query_ratio // 100)]
else:
error_query_index = index_list[:int(data_loader.num_sessions * error_query_ratio // 100)]
if error_type == 'SWDIST':
distribution = [0, 0, 0, 0, 0]
for Y in data_loader.Y:
for i in range(5):
distribution[i] += (Y == i).nonzero().size()[0]
distribution = np.array(distribution, np.double)
print('distribution:', [round(d/distribution.sum(), 4) for d in distribution])
else:
distribution = None
#qids = [full_qids[i] for i in error_query_index]
mislabeled_dict = {}
if error_type == 'RAND2':
error_query_index = tqdm(error_query_index)
for i in error_query_index:
mislabeled_dict[str(i)] = build_error(data_loader.Y[i], error_doc_ratio, error_type, distribution)
data_loader.build_mislabeled(mislabeled_dict, mislabeled_type=error_type)
def build_error(Y, error_doc_ratio, error_type, distribution=None):
if error_type == 'RAND2':
#relevance가 0이 아닌 pair를 shuffle하여 error_doc_ratio 만큼의 index를 저장
#TBD
rel_diff = Y.view(-1, 1) - Y.view(-1, 1).t()
mislabeled_rel_diff = rel_diff.clone()
non_neg_index_list = (rel_diff >= 0.).nonzero().data.tolist()
for self_rel in [[i, i] for i in range(Y.view(-1).size()[0])]:
non_neg_index_list.remove(self_rel)
#assert if all the document label is the same
assert len(non_neg_index_list) > 0
error_doc_num = max(len(non_neg_index_list) * error_doc_ratio // 100, 1)
random.shuffle(non_neg_index_list)
for i, j in non_neg_index_list[:error_doc_num]:
#+ => -
#- => +
assert mislabeled_rel_diff[i, j] == -mislabeled_rel_diff[j, i]
if rel_diff[i, j] == 0.:
cand = [-1., 1.]
mislabeled_rel_diff[i, j] = random.choice(cand)
mislabeled_rel_diff[j, i] = mislabeled_rel_diff[i, j] * -1.
elif rel_diff[i, j] > 0.:
cand = [-1., 0.]
mislabeled_rel_diff[i, j] = mislabeled_rel_diff[i, j] * random.choice(cand)
mislabeled_rel_diff[j, i] = mislabeled_rel_diff[i, j] * -1.
else:
raise NotImplementedError
return mislabeled_rel_diff
mislabeled_Y = Y.clone()
if error_type == 'RAND':
#original label이 아닌 무언가로 random하게 변화
original_label = [0, 1, 2, 3, 4]
elif error_type == 'FN':
#2,3,4 => 0,1
original_label = [2, 3, 4]
elif error_type == 'FP':
#0,1 => 2,3,4
original_label = [0, 1]
elif error_type == 'CE':
#0 => 4 / 4 => 0
original_label = [0, 4]
elif error_type == 'CE2':
#0 => 3, 4 / 3, 4 => 0
original_label = [3, 4]
neg_label = [0]
neg_index_list = [idx for idx in range(len(Y)) if Y[idx] in neg_label]
random.shuffle(neg_index_list)
elif error_type == 'CE3':
#0 => 2, 3, 4 / 2, 3, 4 => 0
original_label = [2, 3, 4]
neg_label = [0]
neg_index_list = [idx for idx in range(len(Y)) if Y[idx] in neg_label]
random.shuffle(neg_index_list)
elif error_type == 'SW' or error_type == 'SWO':
original_label = [2, 3, 4]
neg_label = [0, 1]
neg_index_list = [idx for idx in range(len(Y)) if Y[idx] in neg_label]
random.shuffle(neg_index_list)
elif error_type == 'SW2' or error_type == 'SW3':
original_label = [3, 4]
neg_label = [0, 1]
neg_index_list = [idx for idx in range(len(Y)) if Y[idx] in neg_label]
random.shuffle(neg_index_list)
elif error_type == 'CE2v3pn':
#3, 4 => 0
original_label = [3, 4]
elif error_type == 'CE2v3np':
#0 => 3, 4
original_label = [3, 4]
neg_label = [0]
neg_index_list = [idx for idx in range(len(Y)) if Y[idx] in neg_label]
random.shuffle(neg_index_list)
elif error_type == 'SWDIST':
#2, 3, 4 => 0, 1 / 0, 1 => 2, 3, 4 | train distribution
assert distribution is not None
original_label = [2, 3, 4]
neg_label = [0, 1]
neg_index_list = [idx for idx in range(len(Y)) if Y[idx] in neg_label]
random.shuffle(neg_index_list)
else:
raise NotImplementedError
index_list = [idx for idx in range(len(Y)) if Y[idx] in original_label]
#max(..., 0)이어야 하나..?
#query 쪽이 0%면 어차피 여기까지 안오긴 함
error_doc_num = max(len(index_list) * error_doc_ratio // 100, 1)
random.shuffle(index_list)
if error_type == 'SW' or error_type == 'SWO' or error_type == 'SW2' or error_type == 'SW3':
if error_type == 'SWO':
#4, 3, 2 순으로 Switch
ordered_index_list = []
for l in sorted(original_label, reverse=True):
ordered_index_list.extend([idx for idx in index_list if Y[idx] == l])
assert len(ordered_index_list) == len(index_list)
index_list = ordered_index_list
for i, (p_idx, n_idx) in enumerate(zip(index_list[:error_doc_num],
neg_index_list[:error_doc_num])):
assert Y[p_idx] in original_label
assert Y[n_idx] in neg_label
# 2, 3, 4 => 0, 1 / 0, 1 => 2, 3, 4 (Switch)
mislabeled_Y[p_idx] = Y[n_idx].item()
mislabeled_Y[n_idx] = Y[p_idx].item()
return mislabeled_Y
if error_type == 'SWDIST':
error_neg_doc_num = max(len(neg_index_list) * error_doc_ratio // 100, 1)
pos_distribution = np.array([distribution[2], distribution[3], distribution[4]])
pos_distribution = pos_distribution / pos_distribution.sum()
neg_distribution = np.array([distribution[0], distribution[1]])
neg_distribution = neg_distribution / neg_distribution.sum()
for idx in index_list[:error_doc_num]:
assert Y[idx] in original_label
mislabeled_Y[idx] = int(np.random.choice([0, 1], 1, p=neg_distribution)[0])
for idx in neg_index_list[:error_neg_doc_num]:
assert Y[idx] in neg_label
mislabeled_Y[idx] = int(np.random.choice([2, 3, 4], 1, p=pos_distribution)[0])
return mislabeled_Y
for idx in index_list[:error_doc_num]:
assert Y[idx] in original_label
if error_type == 'CE2v3np':
break
if error_type == 'RAND':
#original label이 아닌 무언가로 random하게 변화
cand = [0, 1, 2, 3, 4]
cand.remove(Y[idx])
elif error_type == 'FN':
#2,3,4 => 0,1
cand = [0, 1]
elif error_type == 'FP':
#0,1 => 2,3,4
cand = [2, 3, 4]
elif error_type == 'CE':
#0 => 4 / 4 => 0
if Y[idx] == 0:
cand = [4]
elif Y[idx] == 4:
cand = [0]
elif error_type == 'CE2':
#0 => 3, 4 / 3, 4 => 0
cand = [0]
elif error_type == 'CE3' or error_type == 'CE2v3pn':
#0 => 2, 3, 4 / 2, 3, 4 => 0
cand = [0]
mislabeled_Y[idx] = random.choice(cand)
if error_type == 'CE2' or error_type == 'CE3' or error_type == 'CE2v3np':
for i, idx in enumerate(neg_index_list[:error_doc_num]):
assert Y[idx] in neg_label
mislabeled_Y[idx] = Y[index_list[i]].item()
return mislabeled_Y
def get_lambda_grad(y_pred, Y, pairs, precision=torch.float32, sigma=1.0, ndcg_gain_in_train="exp2"):
# compute the rank order of each document
Y_list = Y.data.tolist()
ideal_dcg = NDCG(2**9, ndcg_gain_in_train)
N = 1.0 / ideal_dcg.maxDCG(Y_list)
Y = Y.to(precision)
rank_df = pd.DataFrame({"Y": Y_list, "doc": np.arange(Y.shape[0])})
rank_df = rank_df.sort_values("Y").reset_index(drop=True)
rank_order = rank_df.sort_values("doc").index.values + 1
device = y_pred.get_device()
with torch.no_grad():
pairs_score_diff = 1.0 + torch.exp(sigma * (y_pred - y_pred.t()))
rel_diff = Y - Y.t()
neg_pairs = (rel_diff < 0).type(precision)
Sij = pairs - neg_pairs
gain_diff = torch.pow(2.0, Y) - torch.pow(2.0, Y.t())
rank_order_tensor = torch.tensor(rank_order, dtype=precision, device=device).view(-1, 1)
decay_diff = 1.0 / torch.log2(rank_order_tensor + 1.0) - 1.0 / torch.log2(rank_order_tensor.t() + 1.0)
delta_ndcg = torch.abs(N * gain_diff * decay_diff)
lambda_update = sigma * (0.5 * (1 - Sij) - 1 / pairs_score_diff) * delta_ndcg
lambda_update = torch.sum(lambda_update, 1, keepdim=True)
assert lambda_update.shape == y_pred.shape
check_grad = torch.sum(lambda_update, (0, 1)).item()
if check_grad == float('inf') or np.isnan(check_grad):
import ipdb; ipdb.set_trace()
return lambda_update
def factorized_training_loop(
epoch, net, loss_func, optimizer,
train_loader, batch_size=200, sigma=1.0,
training_algo=SUM_SESSION,
precision=torch.float32, device="cpu",
debug=False,
LambdaRank=False
):
print(training_algo)
minibatch_loss = []
count, loss, total_pairs = 0, 0, 0
grad_batch, y_pred_batch = [], []
tmp_idx_order = []
for X, Y in train_loader.generate_batch_per_query(shuffle=True):
###############################
tmp_idx_order.append(train_loader.current_idx)
#continue
###############################
if X is None or X.shape[0] == 0:
continue
Y = Y.view(-1, 1)
rel_diff = Y - Y.t()
#Handling pairwise relevance mislabel
#TBD binary label will not be applied
if train_loader.mislabeled_type == 'RAND2' and train_loader.mislabeled_on \
and (train_loader.mislabeled_dict is not None) \
and (str(train_loader.current_idx) in train_loader.mislabeled_dict.keys()):
#print('RAND2 is working')
m_rel_diff = train_loader.mislabeled_dict[str(train_loader.current_idx)]
assert (rel_diff - m_rel_diff).nonzero().sum() > 0
rel_diff = m_rel_diff
#Handling document drop
if train_loader.current_idx in train_loader.drop_documents.keys():
for drop_doc_idx in train_loader.drop_documents[train_loader.current_idx]:
rel_diff[drop_doc_idx, :] = 0
rel_diff[:, drop_doc_idx] = 0
#Handling document drop
if train_loader.current_idx in train_loader.drop_pairs.keys():
for (drop_doc1, drop_doc2) in train_loader.drop_pairs[train_loader.current_idx]:
rel_diff[drop_doc1, drop_doc2] = 0
rel_diff[drop_doc2, drop_doc1] = 0
pairs = (rel_diff > 0).to(precision)
num_pairs = torch.sum(pairs, (0, 1))
# skip negative sessions, no relevant info:
if num_pairs == 0:
continue
X_tensor = X.to(precision)
y_pred = net(X_tensor)
if training_algo == SUM_SESSION:
#2020.05.07
if LambdaRank:
y_pred_batch.append(y_pred)
lambda_update = get_lambda_grad(y_pred, Y, pairs, precision=precision)
grad_batch.append(lambda_update)
#LambdaRank: DO SOMETHING
else:
C = criterion(y_pred, pairs)
loss += torch.sum(C)
else:
raise ValueError("training algo {} not implemented".format(training_algo))
total_pairs += num_pairs
count += 1
if count % batch_size == 0:
loss /= total_pairs
minibatch_loss.append(loss.item())
if debug:
print("Epoch {}, number of pairs {}, loss {}".format(epoch, total_pairs, loss.item()))
if training_algo == SUM_SESSION:
if USE_AMP:
pass
# with amp.scale_loss(loss, optimizer) as scaled_loss:
# scaled_loss.backward()
else:
if LambdaRank:
for grad, y_pred in zip(grad_batch, y_pred_batch):
y_pred.backward(grad / batch_size)
else:
loss.backward()
elif training_algo == ACC_GRADIENT:
for grad, y_pred in zip(grad_batch, y_pred_batch):
y_pred.backward(grad / batch_size)
if count % (4 * batch_size) and debug:
net.dump_param()
optimizer.step()
net.zero_grad()
loss, total_pairs = 0, 0 # loss used for sum_session
grad_batch, y_pred_batch = [], [] # grad_batch, y_pred_batch used for gradient_acc
#torch.cuda.empty_cache()
#print(tmp_idx_order[:10])
if total_pairs:
print('+' * 10, "End of batch, remaining pairs {}".format(total_pairs.item()))
loss /= total_pairs
minibatch_loss.append(loss.item())
if training_algo == SUM_SESSION:
if USE_AMP:
pass
# with amp.scale_loss(loss, optimizer) as scaled_loss:
# scaled_loss.backward()
else:
if LambdaRank:
for grad, y_pred in zip(grad_batch, y_pred_batch):
y_pred.backward(grad / batch_size)
else:
loss.backward()
else:
for grad, y_pred in zip(grad_batch, y_pred_batch):
y_pred.backward(grad / total_pairs)
if debug:
net.dump_param()
optimizer.step()
return np.mean(minibatch_loss)
#================================================================
#INFLUENCE FUNCTIONS
#================================================================
# 같은 query에 대한 모든 document pair loss를 반환
def get_prediction(X, Y, net, data_loader, precision=torch.float32):
if X is None or X.size()[0] == 0:
return None, None
#Handling pairwise relevance mislabel
#TBD binary label will not be applied
if data_loader.mislabeled_type == 'RAND2' and data_loader.mislabeled_on \
and (data_loader.mislabeled_dict is not None) \
and (str(data_loader.current_idx) in data_loader.mislabeled_dict.keys()):
rel_diff = data_loader.mislabeled_dict[str(data_loader.current_idx)]
else:
Y = Y.view(-1, 1)
rel_diff = Y - Y.t()
#del Y
if data_loader.current_idx in data_loader.drop_documents.keys():
for drop_doc_idx in data_loader.drop_documents[data_loader.current_idx]:
rel_diff[drop_doc_idx, :] = 0
rel_diff[:, drop_doc_idx] = 0
#Handling document drop
if data_loader.current_idx in data_loader.drop_pairs.keys():
for (drop_doc1, drop_doc2) in data_loader.drop_pairs[data_loader.current_idx]:
rel_diff[drop_doc1, drop_doc2] = 0
rel_diff[drop_doc2, drop_doc1] = 0
pos_pairs = (rel_diff > 0).to(precision)
num_pos_pairs = torch.sum(pos_pairs, (0, 1))
if num_pos_pairs == 0:
return None, None#, None
if num_pos_pairs == 0:
return None, None#, None
#neg_pairs = (rel_diff < 0).to(precision)
#num_pairs = 2 * num_pos_pairs # num pos pairs and neg pairs are always the same
#X_tensor = X.to(torch.float32)#torch.tensor(X, dtype=precision, device=device)
y_pred = net(X.to(precision))
#del X
#torch.cuda.empty_cache()
return y_pred, pos_pairs#, neg_pairs
def criterion(y_pred, pairs, sigma=1.0, precision=torch.float32):
damping = 1e-8
C = torch.log(1 + torch.exp(-sigma * torch.sigmoid(y_pred - y_pred.t())) + damping).to(precision)
loss = pairs * C
return loss
model_name = 'RankNet'
def get_loss(model, data_loader, criterion, indices, ij_index=None, bar=False, precision=torch.float32):
losses = []
if bar:
indices = tqdm(indices)
cnt = 0
for idx in indices:
cnt += 1
X, Y = data_loader.indexing_batch_per_query(idx)
y_pred, pairs = get_prediction(X, Y, model, data_loader, precision=precision)
if y_pred is None:
losses.append(torch.tensor([]).to(list(model.parameters())[0].get_device()))
continue
loss = criterion(y_pred, pairs, precision=precision)
del y_pred
if ij_index is not None:
_pairs = torch.zeros(pairs.size())
_pairs[ij_index] = pairs[ij_index]
pairs = _pairs
# 여기에 weighting 가능
# loss = loss * weight
losses.append(loss[pairs.bool()])
#print(losses[-1].dtype, len(losses[-1]), len(losses), sum([len(l) for l in losses]))
torch.cuda.empty_cache()
return losses
def get_loss_in_the_same_query(model, data_loader, criterion, indices, bar=False, precision=torch.float32):
losses = []
if bar:
indices = tqdm(indices)
for idx in indices:
X, Y = data_loader.indexing_batch_per_query(idx)
y_pred, pairs = get_prediction(X, Y, model, data_loader, precision=precision)
if y_pred is None:
continue
loss = criterion(y_pred, pairs, precision=precision)
for ij_index in range(len(Y)):
_pairs = torch.zeros(pairs.size())
_pairs[ij_index] = pairs[ij_index]
losses.append(loss[_pairs.bool()])
return losses
def get_query_loss(model, data_loader, criterion, indices, bar=False, precision=torch.float32):
losses = []
if bar:
indices = tqdm(indices)
for idx in indices:
X, Y = data_loader.indexing_batch_per_query(idx)
y_pred, pairs = get_prediction(X, Y, model, data_loader, precision=precision)
if y_pred is None:
continue
loss = criterion(y_pred, pairs, precision=precision)
losses.append(loss)
#losses.append(loss.sum())
return losses
def get_doc_loss(model, data_loader, criterion, indices, bar=False, precision=torch.float32):
losses = []
if bar:
indices = tqdm(indices)
for idx in indices:
X, Y = data_loader.indexing_batch_per_query(idx)
y_pred, pairs = get_prediction(X, Y, model, data_loader, precision=precision)
if y_pred is None:
continue
loss = criterion(y_pred, pairs, precision=precision)
all_loss = loss + loss.t()
losses.append(all_loss.sum(dim=1))
#losses.append(all_loss.mean(dim=1))
return losses
def get_pair_loss(model, data_loader, criterion, indices, bar=False, precision=torch.float32):
losses = []
if bar:
indices = tqdm(indices)
for idx in indices:
X, Y = data_loader.indexing_batch_per_query(idx)
y_pred, pairs = get_prediction(X, Y, model, data_loader, precision=precision)
if y_pred is None:
continue
loss = criterion(y_pred, pairs, precision=precision)
losses.append(loss)
return losses
def get_grad_loss_no_reg_val(trained_model, data_loader, criterion, indices, ij_index=None,
query_loss=True, individual_weight=False, mean=True, bar=False, losses=None):
params = trained_model.parameters()
# print("get_grad_loss_no_reg_val params", sum(p.numel() for p in params if p.requires_grad))
# print("get_grad_loss_no_reg_val model.parameters()", sum(p.numel() for p in trained_model.parameters() if p.requires_grad))
grad_loss_no_reg_val = None
if losses is None:
assert indices is not None
losses = get_loss(trained_model, data_loader, criterion, indices, ij_index, bar)
empty_loss = 0
for loss in losses:
if len(loss) == 0 or (loss == 0.).int().sum() == len(loss):
empty_loss += 1
continue
if not individual_weight: #calcutate same query losses all at once
grad = autograd.grad(loss.sum(), trained_model.parameters(), retain_graph=True)
grad = list(grad)
else:
grad = None
for l in tqdm(loss.view(-1)):
_grad = autograd.grad(l, trained_model.parameters(), retain_graph=True)
raise NotImplementedError
# individual ij grad에 weighting
#_grad = [a * weight for a in _grad]
with torch.no_grad():
if grad is None:
grad = _grad
else:
grad = [a + b for (a, b) in zip(grad, _grad)]
# 각 query 별로 grad 평균
if query_loss:
grad = [a/loss.view(-1).size()[0] for a in grad]
with torch.no_grad():
if grad_loss_no_reg_val is None: # 'initialized' at first call
grad_loss_no_reg_val = grad
else:
grad_loss_no_reg_val = [a + b for (a, b) in zip(grad_loss_no_reg_val, grad)]
if mean:
if query_loss: # query 별 grad 평균
grad_loss_no_reg_val = [a/(len(losses)-empty_loss) for a in grad_loss_no_reg_val]