-
Notifications
You must be signed in to change notification settings - Fork 2
/
train_encoder.py
180 lines (151 loc) · 7.55 KB
/
train_encoder.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
import os
import sys
import random
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as F
from tqdm import tqdm
from torchvision.utils import make_grid
from torch.optim.lr_scheduler import StepLR
here_dir = '.'
sys.path.append(os.path.join(here_dir, 'src'))
import models
from utils import KLD_COLORS
from models import DecisionDensenetModel
from omegaconf import OmegaConf
from data.utils import CustomImageDataset
#output_dir = 'encoder_finetuning'
#output_dir = 'encoder_finetuning_no_decision'
output_dir = 'encoder_finetuning_l1_lpips'
#loss_type = "l2"
loss_type = "l1"
os.makedirs(output_dir, exist_ok=True)
device = 'cuda'
bs = 6 # ok for urus 40
bs = 2 # ok for urus 20
bs = 1 # ok for other gpus
mlp_idx = -1
log_imgs_every = 500
save_every = 1000
lr = 0.002
n_iters = 150000
blobgan_weights = 'checkpoints/blobgan_256x512.ckpt'
decision_model_weights = 'checkpoints/decision_densenet.tar'
config = OmegaConf.load('src/configs/experiment/invertblobgan_rect.yaml')
#config = OmegaConf.load('src/configs/experiment/invertblobgan_rect_no_decision.yaml')
config.model.generator_pretrained = blobgan_weights
model = models.get_model(**config.model).to(device)
model.inverter.load_state_dict(torch.load('encoder_pretraining/best.pt')['model']) # best is step 55k (killed after 100k steps), with bs=16 for pretraining
decision_model = DecisionDensenetModel(num_classes=4)
decision_model.load_state_dict(torch.load(decision_model_weights)['model_state_dict'])
decision_model.eval().to(device)
no_jiter = True
stats = {'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5)}
aspect_ratio, resolution = config.model.generator.aspect_ratio, config.model.generator.resolution
if aspect_ratio != 1 and type(resolution) == int:
resolution = (resolution, int(aspect_ratio*resolution))
transform = T.Compose([
t for t in [
T.Resize(resolution, T.InterpolationMode.LANCZOS),
T.CenterCrop(resolution),
#T.RandomHorizontalFlip(),
T.ToTensor(),
T.Normalize(stats['mean'], stats['std'], inplace=True),
]
])
dataset_path = '/datasets_local/BDD/bdd100k/images/100k/train'
dataset = CustomImageDataset(dataset_path, transform)
dataloader_train = torch.utils.data.DataLoader(dataset, batch_size=bs, shuffle=True, drop_last=True)
params = list(model.inverter.parameters())
print(f'Optimizing {sum([p.numel() for p in params]) / 1e6:.2f}M params')
optimizer = torch.optim.Adam(params, lr=lr)
scheduler_steplr = StepLR(optimizer, step_size=5000, gamma=0.5)
losses_ = {'fake_MSE':[], 'fake_LPIPS':[], 'fake_decision':[], 'fake_latents_MSE':[],
'real_MSE':[], 'real_LPIPS':[], 'real_decision':[], 'T_loss':[]}
iters = 0
best_loss = 100
while iters < n_iters:
pbar = tqdm(dataloader_train, leave=True)#, desc=f'Image {i}')
for batch_idx, batch in enumerate(pbar):
batch_real, batch_labels = batch
batch_real = batch_real.to(device)
z = torch.randn(bs, model.generator.noise_dim).to(device)
log_images = batch_idx % log_imgs_every ==0
with torch.no_grad():
layout_gt_fake, gen_imgs = model.generator.gen(z, ema=True, viz=log_images, no_jiter=no_jiter,
ret_layout=True, viz_colors=KLD_COLORS)
target_decision_feat_fake = decision_model.feat_extract(gen_imgs)
target_decision_feat_real = decision_model.feat_extract(batch_real)
losses = dict()
z_pred_fake = model.inverter(gen_imgs.detach())
layout_pred_fake, reconstr_fake = model.generator.gen(z=z_pred_fake, ema=True, no_jiter=no_jiter, viz=log_images, ret_layout=True, mlp_idx=-1, viz_colors=KLD_COLORS)
if loss_type == "l2":
losses['fake_MSE'] = (gen_imgs - reconstr_fake).pow(2).mean()
elif loss_type == "l1":
losses['fake_MSE'] = torch.abs(gen_imgs - reconstr_fake).mean()
else:
assert False
losses['fake_LPIPS'] = model.L_LPIPS(reconstr_fake, gen_imgs).mean()
decision_feat_fake = decision_model.feat_extract(reconstr_fake)
losses['fake_decision'] = torch.mean((decision_feat_fake - target_decision_feat_fake) ** 2)
latent_l2_loss = []
for k in ('xs', 'ys', 'covs', 'sizes', 'features', 'spatial_style'):
latent_l2_loss.append((layout_pred_fake[k] - layout_gt_fake[k].detach()).pow(2).mean())
losses['fake_latents_MSE'] = sum(latent_l2_loss) / len(latent_l2_loss)
z_pred_real = model.inverter(batch_real.detach())
layout_pred_real, reconstr_real = model.generator.gen(z_pred_real, ema=True, viz=log_images, ret_layout=True,
no_jiter=no_jiter, mlp_idx=-1, viz_colors=KLD_COLORS)
#mlp_idx=len(self.generator.layout_net_ema.mlp))
if loss_type == "l2":
losses['real_MSE'] = (batch_real - reconstr_real).pow(2).mean()
elif loss_type == "l1":
losses['real_MSE'] = torch.abs(batch_real - reconstr_real).mean()
else:
assert False
losses['real_LPIPS'] = model.L_LPIPS(reconstr_real, batch_real).mean()
decision_feat_real = decision_model.feat_extract(reconstr_real)
losses['real_decision'] = torch.mean((decision_feat_real - target_decision_feat_real) ** 2)
total_loss = f'T_loss'
losses[total_loss] = sum(map(lambda k: losses[k] * model.λ[k], losses))
log_message = ''
for (key,val) in losses.items():
losses_[key].append(val.item())
if len(losses_[key])>100:
losses_[key].pop(0)
short_key = key.replace('fake','F').replace('real','R').replace('decision', 'Dec').replace('latents','lat')
log_message += f'{short_key}: {sum(losses_[key])/len(losses_[key]):.3f}, '
pbar.set_description_str(log_message)
# Do optimization.
optimizer.zero_grad()
losses[total_loss].backward()
optimizer.step()
scheduler_steplr.step()
if log_images:
with torch.no_grad():
imgs = {
'real': batch_real,
'real_reconstr': reconstr_real,
'fake': gen_imgs,
'fake_reconstr': reconstr_fake,
'real_reconstr_feats': torch.nn.functional.interpolate(layout_pred_real['feature_img'], size=resolution),
'fake_reconstr_feats': torch.nn.functional.interpolate(layout_pred_fake['feature_img'], size=resolution),
'fake_feats': torch.nn.functional.interpolate(layout_gt_fake['feature_img'], size=resolution)
}
imgs = {k: v.clone().detach().float().cpu() for k, v in imgs.items()}
imgs = torch.cat([v for v in imgs.values()], 0)
image_grid = make_grid(
imgs, normalize=True, value_range=(-1, 1), nrow=bs
)
image_grid = F.to_pil_image(image_grid)
image_grid = image_grid.save(f"{output_dir}/step_{iters}.jpg")
iters += 1
if iters % save_every == 0:
state_dict = {'model': model.inverter.state_dict(),
'optimizer': optimizer.state_dict(),
'scheduler': scheduler_steplr.state_dict(),
'iter': iters}
torch.save(state_dict,f"{output_dir}/last.pt")
mean_loss = sum(losses_[key])/len(losses_[key])
if mean_loss < best_loss:
best_loss = mean_loss
torch.save(state_dict,f"{output_dir}/best.pt")