-
Notifications
You must be signed in to change notification settings - Fork 0
/
finetune_core_icub.py
317 lines (262 loc) · 11 KB
/
finetune_core_icub.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
################################################################################
# Copyright (c) 2024 Samsung Electronics Co., Ltd.
#
# Author(s):
# Francesco Barbato ([email protected]; [email protected])
# Umberto Michieli ([email protected])
# Jijoong Moon ([email protected])
# Pietro Zanuttigh ([email protected])
# Mete Ozay ([email protected])
#
# Licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) License, (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at https://creativecommons.org/licenses/by-nc-sa/4.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
# For conditions of distribution and use, see the accompanying LICENSE.md file.
################################################################################
import random
from copy import deepcopy
from shutil import rmtree
from tqdm import tqdm
from numpy import random as npr
import torch
from torch.optim import Adam, lr_scheduler
from torch.utils.tensorboard.writer import SummaryWriter
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
from datasets import CORe50Dataset, iCubWorldDataset
from models import YoloFeats
from utils import clean_predictions, Metrics
def set_seed(seed):
"""
sets the rng seeds for all libraries
"""
torch.manual_seed(seed)
npr.seed(seed)
random.seed(seed)
def str2bool(s):
"""
string to bool
"""
s = s.lower()
if s in ['1', 't', 'true']:
return True
if s in ['0', 'f', 'false']:
return False
raise ValueError(f"[{s}] cannot be parsed as boolean")
def init_loaders_and_models(rank, world_size, args):
"""
initialize stuff here, to reduce SAM cost
"""
if args.dataset == "icub":
tset = iCubWorldDataset(imgsz=672)
vset = iCubWorldDataset(imgsz=672, augment=False)
else:
tset = CORe50Dataset(imgsz=672)
vset = CORe50Dataset(imgsz=672, augment=False)
tsampler = DistributedSampler(tset, num_replicas=world_size, rank=rank, shuffle=True)
tloader = DataLoader(tset,
args.batch_per_gpu,
num_workers=16,
pin_memory=True,
drop_last=True,
sampler=tsampler,
collate_fn=tset.collate_fn)
vloader = DataLoader(vset,
args.batch_per_gpu,
num_workers=8,
pin_memory=True,
drop_last=False,
shuffle=False,
collate_fn=tset.collate_fn)
yolo = YoloFeats(nc=tset.nc, verbose=False)
sdict = dict(yolo.state_dict()) #silence pylint bug
ndict = torch.load(args.pretrained_ckpt, map_location='cpu')
if 'model' in ndict:
ndict = ndict['model'].state_dict()
for k in sdict:
if 'model.22.cv3' not in k and 'fmap' not in k:
sdict[k] = ndict[k]
else:
sdict = {k.replace('module.', ''): v for k,v in ndict.items()}
yolo.load_state_dict(sdict) # initialize yolo with distilled dino weights
yolo.to('cuda')
yolo.eval()
yolo = DDP(yolo, device_ids=[rank], find_unused_parameters=True)
ema_dict = deepcopy(yolo.state_dict())
# freeze layers as in: https://github.com/ultralytics/
# ultralytics/blob/main/ultralytics/engine/trainer.py#L214
for n, p in yolo.named_parameters():
if 'model.22.cv3' in n:
print("Parameter", n, "is trainable.")
else:
p.requires_grad = False
return vset, tloader, vloader, yolo, ema_dict
def init_losses_and_optim(args, yolo, tloader):
"""
init stuff here, to reduce SAM cost
"""
det = yolo.module.init_criterion()
param_groups = [
{'lr': args.lr, 'params':
[p for p in yolo.parameters() if p.requires_grad],
'weight_decay': args.wd}
]
optim = Adam(param_groups, betas=(0.937, 0.999))
scheduler = lr_scheduler.ChainedScheduler([
lr_scheduler.CosineAnnealingLR(optim, args.epochs*len(tloader))
])
return det, optim, scheduler
def train_log(writer, l, it, optim, yo, box, cls, dfl):
"""
log stuff here to reduce sam cost
"""
writer.add_scalar('train/ltot', l.item(), it)
writer.add_scalar('train/lr/yolo', optim.param_groups[0]['lr'], it)
writer.add_scalar('train/wd/yolo', optim.param_groups[0]['weight_decay'], it)
writer.add_scalar('train/lr/dino', optim.param_groups[-1]['lr'], it)
writer.add_scalar('train/yolo/tot', yo.item(), it)
writer.add_scalar('train/yolo/box', box.item(), it)
writer.add_scalar('train/yolo/cls', cls.item(), it)
writer.add_scalar('train/yolo/dfl', dfl.item(), it)
def update_ema(it, args, yolo, ema_dict):
"""
ema
"""
# ema step and reset yolo
if it % args.ema_step == 0:
sdict = dict(yolo.state_dict()) # silence error again
for k in ema_dict:
ema_dict[k] = args.ema_rate*ema_dict[k] + (1-args.ema_rate)*sdict[k]
yolo.load_state_dict(ema_dict)
return yolo, ema_dict
def set_wd(optim, args):
"""
set weight decay based on learning rate
"""
for pg in optim.param_groups:
if pg['weight_decay'] > 0:
pg['weight_decay'] = args.wd * pg['lr']/args.lr
def train_epoch(tloader, e, args, rank, optim, yolo, det, scheduler, ema_dict, writer, it):
"""
do stuff here to reduce SAM cost
"""
# set the current epoch, otherwise same order will be used each time
tloader.sampler.set_epoch(e)
for _, sample in enumerate(tqdm(tloader, desc='Training Epoch \
[%03d/%03d]'%(e+1, args.epochs), disable=rank>0, ncols=150)):
set_wd(optim, args)
optim.zero_grad()
x = sample['img'] / 255.
x = x.to('cuda', dtype=torch.float32)
# yolo input: simple normalization in 0-1
pfeats, _ = yolo(x)
# yolo detection loss
yo, (box, cls, dfl) = det(pfeats, sample)
l = yo/args.batch_per_gpu
l.backward()
if rank == 0:
train_log(writer, l, it, optim, yo, box, cls, dfl)
optim.step()
scheduler.step()
it += 1
yolo, ema_dict = update_ema(it, args, yolo, ema_dict)
return it
def eval_epoch(yolo, args, vset, vloader, e, rank, det, writer):
"""
do stuff here to reduce SAM cost
"""
torch.save(yolo.state_dict(), args.logdir+'/yolo_latest.pth')
metrics = Metrics(vset.names, conf=0.001)
ayo, abox, acls, adfl = 0, 0, 0, 0
with torch.inference_mode():
pbar = tqdm(vloader, desc='Validation Epoch [%03d/%03d], mAP50-90: \
%02.2f%%'%(e+1, args.epochs, 0), disable=rank>0, ncols=150)
for _, sample in enumerate(pbar):
x = sample['img'] / 255.
x = x.to('cuda', dtype=torch.float32)
# yolo input: simple normalization in 0-1
(pred, pfeats), _ = yolo(x)
boxes = yolo.module.get_results(pred)
for i, box in enumerate(boxes):
box, labels, cls = clean_predictions(box, sample, i)
metrics(box, labels, cls)
yo, (box, cls, dfl) = det(pfeats, sample)
ayo += yo
abox += box
acls += cls
adfl += dfl
map50, map75, map50_95 = metrics.get_ap()
pbar.set_description('Validation Epoch [%03d/%03d], mAP50-90: %02.2f%%'%(e+1, args.epochs, map50_95))
writer.add_scalar('val/yolo/tot', ayo.item()/len(vloader), e+1)
writer.add_scalar('val/yolo/box', abox.item()/len(vloader), e+1)
writer.add_scalar('val/yolo/cls', acls.item()/len(vloader), e+1)
writer.add_scalar('val/yolo/dfl', adfl.item()/len(vloader), e+1)
writer.add_scalar('val/metrics/mAP50', map50, e+1)
writer.add_scalar('val/metrics/mAP75', map75, e+1)
writer.add_scalar('val/metrics/mAP50-95', map50_95, e+1)
return map50_95
def main(rank, world_size, args):
"""
main function, as required by DDP
"""
dist_url = "env://"
# select the correct cuda device
torch.cuda.set_device(rank)
# initialize the process group
print(f"| distributed init (rank {rank}): {dist_url}", flush=True)
dist.init_process_group("nccl",
rank=rank,
init_method=dist_url,
world_size=world_size)
dist.barrier()
set_seed(args.seed)
if rank == 0:
rmtree(args.logdir, ignore_errors=True)
writer = SummaryWriter(args.logdir, flush_secs=0.5)
# extra initializations that need first run on master process
if args.dataset == "icub":
_ = iCubWorldDataset(imgsz=672)
_ = iCubWorldDataset(imgsz=672, augment=False)
else:
_ = CORe50Dataset(imgsz=672)
_ = CORe50Dataset(imgsz=672, augment=False)
else:
writer = None
dist.barrier()
vset, tloader, vloader, yolo, ema_dict = init_loaders_and_models(rank, world_size, args)
det, optim, scheduler = init_losses_and_optim(args, yolo, tloader)
bap = 0
it = 0
for e in range(args.epochs):
yolo.eval()
it = train_epoch(tloader, e, args, rank, optim, yolo, det, scheduler, ema_dict, writer, it)
dist.barrier()
yolo.eval()
if rank == 0:
map50_95 = eval_epoch(yolo, args, vset, vloader, e, rank, det, writer)
if bap < map50_95:
bap = map50_95
torch.save(yolo.state_dict(), args.logdir+'/yolo_best.pth')
if rank == 0:
torch.save(yolo.state_dict(), args.logdir+'/yolo_final.pth')
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--epochs", type=int, default=10)
parser.add_argument("--batch_per_gpu", type=int, default=16)
parser.add_argument("--ema_step", type=int, default=10)
parser.add_argument("--ema_rate", type=float, default=.6)
parser.add_argument("--lr", type=float, default=1e-3)
parser.add_argument("--wd", type=float, default=1e-4)
parser.add_argument("--pretrained_ckpt", default="ckpts/auxft.pth")
parser.add_argument("--dataset", default="core50", choices=['core50', 'icub'])
parser.add_argument("--logdir", type=str, default="logs/finetune")
g_args = parser.parse_args()
import os
g_args.logdir = os.path.join(g_args.logdir, g_args.dataset).replace("\\", "/")
main(int(os.environ["LOCAL_RANK"]), int(os.environ["WORLD_SIZE"]), g_args)