-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain_end2end.py
executable file
·620 lines (530 loc) · 22.4 KB
/
train_end2end.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
import argparse
import copy
import logging
import math
import os
import os.path as osp
import random
import time
import warnings
from collections import OrderedDict
from datetime import datetime
from pathlib import Path
from tempfile import TemporaryDirectory
import diffusers
import mlflow
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint
import transformers
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import DistributedDataParallelKwargs
from diffusers import AutoencoderKL, DDIMScheduler
from diffusers.optimization import get_scheduler
from diffusers.utils import check_min_version
from diffusers.utils.import_utils import is_xformers_available
from einops import rearrange
from omegaconf import OmegaConf
from PIL import Image
from torchvision import transforms
from tqdm.auto import tqdm
from transformers import CLIPVisionModelWithProjection
from pose_DeepFashion_dataset import HumanPoseDataset
# from pose_dataset import HumanPoseDataset
# from models.mutual_self_attention import ReferenceAttentionControl
from models.pose_guider import PoseGuider
# from models.unet_2d_condition import UNet2DConditionModel
from models.unet_3d import UNet3DConditionModel
# from src.pipelines.pipeline_pose2vid import Pose2VideoPipeline
from utils import (
delete_additional_ckpt,
import_filename,
read_frames,
save_videos_grid,
seed_everything,
)
from transformers import Dinov2Model
from diffusers.models.modeling_utils import ModelMixin
import os
os.environ["NCCL_BLOCKING_WAIT"] = "1"
warnings.filterwarnings("ignore")
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
check_min_version("0.10.0.dev0")
logger = get_logger(__name__, log_level="INFO")
class PatchEmbedding(ModelMixin):
def __init__(self, patch_size, in_chans, embed_dim):
super().__init__()
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
def forward(self, x):
x = self.proj(x) # (B, E, H, W)
return x.flatten(2).transpose(1, 2) # (B, N, E)
class Net(nn.Module):
def __init__( self, denoising_unet: UNet3DConditionModel, pose_guider: PoseGuider, patch : PatchEmbedding):
super().__init__()
self.denoising_unet = denoising_unet
self.pose_guider = pose_guider
self.patch = patch
def forward( self, noisy_latents, timesteps, clip_image_embeds, pose_img, ref_latents):
pose_fea = self.pose_guider(pose_img) #[1, 320, 192, 128]
patch_ref_latents = self.patch(ref_latents) #bs, 4, 64, 64 - > bs, 16, 768
clip_vae_embeds = torch.cat([clip_image_embeds, patch_ref_latents], dim=1) # bs, (257+24), 768
model_pred = self.denoising_unet(noisy_latents, timesteps,pose_cond_fea=pose_fea,encoder_hidden_states=clip_vae_embeds).sample
return model_pred
def compute_snr(noise_scheduler, timesteps):
"""
Computes SNR as per
https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
"""
alphas_cumprod = noise_scheduler.alphas_cumprod
sqrt_alphas_cumprod = alphas_cumprod**0.5
sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
# Expand the tensors.
# Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026
sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[
timesteps
].float()
while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape):
sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None]
alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(
device=timesteps.device
)[timesteps].float()
while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape):
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None]
sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
# Compute SNR.
snr = (alpha / sigma) ** 2
return snr
def main(cfg):
kwargs = DistributedDataParallelKwargs(find_unused_parameters=False)
accelerator = Accelerator(
gradient_accumulation_steps=cfg.solver.gradient_accumulation_steps,
mixed_precision=cfg.solver.mixed_precision,
log_with="mlflow",
project_dir="./mlruns",
kwargs_handlers=[kwargs],
)
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger.info(accelerator.state, main_process_only=False)
if accelerator.is_local_main_process:
transformers.utils.logging.set_verbosity_warning()
diffusers.utils.logging.set_verbosity_info()
else:
transformers.utils.logging.set_verbosity_error()
diffusers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if cfg.seed is not None:
seed_everything(cfg.seed)
exp_name = cfg.exp_name
save_dir = f"{cfg.output_dir}/{exp_name}"
if accelerator.is_main_process:
if not os.path.exists(save_dir):
os.makedirs(save_dir)
inference_config_path = "./configs/inference.yaml"
infer_config = OmegaConf.load(inference_config_path)
if cfg.weight_dtype == "fp16":
weight_dtype = torch.float16
elif cfg.weight_dtype == "fp32":
weight_dtype = torch.float32
else:
raise ValueError(
f"Do not support weight dtype: {cfg.weight_dtype} during training"
)
sched_kwargs = OmegaConf.to_container(cfg.noise_scheduler_kwargs)
if cfg.enable_zero_snr:
sched_kwargs.update(
rescale_betas_zero_snr=True,
timestep_spacing="trailing",
prediction_type="v_prediction",
)
# val_noise_scheduler = DDIMScheduler(**sched_kwargs)
sched_kwargs.update({"beta_schedule": "scaled_linear"})
train_noise_scheduler = DDIMScheduler(**sched_kwargs)
image_enc = Dinov2Model.from_pretrained(
cfg.image_encoder_path,
).to(dtype=weight_dtype, device="cuda")
vae = AutoencoderKL.from_pretrained(cfg.vae_model_path).to(
"cuda", dtype=weight_dtype
)
denoising_unet = UNet3DConditionModel.from_pretrained_2d(
cfg.base_model_path,
cfg.mm_path,
subfolder="unet",
unet_additional_kwargs=OmegaConf.to_container(
infer_config.unet_additional_kwargs
),
).to(device="cuda")
pose_guider = PoseGuider(
conditioning_embedding_channels=320, block_out_channels=(16, 32, 96, 256)
).to(device="cuda", dtype=weight_dtype)
patch = PatchEmbedding(patch_size=16, in_chans=4, embed_dim=768).to(device="cuda", dtype=weight_dtype)
stage1_ckpt_dir = cfg.stage1_ckpt_dir
stage1_ckpt_step = cfg.stage1_ckpt_step
denoising_unet.load_state_dict(
torch.load(
os.path.join(stage1_ckpt_dir, f"denoising_unet-{stage1_ckpt_step}.pth"),
map_location="cpu",
),
strict=False,
)
patch.load_state_dict(
torch.load(
os.path.join(stage1_ckpt_dir, f"patch-{stage1_ckpt_step}.pth"),
map_location="cpu",
),
strict=False,
)
pose_guider.load_state_dict(
torch.load(
os.path.join(stage1_ckpt_dir, f"pose_guider-{stage1_ckpt_step}.pth"),
map_location="cpu",
),
strict=False,
)
# Freeze
vae.requires_grad_(False)
image_enc.requires_grad_(False)
patch.requires_grad_(True)
pose_guider.requires_grad_(True)
denoising_unet.requires_grad_(True)
net = Net(
denoising_unet,
pose_guider,
patch,
)
if cfg.solver.enable_xformers_memory_efficient_attention:
if is_xformers_available():
denoising_unet.enable_xformers_memory_efficient_attention()
else:
raise ValueError(
"xformers is not available. Make sure it is installed correctly"
)
if cfg.solver.gradient_checkpointing:
# reference_unet.enable_gradient_checkpointing()
denoising_unet.enable_gradient_checkpointing()
if cfg.solver.scale_lr:
learning_rate = (
cfg.solver.learning_rate
* cfg.solver.gradient_accumulation_steps
* cfg.data.train_bs
* accelerator.num_processes
)
else:
learning_rate = cfg.solver.learning_rate
# Initialize the optimizer
if cfg.solver.use_8bit_adam:
try:
import bitsandbytes as bnb
except ImportError:
raise ImportError(
"Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
)
optimizer_cls = bnb.optim.AdamW8bit
else:
optimizer_cls = torch.optim.AdamW
trainable_params = list(filter(lambda p: p.requires_grad, net.parameters()))
logger.info(f"Total trainable params {len(trainable_params)}")
optimizer = optimizer_cls(
trainable_params,
lr=learning_rate,
betas=(cfg.solver.adam_beta1, cfg.solver.adam_beta2),
weight_decay=cfg.solver.adam_weight_decay,
eps=cfg.solver.adam_epsilon,
)
# Scheduler
lr_scheduler = get_scheduler(
cfg.solver.lr_scheduler,
optimizer=optimizer,
num_warmup_steps=cfg.solver.lr_warmup_steps
* cfg.solver.gradient_accumulation_steps,
num_training_steps=cfg.solver.max_train_steps
* cfg.solver.gradient_accumulation_steps,
)
train_dataset = HumanPoseDataset(
width=cfg.data.train_width,
height=cfg.data.train_height,
img_scale=(1.0, 1.0),
json_file=cfg.data.json_file,
)
train_dataloader = torch.utils.data.DataLoader(
train_dataset, batch_size=cfg.data.train_bs, shuffle=True, num_workers=4
)
# Prepare everything with our `accelerator`.
(
net,
optimizer,
train_dataloader,
lr_scheduler,
) = accelerator.prepare(
net,
optimizer,
train_dataloader,
lr_scheduler,
)
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
num_update_steps_per_epoch = math.ceil(
len(train_dataloader) / cfg.solver.gradient_accumulation_steps
)
# Afterwards we recalculate our number of training epochs
num_train_epochs = math.ceil(
cfg.solver.max_train_steps / num_update_steps_per_epoch
)
# We need to initialize the trackers we use, and also store our configuration.
# The trackers initializes automatically on the main process.
if accelerator.is_main_process:
run_time = datetime.now().strftime("%Y%m%d-%H%M")
accelerator.init_trackers(
exp_name,
init_kwargs={"mlflow": {"run_name": run_time}},
)
# dump config file
mlflow.log_dict(OmegaConf.to_container(cfg), "config.yaml")
# Train!
total_batch_size = (
cfg.data.train_bs
* accelerator.num_processes
* cfg.solver.gradient_accumulation_steps
)
logger.info("***** Running training *****")
logger.info(f" Num examples = {len(train_dataset)}")
logger.info(f" Num Epochs = {num_train_epochs}")
logger.info(f" Instantaneous batch size per device = {cfg.data.train_bs}")
logger.info(
f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}"
)
logger.info(
f" Gradient Accumulation steps = {cfg.solver.gradient_accumulation_steps}"
)
logger.info(f" Total optimization steps = {cfg.solver.max_train_steps}")
global_step = 0
first_epoch = 0
# Potentially load in the weights and states from a previous save
if cfg.resume_from_checkpoint:
if cfg.resume_from_checkpoint != "latest":
resume_dir = cfg.resume_from_checkpoint
else:
resume_dir = save_dir
# Get the most recent checkpoint
dirs = os.listdir(resume_dir)
dirs = [d for d in dirs if d.startswith("checkpoint")]
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
path = dirs[-1]
accelerator.load_state(os.path.join(resume_dir, path))
accelerator.print(f"Resuming from checkpoint {path}")
global_step = int(path.split("-")[1])
first_epoch = global_step // num_update_steps_per_epoch
resume_step = global_step % num_update_steps_per_epoch
# Only show the progress bar once on each machine.
progress_bar = tqdm(
range(global_step, cfg.solver.max_train_steps),
disable=not accelerator.is_local_main_process,
)
progress_bar.set_description("Steps")
for epoch in range(first_epoch, num_train_epochs):
train_loss = 0.0
t_data_start = time.time()
for step, batch in enumerate(train_dataloader):
t_data = time.time() - t_data_start
with accelerator.accumulate(net):
# Convert videos to latent space
pixel_values_vid = batch["pixel_values_person"].to(weight_dtype) # b, c, 2h, 2w,
pixel_values_image_mask = batch["pixel_values_image_mask"].to(weight_dtype) # b, c, 2h, 2w,
vae_ref_img = batch["vae_ref_img"].to(weight_dtype)
with torch.no_grad():
latents = vae.encode(pixel_values_vid).latent_dist.sample().unsqueeze(2) # b,c,f,2h,2w
latents = latents * 0.18215
# Get the masked image latents
masked_latents = vae.encode(pixel_values_image_mask).latent_dist.sample().unsqueeze(2)
masked_latents = masked_latents * 0.18215
# Get the ref image latents
ref_latents = vae.encode(vae_ref_img).latent_dist.sample() # b,4, h/8, w/8
ref_latents = ref_latents * 0.18215
noise = torch.randn_like(latents)
if cfg.noise_offset > 0:
noise += cfg.noise_offset * torch.randn(
(latents.shape[0], latents.shape[1], 1, 1, 1),
device=latents.device,
)
bsz = latents.shape[0]
# Sample a random timestep for each video
timesteps = torch.randint(
0,
train_noise_scheduler.num_train_timesteps,
(bsz,),
device=latents.device,
)
timesteps = timesteps.long()
pixel_values_pose = batch["pixel_values_pose"].unsqueeze(2).to(device="cuda", dtype=weight_dtype) # (bs, c, H, W)
clip_image_list = []
ref_latents_list = []
# print(len(batch["clip_ref_img"]), len(ref_latents))
for clip_img, ref_latent in zip((batch["clip_ref_img"]), ref_latents):
rand_num = random.random()
if rand_num < 0.05:
clip_image_list.append(torch.zeros_like(clip_img))
ref_latents_list.append(ref_latent)
elif rand_num < 0.1:
clip_image_list.append(clip_img)
ref_latents_list.append(torch.zeros_like(ref_latent))
elif rand_num < 0.15:
clip_image_list.append(torch.zeros_like(clip_img))
ref_latents_list.append(torch.zeros_like(ref_latent))
else:
clip_image_list.append(clip_img)
ref_latents_list.append(ref_latent)
ref_latents = torch.stack(ref_latents_list, dim=0)
with torch.no_grad():
clip_img = torch.stack(clip_image_list, dim=0).to(
dtype=image_enc.dtype, device=image_enc.device
)
clip_img = clip_img.to(device="cuda", dtype=weight_dtype)
clip_image_embeds = image_enc(
clip_img.to("cuda", dtype=weight_dtype)
).last_hidden_state # (bs, 257, d)
# add noise
noisy_latents = train_noise_scheduler.add_noise(latents, noise, timesteps)
# 9 channel input
pixel_values_flag_label = batch["pixel_values_flag_label"].unsqueeze(2).to(accelerator.device,dtype=weight_dtype) # b, c, f, 2h/8, 2w/8,
noisy_latents = torch.cat([noisy_latents, pixel_values_flag_label, masked_latents], dim=1)
# Get the target for loss depending on the prediction type
if train_noise_scheduler.prediction_type == "epsilon":
target = noise
elif train_noise_scheduler.prediction_type == "v_prediction":
target = train_noise_scheduler.get_velocity(
latents, noise, timesteps
)
else:
raise ValueError(
f"Unknown prediction type {train_noise_scheduler.prediction_type}"
)
# ---- Forward!!! -----
model_pred = net(
noisy_latents,
timesteps,
clip_image_embeds,
pixel_values_pose,
ref_latents,
)
if cfg.snr_gamma == 0:
loss = F.mse_loss(
model_pred.float(), target.float(), reduction="mean"
)
else:
snr = compute_snr(train_noise_scheduler, timesteps)
if train_noise_scheduler.config.prediction_type == "v_prediction":
# Velocity objective requires that we add one to SNR values before we divide by them.
snr = snr + 1
mse_loss_weights = (
torch.stack(
[snr, cfg.snr_gamma * torch.ones_like(timesteps)], dim=1
).min(dim=1)[0]
/ snr
)
loss = F.mse_loss(
model_pred.float(), target.float(), reduction="none"
)
loss = (
loss.mean(dim=list(range(1, len(loss.shape))))
* mse_loss_weights
)
loss = loss.mean()
# Gather the losses across all processes for logging (if we use distributed training).
avg_loss = accelerator.gather(loss.repeat(cfg.data.train_bs)).mean()
train_loss += avg_loss.item() / cfg.solver.gradient_accumulation_steps
# Backpropagate
accelerator.backward(loss)
if accelerator.sync_gradients:
accelerator.clip_grad_norm_(
trainable_params,
cfg.solver.max_grad_norm,
)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
if accelerator.sync_gradients:
progress_bar.update(1)
global_step += 1
accelerator.log({"train_loss": train_loss}, step=global_step)
train_loss = 0.0
logs = {
"step_loss": loss.detach().item(),
"lr": lr_scheduler.get_last_lr()[0],
"td": f"{t_data:.2f}s",
}
t_data_start = time.time()
progress_bar.set_postfix(**logs)
if global_step >= cfg.solver.max_train_steps:
break
if global_step % cfg.checkpointing_steps == 1:
save_path = os.path.join(save_dir, f"checkpoint-{global_step}")
# delete_additional_ckpt(save_dir, 1)
accelerator.save_state(save_path)
# save motion module only
unwrap_net = accelerator.unwrap_model(net)
save_checkpoint(
unwrap_net.denoising_unet,
save_dir,
"motion_module",
global_step,
total_limit=3,
)
save_checkpoint(
unwrap_net.denoising_unet,
save_dir,
"denoising_unet",
global_step,
total_limit=3,
)
save_checkpoint(
unwrap_net.pose_guider,
save_dir,
"pose_guider",
global_step,
total_limit=3,
)
save_checkpoint(
unwrap_net.patch,
save_dir,
"patch",
global_step,
total_limit=3,
)
# Create the pipeline using the trained modules and save it.
accelerator.wait_for_everyone()
accelerator.end_training()
def save_checkpoint(model, save_dir, prefix, ckpt_num, total_limit=None):
save_path = osp.join(save_dir, f"{prefix}-{ckpt_num}.pth")
state_dict = model.state_dict()
torch.save(state_dict, save_path)
def decode_latents(vae, latents):
video_length = latents.shape[2]
latents = 1 / 0.18215 * latents
latents = rearrange(latents, "b c f h w -> (b f) c h w")
# video = self.vae.decode(latents).sample
video = []
for frame_idx in tqdm(range(latents.shape[0])):
video.append(vae.decode(latents[frame_idx : frame_idx + 1]).sample)
video = torch.cat(video)
video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
video = (video / 2 + 0.5).clamp(0, 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
video = video.cpu().float().numpy()
return video
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=str, default="./configs/train_end2end.yaml")
args = parser.parse_args()
if args.config[-5:] == ".yaml":
config = OmegaConf.load(args.config)
elif args.config[-3:] == ".py":
config = import_filename(args.config).cfg
else:
raise ValueError("Do not support this format config file")
main(config)