-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain_cvact_bev.py
499 lines (379 loc) · 21.4 KB
/
train_cvact_bev.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
import os
import time
import math
import shutil
import sys
import torch
import pickle
from dataclasses import dataclass
from torch.cuda.amp import GradScaler
from torch.utils.data import DataLoader
from transformers import get_constant_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup
from retrieval.dataset.cvact_bev import CVACTDatasetTrain, CVACTDatasetEval, CVACTDatasetTest
from retrieval.transforms import get_transforms_train, get_transforms_val
from retrieval.utils import setup_system, Logger
from retrieval.trainer import train
from retrieval.evaluate.cvact import evaluate, calc_sim
from retrieval.loss import InfoNCE
from retrieval.model import TimmModel
@dataclass
class Configuration:
# Model
model: str = 'convnext_base.fb_in22k_ft_in1k_384'
# Override model image size
img_size: int = 384
# Training
mixed_precision: bool = True
seed = 1
epochs: int = 60
batch_size: int = 128 # keep in mind real_batch_size = 2 * batch_size
verbose: bool = True
gpu_ids: tuple = (0,1,2,3) # GPU ids for training
# Similarity Sampling
custom_sampling: bool = True # use custom sampling instead of random
gps_sample: bool = True # use gps sampling
sim_sample: bool = True # use similarity sampling
neighbour_select: int = 64 # max selection size from pool
neighbour_range: int = 128 # pool size for selection
gps_dict_path: str = "./GPS/CVACT/gps_dict.pkl" # path to pre-computed distances
# Eval
batch_size_eval: int = 128
eval_every_n_epoch: int = 4 # eval every n Epoch
normalize_features: bool = True
# Optimizer
clip_grad = 100. # None | float
decay_exclue_bias: bool = False
grad_checkpointing: bool = False # Gradient Checkpointing
# Loss
label_smoothing: float = 0.1
# Learning Rate
lr: float = 0.001 # 1 * 10^-4 for ViT | 1 * 10^-3 for CNN
scheduler: str = "cosine" # "polynomial" | "cosine" | "constant" | None
warmup_epochs: int = 1
lr_end: float = 0.0001 # only for "polynomial"
# Dataset
data_folder = "datapath"
# Augment Images
prob_rotate: float = 0.75 # rotates the sat image and ground images simultaneously
prob_flip: float = 0.5 # flipping the sat image and ground images simultaneously
# Savepath for model checkpoints
model_path: str = "./result"
# Eval before training
zero_shot: bool = False
# Checkpoint to start from
checkpoint_start = None
# set num_workers to 0 if on Windows
num_workers: int = 0 if os.name == 'nt' else 4
# train on GPU if available
device: str = 'cuda' if torch.cuda.is_available() else 'cpu'
# for better performance
cudnn_benchmark: bool = True
# make cudnn deterministic
cudnn_deterministic: bool = False
#-----------------------------------------------------------------------------#
# Train Config #
#-----------------------------------------------------------------------------#
config = Configuration()
if __name__ == '__main__':
model_path = "{}/{}/{}".format(config.model_path,
config.model,
time.strftime("%H%M%S"))
if not os.path.exists(model_path):
os.makedirs(model_path)
shutil.copyfile(os.path.basename(__file__), "{}/train.py".format(model_path))
# Redirect print to both console and log file
sys.stdout = Logger(os.path.join(model_path, 'log.txt'))
setup_system(seed=config.seed,
cudnn_benchmark=config.cudnn_benchmark,
cudnn_deterministic=config.cudnn_deterministic)
#-----------------------------------------------------------------------------#
# Model #
#-----------------------------------------------------------------------------#
print("\nModel: {}".format(config.model))
model = TimmModel(config.model,
pretrained=True,
img_size=config.img_size)
data_config = model.get_config()
print(data_config)
mean = data_config["mean"]
std = data_config["std"]
img_size = config.img_size
image_size_sat = (img_size, img_size)
new_width = config.img_size * 2
new_hight = round((224 / 1232) * new_width)
# img_size_ground = (new_hight, new_width)
# The size of the BEV image is consistent with the satellite image.
img_size_ground = image_size_sat
# Activate gradient checkpointing
if config.grad_checkpointing:
model.set_grad_checkpointing(True)
# Load pretrained Checkpoint
if config.checkpoint_start is not None:
print("Start from:", config.checkpoint_start)
model_state_dict = torch.load(config.checkpoint_start)
model.load_state_dict(model_state_dict, strict=False)
# Data parallel
print("GPUs available:", torch.cuda.device_count())
if torch.cuda.device_count() > 1 and len(config.gpu_ids) > 1:
model = torch.nn.DataParallel(model, device_ids=config.gpu_ids)
# Model to device
model = model.to(config.device)
print("\nImage Size Sat:", image_size_sat)
print("Image Size Ground:", img_size_ground)
print("Mean: {}".format(mean))
print("Std: {}\n".format(std))
#-----------------------------------------------------------------------------#
# DataLoader #
#-----------------------------------------------------------------------------#
# Transforms
# All transforms use the satellite's
sat_transforms_train, ground_transforms_train = get_transforms_train(image_size_sat,
img_size_ground,
mean=mean,
std=std,
)
# Train
train_dataset = CVACTDatasetTrain(data_folder=config.data_folder ,
transforms_query=sat_transforms_train,
transforms_reference=sat_transforms_train,
prob_flip=config.prob_flip,
prob_rotate=config.prob_rotate,
shuffle_batch_size=config.batch_size
)
train_dataloader = DataLoader(train_dataset,
batch_size=config.batch_size,
num_workers=config.num_workers,
shuffle=not config.custom_sampling,
pin_memory=True)
# Eval
# All transforms use the satellite's
sat_transforms_val, ground_transforms_val = get_transforms_val(image_size_sat,
img_size_ground,
mean=mean,
std=std,
)
# Reference Satellite Images
reference_dataset_val = CVACTDatasetEval(data_folder=config.data_folder ,
split="val",
img_type="reference",
transforms=sat_transforms_val,
)
reference_dataloader_val = DataLoader(reference_dataset_val,
batch_size=config.batch_size_eval,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
length_of_reference_dataset = len(reference_dataset_val)
print("Length of reference dataset:", length_of_reference_dataset)
# Query Ground Images Test
query_dataset_val = CVACTDatasetEval(data_folder=config.data_folder ,
split="val",
img_type="query",
transforms=sat_transforms_val,
)
query_dataloader_val = DataLoader(query_dataset_val,
batch_size=config.batch_size_eval,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
print("Reference Images Val:", len(reference_dataset_val))
print("Query Images Val:", len(query_dataset_val))
#-----------------------------------------------------------------------------#
# GPS Sample #
#-----------------------------------------------------------------------------#
if config.gps_sample:
with open(config.gps_dict_path, "rb") as f:
sim_dict = pickle.load(f)
else:
sim_dict = None
# sim_dict = None
#-----------------------------------------------------------------------------#
# Sim Sample #
#-----------------------------------------------------------------------------#
if config.sim_sample:
# Query Ground Images Train for simsampling
query_dataset_train = CVACTDatasetEval(data_folder=config.data_folder ,
split="train",
img_type="query",
transforms=ground_transforms_val,
)
query_dataloader_train = DataLoader(query_dataset_train,
batch_size=config.batch_size_eval,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
reference_dataset_train = CVACTDatasetEval(data_folder=config.data_folder ,
split="train",
img_type="reference",
transforms=sat_transforms_val,
)
reference_dataloader_train = DataLoader(reference_dataset_train,
batch_size=config.batch_size_eval,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
print("\nReference Images Train:", len(reference_dataset_train))
print("Query Images Train:", len(query_dataset_train))
#-----------------------------------------------------------------------------#
# Loss #
#-----------------------------------------------------------------------------#
loss_fn = torch.nn.CrossEntropyLoss(label_smoothing=config.label_smoothing)
loss_function = InfoNCE(loss_function=loss_fn,
device=config.device,
)
if config.mixed_precision:
scaler = GradScaler(init_scale=2.**10)
else:
scaler = None
#-----------------------------------------------------------------------------#
# optimizer #
#-----------------------------------------------------------------------------#
if config.decay_exclue_bias:
param_optimizer = list(model.named_parameters())
no_decay = ["bias", "LayerNorm.bias"]
optimizer_parameters = [
{
"params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
"weight_decay": 0.01,
},
{
"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
},
]
optimizer = torch.optim.AdamW(optimizer_parameters, lr=config.lr)
else:
optimizer = torch.optim.AdamW(model.parameters(), lr=config.lr)
#-----------------------------------------------------------------------------#
# Scheduler #
#-----------------------------------------------------------------------------#
train_steps = len(train_dataloader) * config.epochs
warmup_steps = len(train_dataloader) * config.warmup_epochs
if config.scheduler == "polynomial":
print("\nScheduler: polynomial - max LR: {} - end LR: {}".format(config.lr, config.lr_end))
scheduler = get_polynomial_decay_schedule_with_warmup(optimizer,
num_training_steps=train_steps,
lr_end = config.lr_end,
power=1.5,
num_warmup_steps=warmup_steps)
elif config.scheduler == "cosine":
print("\nScheduler: cosine - max LR: {}".format(config.lr))
scheduler = get_cosine_schedule_with_warmup(optimizer,
num_training_steps=train_steps,
num_warmup_steps=warmup_steps)
elif config.scheduler == "constant":
print("\nScheduler: constant - max LR: {}".format(config.lr))
scheduler = get_constant_schedule_with_warmup(optimizer,
num_warmup_steps=warmup_steps)
else:
scheduler = None
print("Warmup Epochs: {} - Warmup Steps: {}".format(str(config.warmup_epochs).ljust(2), warmup_steps))
print("Train Epochs: {} - Train Steps: {}".format(config.epochs, train_steps))
#-----------------------------------------------------------------------------#
# Zero Shot #
#-----------------------------------------------------------------------------#
if config.zero_shot:
print("\n{}[{}]{}".format(30*"-", "Zero Shot", 30*"-"))
r1_test = evaluate(config=config,
model=model,
reference_dataloader=reference_dataloader_val,
query_dataloader=query_dataloader_val,
ranks=[1, 5, 10],
step_size=1000,
cleanup=True)
if config.sim_sample:
r1_train, sim_dict = calc_sim(config=config,
model=model,
reference_dataloader=reference_dataloader_train,
query_dataloader=query_dataloader_train,
ranks=[1, 5, 10],
step_size=1000,
cleanup=True)
#-----------------------------------------------------------------------------#
# Shuffle #
#-----------------------------------------------------------------------------#
if config.custom_sampling:
train_dataloader.dataset.shuffle(sim_dict,
neighbour_select=config.neighbour_select,
neighbour_range=config.neighbour_range)
#-----------------------------------------------------------------------------#
# Train #
#-----------------------------------------------------------------------------#
start_epoch = 0
best_score = 0
for epoch in range(1, config.epochs+1):
print("\n{}[Epoch: {}]{}".format(30*"-", epoch, 30*"-"))
train_loss = train(config,
model,
dataloader=train_dataloader,
loss_function=loss_function,
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler)
print("Epoch: {}, Train Loss = {:.3f}, Lr = {:.6f}".format(epoch,
train_loss,
optimizer.param_groups[0]['lr']))
# evaluate
if (epoch % config.eval_every_n_epoch == 0 and epoch != 0) or epoch == config.epochs:
print("\n{}[{}]{}".format(30*"-", "Evaluate", 30*"-"))
r1_test = evaluate(config=config,
model=model,
reference_dataloader=reference_dataloader_val,
query_dataloader=query_dataloader_val,
ranks=[1, 5, 10],
step_size=1000,
cleanup=True)
if config.sim_sample:
r1_train, sim_dict = calc_sim(config=config,
model=model,
reference_dataloader=reference_dataloader_train,
query_dataloader=query_dataloader_train,
ranks=[1, 5, 10],
step_size=1000,
cleanup=True)
if r1_test > best_score:
best_score = r1_test
if torch.cuda.device_count() > 1 and len(config.gpu_ids) > 1:
torch.save(model.module.state_dict(), '{}/weights_e{}_{:.4f}.pth'.format(model_path, epoch, r1_test))
else:
torch.save(model.state_dict(), '{}/weights_e{}_{:.4f}.pth'.format(model_path, epoch, r1_test))
if config.custom_sampling:
train_dataloader.dataset.shuffle(sim_dict,
neighbour_select=config.neighbour_select,
neighbour_range=config.neighbour_range)
if torch.cuda.device_count() > 1 and len(config.gpu_ids) > 1:
torch.save(model.module.state_dict(), '{}/weights_end.pth'.format(model_path))
else:
torch.save(model.state_dict(), '{}/weights_end.pth'.format(model_path))
#-----------------------------------------------------------------------------#
# Test #
#-----------------------------------------------------------------------------#
# Reference Satellite Images
reference_dataset_test = CVACTDatasetTest(data_folder=config.data_folder ,
img_type="reference",
transforms=sat_transforms_val)
reference_dataloader_test = DataLoader(reference_dataset_test,
batch_size=config.batch_size_eval,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
# Query Ground Images Test
query_dataset_test = CVACTDatasetTest(data_folder=config.data_folder ,
img_type="query",
transforms=sat_transforms_val,
)
query_dataloader_test = DataLoader(query_dataset_test,
batch_size=config.batch_size_eval,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
print("Reference Images Test:", len(reference_dataset_test))
print("Query Images Test:", len(query_dataset_test))
print("\n{}[{}]{}".format(30*"-", "Test", 30*"-"))
r1_test = evaluate(config=config,
model=model,
reference_dataloader=reference_dataloader_test,
query_dataloader=query_dataloader_test,
ranks=[1, 5, 10],
step_size=1000,
cleanup=True)