-
Notifications
You must be signed in to change notification settings - Fork 2
/
metadata_archaeology.py
2083 lines (1509 loc) · 81.3 KB
/
metadata_archaeology.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
#!/usr/bin/env python
# coding: utf-8
"""
PyTorch code for surfacing examples from the dataset.
Converted from other internal code.
Paper: Metadata Archaeology: Unearthing Data Subsets by Leveraging Training Dynamics
Author: Shoaib Ahmed Siddiqui (msas3@cam.ac.uk)
"""
# In[ ]:
import os
import sys
import copy
import shutil
import pickle
import random
import urllib
import natsort
import warnings
import itertools
from tqdm import tqdm
import torch
from torchvision.datasets import CIFAR10, CIFAR100, ImageFolder
from torchvision import transforms, models
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import PIL
import cv2
import dist_utils
from catalyst.data import DistributedSamplerWrapper
import sklearn.neighbors
from sklearn.metrics import confusion_matrix
# In[ ]:
# Set random seed
seed = 3
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed=seed)
random.seed(seed)
# In[ ]:
# Plotting config
include_plot_title = False
font_size = 16
# In[ ]:
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} <Dataset: cifar10/cifar100/imagenet> <Use OOD: T/F>")
dataset = sys.argv[1]
use_ood = sys.argv[2].lower()
assert use_ood in ["t", "f", "true", "false"], use_ood
use_ood = use_ood in ["t", "true"]
assert dataset in ["cifar10", "cifar100", "imagenet"]
# In[ ]:
# Essential config
fraction_of_noisy_labels = 0.0
log_predictions = True
use_ood_random_inputs = use_ood
distributed = True if dataset == "imagenet" else False
num_train_probes = 250
num_val_probes = 250
use_val_probes_for_training = True
num_example_probes = num_train_probes + num_val_probes
experiment_output_dir = f"./surfaced_examples_{dataset}{'_wo_ood_random_inputs' if not use_ood_random_inputs else ''}"
num_workers = 8
surface_examples = False
feat_dim = 2048 # Feature dimensions for ResNet-50
dataset_name = dataset
print("Dataset:", dataset)
print("Using OOD:", use_ood_random_inputs)
print("Distributed training:", distributed)
# In[ ]:
# Initialize the distributed environment
gpu = 0
world_size = 1
distributed = distributed or int(os.getenv('WORLD_SIZE', 1)) > 1
rank = int(os.getenv('RANK', 0))
local_rank = 0
if "SLURM_NNODES" in os.environ:
local_rank = rank % torch.cuda.device_count()
print(f"SLURM tasks/nodes: {os.getenv('SLURM_NTASKS', 1)}/{os.getenv('SLURM_NNODES', 1)}")
elif "WORLD_SIZE" in os.environ:
local_rank = int(os.getenv('LOCAL_RANK', 0))
if distributed:
gpu = local_rank
torch.cuda.set_device(gpu)
torch.distributed.init_process_group(backend="nccl", init_method="env://")
world_size = torch.distributed.get_world_size()
assert int(os.getenv('WORLD_SIZE', 1)) == world_size
print(f"Initializing the environment with {world_size} processes | Current process rank: {local_rank}")
main_proc = dist_utils.is_main_proc(local_rank, shared_fs=True)
print("Is main proc?", main_proc)
# In[ ]:
def setup_for_distributed(is_master):
"""
This function disables printing when not in master process
"""
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if is_master or force:
builtin_print(*args, **kwargs)
__builtin__.print = print
# In[ ]:
setup_for_distributed(main_proc)
warnings.filterwarnings("ignore", "Warning: Leaking Caffe2 thread-pool after fork. (function pthreadpool)", UserWarning)
# In[ ]:
recompute_results = False
if main_proc:
if recompute_results:
if os.path.exists(experiment_output_dir):
shutil.rmtree(experiment_output_dir)
os.makedirs(experiment_output_dir)
else:
if not os.path.exists(experiment_output_dir):
os.makedirs(experiment_output_dir)
# In[ ]:
data_dir = "../data/"
assert os.path.exists(data_dir)
# In[ ]:
files = os.listdir(data_dir)
files = [os.path.join(data_dir, x) for x in files]
print(files)
# In[ ]:
use_cscores = True # True if dataset == "cifar10" else False
if dataset == "cifar10":
if use_cscores:
mem_scores_file = "cifar10-cscores-orig-order.npz"
else:
raise NotImplementedError
elif dataset == "cifar100":
if use_cscores:
mem_scores_file = "cifar100-cscores-orig-order.npz"
else:
mem_scores_file = "cifar100_infl_matrix.npz"
else:
assert dataset == "imagenet"
if use_cscores:
mem_scores_file = "imagenet-cscores-with-filename.npz"
else:
mem_scores_file = "imagenet_index.npz"
mem_scores_file = os.path.join(data_dir, mem_scores_file)
assert os.path.exists(mem_scores_file)
print("Memorization scores file:", mem_scores_file)
# In[ ]:
if dataset == "cifar10":
if use_cscores:
cscore_data = np.load(mem_scores_file, allow_pickle=True)
memorization_labels = cscore_data['labels']
memorization_values = 1. - cscore_data['scores']
else:
raise NotImplementedError
elif dataset == "cifar100":
if use_cscores:
cscore_data = np.load(mem_scores_file, allow_pickle=True)
memorization_labels = cscore_data['labels']
memorization_values = 1. - cscore_data['scores']
else:
with np.load(mem_scores_file) as data:
print(list(data.keys()))
memorization_values = data["tr_mem"]
else:
assert dataset == "imagenet"
if use_cscores:
cscore_data = np.load(mem_scores_file, allow_pickle=True)
cscore_labels = cscore_data['labels']
cscore_values = cscore_data['scores']
cscore_filenames = cscore_data['filenames']
print("CScore keys:", list(cscore_data.keys()), cscore_labels.shape, cscore_values.shape, cscore_filenames.shape)
memorization_filenames = [x.decode("utf-8") for x in cscore_filenames] # Decode since the data is encoded as bytes
memorization_labels = cscore_labels
memorization_values = 1. - cscore_values
else:
memorization_data = np.load(mem_scores_file, allow_pickle=True)
memorization_values = memorization_data["tr_mem"]
memorization_filenames = memorization_data["tr_filenames"]
memorization_labels = memorization_data["tr_labels"]
memorization_filenames = [x.decode("utf-8") for x in memorization_filenames] # Decode since the data is encoded as bytes
# In[ ]:
print(memorization_values.shape)
print(memorization_values.min(), memorization_values.max(), memorization_values.mean(), np.median(memorization_values))
# In[ ]:
plt.figure(figsize=(12, 8))
plt.hist(memorization_values, bins=100)
plt.xlabel("Memorization value", fontsize=font_size)
plt.ylabel("Number of examples", fontsize=font_size)
plt.tight_layout()
plt.savefig(os.path.join(experiment_output_dir, f"mem_dist_{dataset}.png"), dpi=300, bbox_inches="tight")
plt.show()
# ## Visualize the examples from the dataset
# In[ ]:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Current device:", device)
# In[ ]:
def load_class_mapping(dataset):
if dataset == "imagenet":
# Load idx to class name mapping
url = "https://gist.githubusercontent.com/yrevar/942d3a0ac09ec9e5eb3a/raw/238f720ff059c1f82f368259d1ca4ffa5dd8f9f5/imagenet1000_clsidx_to_labels.txt"
response = urllib.request.urlopen(url)
lines = response.readlines()
string = ''.join([line.decode("utf-8") for line in lines])
label2name = eval(string)
elif dataset == "imagenette":
classes = ["tench", "english springer", "cassette player", "chain saw", "church", "french horn", "garbage truck",
"gas pump", "golf ball", "parachute"]
label2name = {k: v for k, v in enumerate(classes)}
elif dataset == "cifar10":
classes = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
label2name = {k: v for k, v in enumerate(classes)}
elif dataset == "cifar100":
classes = ["beaver", "dolphin", "otter", "seal", "whale", "aquarium fish", "flatfish", "ray", "shark", "trout",
"orchids", "poppies", "roses", "sunflowers", "tulips", "bottles", "bowls", "cans", "cups", "plates",
"apples", "mushrooms", "oranges", "pears", "sweet peppers", "clock", "computer keyboard", "lamp",
"telephone", "television", "bed", "chair", "couch", "table", "wardrobe", "bee", "beetle", "butterfly",
"caterpillar", "cockroach", "bear", "leopard", "lion", "tiger", "wolf", "bridge", "castle", "house",
"road", "skyscraper", "cloud", "forest", "mountain", "plain", "sea", "camel", "cattle", "chimpanzee",
"elephant", "kangaroo", "fox", "porcupine", "possum", "raccoon", "skunk", "crab", "lobster", "snail",
"spider", "worm", "baby", "boy", "girl", "man", "woman", "crocodile", "dinosaur", "lizard", "snake",
"turtle", "hamster", "mouse", "rabbit", "shrew", "squirrel", "maple", "oak", "palm", "pine", "willow",
"bicycle", "bus", "motorcycle", "pickup truck", "train", "lawn-mower", "rocket", "streetcar", "tank", "tractor"]
label2name = {k: v for k, v in enumerate(classes)}
else:
raise RuntimeError(f"Unknown dataset: {dataset}")
name2label = {label2name[key]: key for key in label2name.keys()}
assert name2label[label2name[0]] == 0
return label2name, name2label
# In[ ]:
if "cifar" in dataset:
train_transform = [transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32, padding=4, padding_mode="reflect"),
transforms.ToTensor()]
test_transform = [transforms.ToTensor()]
no_transform = test_transform
DatasetCls = CIFAR100 if dataset == "cifar100" else CIFAR10 if dataset == "cifar10" else None
assert DatasetCls is not None
# data_dir = f"/mnt/sas/Datasets/{dataset}/"
data_dir = f"/netscratch/siddiqui/Datasets/{dataset}/"
train_set = DatasetCls(data_dir, download=True, train=True, transform=transforms.Compose(train_transform))
test_set = DatasetCls(data_dir, download=True, train=False, transform=transforms.Compose(test_transform))
else:
assert dataset == "imagenet"
use_augmentations = True
if use_augmentations:
print("Training w/ augmentations...")
train_transform = [transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()]
test_transform = [transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor()]
no_transform = [transforms.Resize((224, 224)),
transforms.ToTensor()]
else:
print("Training w/o augmentations...")
train_transform = [transforms.Resize((224, 224)),
transforms.ToTensor()]
test_transform = [transforms.Resize((224, 224)),
transforms.ToTensor()]
no_transform = test_transform
# data_dir = "/mnt/sas/Datasets/ilsvrc12/"
data_dir = "/ds/images/imagenet/"
train_set = ImageFolder(os.path.join(data_dir, "train"), transform=transforms.Compose(train_transform))
# train_set_wo_aug = ImageFolder(os.path.join(data_dir, "train"), transform=transforms.Compose(no_transform))
test_set = ImageFolder(os.path.join(data_dir, "val"), transform=transforms.Compose(test_transform))
# Replace train_set.classes with real names
train_set.original_classes = train_set.classes
label2name, _ = load_class_mapping(dataset)
label2name = {k: v.split(',')[0][:20] for k, v in label2name.items()}
train_set.classes = label2name # Dict mapping from label to class name
print(dataset, len(train_set), len(test_set))
# In[ ]:
if dataset == "imagenet":
print("Sorting the memorization values w.r.t. the dataset file names...")
# Sort the memorization values based on the filenames
train_paths = [x[0] for x in train_set.samples]
train_targets = [x[1] for x in train_set.samples]
train_paths = [os.path.split(x)[1] for x in train_paths]
# Compute the memorization file index
sorting_idx_mem_scores = []
memorization_filenames_map = {k: v for v, k in enumerate(memorization_filenames)}
for filename in train_paths:
sorting_idx_mem_scores.append(memorization_filenames_map[filename])
# Sort memorization values
memorization_values = [memorization_values[sorting_idx_mem_scores[i]] for i in range(len(memorization_values))]
memorization_labels = [memorization_labels[sorting_idx_mem_scores[i]] for i in range(len(memorization_labels))]
assert all([i == j for i, j in zip(train_targets, memorization_labels)])
# In[ ]:
sorted_mem_idx = np.argsort(memorization_values)
# In[ ]:
print(sorted_mem_idx.shape)
print("Typical examples:", sorted_mem_idx[:10], [memorization_values[i] for i in sorted_mem_idx[:10]])
print("Atypical examples:", sorted_mem_idx[-10:], [memorization_values[i] for i in sorted_mem_idx[-10:]])
# In[ ]:
def get_loader(dataset, indices=None, batch_size=16, shuffle=False):
sampler = None
if indices is not None:
sampler = torch.utils.data.SubsetRandomSampler(indices)
if distributed:
if sampler is not None:
print("Using distributed sampler on top of previous sampler...")
sampler = DistributedSamplerWrapper(sampler)
else:
sampler = torch.utils.data.distributed.DistributedSampler(dataset)
loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, sampler=sampler, num_workers=num_workers, pin_memory=True)
return loader
# In[ ]:
def plot(x, y=None, memorization_val=None, class_names=None, output_file=None, add_mem_scores=False):
num_plots_per_row = 3
plot_rows = 3
plot_size = 3
fig, ax = plt.subplots(plot_rows, num_plots_per_row, figsize=(plot_size * num_plots_per_row, plot_size * plot_rows), sharex=True, sharey=True)
input = x.cpu().numpy()
is_grayscale = input.shape[1] == 1
input = input[:, 0, :, :] if is_grayscale else np.transpose(input, (0, 2, 3, 1))
if class_names is not None:
y = [class_names[int(i)] for i in y]
for idx in range(len(input)):
ax[idx // num_plots_per_row, idx % num_plots_per_row].imshow(input[idx], cmap='gray' if is_grayscale else None)
if y is not None:
if add_mem_scores:
ax[idx // num_plots_per_row, idx % num_plots_per_row].set_title(f"{'Label: ' if class_names is None else ''}{y[idx]}" + (f"\n(Mem: {memorization_val[idx]:.4f})" if memorization_val is not None else ""), color='g')
else:
ax[idx // num_plots_per_row, idx % num_plots_per_row].set_title(f"{'Label: ' if class_names is None else ''}{y[idx].replace('_', ' ').title()}", color='k', fontsize=font_size)
if idx == plot_rows * num_plots_per_row - 1:
break
for a in ax.ravel():
a.set_axis_off()
a.set_yticklabels([])
a.set_xticklabels([])
fig.tight_layout()
if output_file is not None:
plt.savefig(os.path.join(experiment_output_dir, output_file), dpi=300, bbox_inches="tight")
plt.show()
plt.close('all')
# ## Setup probes
# In[ ]:
num_classes = len(train_set.classes)
assert num_classes == 10 if dataset == "cifar10" else num_classes == 100 if dataset == "cifar100" else num_classes == 1000
print(dataset, num_classes)
# In[ ]:
probes = {"typical": [], "atypical": [], "random_outputs": [], "random_inputs_outputs": [], "corrupted": []}
probes.update({"typical_idx": sorted_mem_idx[:num_example_probes], "atypical_idx": sorted_mem_idx[-num_example_probes:]})
# In[ ]:
probes["typical"] = torch.stack([train_set[i][0] for i in probes["typical_idx"]], dim=0).to(device)
probes["typical_labels"] = torch.from_numpy(np.array([train_set[i][1] for i in probes["typical_idx"]])).to(device)
probes["typical_mem"] = torch.from_numpy(np.array([memorization_values[i] for i in probes["typical_idx"]])).to(device)
probes["atypical"] = torch.stack([train_set[i][0] for i in probes["atypical_idx"]], dim=0).to(device)
probes["atypical_labels"] = torch.from_numpy(np.array([train_set[i][1] for i in probes["atypical_idx"]])).to(device)
probes["atypical_mem"] = torch.from_numpy(np.array([memorization_values[i] for i in probes["atypical_idx"]])).to(device)
print(probes["typical"].shape, probes["atypical"].shape)
# In[ ]:
# Add mislabeled examples
remaining_indices = [i for i in range(len(train_set)) if i not in probes["typical_idx"] and i not in probes["atypical_idx"]]
new_indices = np.random.choice(remaining_indices, size=num_example_probes, replace=False)
probes.update({"random_outputs_idx": new_indices})
probes["random_outputs"] = torch.stack([train_set[i][0] for i in probes["random_outputs_idx"]], dim=0).to(device)
probes["random_outputs_labels_orig"] = torch.from_numpy(np.array([train_set[i][1] for i in probes["random_outputs_idx"]])).to(device)
probes["random_outputs_labels"] = torch.from_numpy(np.random.choice(range(num_classes), size=len(probes["random_outputs_idx"]), replace=True)).to(device)
num_labels_adjusted = 0
for i in range(len(probes["random_outputs_labels"])): # Ensure that the correct labels are not assigned by mistake
if probes["random_outputs_labels"][i] == probes["random_outputs_labels_orig"][i]:
# Chance the assigned label
choice_list = list(range(num_classes))
choice_list.remove(int(probes["random_outputs_labels_orig"][i]))
assert len(choice_list) == num_classes - 1
new_label = np.random.choice(choice_list)
probes["random_outputs_labels"][i] = new_label
num_labels_adjusted += 1
assert probes["random_outputs_labels"][i] != probes["random_outputs_labels_orig"][i]
probes["random_outputs_mem"] = torch.from_numpy(np.array([-1. for i in probes["random_outputs_idx"]])).to(device)
print("Number of random output labels adjusted:", num_labels_adjusted)
# In[ ]:
class AddGaussianNoise(object):
def __init__(self, mean=0., std=1.):
self.std = std
self.mean = mean
def __call__(self, tensor):
return torch.clip(tensor + torch.randn(tensor.size()) * self.std + self.mean, 0.0, 1.0)
# In[ ]:
class ClampRangeTransform(object):
def __init__(self):
pass
def __call__(self, x):
return torch.clamp(x, 0., 1.)
# In[ ]:
# Add naturally corrupted examples
remaining_indices = [i for i in range(len(train_set)) if i not in probes["typical_idx"] and i not in probes["atypical_idx"] and i not in probes["random_outputs_idx"]]
new_indices = np.random.choice(remaining_indices, size=num_example_probes, replace=False)
probes.update({"corrupted_idx": new_indices})
corruption_transform = transforms.Compose([AddGaussianNoise(mean=0.0, std=0.1 if "cifar" in dataset else 0.25),
ClampRangeTransform()])
probes["corrupted"] = torch.stack([corruption_transform(train_set[i][0]) for i in probes["corrupted_idx"]], dim=0).to(device)
probes["corrupted_labels"] = torch.from_numpy(np.array([train_set[i][1] for i in probes["corrupted_idx"]])).to(device)
probes["corrupted_mem"] = torch.from_numpy(np.array([-1. for i in probes["corrupted_idx"]])).to(device)
if use_ood_random_inputs:
# In[ ]:
class ConvertToSketch(object):
def __init__(self):
pass
@staticmethod
def blend(x, y):
return cv2.divide(x, 255 - y, scale=256)
def __call__(self, x):
assert isinstance(x, np.ndarray)
assert len(x.shape) == 3
assert x.shape[-1] == 3
grayed = cv2.cvtColor(x, cv2.COLOR_RGB2GRAY)
inverted = cv2.bitwise_not(grayed)
blurred = cv2.GaussianBlur(inverted, (7, 7) if "cifar" in dataset else (21, 21), sigmaX=0, sigmaY=0)
sketch_out = ConvertToSketch.blend(grayed, blurred)
sketch_out = np.stack([sketch_out, sketch_out, sketch_out], axis=2)
return sketch_out
# In[ ]:
class ToNumpyArray(object):
def __init__(self):
pass
def __call__(self, x):
if isinstance(x, np.ndarray):
return x
elif isinstance(x, PIL.Image.Image):
return np.array(x)
else:
raise RuntimeError(f"Input not supported: {type(x)}")
# In[ ]:
# Add OOD examples via sketches
remaining_indices = [i for i in range(len(train_set)) if i not in probes["typical_idx"] and i not in probes["atypical_idx"] and i not in probes["random_outputs_idx"] and i not in probes["corrupted_idx"]]
new_indices = np.random.choice(remaining_indices, size=num_example_probes, replace=False)
probes.update({"out_of_distribution_idx": new_indices})
if "cifar" in dataset:
sketch_transform = transforms.Compose([ConvertToSketch(), transforms.ToTensor()])
probes["out_of_distribution"] = torch.stack([sketch_transform(train_set.data[i]) for i in probes["out_of_distribution_idx"]], dim=0).to(device)
else:
sketch_transform = transforms.Compose([transforms.Resize((224, 224)), ToNumpyArray(), ConvertToSketch(), transforms.ToTensor()])
train_set.transform = sketch_transform # Replace the original transform
probes["out_of_distribution"] = torch.stack([train_set[i][0] for i in probes["out_of_distribution_idx"]], dim=0).to(device)
train_set.transform = transforms.Compose(train_transform) # Reattach the original transform
probes["out_of_distribution_labels"] = torch.from_numpy(np.array([train_set.targets[i] for i in probes["out_of_distribution_idx"]])).to(device)
probes["out_of_distribution_mem"] = torch.from_numpy(np.array([-1. for i in probes["out_of_distribution_idx"]])).to(device)
# In[ ]:
# Add noisy examples
tensor_shape = probes["typical"].shape
probes["random_inputs_outputs"] = torch.clip(torch.randn(*tensor_shape), 0., 1.).to(device)
probes["random_inputs_outputs_labels"] = torch.randint(0, num_classes, (num_example_probes,)).to(device)
probes["random_inputs_outputs_mem"] = torch.from_numpy(np.array([-1. for i in probes["random_outputs_idx"]])).to(device)
# In[ ]:
print("Typical examples")
plot(probes["typical"], probes["typical_labels"], probes["typical_mem"], class_names=train_set.classes,
output_file=f"typical_{dataset}_{rank}.png")
# In[ ]:
print("Atypical examples")
plot(probes["atypical"], probes["atypical_labels"], probes["atypical_mem"], class_names=train_set.classes,
output_file=f"atypical_{dataset}_{rank}.png")
# In[ ]:
print("Corrupted examples")
plot(probes["corrupted"], probes["corrupted_labels"], probes["corrupted_mem"], class_names=train_set.classes,
output_file=f"corrupted_{dataset}_{rank}.png")
# In[ ]:
print("Random output examples")
plot(probes["random_outputs"], probes["random_outputs_labels"], probes["random_outputs_mem"], class_names=train_set.classes,
output_file=f"random_outputs_{dataset}_{rank}.png")
if use_ood_random_inputs:
# In[ ]:
print("Out-of-distribution examples")
plot(probes["out_of_distribution"], probes["out_of_distribution_labels"], probes["out_of_distribution_mem"], class_names=train_set.classes,
output_file=f"ood_{dataset}_{rank}.png")
# In[ ]:
print("Random input & output examples")
plot(probes["random_inputs_outputs"], probes["random_inputs_outputs_labels"], probes["random_inputs_outputs_mem"], class_names=train_set.classes,
output_file=f"random_inputs_outputs_{dataset}_{rank}.png")
# ## Train on these examples
# In[ ]:
# Hyperparameters
if "cifar" in dataset:
num_epochs = 150
batch_size = 128
else:
assert dataset == "imagenet"
num_epochs = 100
optimizer_batch_size = 256
batch_size = 256
if distributed:
assert batch_size % world_size == 0
batch_size = batch_size // world_size
print(f"Optimizer batch size: {optimizer_batch_size} / World size: {world_size} / Local batch size: {batch_size}")
lr = 0.1
momentum = 0.9
wd = 0.0001
# In[ ]:
# Remove typical and atypical examples from the dataset -- will train on the probes separately
if use_ood_random_inputs:
discarded_idx = list(probes["typical_idx"]) + list(probes["atypical_idx"]) + list(probes["random_outputs_idx"]) + list(probes["corrupted_idx"]) + list(probes["out_of_distribution_idx"])
else:
discarded_idx = list(probes["typical_idx"]) + list(probes["atypical_idx"]) + list(probes["random_outputs_idx"]) + list(probes["corrupted_idx"])
train_indices = [i for i in range(len(train_set)) if i not in discarded_idx]
print("Discarded examples:", len(train_set) - len(train_indices))
assert len(train_set) - len(train_indices) == len(discarded_idx)
train_loader = get_loader(train_set, train_indices, batch_size=batch_size)
test_loader = get_loader(test_set, batch_size=batch_size)
# In[ ]:
class CustomTensorDataset(torch.utils.data.Dataset):
def __init__(self, x: torch.Tensor, y: list) -> None:
self.x = x
self.y = y
def __getitem__(self, index):
return self.x[index], self.y[index]
def __len__(self):
return self.x.size(0)
# In[ ]:
if use_ood_random_inputs:
probes_to_be_used = ["typical", "atypical", "corrupted", "random_outputs", "out_of_distribution", "random_inputs_outputs"]
else:
probes_to_be_used = ["typical", "atypical", "corrupted", "random_outputs"]
print("Selected probes to be used:", probes_to_be_used)
val_idx = np.random.choice(range(num_example_probes), size=num_val_probes, replace=False)
# Filter the train indexes
val_probes = {}
probe_identity = []
val_probe_identity = []
for primary_k in probes_to_be_used:
for suffix in ["", "_labels", "_mem"]:
k = f"{primary_k}{suffix}"
print("Current key:", k)
assert len(probes[k]) == num_example_probes
shape_len = len(probes[k].shape)
val_probes[k] = torch.cat([probes[k][i:i+1] for i in range(len(probes[k])) if i in val_idx], dim=0) # Transfer val indices from train
probes[k] = torch.cat([probes[k][i:i+1] for i in range(len(probes[k])) if i not in val_idx], dim=0) # Discard val index from train
assert len(val_probes[k].shape) == shape_len
assert len(probes[k].shape) == shape_len
assert len(val_probes[k]) == num_val_probes
assert len(probes[k]) == num_train_probes
probe_identity += [primary_k for _ in range(len(probes[primary_k]))]
val_probe_identity += [f"{primary_k}_val" for _ in range(len(val_probes[primary_k]))]
probe_images = torch.cat([probes[k] for k in probes_to_be_used], dim=0)
probe_labels = torch.cat([probes[f"{k}_labels"] for k in probes_to_be_used], dim=0)
probe_mem = torch.cat([probes[f"{k}_mem"] for k in probes_to_be_used], dim=0)
assert len(probe_identity) == len(probe_images)
# Shuffle
perm = np.random.choice(range(len(probe_images)), size=len(probe_images), replace=False)
probe_images = torch.stack([probe_images[i] for i in perm], dim=0).to(device)
probe_labels = torch.stack([probe_labels[i] for i in perm], dim=0).to(device)
probe_mem = torch.stack([probe_mem[i] for i in perm], dim=0).to(device)
probe_identity = [probe_identity[i] for i in perm]
print(f"Probe | Images: {probe_images.shape} | Labels: {probe_labels.shape} | Mem scores: {probe_mem.shape}")
probe_dataset = torch.utils.data.TensorDataset(probe_images, probe_labels, probe_mem)
probe_dataset_standard = CustomTensorDataset(probe_images.to("cpu"), [int(x) for x in probe_labels.to("cpu").numpy().tolist()])
print("Probe dataset:", len(probe_dataset_standard), probe_dataset_standard[0][0].shape, probe_dataset_standard[0][1])
# Create the validation set for probes
val_probe_images = torch.cat([val_probes[k] for k in probes_to_be_used], dim=0)
val_probe_labels = torch.cat([val_probes[f"{k}_labels"] for k in probes_to_be_used], dim=0)
val_probe_dataset_standard = CustomTensorDataset(val_probe_images.to("cpu"), [int(x) for x in val_probe_labels.to("cpu").numpy().tolist()])
print("Validation probe dataset:", len(val_probe_dataset_standard), val_probe_dataset_standard[0][0].shape, val_probe_dataset_standard[0][1])
# In[ ]:
class ProbeDataset(torch.utils.data.Dataset):
def __init__(self, dataset, probe_identity, remove_val_in_name=True):
self.dataset = dataset
if remove_val_in_name:
probe_identity = [x.replace("_val", "") for x in probe_identity]
print("Validation tag in probe identity removed for probe dataset...")
self.probe_identity = probe_identity
self.class_names = natsort.natsorted(np.unique(probe_identity))
self.iden2label = {iden: i for i, iden in enumerate(self.class_names)}
print("Probe to idx map:", self.iden2label)
def get_probe_map(self):
return self.iden2label
def get_class_names(self):
return self.class_names
def __getitem__(self, idx):
return self.dataset[idx], self.iden2label[self.probe_identity[idx]]
# In[ ]:
# Setup the probe validation set
val_probe_dataset = ProbeDataset(val_probe_dataset_standard, val_probe_identity)
val_probe_indices = [i for i in range(len(val_probe_dataset_standard))]
val_probe_loader = get_loader(val_probe_dataset, val_probe_indices, batch_size=batch_size)
# In[ ]:
print("Curated probe dataset")
plot(torch.stack([x[0] for x in probe_dataset], dim=0), torch.stack([x[1] for x in probe_dataset], dim=0), torch.stack([x[2] for x in probe_dataset], dim=0),
class_names=train_set.classes, output_file=f"probes_dataset_{dataset}.png")
# In[ ]:
# Create ResNet-50
model = models.resnet50(pretrained=False)
if "cifar" in dataset: # Change the first and last layer for cifar10/cifar100
model.conv1 = torch.nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
model = model.to(device)
print(model)
# In[ ]:
# Convert to a distributed model
model = dist_utils.convert_to_distributed(model, local_rank, sync_bn=True, use_torch_ddp=True)
# In[ ]:
def train(model, device, train_loader, optimizer, criterion, scaler, log_interval=10, log_predictions=False, use_autocast=False):
model.train()
optimizer.zero_grad()
example_idx = []
predictions = []
targets = []
loss_values = []
pbar = tqdm(train_loader)
for batch_idx, ((data, target), ex_idx) in enumerate(pbar):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
with torch.cuda.amp.autocast(enabled=use_autocast):
output = model(data)
loss = criterion(output, target)
loss_values.append(loss.detach().clone())
assert loss.shape == (len(data),)
loss = loss.mean() # Reduction has been disabled -- do explicit reduction
if use_autocast:
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
else:
loss.backward()
optimizer.step()
if log_predictions:
predictions.append(output.argmax(dim=1).detach())
example_idx.append(ex_idx.clone())
targets.append(target.clone())
if batch_idx % log_interval == 0:
pbar.set_description(f"Loss: {float(loss):.4f}")
torch.cuda.synchronize()
pbar.close()
output_dict = None
if log_predictions:
# Collect the statistics from all the GPUs
example_idx = torch.cat(dist_utils.gather_tensor(torch.cat(example_idx, dim=0)), dim=0).detach().cpu().numpy()
predictions = torch.cat(dist_utils.gather_tensor(torch.cat(predictions, dim=0)), dim=0).detach().cpu().numpy()
targets = torch.cat(dist_utils.gather_tensor(torch.cat(targets, dim=0)), dim=0).detach().cpu().numpy()
loss_values = torch.cat(dist_utils.gather_tensor(torch.cat(loss_values, dim=0)), dim=0).detach().cpu().numpy()
output_dict = {"ex_idx": example_idx, "preds": predictions, "targets": targets, "loss": loss_values}
return output_dict
# In[ ]:
def test(model, device, criterion, test_loader, set_name="Test", log_predictions=False):
model.eval()
correct = torch.tensor([0]).to(device)
test_loss = torch.tensor([0.0]).to(device)
total = torch.tensor([0]).to(device)
test_acc = 0.
example_idx = []
predictions = []
targets = []
loss_values = []
for (data, target), ex_idx in test_loader:
with torch.no_grad():
data, target = data.to(device), target.to(device)
output = model(data)
loss_vals = criterion(output, target)
test_loss += float(loss_vals.sum())
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
total += len(data)
if log_predictions:
loss_values.append(loss_vals.detach().clone())
predictions.append(output.argmax(dim=1).detach())
example_idx.append(ex_idx.clone())
targets.append(target.clone())
# Reduce all of the values in case of distributed processing
torch.cuda.synchronize()
correct = int(dist_utils.reduce_tensor(correct.data))
test_loss = float(dist_utils.reduce_tensor(test_loss.data))
total = int(dist_utils.reduce_tensor(total.data))
if isinstance(test_loader.sampler, torch.utils.data.distributed.DistributedSampler):
num_dataset_ex = len(test_loader.sampler.dataset)
elif isinstance(test_loader.sampler, DistributedSamplerWrapper):
num_dataset_ex = len(test_loader.sampler.sampler.dataset)
elif isinstance(test_loader.sampler, torch.utils.data.SubsetRandomSampler):
num_dataset_ex = len(test_loader.sampler)
else:
# assert test_loader.sampler is None, test_loader.sampler
num_dataset_ex = len(test_loader.dataset)
if not distributed:
assert total == num_dataset_ex, f"{total} != {num_dataset_ex}"
if total != num_dataset_ex:
print(f"!! Warning -- aggregated total value ({total}) is not equal to the dataset size: {num_dataset_ex}...")
if total > 0:
test_loss /= total
test_acc = 100. * correct / total
output_dict = dict(loss=test_loss, acc=test_acc, correct=correct, total=total)
if distributed:
set_name = f"Rank: {rank} | {set_name}"
print(f"{set_name} set | Average loss: {test_loss:.4f} | Accuracy: {correct}/{total} ({test_acc:.2f}%)")
pred_output_dict = None
if log_predictions:
# Collect the statistics from all the GPUs
example_idx = torch.cat(dist_utils.gather_tensor(torch.cat(example_idx, dim=0)), dim=0).detach().cpu().numpy()
predictions = torch.cat(dist_utils.gather_tensor(torch.cat(predictions, dim=0)), dim=0).detach().cpu().numpy()
targets = torch.cat(dist_utils.gather_tensor(torch.cat(targets, dim=0)), dim=0).detach().cpu().numpy()
loss_values = torch.cat(dist_utils.gather_tensor(torch.cat(loss_values, dim=0)), dim=0).detach().cpu().numpy()
pred_output_dict = {"ex_idx": example_idx, "preds": predictions, "targets": targets, "loss": loss_values}
return output_dict, pred_output_dict
# In[ ]:
def test_tensor(model, device, criterion, data, target, msg=None, log_predictions=False):
assert torch.is_tensor(data) and torch.is_tensor(target)
model.eval()
with torch.no_grad():
output = model(data)
loss_vals = criterion(output, target)
test_loss = float(loss_vals.mean())
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct = pred.eq(target.view_as(pred)).sum().item()
total = len(data)
test_acc = 100. * correct / total
output_dict = dict(loss=test_loss, acc=test_acc, correct=correct, total=total)
loss_vals = loss_vals.detach().cpu().numpy()
output_dict["loss_mean"] = np.mean(loss_vals)
output_dict["loss_var"] = np.var(loss_vals)
output_dict["loss_std"] = np.std(loss_vals)
pred_dict = None
if log_predictions:
pred_dict = {}
pred_dict["ex_idx"] = np.arange(len(loss_vals))
pred_dict["loss_vals"] = loss_vals