Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
308 lines (275 loc) · 10.3 KB
/
Copy pathmain.py
File metadata and controls
308 lines (275 loc) · 10.3 KB
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
import argparse
import sklearn.utils
import torch
import os
import sys
from torchvision.transforms import InterpolationMode
from dassl.utils import setup_logger, set_random_seed
from dassl.config import get_cfg_default
from dassl.engine import build_trainer
import numpy as np
import sklearn
from sklearn.metrics import accuracy_score
import os.path as osp
import matplotlib.pyplot as plt
import seaborn as sns
import datasets.oxford_pets
import datasets.oxford_flowers
import datasets.fgvc_aircraft
import datasets.dtd
import datasets.eurosat
import datasets.stanford_cars
import datasets.food101
import datasets.sun397
import datasets.caltech101
import datasets.ucf101
import datasets.imagenet
import datasets.imagenet_sketch
import datasets.imagenetv2
import datasets.imagenet_a
import datasets.imagenet_r
import datasets.cifar10
import datasets.cifar100
import datasets.stl10
import datasets.imagenet100
import trainers.coop
import trainers.cocoop
import trainers.bicog
import trainers.zsclip
import trainers.maple
import trainers.vpt
import trainers.promptsrc
import trainers.tcp
from trainers.bicog import BiCoG
def setup_cfg(args, model_names):
print("----------Build up cfg----------")
prompts = ["a photo of a", "a photo of a", "a photo of a"]
cfg = [get_cfg_default() for _ in range(3)]
for i in range(3):
extend_cfg(cfg[i])
cfg[i].merge_from_file(args.dataset_config_file)
cfg[i].merge_from_file(f"./configs/trainers/BiCoG/{model_names[i]}.yaml")
cfg[i].TRAINER.PROMPTSRC.CTX_INIT = prompts[i]
if args.root:
cfg[i].DATASET.ROOT = args.root
if args.output_dir:
cfg[i].OUTPUT_DIR = osp.join(args.output_dir, "model_" + str(i))
if args.model_dir:
cfg[i].MODEL_DIR = osp.join(args.model_dir, "model_" + str(i))
if args.resume:
cfg[i].RESUME = args.resume
if args.seed:
cfg[i].SEED = args.seed
if args.source_domains:
cfg[i].DATASET.SOURCE_DOMAINS = args.source_domains
if args.target_domains:
cfg[i].DATASET.TARGET_DOMAINS = args.target_domains
if args.transforms:
cfg[i].INPUT.TRANSFORMS = args.transforms
if args.backbone:
cfg[i].MODEL.BACKBONE.NAME = args.backbone
if args.head:
cfg[i].MODEL.HEAD.NAME = args.head
cfg[i].merge_from_list(args.opts)
cfg[i].freeze()
return cfg
def extend_cfg(cfg):
cfg.TRAINER.MODAL = "classification"
from yacs.config import CfgNode as CN
cfg.TRAINER.COOP = CN()
cfg.TRAINER.COOP.N_CTX = 16 # number of context vectors
cfg.TRAINER.COOP.CSC = False # class-specific context
cfg.TRAINER.COOP.CTX_INIT = "" # initialization words
cfg.TRAINER.COOP.PREC = "fp16" # fp16, fp32, amp
cfg.TRAINER.COOP.CLASS_TOKEN_POSITION = "end" # 'middle' or 'end' or 'front'
# Config for CoCoOp
cfg.TRAINER.COCOOP = CN()
cfg.TRAINER.COCOOP.N_CTX = 16 # number of context vectors
cfg.TRAINER.COCOOP.CTX_INIT = "" # initialization words
cfg.TRAINER.COCOOP.PREC = "fp16" # fp16, fp32, amp
# Config for MaPLe
cfg.TRAINER.MAPLE = CN()
cfg.TRAINER.MAPLE.N_CTX = 2 # number of context vectors
cfg.TRAINER.MAPLE.CTX_INIT = "a photo of a" # initialization words
cfg.TRAINER.MAPLE.PREC = "fp16" # fp16, fp32, amp
cfg.TRAINER.MAPLE.PROMPT_DEPTH = (
9 # Max 12, minimum 0, for 1 it will act as shallow MaPLe (J=1)
)
# Config for VPT
cfg.TRAINER.VPT = CN()
cfg.TRAINER.VPT.N_CTX_VISION = 2 # number of context vectors at the vision branch
cfg.TRAINER.VPT.CTX_INIT = "a photo of a" # initialization words
cfg.TRAINER.VPT.PREC = "fp16" # fp16, fp32, amp
cfg.TRAINER.VPT.PROMPT_DEPTH_VISION = (
1 # if set to 1, will represent shallow vision prompting only
)
# Config for independent Vision Language prompting (independent-vlp)
cfg.TRAINER.IVLP = CN()
cfg.TRAINER.IVLP.N_CTX_VISION = 2 # number of context vectors at the vision branch
cfg.TRAINER.IVLP.N_CTX_TEXT = 2 # number of context vectors at the language branch
cfg.TRAINER.IVLP.CTX_INIT = (
"a photo of a" # initialization words (only for language prompts)
)
cfg.TRAINER.IVLP.PREC = "fp16" # fp16, fp32, amp
# If both variables below are set to 0, 0, will the config will degenerate to COOP model
cfg.TRAINER.IVLP.PROMPT_DEPTH_VISION = (
9 # Max 12, minimum 0, for 0 it will act as shallow IVLP prompting (J=1)
)
cfg.TRAINER.IVLP.PROMPT_DEPTH_TEXT = (
9 # Max 12, minimum 0, for 0 it will act as shallow IVLP prompting(J=1)
)
# Config for PromptSRC
cfg.TRAINER.PROMPTSRC = CN()
cfg.TRAINER.PROMPTSRC.N_CTX_VISION = (
4 # number of context vectors at the vision branch
)
cfg.TRAINER.PROMPTSRC.N_CTX_TEXT = (
4 # number of context vectors at the language branch
)
cfg.TRAINER.PROMPTSRC.CTX_INIT = "a photo of a" # initialization words
cfg.TRAINER.PROMPTSRC.PREC = "fp16" # fp16, fp32, amp
cfg.TRAINER.PROMPTSRC.PROMPT_DEPTH_VISION = (
9 # Max 12, minimum 0, for 0 it will be using shallow IVLP prompting (J=1)
)
cfg.TRAINER.PROMPTSRC.PROMPT_DEPTH_TEXT = (
9 # Max 12, minimum 0, for 0 it will be using shallow IVLP prompting (J=1)
)
cfg.TRAINER.PROMPTSRC.TEXT_LOSS_WEIGHT = 25
cfg.TRAINER.PROMPTSRC.IMAGE_LOSS_WEIGHT = 10
cfg.TRAINER.PROMPTSRC.GPA_MEAN = 15
cfg.TRAINER.PROMPTSRC.GPA_STD = 1
cfg.LOSS = CN()
cfg.LOSS.GM = False
cfg.LOSS.NAME = ""
cfg.LOSS.ALPHA = 0.0
cfg.LOSS.T = 1.0
cfg.LOSS.LAMBDA = 1.0
cfg.DATASET.SUBSAMPLE_CLASSES = "all"
cfg.TRAINER.STRATEGY = "semi-supervised"
cfg.DATASET.NUM_UNLABELED_SHOTS = 0
cfg.TRAIN_OR_TEST = "train"
def get_dataset(model):
return (
model.dm.dataset.train_x,
model.dm.dataset.train_u,
model.dm.dataset.val,
model.dm.dataset.test,
)
def main(args):
model_names = [args.classifier, args.classifier, args.classifier]
cfg = setup_cfg(args, model_names)
base_cfg = cfg[0]
seed = base_cfg.SEED
setup_logger(args.output_dir)
if torch.cuda.is_available() and base_cfg.USE_CUDA:
torch.backends.cudnn.benchmark = True
models_bicog = []
warm_up_epochs = base_cfg.TRAIN.WARMUP
train_x=None
if not args.eval_only:
for i in range(3):
print(f"----------Build up {model_names[i]}----------")
set_random_seed(seed + i)
cfg[i].defrost()
cfg[i].TRAINER.STRATEGY = "supervised"
cfg[i].freeze()
model = build_trainer(cfg[i])
if i == 0:
train_x, train_u, val, test = get_dataset(model)
print(f"train_x size: {len(train_x)}")
sub_train_x = sklearn.utils.resample(train_x, replace=False, n_samples=len(train_x))
print(f"Training model {i} for {warm_up_epochs} epochs")
model.fit(sub_train_x, max_epoch=warm_up_epochs, Save=True)
if seed >= 0:
print("Setting fixed seed: {}".format(seed))
set_random_seed(seed)
for i in range(3):
print(f"----------Build up BiCoG {model_names[i]}----------")
cfg[i].defrost()
cfg[i].TRAINER.STRATEGY = "semi-supervised"
cfg[i].freeze()
model_bicog = build_trainer(cfg[i])
load_dirs = [osp.join(cfg[i].MODEL_DIR, model_names[i]) for i in range(3)]
print(load_dirs[i])
model_bicog.custom_load_model(load_dirs[i], "warmup.pth.tar")
models_bicog.append(model_bicog)
train_x, train_u, val, test = get_dataset(models_bicog[0])
test_y = [datum.label for datum in test]
if args.eval_only:
load_dirs = [osp.join(cfg[i].MODEL_DIR, model_names[i]) for i in range(3)]
for i in range(3):
models_bicog[i].custom_load_model(load_dirs[i])
bicog = BiCoG(base_cfg, *models_bicog)
y_pred = bicog.predict(test)
accuracy = accuracy_score(test_y, y_pred)
print(f"Accuracy: {accuracy}")
sys.stdout.flush()
return
else:
bicog = BiCoG(base_cfg, *models_bicog)
bicog.fit(train_x, train_u, True)
sys.stdout.flush()
return
if __name__ == "__main__":
parser = (
argparse.ArgumentParser()
)
parser.add_argument("--root", type=str, default="", help="path to dataset")
parser.add_argument("--output-dir", type=str, default="", help="output directory")
parser.add_argument(
"--resume",
type=str,
default="",
help="checkpoint directory (from which the training resumes)",
)
parser.add_argument(
"--seed", type=int, default=-1, help="only positive value enables a fixed seed"
)
parser.add_argument(
"--source-domains", type=str, nargs="+", help="source domains for DA/DG"
)
parser.add_argument(
"--target-domains", type=str, nargs="+", help="target domains for DA/DG"
)
parser.add_argument(
"--transforms", type=str, nargs="+", help="data augmentation methods"
)
parser.add_argument(
"--config-file", type=str, default="", help="path to config file"
) # configs/trainers/CoOp/vit_b16.yaml
parser.add_argument(
"--dataset-config-file",
type=str,
default="",
help="path to config file for dataset setup",
)
parser.add_argument("--trainer", type=str, default="", help="name of trainer")
parser.add_argument("--backbone", type=str, default="", help="name of CNN backbone")
parser.add_argument("--head", type=str, default="", help="name of head")
parser.add_argument("--eval-only", action="store_true", help="evaluation only")
parser.add_argument(
"--model-dir",
type=str,
default="",
help="load model from this directory for eval-only mode",
)
parser.add_argument(
"--load-epoch", type=int, help="load model weights at this epoch for evaluation"
)
parser.add_argument(
"--no-train", action="store_true", help="do not call trainer.train()"
)
parser.add_argument(
"--classifier", type=str, default="", help="name of classifier"
)
parser.add_argument(
"opts",
default=None,
nargs=argparse.REMAINDER,
help="modify config options using the command-line",
)
args = (
parser.parse_args()
)
main(args)
os._exit(0)