-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrain_probVLM.py
292 lines (267 loc) · 9.49 KB
/
train_probVLM.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
import os
from os.path import join as ospj
from os.path import expanduser
from munch import Munch as mch
from tqdm import tqdm_notebook
import numpy as np
import torch
import torch.nn as nn
import clip
import ds
from ds import prepare_coco_dataloaders, prepare_flickr_dataloaders, prepare_cub_dataloaders, prepare_flo_dataloaders
from tqdm import tqdm
from losses import *
from utils import *
def train_ProbVLM(
CLIP_Net,
BayesCap_Net,
train_loader,
eval_loader,
Cri = TempCombLoss(),
device='cuda',
dtype=torch.cuda.FloatTensor(),
init_lr=1e-4,
num_epochs=100,
eval_every=1,
ckpt_path='../ckpt/ProbVLM',
cross_modal_lambda=1e-4,
T1=1e0,
T2=5e-2
):
CLIP_Net.to(device)
CLIP_Net.eval()
##
BayesCap_Net.to(device)
BayesCap_Net.img_BayesCap.train()
BayesCap_Net.txt_BayesCap.train()
##
optimizer = torch.optim.Adam(
list(BayesCap_Net.img_BayesCap.parameters())+list(BayesCap_Net.txt_BayesCap.parameters()),
lr=init_lr
)
optim_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, num_epochs)
score = 1e8
all_loss = []
for eph in range(num_epochs):
eph_loss = 0
BayesCap_Net.train()
with tqdm(train_loader, unit='batch') as tepoch:
for (idx, batch) in enumerate(tepoch):
if idx>2000:
break
tepoch.set_description('Epoch {}'.format(eph))
##
xI, xT = batch[0].to(device), batch[1].to(device)
with torch.no_grad():
xfI, xfT = CLIP_Net(xI, xT)
# xI, xT = xI.type(dtype), xT.type(dtype)
# pass them through the network
(img_mu, img_1alpha, img_beta), (txt_mu, txt_1alpha, txt_beta) = BayesCap_Net(xfI, xfT)
optimizer.zero_grad()
loss_i = Cri(img_mu, img_1alpha, img_beta, xfI, T1=T1, T2=T2)
loss_t = Cri(txt_mu, txt_1alpha, txt_beta, xfT, T1=T1, T2=T2)
#cross modal terms
loss_i4t = Cri(img_mu, img_1alpha, img_beta, xfT, T1=T1, T2=T2)
loss_t4i = Cri(txt_mu, txt_1alpha, txt_beta, xfI, T1=T1, T2=T2)
loss = loss_i + loss_t + cross_modal_lambda*(loss_i4t + loss_t4i)
# print(loss)
loss.backward()
optimizer.step()
##
eph_loss += loss.item()
tepoch.set_postfix(loss=loss.item())
eph_loss /= len(train_loader)
all_loss.append(eph_loss)
print('Avg. loss: {}'.format(eph_loss))
# evaluate and save the models
torch.save(BayesCap_Net.state_dict(), ckpt_path+'_last.pth')
if eph%eval_every == 0:
curr_score = eval_ProbVLM(
CLIP_Net,
BayesCap_Net,
eval_loader,
device=device,
dtype=dtype,
)
print('current score: {} | Last best score: {}'.format(curr_score, score))
if curr_score <= score:
score = curr_score
torch.save(BayesCap_Net.state_dict(), ckpt_path+'_best.pth')
optim_scheduler.step()
def eval_ProbVLM(
CLIP_Net,
BayesCap_Net,
eval_loader,
device='cuda',
dtype=torch.cuda.FloatTensor,
):
CLIP_Net.to(device)
CLIP_Net.eval()
BayesCap_Net.to(device)
BayesCap_Net.eval()
mean_mse = 0
mean_mae = 0
num_imgs = 0
list_error = []
list_var = []
with tqdm(eval_loader, unit='batch') as tepoch:
for (idx, batch) in enumerate(tepoch):
tepoch.set_description('Validating ...')
##
xI, xT = batch[0].to(device), batch[1].to(device)
# xI, xT = xI.type(dtype), xT.type(dtype)
# pass them through the network
with torch.no_grad():
xfI, xfT = CLIP_Net(xI, xT)
(img_mu, img_1alpha, img_beta), (txt_mu, txt_1alpha, txt_beta) = BayesCap_Net(xfI, xfT)
n_batch = img_mu.shape[0]
for j in range(n_batch):
num_imgs += 1
mean_mse += emb_mse(img_mu[j], xfI[j]) + emb_mse(txt_mu[j], xfT[j])
mean_mae += emb_mae(img_mu[j], xfI[j]) + emb_mae(txt_mu[j], xfT[j])
##
mean_mse /= num_imgs
mean_mae /= num_imgs
print(
'Avg. MSE: {} | Avg. MAE: {}'.format
(
mean_mse, mean_mae
)
)
return mean_mae
def train_ProbVLM_HF(
CLIP_Net,
BayesCap_Net,
train_loader,
eval_loader,
Cri = TempCombLoss(),
device='cuda',
dtype=torch.cuda.FloatTensor(),
init_lr=1e-4,
num_epochs=100,
eval_every=1,
ckpt_path='../ckpt/ProbVLM',
cross_modal_lambda=1e-4,
T1=1e0,
T2=5e-2
):
CLIP_Net['img'].to(device)
CLIP_Net['txt'].to(device)
CLIP_Net['img'].eval()
CLIP_Net['txt'].eval()
##
BayesCap_Net.to(device)
# BayesCap_Net.img_BayesCap.train()
BayesCap_Net.txt_BayesCap.train()
##
optimizer = torch.optim.Adam(
# list(BayesCap_Net.img_BayesCap.parameters())+list(BayesCap_Net.txt_BayesCap.parameters()),
list(BayesCap_Net.txt_BayesCap.parameters()),
lr=init_lr
)
optim_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, num_epochs)
score = 1e8
all_loss = []
for eph in range(num_epochs):
eph_loss = 0
BayesCap_Net.train()
with tqdm(train_loader, unit='batch') as tepoch:
for (idx, batch) in enumerate(tepoch):
if idx>2000:
break
tepoch.set_description('Epoch {}'.format(eph))
##
xI, xT = batch[0].to(device), batch[1].to(device)
with torch.no_grad():
xfI = CLIP_Net['img'](xI)
xfT = CLIP_Net['txt'](xT)
# print('dbg1: ', xfI, xfT)
xfI = xfI['last_hidden_state']
xfT = xfT['last_hidden_state']
inb, inc, ind = xfI.shape
tnb, tnc, tnd = xfT.shape
xfI = xfI.reshape(inb, -1)
xfT = xfT.reshape(tnb, -1)
# print('dbg', xfI.shape, xfT.shape)
# print('dbg2: ', xfI.shape, xfT.shape)
# pass them through the network
(img_mu, img_1alpha, img_beta), (txt_mu, txt_1alpha, txt_beta) = BayesCap_Net(xfI, xfT)
optimizer.zero_grad()
loss_i = Cri(img_mu, img_1alpha, img_beta, xfI, T1=T1, T2=T2)
loss_t = Cri(txt_mu, txt_1alpha, txt_beta, xfT, T1=T1, T2=T2)
#cross modal terms
loss_i4t = Cri(img_mu, img_1alpha, img_beta, xfT, T1=T1, T2=T2)
loss_t4i = Cri(txt_mu, txt_1alpha, txt_beta, xfI, T1=T1, T2=T2)
loss = loss_i + loss_t + cross_modal_lambda*(loss_i4t + loss_t4i)
loss = loss_i + loss_t
loss.backward()
optimizer.step()
##
eph_loss += loss.item()
tepoch.set_postfix(loss=loss.item())
eph_loss /= len(train_loader)
all_loss.append(eph_loss)
print('Avg. loss: {}'.format(eph_loss))
# evaluate and save the models
torch.save(BayesCap_Net.state_dict(), ckpt_path+'_last.pth')
if eph%eval_every == 0:
curr_score = eval_ProbVLM_HF(
CLIP_Net,
BayesCap_Net,
eval_loader,
device=device,
dtype=dtype,
)
print('current score: {} | Last best score: {}'.format(curr_score, score))
if curr_score <= score:
score = curr_score
torch.save(BayesCap_Net.state_dict(), ckpt_path+'_best.pth')
optim_scheduler.step()
def eval_ProbVLM_HF(
CLIP_Net,
BayesCap_Net,
eval_loader,
device='cuda',
dtype=torch.cuda.FloatTensor,
):
CLIP_Net['img'].to(device)
CLIP_Net['txt'].to(device)
CLIP_Net['img'].eval()
CLIP_Net['txt'].eval()
BayesCap_Net.to(device)
BayesCap_Net.eval()
mean_mse = 0
mean_mae = 0
num_imgs = 0
list_error = []
list_var = []
with tqdm(eval_loader, unit='batch') as tepoch:
for (idx, batch) in enumerate(tepoch):
tepoch.set_description('Validating ...')
##
xI, xT = batch[0].to(device), batch[1].to(device)
# pass them through the network
with torch.no_grad():
xfI = CLIP_Net['img'](xI)
xfT = CLIP_Net['txt'](xT)
xfI = xfI['last_hidden_state']
xfT = xfT['last_hidden_state']
inb, inc, ind = xfI.shape
tnb, tnc, tnd = xfT.shape
xfI = xfI.reshape(inb, -1)
xfT = xfT.reshape(tnb, -1)
(img_mu, img_1alpha, img_beta), (txt_mu, txt_1alpha, txt_beta) = BayesCap_Net(xfI, xfT)
n_batch = txt_mu.shape[0]
for j in range(n_batch):
num_imgs += 1
mean_mse += emb_mse(txt_mu[j], xfT[j])
mean_mae += emb_mae(txt_mu[j], xfT[j])
mean_mse /= num_imgs
mean_mae /= num_imgs
print(
'Avg. MSE: {} | Avg. MAE: {}'.format
(
mean_mse, mean_mae
)
)
return mean_mae