Open-Sora: Democratizing Efficient Video Production for All
Python
add perceptual loss
Shen-Chenhui3d6d49954339
diff --git a/configs/vae_3d/train/16x256x256.py b/configs/vae_3d/train/16x256x256.pyindex c9aacaa..554080a 100644--- a/configs/vae_3d/train/16x256x256.py+++ b/configs/vae_3d/train/16x256x256.py@@ -16,6 +16,9 @@ sp_size = 1# Define Losskl_weight = 0.000001+use_perceptual_loss = True+perceptual_weight = 1+# Define model@@ -53,5 +56,5 @@ ckpt_every = 1000load = Nonebatch_size = 8-lr = 2e-5+lr = 1e-4grad_clip = 1.0diff --git a/opensora/models/vae/model_utils.py b/opensora/models/vae/model_utils.pyindex 24252a9..37403ce 100644--- a/opensora/models/vae/model_utils.py+++ b/opensora/models/vae/model_utils.py@@ -5,6 +5,7 @@ from typing import Any, Optional, Sequence, Typeimport torch.nn as nnimport numpy as npimport torch+from taming.modules.losses.lpips import LPIPS # need to pip install https://github.com/CompVis/taming-transformers## NOTE: not used since we only have 'GN'@@ -66,6 +67,47 @@ class DiagonalGaussianDistribution(object):return self.meanclass VEA3DLoss(nn.Module):+ def __init__(+ self,+ # disc_start,+ logvar_init=0.0,+ kl_weight=1.0,+ pixelloss_weight=1.0,+ perceptual_weight=1.0,+ disc_loss="hinge"+ ):+ super().__init__()+ assert disc_loss in ["hinge", "vanilla"]+ self.kl_weight = kl_weight+ self.pixel_weight = pixelloss_weight+ # self.perceptual_loss = LPIPS().eval() # TODO+ self.perceptual_weight = perceptual_weight+ # output log variance+ self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init)++ def forward(+ self,+ inputs,+ reconstructions,+ posteriors,+ weights=None,+ ):+ rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())++ nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar+ weighted_nll_loss = nll_loss+ if weights is not None:+ weighted_nll_loss = weights*nll_loss+ weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]+ nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]+ kl_loss = posteriors.kl()+ kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]++ loss = weighted_nll_loss + self.kl_weight * kl_loss # TODO: add discriminator loss later++ return loss++class VEA3DLossWithPerceptualLoss(nn.Module):def __init__(self,# disc_start,@@ -79,13 +121,14 @@ class VEA3DLoss(nn.Module):perceptual_weight=1.0,use_actnorm=False,disc_conditional=False,- disc_loss="hinge"+ disc_loss="hinge",+):- super().__init__()+assert disc_loss in ["hinge", "vanilla"]self.kl_weight = kl_weightself.pixel_weight = pixelloss_weight- # self.perceptual_loss = LPIPS().eval() # TODO+ self.perceptual_loss = LPIPS().eval()self.perceptual_weight = perceptual_weight# output log varianceself.logvar = nn.Parameter(torch.ones(size=()) * logvar_init)@@ -127,9 +170,9 @@ class VEA3DLoss(nn.Module):weights=None,):rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())- # if self.perceptual_weight > 0: # TODO- # p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous())- # rec_loss = rec_loss + self.perceptual_weight * p_loss+ if self.perceptual_weight > 0:+ p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous())+ rec_loss = rec_loss + self.perceptual_weight * p_lossnll_loss = rec_loss / torch.exp(self.logvar) + self.logvarweighted_nll_loss = nll_loss@@ -152,5 +195,4 @@ class VEA3DLoss(nn.Module):# # "{}/g_loss".format(split): g_loss.detach().mean(),# }- return loss-+ return loss\ No newline at end of filediff --git a/scripts/train-vae.py b/scripts/train-vae.pyindex 17407e6..8c36af0 100644--- a/scripts/train-vae.py+++ b/scripts/train-vae.py@@ -33,7 +33,7 @@ from opensora.utils.config_utils import ()from opensora.utils.misc import all_reduce_mean, format_numel_str, get_model_numel, requires_grad, to_torch_dtypefrom opensora.utils.train_utils import update_ema, MaskGenerator-from opensora.models.vae.model_utils import VEA3DLoss+from opensora.models.vae.model_utils import VEA3DLoss, VEA3DLossWithPerceptualLossdef main():@@ -188,6 +188,13 @@ def main():dataloader.sampler.set_start_index(sampler_start_idx)+ # define loss function+ if cfg.use_perceptual_loss:+ loss_function = VEA3DLossWithPerceptualLoss(kl_weight=cfg.kl_weight).to(device, dtype)+ else:+ loss_function = VEA3DLoss(kl_weight=cfg.kl_weight, perceptual_weight=cfg.perceptual_weight).to(device, dtype).to(device, dtype)++# 6.2. training loopfor epoch in range(start_epoch, cfg.epochs):dataloader.sampler.set_epoch(epoch)@@ -206,7 +213,6 @@ def main():x = batch["video"].to(device, dtype) # [B, C, T, H, W]# loss = vae.get_loss(x)- loss_function = VEA3DLoss(kl_weight=cfg.kl_weight).to(device, dtype)reconstructions, posterior = vae(x)loss = loss_function(x, reconstructions, posterior)