-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1650 lines (1483 loc) · 75.4 KB
/
main.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
# MKL_THREADING_LAYER=GNU
import os
import shutil
import signal
s3_prefix = ""
# import sshfs
# from sshfs import SSHFileSystem
# remote = SSHFileSystem(
# host='AMASK.asuscomm.com',
# port=23,
# username='AMASK',
# password='AMASK',
# )
from lightning.pytorch.plugins.io import AsyncCheckpointIO
from pathlib import Path
import numpy as np
import socket
import lightning as pl
import torch
import wandb
import hydra
from os import path
import yaml
import pickle as pkl
from domainbed_utils import get_best_model_path_domainbed
from torch.utils.data import random_split
import re
import seaborn as sns
import matplotlib.pyplot as plt
from omegaconf import OmegaConf, open_dict
import torchmetrics
from lightning.pytorch.callbacks import StochasticWeightAveraging
import torch.nn as nn
from itertools import product
# from pytorch_adapt.datasets import get_officehome
# from pytorch_adapt.datasets import OfficeHome
from torchvision import transforms
from torchvision.datasets import MNIST, CIFAR10
from typing import Optional
from torchvision.models import resnet50, resnet18
from lightning.pytorch.callbacks import ModelCheckpoint
from lightning.pytorch.loggers import WandbLogger
from lightning.pytorch import LightningDataModule, LightningModule
# from pytorch_adapt.datasets import get_officehome
from torch.utils.data import DataLoader, Dataset
from linear_svd import *
from domainbed_dataset import get_dataset
def assert_file(path):
if os.path.exists(path):
return
os.makedirs(os.path.dirname(path), exist_ok=True)
os.system(f"rsync -avzrP ai:AMASK/AMASK/AMASKPATH/{path} {os.path.dirname(path)}")
os.system(f"rsync -avzrP MYMACHINE:/mnt/AMASK/AMASKPATH/{path} {os.path.dirname(path)}")
return
def myload(path, map_location="cpu"):
assert_file(path)
logger.info(f"Loading from {path}")
if "mnt" in path:
logger.debug(f"Loading from remote: {path}")
with remote.open(path, "rb") as f:
return torch.load(f, map_location=map_location)
else:
return torch.load(path, map_location=map_location)
import logging
logger = logging.getLogger(f"./logs/{__name__}.log")
logger.setLevel(logging.DEBUG)
def myhash(cfg):
# ignore all the default, null, none, empty
cfg = OmegaConf.to_container(cfg, resolve=True)
cfg = {k: v for k, v in cfg.items() if v is not None and v != "null" and v != ""}
return hash(tuple(sorted(cfg.items())))
#* TODO: fixme
def mylistdir(path):
print(path)
if os.path.exists(path):
ckpt_files = [file for file in os.listdir(path) if file.endswith(".ckpt")]
if len(ckpt_files) > 0:
return os.listdir(path)
pieces = path.split("/")
pieces = [piece for piece in pieces if piece != ""]
path = "/".join(pieces)
# listdir = remote.ls(f"/mnt/AMASK/AMASKPATH/{path}")
os.makedirs(os.path.dirname(path), exist_ok=True)
source_path = fr"MYMACHINE:/mnt/AMASK/AMASKPATH/{path}/".replace("[", r"\\[").replace("]", r"\\]").replace("'", r"\'").replace(" ", "' '")
os.makedirs(path, exist_ok=True)
target_path = path.replace("[", "").replace("]", "").replace("'", "").replace(" ", "")
os.makedirs(target_path, exist_ok=True)
cmd = f"rsync -azP --ignore-existing {source_path} {target_path}"
os.system(cmd)
logger.debug(cmd)
source_path = fr"ai:AMASK/AMASK/AMASKPATH/{path}/".replace("[", r"\\[").replace("]", r"\\]").replace("'", r"\'").replace(" ", "' '")
target_path = path.replace("[", "").replace("]", "").replace("'", "").replace(" ", "")
cmd = f"rsync -azP --ignore-existing {source_path} {target_path}"
logger.debug(cmd)
os.system(cmd)
for entry in os.listdir(target_path):
if os.path.isfile(f"{target_path}/{entry}"):
shutil.move(f"{target_path}/{entry}", f"{path}/{entry}")
elif os.path.isdir(f"{target_path}/{entry}"):
shutil.rmtree(f"{path}/{entry}", ignore_errors=True)
shutil.move(f"{target_path}/{entry}", f"{path}/{entry}")
return os.listdir(path)
#
def get_best_model_path(output_dir, monitor):
# output_pieces = output_dir.split("/")
# output_dir = "/".join(output_pieces)
# files = os.listdir(output_dir)
files = mylistdir(output_dir)
files = [file for file in files if file.endswith(".ckpt")]
# contain monitor
logger.debug(monitor)
files = [file for file in files if re.search(f"{monitor}=[0-9\.]+", file) is not None]
logger.debug(files)
# get the monitor value but not the .ckpt
monitor_values = [re.search(f"{monitor}=([0-9\.]+)", file).group(1) for file in files]
monitor_values = [float(value[:-1]) if value.endswith(".") else float(value) for value in monitor_values]
if "acc" in monitor:
best = max(monitor_values)
else:
best = min(monitor_values)
# get the
best_file = [file for file in files if re.search(f"{monitor}={best}", file) is not None][0]
# source_path = output_dir.replace("[", r"\\\[").replace("]", r"\\\]").replace("'", r"\'").replace(" ", "' '")
# target_path = f"./outputs" + str(hash(source_path))
# source_file = f"MYMACHINE:/mnt/AMASK/labs/{source_path}/"
# target_file = target_path + "/" + best_file
# cmd = f"rsync -azP {source_file} {target_path}"
# os.system(cmd)
# import shutil
# shutil.move(target_file, output_dir)
return f"{output_dir}/{best_file}"
class DataModule(LightningDataModule):
def __init__(self, cfg) -> None:
super().__init__()
self.cfg = cfg
self.batch_size = cfg.training.batch_size
# seed = cfg.dataset.seed
# souce_domains = cfg.dataset.source_domains
# traget_domains = cfg.dataset.target_domains
# full_domains = cfg.dataset.full_domains
# source_domain_idxs = [full_domains.index(d) for d in souce_domains]
# target_domain_idxs = [full_domains.index(d) for d in traget_domains]
# source_train_datasets = get_dataset(cfg.server.data_root_folder, source_domains=cfg.dataset.source_domains, source_domain_idxs=source_domain_idxs)
# target_train_datasets = get_dataset(cfg.server.data_root_folder, target_domains=cfg.dataset.target_domains, target_domain_idxs=target_domain_idxs)
# self.source_test_datasets = source_train_datasets["src_val"]
# self.target_test_datasets = target_train_datasets["target_val"]
# # split source datasets into train and val
# source_train_val_datasets = source_train_datasets["src_train"]
# # set split seed
# torch.manual_seed(seed)
# source_train_size = int(len(source_train_val_datasets)*0.8)
# source_val_size = len(source_train_val_datasets) - source_train_size
# self.source_train_datasets, self.source_val_datasets = torch.utils.data.random_split(source_train_val_datasets, [source_train_size, source_val_size])
# target_train_val_datasets = target_train_datasets["target_train"]
# target_train_size = int(len(target_train_val_datasets)*0.8)
# target_val_size = len(target_train_val_datasets) - target_train_size
# self.target_train_datasets, self.target_val_datasets = torch.utils.data.random_split(target_train_val_datasets, [target_train_size, target_val_size])
# self.batch_size = cfg.training.batch_size
# self.dataset_dict = {
# "source_train": self.source_train_datasets,
# "source_val": self.source_val_datasets,
# "source_test": self.source_test_datasets,
# "target_train": self.target_train_datasets,
# "target_val": self.target_val_datasets,
# "target_test": self.target_test_datasets,
# }
# logger.info(f"Source train size: {len(self.source_train_datasets)}")
# logger.info(f"Source val size: {len(self.source_val_datasets)}")
# logger.info(f"Target train size: {len(self.target_train_datasets)}")
# logger.info(f"Target val size: {len(self.target_val_datasets)}")
# logger.info(f"Source test size: {len(self.source_test_datasets)}")
# logger.info(f"Target test size: {len(self.target_test_datasets)}")
# self.target_fsl = cfg.target_fsl
self.dataset_dict = get_dataset(cfg)
for split in self.dataset_dict:
logger.info(f"{split} size: {len(self.dataset_dict[split])}")
self.__setattr__(split, self.dataset_dict[split])
self.mode = cfg.mode
def train_dataloader(self):
if self.mode == "source_pretrain":
return DataLoader(self.source_train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=4)
elif self.mode == "target_finetune":
if self.cfg.fsl != -1:
# random sample the target train datasets
if type(self.cfg.fsl) == float:
self.cfg.fsl = int(self.cfg.fsl * len(self.target_train_dataset))
self.target_train_dataset = torch.utils.data.Subset(self.target_train_dataset, np.random.choice(len(self.target_train_dataset), self.cfg.fsl, replace=False))
return DataLoader(self.target_train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=4)
else:
raise NotImplementedError
def val_dataloader(self):
if self.mode == "target_finetune":
# make source val dataset empty
self.source_val_dataset = torch.utils.data.Subset(self.source_val_dataset, [])
source_val_dataloader = DataLoader(self.source_val_dataset, batch_size=self.batch_size, shuffle=False, num_workers=4)
target_val_dataloader = DataLoader(self.target_val_dataset, batch_size=self.batch_size, shuffle=False, num_workers=4)
return [source_val_dataloader, target_val_dataloader]
def test_dataloader(self):
return DataLoader(self.target_test_dataset, batch_size=self.batch_size, shuffle=False, num_workers=4)
def predict_dataloader(self):
return DataLoader(self.target_test_dataset, batch_size=self.batch_size, shuffle=False, num_workers=4)
class ERM(nn.Module):
def __init__(self, num_classes, mode) -> None:
super().__init__()
self.train_step = 0
self.net = resnet50(weights="DEFAULT")
fc_in_features = self.net.fc.in_features
self.fc_in_features = fc_in_features
self.net.fc= nn.Linear(fc_in_features, num_classes)
self.criterion = nn.CrossEntropyLoss()
self.mode = mode
def get_feature_encoder(self):
return nn.Sequential(*list(self.net.children())[:-1])
def get_feature(self, x):
feat = self.get_feature_encoder()(x)
feat = feat.reshape(x.shape[0], -1)
return feat
def forward_feature(self, feat):
logit = self.net.fc(feat)
return logit
def forward(self, x):
if self.mode == "feature_extraction":
feat = self.get_feature(x)
return feat
else:
return self.net(x)
class NUC(ERM):
"""
Empirical Risk Minimization with nuclear norm (ERM_NU)
"""
def __init__(self, num_classes, mode, nuc_scale=0.0) -> None:
super().__init__(num_classes, mode)
self.nuc_scale = nuc_scale
def get_loss(self, x, y, step):
batch_size = x.shape[0]
feat = self.get_feature(x)
y_logit = self.forward_feature(feat)
y_loss = self.criterion(y_logit, y)
# check step
if self.train_step > 100:
u,s,v = torch.svd(feat, compute_uv=True)
nuc_loss = torch.sum(torch.abs(s)) / batch_size
else:
nuc_loss = torch.tensor(0.0).to("cuda")
nuc_loss = nuc_loss * self.nuc_scale
loss = y_loss + self.nuc_scale * nuc_loss
loss_dict = {
"loss": loss,
"y_loss": y_loss,
"nuc_loss": nuc_loss,
}
return loss_dict, y_logit
def mat_plot(mat, step):
if len(mat.shape) == 1:
mat = mat.unsqueeze(0)
plt.figure(figsize=(mat.shape[1]*0.1, mat.shape[0]*0.1))
mat = mat.detach().cpu().numpy()
sns.heatmap(mat, vmin=-1, vmax=1, annot=True, cmap="PiYG", square=True)
plt.text(0, 0.5, str(step), color='blue', fontsize=20)
return wandb.Image(plt)
class DragonNet(nn.Module):
def __init__(self, num_classes, use_fc_bias=False, mode="source_pretrain") -> None:
super().__init__()
net = resnet50(weights="DEFAULT")
fc_in_features = net.fc.in_features
self.feature_encoder = nn.Sequential(*list(net.children())[:-1])
#
# self.classifier = nn.Linear(2048, num_classes)
self.fc_list = nn.ModuleList([nn.Linear(fc_in_features, num_classes, bias=use_fc_bias
).to("cuda") for _ in range(4)])
self.avg_fc = nn.Linear(fc_in_features, num_classes, bias=use_fc_bias)
self.num_classes = num_classes
self.use_fc_bias = use_fc_bias
self.mode = mode
def set_head(self, avg_list, target_index, avg_method="mean"):
fc_weights = torch.stack([fc.weight.data for fc in self.fc_list], dim=0)
avg_weights = fc_weights[avg_list,:,:]
if avg_method == "mean":
avg_weight = torch.mean(avg_weights, dim=0)
else:
raise NotImplementedError
self.fc_list[target_index].weight.data = avg_weight
def update_avg_fc(self, epoch, mode=None):
# udpate self.avg_fc
self.fc_weights = torch.stack([fc.weight.data for fc in self.fc_list], dim=0)
# 3 * 65 * 2048
# 2048 -> k
# 65 * 2048 -> (65 * 65) * (65 * 2048) * (2048 * 2048)
# U S V
# w0, w1, w2
# drop the last fc layer
if mode is None:
mode = self.mode
if mode == "source_pretrain" or mode == "feature_selection":
#FIXME
useable_list = [0, 1, 2]
elif mode == "target_finetune":
useable_list = [0, 1, 2, 3]
useable_fc_weights = self.fc_weights[useable_list,:, :]
mean_fc_weights = torch.mean(useable_fc_weights, dim=0)
std_fc_weights = torch.std(useable_fc_weights, dim=0)
self.avg_fc.weight.data = mean_fc_weights
if self.use_fc_bias:
self.fc_bias = torch.stack([fc.bias.data for fc in self.fc_list], dim=0)
useable_fc_bias = self.fc_bias[useable_list, :]
mean_fc_bias = torch.mean(useable_fc_bias, dim=0)
std_fc_bias = torch.std(useable_fc_bias, dim=0)
self.avg_fc.bias.data = mean_fc_bias
return self.avg_fc
def get_feature(self, x):
feat = self.feature_encoder(x)
feat = feat.reshape(x.shape[0], -1)
return feat
def forward(self, x, e):
if self.training:
feat = self.get_feature(x)
batch_size = x.shape[0]
logit_list = torch.empty((batch_size, self.num_classes)).to("cuda")
for e_idx in torch.Tensor([0, 1, 2, 3]).to("cuda"):
e_feat = feat[e==e_idx]
logit = self.fc_list[int(e_idx)](e_feat)
logit_list[e==e_idx] = logit
return logit_list
else:
if self.mode == "source_pretrain":
feat = self.get_feature(x)
logit = self.avg_fc(feat)
return logit
elif self.mode == "target_finetune":
feat = self.get_feature(x)
batch_size = x.shape[0]
logit_list = torch.empty((batch_size, self.num_classes)).to("cuda")
for e_idx in torch.Tensor([3]).to("cuda"):
e_feat = feat[e==e_idx]
logit = self.fc_list[int(e_idx)](e_feat)
logit_list[e==e_idx] = logit
return logit_list
class LinearSVDWrapper(nn.Module):
def __init__(self, U, D, V):
super(LinearSVDWrapper, self).__init__()
self.U = U
self.D = D
self.V = V
def forward(self, X):
X = X.T
X = self.U(X)
X = self.D * X
X = self.V(X)
X = X.T
return X
class FeatureEncoder(nn.Module):
def __init__(self, num_classes) -> None:
super().__init__()
net = resnet50(weights="DEFAULT")
fc_in_features = net.fc.in_features
self.feature_encoder = nn.Sequential(*list(net.children())[:-1])
self.fc = nn.Linear(fc_in_features, num_classes)
def forward(self, x):
feat = self.feature_encoder(x)
feat = feat.reshape(x.shape[0], -1)
logit = self.fc(feat)
return logit
class ProjectionNet(nn.Module):
def __init__(self,
num_classes,
num_envs=4,
feature_source=["y", "s", "e"],
mode="source_pretrain",
ys_orth_reg_scale=1.0,
ye_orth_reg_scale=1.0,
projection_method="svd") -> None:
super().__init__()
net = resnet50(weights="DEFAULT")
fc_in_features = net.fc.in_features
self.fc_in_features = fc_in_features
self.feature_encoder = nn.Sequential(*list(net.children())[:-1])
self.feature_source = feature_source
self.mode = mode
if self.mode in ["source_pretrain", "feature_extraction"]:
self.y_classifier = nn.Linear(fc_in_features * 2, num_classes)
self.e_classifier = nn.Linear(fc_in_features * 2, num_envs)
elif self.mode == "target_finetune":
self.y_classifier = nn.Linear(fc_in_features * len(self.feature_source), num_classes)
logger.debug(f"y_classifier weight shape: {self.y_classifier.weight.shape}")
self.e_classifier = None
self.num_classes = num_classes
self.projection_method = projection_method
if self.projection_method == "inverse":
self.y_mat = nn.Parameter(torch.randn(fc_in_features, fc_in_features))
self.e_mat = nn.Parameter(torch.randn(fc_in_features, fc_in_features))
self.s_mat = nn.Parameter(torch.randn(fc_in_features, fc_in_features))
self.y_proj = self.get_projection(self.y_mat)
self.e_proj = self.get_projection(self.e_mat)
self.s_proj = self.get_projection(self.s_mat)
elif self.projection_method == "optimization":
self.y_proj = nn.Linear(fc_in_features, fc_in_features, bias=False)
self.e_proj = nn.Linear(fc_in_features, fc_in_features, bias=False)
self.s_proj = nn.Linear(fc_in_features, fc_in_features, bias=False)
elif self.projection_method == "svd":
device = "cuda"
self.U = Orthogonal(d=fc_in_features).to(device)
# initialize D to be binary, select 683 random indices
y_idxs = np.random.choice(fc_in_features, 683, replace=False)
# select 683 random indices and not in y_idxs
e_idxs = np.random.choice(np.setdiff1d(np.arange(fc_in_features), y_idxs), 683, replace=False)
# select 682 random indices and not in y_idxs or e_idxs
s_idxs = np.random.choice(np.setdiff1d(np.arange(fc_in_features), np.union1d(y_idxs, e_idxs)), 682, replace=False)
self.y_D = torch.empty(fc_in_features, 1).uniform_(0.99, 1.01).to(device)
self.y_D[y_idxs] = 1
self.y_D[s_idxs] = 0.01
self.y_D[e_idxs] = 0.01
self.s_D = torch.empty(fc_in_features, 1).uniform_(0.99, 1.01).to(device)
self.s_D[y_idxs] = 1
self.s_D[s_idxs] = 0.01
self.s_D[e_idxs] = 0.01
self.e_D = torch.empty(fc_in_features, 1).uniform_(0.99, 1.01).to(device)
self.e_D[e_idxs] = 1
self.e_D[s_idxs] = 0.01
self.e_D[y_idxs] = 0.01
self.V = Orthogonal(d=fc_in_features).to(device)
self.y_proj = LinearSVDWrapper(self.U, self.y_D, self.V)
self.e_proj = LinearSVDWrapper(self.U, self.e_D, self.V)
self.s_proj = LinearSVDWrapper(self.U, self.s_D, self.V)
else:
raise NotImplementedError
self.none_reduction_criterion = nn.CrossEntropyLoss(reduction="none")
self.criterion = nn.CrossEntropyLoss()
self.feature_source = feature_source
self.ye_orth_reg_scale = ye_orth_reg_scale
self.ys_orth_reg_scale = ys_orth_reg_scale
self.mode = mode
def get_feature_encoder(self):
return self.feature_encoder
def get_ls_project(self, A):
P = A @ (torch.inverse(A.T @ A) @ A.T)
return P
def apply_projection(self, x, P):
return (P @ x.T).T
def linear_orth_reg(self, a_mat, b_mat):
assert self.projection_method in ["optimization", "inverse"]
a_dim = a_mat.shape[0]
a = torch.norm(torch.trace(a_mat @ b_mat.T), p=2) + torch.norm(torch.trace(a_mat.T @ b_mat), p=2)
a = a / (2 * a_dim)
return a
def sigma_orth_reg(self, sigma_1, sigma_2):
assert self.projection_method == "svd"
return torch.norm(torch.trace(sigma_1 @ sigma_2.T), p=2) / sigma_1.shape[0]
def binary_regularization(self, D, p=2):
assert self.projection_method == "svd"
assert p % 2 == 0
# Calculate the difference from the nearest binary value (0 or 1)
diff_from_binary = torch.min(D, 1 - D)
# Square these differences and sum
penalty = torch.sum(diff_from_binary ** p)
return penalty
def check_projection(self, P, P_name):
diff_1 = torch.norm(P - P.T, p=2)
logger.info(f"{P_name}/diff_1: {diff_1}")
wandb.log({f"{P_name}/diff_1": diff_1})
# assert torch.allclose(P, P.T, atol=1e-6)
diff_2 = torch.norm(P @ P - P, p=2)
logger.info(f"{P_name}/diff_2: {diff_2}")
wandb.log({f"{P_name}/diff_2": diff_2})
# assert torch.allclose(P @ P, P)
P_rank = torch.linalg.matrix_rank(P)
logger.info(f"{P_name}/rank: {P_rank}")
wandb.log({f"{P_name}/rank": P_rank})
def get_projection(self, feat):
if self.projection_method == "inverse":
self.y_proj = self.get_ls_project(self.y_mat)
self.e_proj = self.get_ls_project(self.e_mat)
self.s_proj = self.get_ls_project(self.s_mat)
y_projected = self.apply_projection(feat, self.y_proj)
e_projected = self.apply_projection(feat, self.e_proj)
s_projected = self.apply_projection(feat, self.s_proj)
return y_projected, s_projected,e_projected
elif self.projection_method == "optimization":
y_projected = self.y_proj(feat)
e_projected = self.e_proj(feat)
s_projected = self.s_proj(feat)
return y_projected, s_projected,e_projected
elif self.projection_method == "svd":
y_projected = self.y_proj(feat)
e_projected = self.e_proj(feat)
s_projected = self.s_proj(feat)
return y_projected, s_projected,e_projected
def forward(self, x):
if self.mode == "source_pretrain":
feat = self.get_base_feature(x)
y_projected, s_projected,e_projected = self.get_projection(feat)
y_feat = torch.cat([y_projected, s_projected], dim=1)
e_feat = torch.cat([e_projected, s_projected], dim=1)
y_logit = self.y_classifier(y_feat)
e_logit = self.e_classifier(e_feat)
return y_logit, e_logit
elif self.mode == "target_finetune":
feat = self.get_base_feature(x)
if self.feature_source == ["y"]:
y_projected, s_projected,e_projected = self.get_projection(feat)
y_feat = y_projected
y_logit = self.y_classifier(y_feat)
e_logit = None
return y_logit, e_logit
elif self.feature_source == ["y", "s"]:
y_projected, s_projected,e_projected = self.get_projection(feat)
y_feat = torch.cat([y_projected, s_projected], dim=1)
y_logit = self.y_classifier(y_feat)
e_logit = None
return y_logit, e_logit
elif self.feature_source == ["y", "s", "e"]:
y_projected, s_projected,e_projected = self.get_projection(feat)
y_feat = torch.cat([y_projected, s_projected,e_projected], dim=1)
y_logit = self.y_classifier(y_feat)
e_logit = None
return y_logit, e_logit
else:
raise NotImplementedError
elif self.mode == "feature_extraction":
feat = self.get_base_feature(x)
y_projected, s_projected,e_projected = self.get_projection(feat)
return feat, y_projected, s_projected,e_projected
raise NotImplementedError
def get_base_feature(self, x):
feat = self.feature_encoder(x)
feat = feat.reshape(x.shape[0], -1)
return feat
def linear_projection_reg(self, weight):
#! Only for projection method = "optimization"
assert self.projection_method == "optimization"
# weight is 2028 * 10
# weight @ weight^T
return torch.norm(weight @ weight.T - torch.eye(weight.shape[0]).to("cuda"))
def ls_projection_matrix_reg(self, P):
assert self.projection_method == "inverse"
return (torch.norm(P @ P - P) + torch.norm(P - P.T))/P.shape[0]
def get_loss(self, x, y, e):
y_logit, e_logit = self.forward(x)
y_loss = self.criterion(y_logit, y)
y_loss_unreduced = self.none_reduction_criterion(y_logit, y)
y_loss = y_loss.mean()
if self.projection_method == "inverse":
if self.mode == "source_pretrain":
# logger.debug(torch.unique(e))
e_loss = self.criterion(e_logit, e)
ye_orth_reg = self.linear_orth_reg(self.y_mat, self.e_mat)
ys_orth_reg = self.linear_orth_reg(self.y_mat, self.s_mat)
es_orth_reg = self.linear_orth_reg(self.e_mat, self.s_mat)
y_proj_reg = self.ls_projection_matrix_reg(self.y_proj)
e_proj_reg = self.ls_projection_matrix_reg(self.e_proj)
s_proj_reg = self.ls_projection_matrix_reg(self.s_proj)
loss_dict = {"y_loss": y_loss,
"e_loss": e_loss,
"ye_orth_reg": ye_orth_reg * self.ye_orth_reg_scale,
"ys_orth_reg": ys_orth_reg * self.ys_orth_reg_scale,
"es_orth_reg": es_orth_reg,
"y_proj_reg": y_proj_reg,
"e_proj_reg": e_proj_reg,
"s_proj_reg": s_proj_reg,
"loss": y_loss + e_loss + ye_orth_reg + ys_orth_reg + es_orth_reg + y_proj_reg + e_proj_reg + s_proj_reg,
}
elif self.mode == "target_finetune":
y_proj_reg = self.projection_matrix_reg(self.y_proj)
s_proj_reg = self.projection_matrix_reg(self.s_proj)
e_logit = None
ys_orth_reg = self.orth_reg(self.y_mat, self.s_mat)
loss_dict = {"y_loss": y_loss,
"y_proj_reg": y_proj_reg,
"s_proj_reg": s_proj_reg,
"ys_orth_reg": ys_orth_reg * self.ys_orth_reg_scale,
"loss": y_loss + y_proj_reg + s_proj_reg,
}
elif self.projection_method == "optimization":
if self.mode == "source_pretrain":
e_loss = self.criterion(e_logit, e)
y_proj_reg = self.linear_projection_reg(self.y_proj.weight)
e_proj_reg = self.linear_projection_reg(self.e_proj.weight)
s_proj_reg = self.linear_projection_reg(self.s_proj.weight)
ye_orth_reg = self.linear_orth_reg(self.y_proj.weight, self.e_proj.weight)
ys_orth_reg = self.linear_orth_reg(self.y_proj.weight, self.s_proj.weight)
es_orth_reg = self.linear_orth_reg(self.e_proj.weight, self.s_proj.weight)
loss_dict = {"y_loss": y_loss,
"e_loss": e_loss,
"y_proj_reg": y_proj_reg,
"e_proj_reg": e_proj_reg,
"s_proj_reg": s_proj_reg,
"loss": y_loss + e_loss + y_proj_reg + e_proj_reg + s_proj_reg}
elif self.mode == "target_finetune":
y_proj_reg = self.linear_projection_reg(self.y_proj.weight)
s_proj_reg = self.linear_projection_reg(self.s_proj.weight)
ys_orth_reg = self.linear_orth_reg(self.y_proj.weight, self.s_proj.weight)
loss_dict = {"y_loss": y_loss,
"y_proj_reg": y_proj_reg,
"s_proj_reg": s_proj_reg,
"ys_orth_reg": ys_orth_reg * self.ys_orth_reg_scale,
"loss": y_loss + y_proj_reg + s_proj_reg}
elif self.projection_method == "svd":
if self.mode == "source_pretrain":
y_proj_reg = self.binary_regularization(self.y_D)
e_proj_reg = self.binary_regularization(self.e_D)
s_proj_reg = self.binary_regularization(self.s_D)
ye_orth_reg = self.sigma_orth_reg(self.y_D, self.e_D)
ys_orth_reg = self.sigma_orth_reg(self.y_D, self.s_D)
es_orth_reg = self.sigma_orth_reg(self.e_D, self.s_D)
y_loss = self.criterion(y_logit, y)
e_loss = self.criterion(e_logit, e)
loss_dict = {
"y_loss": y_loss,
"e_loss": e_loss,
"y_proj_reg": y_proj_reg,
"e_proj_reg": e_proj_reg,
"s_proj_reg": s_proj_reg,
"ye_orth_reg": ye_orth_reg * self.ye_orth_reg_scale,
"ys_orth_reg": ys_orth_reg * self.ys_orth_reg_scale,
"es_orth_reg": es_orth_reg,
"loss": y_loss + e_loss + y_proj_reg + e_proj_reg + s_proj_reg + ye_orth_reg + ys_orth_reg + es_orth_reg,
}
elif self.mode == "target_finetune":
y_proj_reg = self.binary_regularization(self.y_D)
s_proj_reg = self.binary_regularization(self.s_D)
ys_orth_reg = self.sigma_orth_reg(self.y_D, self.s_D)
loss_dict = {
"y_loss": y_loss,
"y_proj_reg": y_proj_reg,
"s_proj_reg": s_proj_reg,
"ys_orth_reg": ys_orth_reg * self.ys_orth_reg_scale,
"loss": y_loss + y_proj_reg + s_proj_reg,
}
return loss_dict, y_logit, y_loss_unreduced, e_logit
# class SVDNet(nn.Module):
# def __init__(self, num_classes, num_envs, mode) -> None:
# super().__init__()
# net = resnet50(weights="DEFAULT")
# fc_in_features = self.net.fc.in_features
# self.feature_encoder = nn.Sequential(*list(self.net.children())[:-1])
# self.U = Orthogonal(d=fc_in_features)
# self.V = Orthogonal(d=fc_in_features)
# self.y_D = torch.empty(fc_in_features, 1).uniform_(0.99, 1.01)
# self.s_D = torch.empty(fc_in_features, 1).uniform_(0.99, 1.01)
# self.e_D = torch.empty(fc_in_features, 1).uniform_(0.99, 1.01)
# self.y_classifier = nn.Linear(fc_in_features, num_classes)
# self.e_classifier = nn.Linear(fc_in_features, num_envs)
# self.none_reduction_criterion = nn.CrossEntropyLoss(reduction="none")
# self.criterion = nn.CrossEntropyLoss()
# self.projection_method = "svd"
# def orth_reg(self, D1, D2):
# # D1 is 2048 * 1
# # D2 is 2048 * 1
# # D1.T @ D2
# return torch.norm(torch.trace(D1.T @ D2), p=2)
# def binary_regularization(D):
# # Calculate the difference from the nearest binary value (0 or 1)
# diff_from_binary = torch.min(D, 1 - D)
# # Square these differences and sum
# penalty = torch.sum(diff_from_binary ** 2)
# return penalty
# def svd_forward(self, x, D):
# x = self.U(x)
# x = D * x
# x = self.V(x)
# return x
# def get_base_feature(self, x):
# feat = self.feature_encoder(x)
# feat = feat.reshape(x.shape[0], -1)
# return feat
# def forward(self, x):
# feat = self.get_base_feature(x)
# y_feat = self.svd_forward(feat, self.y_D)
# s_feat = self.svd_forward(feat, self.s_D)
# e_feat = self.svd_forward(feat, self.e_D)
# y_logit = self.y_classifier(y_feat)
# e_logit = self.e_classifier(e_feat)
# return y_logit, e_logit
# def get_loss(self, x, y, e):
# y_logit, e_logit = self.forward(x)
# y_loss = self.criterion(y_logit, y)
# y_loss_unreduced = self.none_reduction_criterion(y_logit, y)
# y_loss = y_loss.mean()
# if self.projection_method == "svd":
# if self.mode == "source_pretrain":
# e_loss = self.criterion(e_logit, e)
# y_loss = self.criterion(y_logit, y)
# ye_orth_reg = self.orth_reg(self.y_D, self.e_D)
# ys_orth_reg = self.orth_reg(self.y_D, self.s_D)
# es_orth_reg = self.orth_reg(self.e_D, self.s_D)
# loss_dict = {"y_loss": y_loss,
# "e_loss": e_loss,
# "ye_orth_reg": ye_orth_reg,
# "ys_orth_reg": ys_orth_reg * self.ys_orth_reg_scale,
# }
class DANN(nn.Module):
def __init__(self, num_classes) -> None:
super().__init__()
net = resnet50(weights="DEFAULT")
fc_in_features = self.net.fc.in_features
self.feature_encoder = nn.Sequential(*list(self.net.children())[:-1])
self.y_classifier = nn.Linear(fc_in_features, num_classes)
self.e_classifier = nn.Linear(fc_in_features, 3)
def forward(self, x):
feat = self.feature_encoder(x)
feat = feat.reshape(x.shape[0], -1)
y_logit = self.y_classifier(feat)
e_logit = self.e_classifier(feat)
return y_logit, e_logit
def get_feature(self, x):
feat = self.feature_encoder(x)
feat = feat.reshape(x.shape[0], -1)
return feat
class DomainAdaptationModule(LightningModule):
def __init__(self, cfg) -> None:
super().__init__()
self.cfg = cfg
self.mode = cfg.mode
num_classes = self.cfg.dataset.num_classes
num_envs = self.cfg.dataset.num_envs
if cfg.training.method == "erm":
self.model = ERM(num_classes, mode=cfg.mode)
elif cfg.training.method == "nuc":
self.model = NUC(num_classes, mode=cfg.mode, nuc_scale=cfg.training.nuc_scale)
elif cfg.training.method == "dragonnet":
self.model = DragonNet(num_classes, use_fc_bias=cfg.training.use_fc_bias, mode=cfg.mode)
elif cfg.training.is_domainbed:
self.model = ERM(num_classes, mode=cfg.mode)
elif cfg.training.method == "projectionnet":
self.model = ProjectionNet(num_classes,
num_envs=num_envs,
feature_source=cfg.training.feature_source,
mode=cfg.mode,
ye_orth_reg_scale=cfg.training.ye_orth_reg_scale,
ys_orth_reg_scale=cfg.training.ys_orth_reg_scale,
projection_method=cfg.training.projection_method)
elif cfg.training.method == "diwa" and cfg.training.base_method == "ERM":
self.model = ERM(num_classes, mode=cfg.mode)
self.criterion = nn.CrossEntropyLoss(reduction="none")
self.y_acc_metric = torchmetrics.Accuracy(task="multiclass", num_classes=num_classes)
self.e_acc_metric = torchmetrics.Accuracy(task="multiclass", num_classes=num_envs)
self.num_domains = len(cfg.dataset.full_domains)
self.domain_list = list(range(self.num_domains))
self.input_e = cfg.training.input_e
self.test_prefix = ""
self.test_outputs = []
def forward(self, x, e=None):
if self.input_e:
return self.model(x, e)
else:
return self.model(x)
def debatch(self, batch, debug=False):
x, y, e = batch
return x, y, e
def deloss(self, loss, loss_lambda):
return loss + loss_lambda
def general_step(self, batch, batch_idx, stage, dataloader_idx=0):
x, y, e = self.debatch(batch)
# logger.debug(y)
if self.cfg.training.method == "dann":
e_loss = self.criterion(e_logit, e)
elif self.cfg.training.method == "projectionnet":
loss_dict, y_logit, y_loss_unreduced, e_logit = self.model.get_loss(x, y, e)
# log the loss
for k, v in loss_dict.items():
self.log(f"{stage}/{k}", v)
y_acc = self.y_acc_metric(y_logit, y)
if self.mode == "source_pretrain":
e_acc = self.e_acc_metric(e_logit, e)
self.log(f"{stage}/e_acc", e_acc, prog_bar=True)
self.log(f"{stage}/y_acc", y_acc, prog_bar=True)
y_loss_unreduced = self.criterion(y_logit, y)
y_pred = torch.argmax(y_logit, dim=1)
loss = loss_dict["loss"]
elif self.cfg.training.method == "erm":
y_logit = self.forward(x)
y_loss_unreduced = self.criterion(y_logit, y)
loss = y_loss_unreduced.mean()
y_pred = torch.argmax(y_logit, dim=1)
self.log(f"{stage}/y_loss", loss, prog_bar=True)
self.log(f"{stage}/y_acc", self.y_acc_metric(y_pred, y), prog_bar=True)
elif self.cfg.training.method == "nuc":
loss_dict, y_logit = self.model.get_loss(x, y, e)
for k, v in loss_dict.items():
self.log(f"{stage}/{k}", v)
y_acc = self.y_acc_metric(y_logit, y)
self.log(f"{stage}/y_acc", y_acc, prog_bar=True)
y_loss_unreduced = self.criterion(y_logit, y)
y_pred = torch.argmax(y_logit, dim=1)
loss = loss_dict["loss"]
self.model.train_step += 1
else:
if self.input_e:
output = self.forward(x, e)
else:
output = self.forward(x)
if type(output) == tuple:
y_logit, e_logit = output
if type(output) == dict:
y_logit = output["y_logit"]
e_logit = output["e_logit"]
else:
y_logit = output
assert y_logit.shape[0] == y.shape[0]
assert y_logit.shape[1] == self.cfg.dataset.num_classes
y_loss_unreduced = self.criterion(y_logit, y)
loss = y_loss_unreduced.mean()
y_pred = torch.argmax(y_logit, dim=1)
self.log(f"{stage}/y_loss", loss, prog_bar=True)
self.log(f"{stage}/y_acc", self.y_acc_metric(y_pred, y), prog_bar=True)
for domain in self.domain_list:
e_idx = torch.where(e == domain)[0]
if len(e_idx) == 0:
continue
domain_y_loss = y_loss_unreduced[e_idx].mean()
# logger.debug("e_idx", e_idx, len(e_idx))
# logger.debug(y[e_idx].shape, y.shape)
domain_y_acc = self.y_acc_metric(y_pred[e_idx], y[e_idx])
self.log(f"{stage}/e={domain}/y_loss", domain_y_loss)
self.log(f"{stage}/e={domain}/y_acc", domain_y_acc)
return loss
def training_step(self, batch, batch_idx):
return self.general_step(batch, batch_idx, "train")
# def on_train_batch_end(self, **params):
# if self.cfg.training.method == "nuc":
# self.model.train_step += 1
def validation_step(self, batch, batch_idx, dataloader_idx=0):
return self.general_step(batch, batch_idx, "val", dataloader_idx=dataloader_idx)
def on_test_epoch_start(self):
self.test_outputs = []
def test_step(self, batch, batch_idx):
prefix = "test" if self.test_prefix == "" else f"test/{self.test_prefix}"
if self.mode != "feature_extraction":
return self.general_step(batch, batch_idx, prefix)
else:
x, y, e = self.debatch(batch)
output = self.model(x)
if type(output) == torch.Tensor:
# erm
output = [output]
elif type(output) == tuple:
# projectionnet
output = list(output)
append_list = output + [y, e]
self.test_outputs.append(append_list)
return None
def on_test_epoch_end(self):
if self.mode == "feature_extraction":
if self.cfg.training.method == "projectionnet":
base_feature, y_projected, s_projected,e_projected, y, e = zip(*self.test_outputs)
base_feature = torch.cat(base_feature, dim=0)
y_projected = torch.cat(y_projected, dim=0)
s_projected = torch.cat(s_projected, dim=0)
e_projected = torch.cat(e_projected, dim=0)
y = torch.cat(y, dim=0)
e = torch.cat(e, dim=0)
feature_dict = {
"base_feature": base_feature,
"y_projected": y_projected,
"s_projected": s_projected,
"e_projected": e_projected,
"y": y,
"e": e,
}
full_path = f"outputs/{self.cfg.feature_extraction_str}/{self.checkpoint_filename}"
os.makedirs(full_path, exist_ok=True)
logger.info(f"Saving feature_dict to {full_path}/{self.test_prefix}.pt")
torch.save(feature_dict, f"{full_path}/{self.test_prefix}.pt")
elif self.cfg.training.method in ["erm","nuc"] or self.cfg.training.is_domainbed or self.cfg.training.method == "diwa":
base_feature, y, e = zip(*self.test_outputs)
base_feature = torch.cat(base_feature, dim=0)
y = torch.cat(y, dim=0)
e = torch.cat(e, dim=0)
feature_dict = {
"base_feature": base_feature,
"y": y,
"e": e,
}
full_path = f"outputs/{self.cfg.feature_extraction_str}/{self.checkpoint_filename}"
os.makedirs(full_path, exist_ok=True)
logger.info(f"Saving feature_dict to {full_path}/{self.test_prefix}.pt")
torch.save(feature_dict, f"{full_path}/{self.test_prefix}.pt")
return self.test_outputs
else:
return None
def configure_optimizers(self):
if self.cfg.training.optimizer.feature_lr_scale == 1.0:
if self.cfg.training.optimizer.name == "adam":
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.cfg.training.optimizer.lr, weight_decay=0)
elif self.cfg.training.optimizer.feature_lr_scale == 0.0:
if self.cfg.training.optimizer.name == "adam":
if self.cfg.training.method == "projectionnet":
optimizer = torch.optim.Adam([{"params": self.model.y_classifier.parameters()},
{"params": self.model.e_classifier.parameters()},
], lr=self.cfg.training.optimizer.lr, weight_decay=0)
elif self.cfg.training.method == "erm":
optimizer = torch.optim.Adam([{"params": self.model.net.fc.parameters()},
], lr=self.cfg.training.optimizer.lr, weight_decay=0)
else:
if self.cfg.training.optimizer.name == "adam":
encoder = self.model.get_feature_encoder() # sequential
# encoder_parameters = encoder.parameters()
# print("encoder_parameters", encoder_parameters)
encoder_parameters = []
other_parameters = []
# not in encoder
for name, param in self.model.named_parameters():
logger.debug(f"name: {name}")
if "feature_encoder" not in name:
logger.debug(f"other_parameters: {name}")
other_parameters.append(param)
else: