File size: 12,404 Bytes
1ab03a3 |
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 |
from config import *
from dataset import *
import pandas as pd
import json
import os
import copy
import numpy as np
import pytorch_lightning as pl
from pytorch_lightning import loggers as pl_loggers
from pytorch_lightning.callbacks import *
import torch
class ZipLoader:
def __init__(self, loaders):
self.loaders = loaders
def __len__(self):
return len(self.loaders[0])
def __iter__(self):
for each in zip(*self.loaders):
yield each
class ClsModel(pl.LightningModule):
def __init__(self, conf: TrainConfig):
super().__init__()
assert conf.train_mode.is_manipulate()
if conf.seed is not None:
pl.seed_everything(conf.seed)
self.save_hyperparameters(conf.as_dict_jsonable())
self.conf = conf
# preparations
if conf.train_mode == TrainMode.manipulate:
# this is only important for training!
# the latent is freshly inferred to make sure it matches the image
# manipulating latents require the base model
self.model = conf.make_model_conf().make_model()
self.ema_model = copy.deepcopy(self.model)
self.model.requires_grad_(False)
self.ema_model.requires_grad_(False)
self.ema_model.eval()
if conf.pretrain is not None:
print(f'loading pretrain ... {conf.pretrain.name}')
state = torch.load(conf.pretrain.path, map_location='cpu')
print('step:', state['global_step'])
self.load_state_dict(state['state_dict'], strict=False)
# load the latent stats
if conf.manipulate_znormalize:
print('loading latent stats ...')
state = torch.load(conf.latent_infer_path)
self.conds = state['conds']
self.register_buffer('conds_mean',
state['conds_mean'][None, :])
self.register_buffer('conds_std', state['conds_std'][None, :])
else:
self.conds_mean = None
self.conds_std = None
if conf.manipulate_mode in [ManipulateMode.celebahq_all]:
num_cls = len(CelebAttrDataset.id_to_cls)
elif conf.manipulate_mode.is_single_class():
num_cls = 1
else:
raise NotImplementedError()
# classifier
if conf.train_mode == TrainMode.manipulate:
# latent manipluation requires only a linear classifier
self.classifier = nn.Linear(conf.style_ch, num_cls)
else:
raise NotImplementedError()
self.ema_classifier = copy.deepcopy(self.classifier)
def state_dict(self, *args, **kwargs):
# don't save the base model
out = {}
for k, v in super().state_dict(*args, **kwargs).items():
if k.startswith('model.'):
pass
elif k.startswith('ema_model.'):
pass
else:
out[k] = v
return out
def load_state_dict(self, state_dict, strict: bool = None):
if self.conf.train_mode == TrainMode.manipulate:
# change the default strict => False
if strict is None:
strict = False
else:
if strict is None:
strict = True
return super().load_state_dict(state_dict, strict=strict)
def normalize(self, cond):
cond = (cond - self.conds_mean.to(self.device)) / self.conds_std.to(
self.device)
return cond
def denormalize(self, cond):
cond = (cond * self.conds_std.to(self.device)) + self.conds_mean.to(
self.device)
return cond
def load_dataset(self):
if self.conf.manipulate_mode == ManipulateMode.d2c_fewshot:
return CelebD2CAttrFewshotDataset(
cls_name=self.conf.manipulate_cls,
K=self.conf.manipulate_shots,
img_folder=data_paths['celeba'],
img_size=self.conf.img_size,
seed=self.conf.manipulate_seed,
all_neg=False,
do_augment=True,
)
elif self.conf.manipulate_mode == ManipulateMode.d2c_fewshot_allneg:
# positive-unlabeled classifier needs to keep the class ratio 1:1
# we use two dataloaders, one for each class, to stabiliize the training
img_folder = data_paths['celeba']
return [
CelebD2CAttrFewshotDataset(
cls_name=self.conf.manipulate_cls,
K=self.conf.manipulate_shots,
img_folder=img_folder,
img_size=self.conf.img_size,
only_cls_name=self.conf.manipulate_cls,
only_cls_value=1,
seed=self.conf.manipulate_seed,
all_neg=True,
do_augment=True),
CelebD2CAttrFewshotDataset(
cls_name=self.conf.manipulate_cls,
K=self.conf.manipulate_shots,
img_folder=img_folder,
img_size=self.conf.img_size,
only_cls_name=self.conf.manipulate_cls,
only_cls_value=-1,
seed=self.conf.manipulate_seed,
all_neg=True,
do_augment=True),
]
elif self.conf.manipulate_mode == ManipulateMode.celebahq_all:
return CelebHQAttrDataset(data_paths['celebahq'],
self.conf.img_size,
data_paths['celebahq_anno'],
do_augment=True)
else:
raise NotImplementedError()
def setup(self, stage=None) -> None:
##############################################
# NEED TO SET THE SEED SEPARATELY HERE
if self.conf.seed is not None:
seed = self.conf.seed * get_world_size() + self.global_rank
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
print('local seed:', seed)
##############################################
self.train_data = self.load_dataset()
if self.conf.manipulate_mode.is_fewshot():
# repeat the dataset to be larger (speed up the training)
if isinstance(self.train_data, list):
# fewshot-allneg has two datasets
# we resize them to be of equal sizes
a, b = self.train_data
self.train_data = [
Repeat(a, max(len(a), len(b))),
Repeat(b, max(len(a), len(b))),
]
else:
self.train_data = Repeat(self.train_data, 100_000)
def train_dataloader(self):
# make sure to use the fraction of batch size
# the batch size is global!
conf = self.conf.clone()
conf.batch_size = self.batch_size
if isinstance(self.train_data, list):
dataloader = []
for each in self.train_data:
dataloader.append(
conf.make_loader(each, shuffle=True, drop_last=True))
dataloader = ZipLoader(dataloader)
else:
dataloader = conf.make_loader(self.train_data,
shuffle=True,
drop_last=True)
return dataloader
@property
def batch_size(self):
ws = get_world_size()
assert self.conf.batch_size % ws == 0
return self.conf.batch_size // ws
def training_step(self, batch, batch_idx):
self.ema_model: BeatGANsAutoencModel
if isinstance(batch, tuple):
a, b = batch
imgs = torch.cat([a['img'], b['img']])
labels = torch.cat([a['labels'], b['labels']])
else:
imgs = batch['img']
# print(f'({self.global_rank}) imgs:', imgs.shape)
labels = batch['labels']
if self.conf.train_mode == TrainMode.manipulate:
self.ema_model.eval()
with torch.no_grad():
# (n, c)
cond = self.ema_model.encoder(imgs)
if self.conf.manipulate_znormalize:
cond = self.normalize(cond)
# (n, cls)
pred = self.classifier.forward(cond)
pred_ema = self.ema_classifier.forward(cond)
elif self.conf.train_mode == TrainMode.manipulate_img:
# (n, cls)
pred = self.classifier.forward(imgs)
pred_ema = None
elif self.conf.train_mode == TrainMode.manipulate_imgt:
t, weight = self.T_sampler.sample(len(imgs), imgs.device)
imgs_t = self.sampler.q_sample(imgs, t)
pred = self.classifier.forward(imgs_t, t=t)
pred_ema = None
print('pred:', pred.shape)
else:
raise NotImplementedError()
if self.conf.manipulate_mode.is_celeba_attr():
gt = torch.where(labels > 0,
torch.ones_like(labels).float(),
torch.zeros_like(labels).float())
elif self.conf.manipulate_mode == ManipulateMode.relighting:
gt = labels
else:
raise NotImplementedError()
if self.conf.manipulate_loss == ManipulateLossType.bce:
loss = F.binary_cross_entropy_with_logits(pred, gt)
if pred_ema is not None:
loss_ema = F.binary_cross_entropy_with_logits(pred_ema, gt)
elif self.conf.manipulate_loss == ManipulateLossType.mse:
loss = F.mse_loss(pred, gt)
if pred_ema is not None:
loss_ema = F.mse_loss(pred_ema, gt)
else:
raise NotImplementedError()
self.log('loss', loss)
self.log('loss_ema', loss_ema)
return loss
def on_train_batch_end(self, outputs, batch, batch_idx: int,
dataloader_idx: int) -> None:
ema(self.classifier, self.ema_classifier, self.conf.ema_decay)
def configure_optimizers(self):
optim = torch.optim.Adam(self.classifier.parameters(),
lr=self.conf.lr,
weight_decay=self.conf.weight_decay)
return optim
def ema(source, target, decay):
source_dict = source.state_dict()
target_dict = target.state_dict()
for key in source_dict.keys():
target_dict[key].data.copy_(target_dict[key].data * decay +
source_dict[key].data * (1 - decay))
def train_cls(conf: TrainConfig, gpus):
print('conf:', conf.name)
model = ClsModel(conf)
if not os.path.exists(conf.logdir):
os.makedirs(conf.logdir)
checkpoint = ModelCheckpoint(
dirpath=f'{conf.logdir}',
save_last=True,
save_top_k=1,
# every_n_train_steps=conf.save_every_samples //
# conf.batch_size_effective,
)
checkpoint_path = f'{conf.logdir}/last.ckpt'
if os.path.exists(checkpoint_path):
resume = checkpoint_path
else:
if conf.continue_from is not None:
# continue from a checkpoint
resume = conf.continue_from.path
else:
resume = None
tb_logger = pl_loggers.TensorBoardLogger(save_dir=conf.logdir,
name=None,
version='')
# from pytorch_lightning.
plugins = []
if len(gpus) == 1:
accelerator = None
else:
accelerator = 'ddp'
from pytorch_lightning.plugins import DDPPlugin
# important for working with gradient checkpoint
plugins.append(DDPPlugin(find_unused_parameters=False))
trainer = pl.Trainer(
max_steps=conf.total_samples // conf.batch_size_effective,
resume_from_checkpoint=resume,
gpus=gpus,
accelerator=accelerator,
precision=16 if conf.fp16 else 32,
callbacks=[
checkpoint,
],
replace_sampler_ddp=True,
logger=tb_logger,
accumulate_grad_batches=conf.accum_batches,
plugins=plugins,
)
trainer.fit(model)
|