Skip to content

Open-Sora: Democratizing Efficient Video Production for All

Python

added vae3d training code

shenchenhuia5917c6a3e50
diff --git a/configs/vae_3d/train/16x256x256.py b/configs/vae_3d/train/16x256x256.py
new file mode 100644
index 0000000..9670088
--- /dev/null
+++ b/configs/vae_3d/train/16x256x256.py
@@ -0,0 +1,56 @@
+num_frames = 16
+frame_interval = 3
+image_size = (256, 256)
+
+# Define dataset
+root = None
+data_path = "CSV_PATH"
+use_image_transform = False
+num_workers = 4
+
+# Define acceleration
+dtype = "bf16"
+grad_checkpoint = True
+plugin = "zero2"
+sp_size = 1
+
+# Define model
+
+vae = dict(
+ type="VAE_3D",
+ from_pretrained=None,
+ in_out_channels = 4,
+ latent_embed_dim = 256,
+ filters = 64,
+ num_res_blocks = 2,
+ channel_multipliers = (1, 2, 2, 4),
+ temporal_downsample = (True, True, False),
+ num_groups = 32, # for nn.GroupNorm
+ conv_downsample = False,
+ upsample = "nearest+conv", # options: "deconv", "nearest+conv"
+ kl_embed_dim = 64,
+ custom_conv_padding = None,
+ activation_fn = 'swish',
+ kl_weight = 0.000001,
+)
+
+# TODO: check all these settings
+
+scheduler = dict(
+ type="iddpm",
+ timestep_respacing="",
+)
+
+# Others
+seed = 42
+outputs = "outputs"
+wandb = False
+
+epochs = 3
+log_every = 1
+ckpt_every = 1000
+load = None
+
+batch_size = 8
+lr = 2e-5
+grad_clip = 1.0
diff --git a/configs/vae_3d/vqgan2d_ucf101_config.py b/configs/vae_3d/vqgan2d_ucf101_config.py
new file mode 100644
index 0000000..ee61cab
--- /dev/null
+++ b/configs/vae_3d/vqgan2d_ucf101_config.py
@@ -0,0 +1,178 @@
+# Copyright 2023 The videogvt Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# pylint: disable=line-too-long
+r"""Configs for the VQGAN-2D on the UCF101.
+
+"""
+
+import ml_collections
+
+UCF101_TRAIN_SIZE = 9_537
+UCF101_TEST_SIZE = 3_783
+NUM_CLASSES = 101
+VARIANT = 'VQGAN/2D'
+
+
+def get_config(config_str='B'):
+ """Returns the base experiment configuration."""
+ version, *options = config_str.split('-')
+
+ config = ml_collections.ConfigDict()
+ config.experiment_name = f'UCF101_{VARIANT}'
+
+ # Overall
+ config.rng_seed = 0
+ config.image_size = 128
+ config.batch_size = 256
+ config.eval_batch_size = config.get_ref('batch_size') // 4
+ config.num_training_epochs = 1000
+ config.lax_precision = 'default'
+
+ # Dataset.
+ config.dataset_name = 'ucf101'
+ config.data_dtype_str = 'float32'
+ config.dataset_configs = ml_collections.ConfigDict()
+ config.dataset_configs.num_classes = NUM_CLASSES
+ config.dataset_configs.num_frames = 16
+ config.dataset_configs.stride = 1
+ # TODO(Lijun-Yu, roadjiang): test this augmentation and other augmentations.
+ # min_resize = int(min_resize / 224 * 256)
+ config.dataset_configs.min_resize = config.get_oneway_ref('image_size')
+ config.dataset_configs.crop_size = config.get_ref('image_size')
+ config.dataset_configs.one_hot_label = False
+ config.dataset_configs.zero_centering = False # Range is 0 to 1
+ config.dataset_configs.num_test_clips = 1
+ config.dataset_configs.prefetch_to_device = 2
+ config.num_train_sampled_frames = 4
+
+ # Model: vqvae
+ model_class, model_type = VARIANT.split('/')
+ config.dtype = config.get_ref('data_dtype_str')
+ config.model_class = model_class
+
+ config.pretrained_image_model = True
+ config.perceptual_loss_weight = 0.1
+ config.perceptual_loss_on_logit = True
+ config.polyak_decay = 0.999 # ema decay factor for generator
+
+ config.vqgan = ml_collections.ConfigDict()
+ config.vqgan.model_type = model_type
+ config.vqgan.loss_type = 'non-saturating'
+ config.vqgan.g_adversarial_loss_weight = 0.1
+ config.vqgan.gradient_penalty = 'r1' # r1, none
+ config.vqgan.grad_penalty_cost = 10.0
+ # finetune decoder
+ config.vqgan.finetune_decoder = False
+ config.vqgan.finetune_path = ''
+
+ config.vqvae = ml_collections.ConfigDict()
+ config.vqvae.architecture = '2dcnn'
+ config.vqvae.codebook_size = 1024
+ config.vqvae.entropy_loss_ratio = 0.1
+ config.vqvae.entropy_temperature = 0.01
+ config.vqvae.entropy_loss_type = 'softmax'
+ config.vqvae.commitment_cost = 0.25
+
+ config.vqvae.filters = {'B': 64, 'L': 128}[version]
+ config.vqvae.num_enc_res_blocks = 2
+ config.vqvae.num_dec_res_blocks = 2
+ config.vqvae.channel_multipliers = (1, 2, 2, 4)
+ config.vqvae.embedding_dim = 256
+ config.vqvae.conv_downsample = False
+ config.vqvae.deconv_upsample = False
+ config.vqvae.activation_fn = 'swish'
+ config.vqvae.norm_type = 'GN'
+
+ config.discriminator = ml_collections.ConfigDict()
+ config.discriminator.filters = config.vqvae.get_oneway_ref('filters')
+ config.discriminator.channel_multipliers = (2, 4, 4, 4, 4)
+
+ # Learning rate.
+ config.base_lr = 0.0001
+ config.optimizer = ml_collections.ConfigDict()
+ config.optimizer.lr = config.get_ref('base_lr')
+ config.optimizer.beta1 = 0.0
+ config.optimizer.beta2 = 0.99
+
+ config.optimizer.g_lr = config.get_ref('base_lr')
+ config.optimizer.d_lr = config.get_ref('base_lr')
+
+ steps_per_epoch = UCF101_TRAIN_SIZE // config.get_ref('batch_size')
+ total_steps = config.get_ref('num_training_epochs') * steps_per_epoch
+ config.lr_configs = ml_collections.ConfigDict()
+ config.lr_configs.learning_rate_schedule = 'compound'
+ config.lr_configs.factors = 'constant * cosine_decay * linear_warmup'
+ config.lr_configs.warmup_steps = 1 * steps_per_epoch
+ config.lr_configs.steps_per_cycle = total_steps
+ config.lr_configs.base_learning_rate = config.get_ref('base_lr') # placeholder
+
+ # Pretrained model on ImageNet.
+ config.init_from = ml_collections.ConfigDict()
+ config.init_from.checkpoint_path = {
+ 'B': 'gs://magvit/models/imagenet_2d_base',
+ 'L': 'gs://magvit/models/imagenet_2d_large',
+ }[version]
+
+ # Evaluation.
+ config.eval = ml_collections.ConfigDict()
+ config.eval.enable_inception_score = True
+ config.eval.enable_frechet_distance = True
+ config.eval.data_splits = 'train,validation'
+ config.eval.num_examples = 10000
+ config.eval.final_num_repeats = 1
+ config.eval_from = ml_collections.ConfigDict()
+ config.eval_from.checkpoint_path = None
+ config.eval_from.step = None
+
+ # Logging.
+ config.logging = ml_collections.ConfigDict()
+ config.logging.enable_checkpoint = True
+ config.logging.checkpoint_steps = 1000
+ config.logging.checkpoint_kept = 5
+ config.logging.log_metric_steps = 200
+ config.logging.log_sample_size = 2
+
+ if 'runlocal' in options:
+ config.batch_size = 16
+ config.num_training_epochs = 10
+ config.eval_batch_split = 1
+
+ config.pretrained_image_model = False
+ config.perceptual_loss_weight = 0.0
+
+ config.vqvae.filters = 32
+ config.vqvae.num_enc_res_blocks = 1
+ config.vqvae.num_dec_res_blocks = 1
+ config.vqvae.channel_multipliers = (1,) * len(
+ config.vqvae.channel_multipliers)
+ config.discriminator.channel_multipliers = (1,) * len(
+ config.discriminator.channel_multipliers)
+
+ config.logging.enable_checkpoint = False
+ config.logging.checkpoint_steps = 100
+ config.logging.log_metric_steps = 20
+
+ del config.init_from
+
+ # Standalone evaluation.
+ if 'eval' in options:
+ config.eval_only = True
+ config.eval_from.checkpoint_path = ''
+ config.eval_from.step = -1
+ config.eval_from.legacy_checkpoint = True
+
+ return config
+
+
diff --git a/configs/vae_3d/vqgan3d_ucf101_config.py b/configs/vae_3d/vqgan3d_ucf101_config.py
new file mode 100644
index 0000000..a3875dc
--- /dev/null
+++ b/configs/vae_3d/vqgan3d_ucf101_config.py
@@ -0,0 +1,102 @@
+# Copyright 2023 The videogvt Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# pylint: disable=line-too-long
+r"""
+Configs for the VQGAN-3D on the UCF101.
+
+usage: `config = vqgan3d_ucf101_config.get_config()`
+
+"""
+
+import ml_collections
+
+from opensora.configs.vae_3d import vqgan2d_ucf101_config
+
+VARIANT = 'VQGAN/3D'
+
+
+def get_config(config_str='B'):
+ """Returns the base experiment configuration."""
+ version, *options = config_str.split('-')
+
+ config = vqgan2d_ucf101_config.get_config(config_str)
+ config.experiment_name = f'UCF101_{VARIANT}'
+ model_class, model_type = VARIANT.split('/')
+
+ # Overall
+ config.batch_size = {'B': 128, 'L': 256, 'H': 256}[version]
+ config.eval_batch_size = config.get_ref('batch_size') // 4
+ config.num_training_epochs = {'B': 500, 'L': 2000, 'H': 2000}[version]
+
+ # Dataset.
+ del config.num_train_sampled_frames
+
+ # Model: vqvae
+ config.model_class = model_class
+
+ config.pretrained_image_model = True # TODO(Lijun-Yu): 3d perceptual loss
+
+ config.vqgan.model_type = model_type
+
+ config.vqvae.in_channels = 3 # NOTE: SCH: added
+ config.vqvae.num_groups = 32 # NOTE: SCH: added, for nn.GroupNorm
+ config.vqvae.architecture = '3dcnn'
+ config.vqvae.codebook_size = {'B': 1024, 'L': 1024, 'H': 4096}[version]
+ config.vqvae.filters = {'B': 64, 'L': 128, 'H': 128}[version]
+ config.vqvae.num_enc_res_blocks = {'B': 2, 'L': 2, 'H': 4}[version]
+ config.vqvae.num_dec_res_blocks = {'B': 2, 'L': 2, 'H': 4}[version]
+ config.vqvae.channel_multipliers = (1, 2, 2, 4)
+ config.vqvae.temporal_downsample = (True, True, False)
+ config.vqvae.embedding_dim = {'B': 256, 'L': 256, 'H': 512}[version] # z embedding dimension
+ config.vqvae.conv_downsample = False
+ config.vqvae.deconv_upsample = False
+
+ # Save memory
+ config.vqvae.num_enc_remat_blocks = {'B': 0, 'L': 1, 'H': 3}[version]
+ config.vqvae.num_dec_remat_blocks = config.vqvae.get_ref(
+ 'num_enc_remat_blocks')
+ config.discriminator.num_remat_blocks = config.vqvae.get_ref(
+ 'num_enc_remat_blocks')
+
+ # Pretrained models on ImageNet.
+ config.init_from = ml_collections.ConfigDict()
+ config.init_from.inflation = '2d->3d'
+
+ # Standalone evaluation.
+ if 'eval' in options:
+ config.eval_only = True
+ config.eval_from.checkpoint_path = {
+ 'B': 'gs://magvit/models/ucf_3d_base',
+ 'L': 'gs://magvit/models/ucf_3d_large',
+ }[version]
+ config.eval_from.step = -1
+ config.eval_from.legacy_checkpoint = True
+
+ if 'runlocal' in options:
+ config.batch_size = 16
+ config.num_training_epochs = 10
+ # gets a small model for debugging
+ config.vqvae.filters = 32
+ config.vqvae.embedding_dim = 16
+ config.vqvae.num_enc_res_blocks = 1
+ config.vqvae.num_dec_res_blocks = 1
+ config.discriminator.filters = 1
+ config.discriminator.channel_multipliers = (1,)
+ config.vqvae.channel_multipliers = (1,)
+ config.vqvae.codebook_size = 128
+
+ return config
+
+
diff --git a/opensora/models/vae/__init__.py b/opensora/models/vae/__init__.py
index 63510b0..9eed101 100644
--- a/opensora/models/vae/__init__.py
+++ b/opensora/models/vae/__init__.py
@@ -1 +1,3 @@
from .vae import VideoAutoencoderKL, VideoAutoencoderKLTemporalDecoder
+from .vae_3d import VAE_3D
+
diff --git a/opensora/models/vae/model_utils.py b/opensora/models/vae/model_utils.py
new file mode 100644
index 0000000..7b02ab9
--- /dev/null
+++ b/opensora/models/vae/model_utils.py
@@ -0,0 +1,197 @@
+import functools
+import math
+from typing import Any, Optional, Sequence, Type
+
+import torch.nn as nn
+import numpy as np
+import torch
+
+
+## NOTE: not used since we only have 'GN'
+# def get_norm_layer(norm_type, dtype):
+# if norm_type == 'LN':
+# # supply a few args with partial function and pass the rest of the args when this norm_fn is called
+# norm_fn = functools.partial(nn.LayerNorm, dtype=dtype)
+# elif norm_type == 'GN': #
+# norm_fn = functools.partial(nn.GroupNorm, dtype=dtype)
+# elif norm_type is None:
+# norm_fn = lambda: (lambda x: x)
+# else:
+# raise NotImplementedError(f'norm_type: {norm_type}')
+# return norm_fn
+
+## NOTE: not used since need to put nn.AvgPool3d in init
+# def downsample(x, include_t_dim: bool = True, factor: int = 2):
+# """Downsample via average pooling."""
+# t_factor = factor if include_t_dim else 1
+# shape = (t_factor, factor, factor)
+# average_pool = nn.AvgPool3d(shape) # x shape needs to be [N,C,D,H,W]
+# x = average_pool(x)
+# return x
+
+## NOTE: not used since need to put nn.Upsample in init
+# def upsample(x: jnp.ndarray, include_t_dim: bool = True, factor: int = 2):
+# """Upsample via nearest interpolation."""
+# n, t, h, w, c = x.shape
+# upsample = nn.Upsample(scale_factor=(factor if include_t_dim else 1, factor, factor))
+# x = upsample(x)
+# return x
+
+class Conv(nn.Conv3d):
+ """Convolution with custom padding.
+
+ Attributes:
+ custom_padding: padding mode accepted by jnp.pad. When using this, must set
+ padding=VALID to disable padding in nn.Conv.
+ """
+
+ def __init__(self, custom_padding:Optional[str] = None):
+ self.custom_padding = custom_padding
+
+ def forward(self, x):
+ if self.custom_padding is not None:
+ assert self.padding == 'valid', 'Must use valid padding for raw Conv.'
+ assert self.dilation == 1, 'Kernel dilation not supported.'
+ pads = [((k - 1) // 2, k // 2) for k in self.kernel_size]
+ pads = [(0, 0)] + pads + [(0, 0)]
+ if self.custom_padding.startswith('reflect_') \
+ or self.custom_padding.startswith('symmetric_'):
+ custom_padding, reflect_type = self.custom_padding.split('_')
+ pad_kwargs = {'reflect_type': reflect_type}
+ else:
+ custom_padding = self.custom_padding
+ pad_kwargs = {}
+
+ x = np.pad(x, pads, mode=custom_padding, **pad_kwargs)
+ return super(Conv, self).__call__(x)
+
+
+class DiagonalGaussianDistribution(object):
+ def __init__(self, parameters, deterministic=False):
+ self.parameters = parameters
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) # SCH: channels dim
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
+ self.deterministic = deterministic
+ self.std = torch.exp(0.5 * self.logvar)
+ self.var = torch.exp(self.logvar)
+ if self.deterministic:
+ self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
+
+ def sample(self):
+ x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
+ return x
+
+ def kl(self, other=None):
+ if self.deterministic:
+ return torch.Tensor([0.])
+ else:
+ if other is None:
+ return 0.5 * torch.sum(torch.pow(self.mean, 2)
+ + self.var - 1.0 - self.logvar,
+ dim=[1, 2, 3, 4]) # TODO: check dimensions
+ else:
+ return 0.5 * torch.sum(
+ torch.pow(self.mean - other.mean, 2) / other.var
+ + self.var / other.var - 1.0 - self.logvar + other.logvar,
+ dim=[1, 2, 3, 4]) # TODO: check dimensions
+
+ def nll(self, sample, dims=[1,2,3,4]): # TODO: check dimensions
+ if self.deterministic:
+ return torch.Tensor([0.])
+ logtwopi = np.log(2.0 * np.pi)
+ return 0.5 * torch.sum(
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
+ dim=dims)
+
+ def mode(self):
+ return self.mean
+
+class VEA3DLoss(nn.Module):
+ def __init__(
+ self,
+ # disc_start,
+ logvar_init=0.0,
+ kl_weight=1.0,
+ pixelloss_weight=1.0,
+ disc_num_layers=3,
+ disc_in_channels=3,
+ disc_factor=1.0,
+ disc_weight=1.0,
+ perceptual_weight=1.0,
+ use_actnorm=False,
+ disc_conditional=False,
+ 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)
+
+ # self.discriminator = NLayerDiscriminator(input_nc=disc_in_channels,
+ # n_layers=disc_num_layers,
+ # use_actnorm=use_actnorm
+ # ).apply(weights_init)
+ # self.discriminator_iter_start = disc_start
+ # self.disc_loss = hinge_d_loss if disc_loss == "hinge" else vanilla_d_loss
+ # self.disc_factor = disc_factor
+ # self.discriminator_weight = disc_weight
+ # self.disc_conditional = disc_conditional
+
+ # TODO: for discriminator
+ # def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
+ # if last_layer is not None:
+ # nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
+ # g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
+ # else:
+ # nll_grads = torch.autograd.grad(nll_loss, self.last_layer[0], retain_graph=True)[0]
+ # g_grads = torch.autograd.grad(g_loss, self.last_layer[0], retain_graph=True)[0]
+
+ # d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
+ # d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
+ # d_weight = d_weight * self.discriminator_weight
+ # return d_weight
+
+ def forward(
+ self,
+ inputs,
+ reconstructions,
+ posteriors,
+ # optimizer_idx,
+ # global_step,
+ last_layer=None,
+ cond=None,
+ split="train",
+ 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
+
+ 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
+
+ # log = {"{}/total_loss".format(split): loss.clone().detach().mean(),
+ # "{}/logvar".format(split): self.logvar.detach(),
+ # "{}/kl_loss".format(split): kl_loss.detach().mean(),
+ # "{}/nll_loss".format(split): nll_loss.detach().mean(),
+ # "{}/rec_loss".format(split): rec_loss.detach().mean(),
+ # # "{}/d_weight".format(split): d_weight.detach(),
+ # # "{}/disc_factor".format(split): torch.tensor(disc_factor),
+ # # "{}/g_loss".format(split): g_loss.detach().mean(),
+ # }
+
+ return loss
+
diff --git a/opensora/models/vae/vae_3d.py b/opensora/models/vae/vae_3d.py
new file mode 100644
index 0000000..089b8a0
--- /dev/null
+++ b/opensora/models/vae/vae_3d.py
@@ -0,0 +1,440 @@
+import functools
+from typing import Any, Dict, Tuple, Type, Union, Sequence, Optional
+from absl import logging
+import ml_collections
+import torch
+import torch.nn as nn
+import numpy as np
+from numpy import typing as nptyping
+from opensora.models.vae import model_utils
+from opensora.registry import MODELS
+
+"""Encoder and Decoder stuctures with 3D CNNs."""
+
+"""
+NOTE:
+ removed LayerNorm since not used in this arch
+ GroupNorm: flax uses default `epsilon=1e-06`, whereas torch uses `eps=1e-05`
+ for average pool and upsample, input shape needs to be [N,C,T,H,W] --> if not, adjust the scale factors accordingly
+
+ !!! opensora read video into [B,C,T,H,W] format output
+
+TODO:
+ check data dimensions format
+"""
+
+class ResBlock(nn.Module):
+ def __init__(
+ self,
+ in_out_channels, # SCH: added
+ filters,
+ # norm_fn, # SCH: removed, use GN
+ conv_fn,
+ dtype="fp16",
+ activation_fn=nn.ReLU,
+ use_conv_shortcut=False,
+ num_groups=32,
+ ):
+ super().__init__()
+ self.filters = filters
+
+ # SCH: MAGVIT uses GroupNorm by default
+ self.norm1 = nn.GroupNorm(num_groups, in_out_channels, dtype=dtype)
+ self.conv1 = conv_fn(in_out_channels, self.filters, kernel_size=(3, 3, 3), use_bias=False)
+ self.norm2 = nn.GroupNorm(num_groups, self.filters, dtype=dtype)
+ self.conv2 = conv_fn(self.filters, self.filters, kernel_size=(3, 3, 3), use_bias=False)
+ if self.use_conv_shortcut:
+ self.conv3 = conv_fn(self.filters, self.filters, kernel_size=(3, 3, 3), use_bias=False)
+ else:
+ self.conv3 = conv_fn(self.filters, self.filters, kernel_size=(1, 1, 1), use_bias=False)
+
+ self.dtype = dtype
+ self.activate = activation_fn()
+ self.use_conv_shortcut = use_conv_shortcut
+
+ def forward(self, x):
+ input_dim = x.shape[-1]
+ residual = x
+ x = self.norm1(x)
+ x = self.activate(x)
+ x = self.conv1(x)
+ x = self.norm2(x)
+ x = self.activate(x)
+ x = self.conv2(x)
+ if input_dim != self.filters:
+ residual = self.conv3(residual)
+ return x + residual
+
+def _get_selected_flags(total_len: int, select_len: int, suffix: bool):
+ assert select_len <= total_len
+ selected = np.zeros(total_len, dtype=bool)
+ if not suffix:
+ selected[:select_len] = True
+ else:
+ selected[-select_len:] = True
+ return selected
+
+
+class Encoder(nn.Module):
+ """Encoder Blocks."""
+ def __init__(self,
+ filters = 64,
+ num_res_blocks = 3,
+ channel_multipliers = (1, 2, 2, 4),
+ temporal_downsample = (True, True, False),
+ num_groups = 32, # for nn.GroupNorm
+ in_out_channels = 3, # SCH: added, in_channels at the start
+ latent_embed_dim = 256,
+ conv_downsample = False,
+ custom_conv_padding = None,
+ activation_fn = 'swish',
+ dtype="bf16",
+ ):
+ super().__init__()
+ self.dtype = dtype
+ self.filters = filters
+ self.num_res_blocks = num_res_blocks
+ self.channel_multipliers = channel_multipliers
+ self.temporal_downsample = temporal_downsample
+ self.num_groups = num_groups
+
+ if isinstance(self.temporal_downsample, int):
+ self.temporal_downsample = _get_selected_flags(
+ len(self.channel_multipliers) - 1, self.temporal_downsample, False)
+
+ self.embedding_dim = latent_embed_dim
+ self.conv_downsample = conv_downsample
+ self.custom_conv_padding = custom_conv_padding
+ # self.norm_type = self.config.vqvae.norm_type
+ # self.num_remat_block = self.config.vqvae.get('num_enc_remat_blocks', 0)
+
+ if activation_fn == 'relu':
+ self.activation_fn = nn.ReLU
+ elif activation_fn == 'swish':
+ self.activation_fn = nn.SiLU
+ else:
+ raise NotImplementedError
+ self.activate = self.activation_fn()
+
+ self.conv_fn = functools.partial(
+ model_utils.Conv,
+ dtype=self.dtype,
+ padding='valid' if self.custom_conv_padding is not None else 'same', # SCH: lower letter for pytorch
+ custom_padding=self.custom_conv_padding
+ )
+
+ # self.norm_fn = model_utils.get_norm_layer(
+ # norm_type=self.norm_type, dtype=self.dtype)
+
+ self.block_args = dict(
+ # norm_fn=self.norm_fn,
+ conv_fn=self.conv_fn,
+ dtype=self.dtype,
+ activation_fn=self.activation_fn,
+ use_conv_shortcut=False,
+ num_groups=self.num_groups,
+ )
+
+
+ self.conv1 = self.conv_fn(in_out_channels, self.filters, kernel_size=(3, 3, 3), use_bias=False)
+
+ # ResBlocks and conv downsample
+ self.block_res_blocks = []
+ self.num_blocks = len(self.channel_multipliers)
+ self.conv_blocks = []
+
+ filters = self.filters
+ prev_filters = filters # record for in_channels
+ for i in range(self.num_blocks):
+ # resblock handling
+ filters = self.filters * self.channel_multipliers[i] # SCH: determine the number out_channels
+ block_items = []
+ for _ in range(self.num_res_blocks):
+ block_items.append(ResBlock(prev_filters, filters, **self.block_args))
+ prev_filters = filters # update in_channels
+ self.block_res_blocks.append(block_items)
+
+ if i < self.num_blocks - 1:
+ # conv blocks handling
+ if self.conv_downsample:
+ t_stride = 2 if self.temporal_downsample[i] else 1
+ self.conv_blocks.append(self.conv_fn(prev_filters, filters, kernel_size=(4, 4, 4), strides=(t_stride, 2, 2))) # SCH: should be same in_channel and out_channel
+ prev_filters = filters # update in_channels
+
+ # NOTE: downsample, dimensions T, H, W
+ self.avg_pool_with_t = nn.AvgPool3d((2,2,2))
+ self.avg_pool = nn.AvgPool3d((1,2,2))
+
+ # last layer res block
+ self.res_blocks = []
+ for _ in range(self.num_res_blocks):
+ self.res_blocks.append(ResBlock(prev_filters, filters, **self.block_args))
+ prev_filters = filters # update in_channels
+
+ # MAGVIT uses Group Normalization
+ self.norm1 = nn.GroupNorm(self.num_groups, prev_filters, dtype=dtype) # SCH: separate <prev_filters> channels into 32 groups
+
+ self.conv2 = self.conv_fn(prev_filters, self.embedding_dim, kernel_size=(1, 1, 1))
+
+ def forward(self, x):
+ x = self.conv1(x)
+ for i in range(self.num_blocks):
+ for j in range(self.num_res_blocks):
+ x = self.block_res_blocks[i][j](x)
+
+ if i < self.num_blocks - 1:
+ if self.conv_downsample:
+ x = self.conv_blocks[i](x)
+ else:
+ if self.temporal_downsample[i]:
+ x = self.avg_pool_with_t(x)
+ else:
+ x = self.avg_pool(x)
+
+ for i in range(self.num_res_blocks):
+ x = self.res_blocks[i](x)
+
+ x = self.norm1(x)
+ x = self.activate(x)
+ x = self.conv2(x)
+ return x
+
+
+
+class Decoder(nn.Module):
+ """Decoder Blocks."""
+ def __init__(self,
+ latent_embed_dim = 256,
+ filters = 64,
+ in_out_channels = 4,
+ num_res_blocks = 2,
+ channel_multipliers = (1, 2, 2, 4),
+ temporal_downsample = (True, True, False),
+ num_groups = 32, # for nn.GroupNorm
+ upsample = "nearest+conv", # options: "deconv", "nearest+conv"
+ custom_conv_padding = None,
+ activation_fn = 'swish',
+ dtype="bf16",
+ ):
+
+ self.output_dim = in_out_channels
+ self.embedding_dim = latent_embed_dim
+ self.filters = filters
+ self.num_res_blocks = num_res_blocks
+ self.channel_multipliers = channel_multipliers
+ self.temporal_downsample = temporal_downsample
+ self.num_groups = num_groups
+
+ if isinstance(self.temporal_downsample, int):
+ self.temporal_downsample = _get_selected_flags(
+ len(self.channel_multipliers) - 1, self.temporal_downsample, False)
+
+ self.upsample = upsample
+ self.custom_conv_padding = custom_conv_padding
+ # self.norm_type = self.config.vqvae.norm_type
+ # self.num_remat_block = self.config.vqvae.get('num_dec_remat_blocks', 0)
+
+ if activation_fn == 'relu':
+ self.activation_fn = nn.ReLU
+ elif activation_fn == 'swish':
+ self.activation_fn = nn.SiLU
+ else:
+ raise NotImplementedError
+ self.activate = self.activation_fn()
+
+ self.conv_fn = functools.partial(
+ model_utils.Conv,
+ dtype=self.dtype,
+ padding='VALID' if self.custom_conv_padding is not None else 'SAME',
+ custom_padding=self.custom_conv_padding)
+
+ self.conv_t_fn = functools.partial(nn.ConvTranspose3d, dtype=self.dtype)
+
+ # self.norm_fn = model_utils.get_norm_layer(
+ # norm_type=self.norm_type, dtype=self.dtype)
+
+ self.block_args = dict(
+ # norm_fn=self.norm_fn,
+ conv_fn=self.conv_fn,
+ dtype=self.dtype,
+ activation_fn=self.activation_fn,
+ use_conv_shortcut=False,
+ num_groups=self.num_groups,
+ )
+ self.num_blocks = len(self.channel_multipliers)
+
+ filters = self.filters * self.channel_multipliers[-1]
+
+ self.conv1 = self.conv_fn(self.embedding_dim, filters, kernel_size=(3, 3, 3), use_bias=True)
+
+ # last layer res block
+ self.res_blocks = []
+ for _ in range(self.num_res_blocks):
+ self.res_blocks.append(ResBlock(filters, filters, **self.block_args))
+
+
+ # NOTE: upsample, dimensions T, H, W
+ self.upsample_with_t = nn.Upsample(scale_factor=(2,2,2))
+ self.upsample = nn.Upsample(scale_factor=(1,2,2))
+
+ # ResBlocks and conv upsample
+ prev_filters = filters # SCH: in_channels
+ self.block_res_blocks = []
+ self.num_blocks = len(self.channel_multipliers)
+ self.conv_blocks = []
+ # SCH: reverse to keep track of the in_channels, but append also in a reverse direction
+ for i in reversed(range(self.num_blocks)):
+ filters = self.filters * self.channel_multipliers[i]
+ # resblock handling
+ block_items = []
+ for _ in range(self.num_res_blocks):
+ block_items.append(ResBlock(prev_filters, filters, **self.block_args))
+ prev_filters = filters # SCH: update in_channels
+ self.block_res_blocks.insert(0, block_items) # SCH: append in front
+
+ # conv blocks handling
+ if i > 0:
+ t_stride = 2 if self.temporal_downsample[i - 1] else 1
+ if self.upsample == "deconv":
+ assert self.custom_conv_padding is None, ('Custom padding not implemented for ConvTranspose')
+ # SCH: append in front
+ self.conv_blocks.insert(0,
+ self.conv_t_fn(prev_filters, filters, kernel_size=(4, 4, 4), strides=(t_stride, 2, 2)))
+ prev_filters = filters # SCH: update in_channels
+ elif self.upsample == 'nearest+conv':
+ # SCH: append in front
+ self.conv_blocks.insert(0, self.conv_fn(prev_filters, filters, kernel_size=(3, 3, 3)))
+ prev_filters = filters # SCH: update in_channels
+ else:
+ raise NotImplementedError(f'Unknown upsampler: {self.upsample}')
+
+ self.norm1 = nn.GroupNorm(self.num_groups, prev_filters, dtyep=dtype)
+ self.conv2 = self.conv_fn(prev_filters, self.output_dim, kernel_size=(3, 3, 3))
+
+
+ def forward(
+ self,
+ **kwargs,
+ ):
+
+ x = self.conv1(x)
+ for i in range(self.num_res_blocks):
+ x = self.res_blocks[i](x)
+ for i in reversed(range(self.num_blocks)): # reverse here to make decoder symmetric with encoder
+ for j in range(self.num_res_blocks):
+ x = self.block_res_blocks[i][j](x)
+
+ if i > 0:
+ if self.upsample == 'deconv':
+ assert self.custom_conv_padding is None, ('Custom padding not implemented for ConvTranspose')
+ x = self.conv_blocks[i-1](x)
+ elif self.upsample == 'nearest+conv':
+ if self.temporal_downsample[i - 1]:
+ x = self.upsample_with_t(x)
+ else:
+ x = self.upsample(x)
+ x = self.conv_blocks[i-1](x)
+ else:
+ raise NotImplementedError(f'Unknown upsampler: {self.upsample}')
+ x = self.norm1(x)
+ x = self.activate(x)
+ x = self.conv2(x)
+ return x
+
+
+class VAE_3D(nn.Module):
+ """The 3D VAE """
+ def __init__(
+ self,
+ latent_embed_dim = 256,
+ filters = 64,
+ output_dim: int = 4,
+ num_res_blocks = 2,
+ channel_multipliers = (1, 2, 2, 4),
+ temporal_downsample = (True, True, False),
+ num_groups = 32, # for nn.GroupNorm
+ conv_downsample = False,
+ upsample = "nearest+conv", # options: "deconv", "nearest+conv"
+ custom_conv_padding = None,
+ activation_fn = 'swish',
+ in_out_channels = 4,
+ kl_embed_dim = 64,
+ kl_weight = 0.000001,
+ dtype="bf16",
+ # precision: Any = jax.lax.Precision.DEFAULT
+ ):
+
+
+ self.encoder = Encoder(
+ filters=filters,
+ num_res_blocks=num_res_blocks,
+ channel_multipliers=channel_multipliers,
+ temporal_downsample=temporal_downsample,
+ num_groups = num_groups, # for nn.GroupNorm
+ in_out_channels = in_out_channels,
+ latent_embed_dim = latent_embed_dim,
+ conv_downsample = conv_downsample,
+ custom_conv_padding = custom_conv_padding,
+ activation_fn = activation_fn,
+ dtype=dtype
+ )
+ self.decoder = Decoder(
+ latent_embed_dim = latent_embed_dim,
+ filters = filters,
+ in_out_channels = in_out_channels,
+ num_res_blocks = num_res_blocks,
+ channel_multipliers = channel_multipliers,
+ temporal_downsample = temporal_downsample,
+ num_groups = num_groups, # for nn.GroupNorm
+ upsample = upsample, # options: "deconv", "nearest+conv"
+ custom_conv_padding = custom_conv_padding,
+ activation_fn = activation_fn,
+ dtype=dtype,
+ )
+
+ self.loss = model_utils.VEA3DLoss(kl_weight=kl_weight)
+
+ self.quant_conv = nn.Conv3d(2*latent_embed_dim, 2*kl_embed_dim, 1)
+ self.post_quant_conv = nn.Conv3d(kl_embed_dim, latent_embed_dim, 1)
+
+ def encode(
+ self,
+ x,
+ ):
+ encoded_feature = self.encoder(x)
+ moments = self.quant_conv(encoded_feature)
+ posterior = model_utils.DiagonalGaussianDistribution(moments)
+ return posterior
+
+ def decode(
+ self,
+ z,
+ ):
+ z = self.post_quant_conv(z)
+ dec = self.decoder(z)
+ return dec
+
+ def forward(
+ self,
+ input,
+ sample_posterior=True,
+ ):
+ posterior = self.encode(input)
+ if sample_posterior:
+ z = posterior.sample()
+ else:
+ z = posterior.mode()
+ dec = self.decode(z)
+ return dec, posterior
+
+
+ def get_loss(
+ self,
+ batch, # [B, C, T, H, W]
+ optimizer_idx=None, # NOTE: to add GAN later
+ ):
+ reconstructions, posterior = self(batch)
+ loss = self.loss(batch, reconstructions, posterior)
+
+ return loss
diff --git a/scripts/train-vae.py b/scripts/train-vae.py
new file mode 100644
index 0000000..ec7685f
--- /dev/null
+++ b/scripts/train-vae.py
@@ -0,0 +1,267 @@
+from copy import deepcopy
+
+import colossalai
+import torch
+import torch.nn as nn
+from torch.optim import Optimizer
+from torch.optim.lr_scheduler import _LRScheduler
+import torch.distributed as dist
+import wandb
+from colossalai.booster import Booster
+from colossalai.booster.plugin import LowLevelZeroPlugin
+from colossalai.cluster import DistCoordinator
+from colossalai.nn.optimizer import HybridAdam
+from colossalai.utils import get_current_device
+from tqdm import tqdm
+import os
+
+from opensora.acceleration.checkpoint import set_grad_checkpoint
+from opensora.acceleration.parallel_states import (
+ get_data_parallel_group,
+ set_data_parallel_group,
+ set_sequence_parallel_group,
+)
+from opensora.acceleration.plugin import ZeroSeqParallelPlugin
+from opensora.datasets import DatasetFromCSV, get_transforms_image, get_transforms_video, prepare_dataloader
+from opensora.registry import MODELS, SCHEDULERS, build_module
+from opensora.utils.ckpt_utils import create_logger, load_json, save_json, load, model_sharding, record_model_param_shape, save
+from opensora.utils.config_utils import (
+ create_experiment_workspace,
+ create_tensorboard_writer,
+ parse_configs,
+ save_training_config,
+)
+from opensora.utils.misc import all_reduce_mean, format_numel_str, get_model_numel, requires_grad, to_torch_dtype
+from opensora.utils.train_utils import update_ema, MaskGenerator
+
+
+
+def main():
+ # ======================================================
+ # 1. args & cfg
+ # ======================================================
+ cfg = parse_configs(training=True)
+ print(cfg)
+ exp_name, exp_dir = create_experiment_workspace(cfg)
+ save_training_config(cfg._cfg_dict, exp_dir)
+
+ # ======================================================
+ # 2. runtime variables & colossalai launch
+ # ======================================================
+ assert torch.cuda.is_available(), "Training currently requires at least one GPU."
+ assert cfg.dtype in ["fp16", "bf16"], f"Unknown mixed precision {cfg.dtype}"
+
+ # 2.1. colossalai init distributed training
+ colossalai.launch_from_torch({})
+ coordinator = DistCoordinator()
+ device = get_current_device()
+ dtype = to_torch_dtype(cfg.dtype)
+
+ # 2.2. init logger, tensorboard & wandb
+ if not coordinator.is_master():
+ logger = create_logger(None)
+ else:
+ logger = create_logger(exp_dir)
+ logger.info(f"Experiment directory created at {exp_dir}")
+
+ writer = create_tensorboard_writer(exp_dir)
+ if cfg.wandb:
+ wandb.init(project="minisora", name=exp_name, config=cfg._cfg_dict)
+
+ # 2.3. initialize ColossalAI booster
+ if cfg.plugin == "zero2":
+ plugin = LowLevelZeroPlugin(
+ stage=2,
+ precision=cfg.dtype,
+ initial_scale=2**16,
+ max_norm=cfg.grad_clip,
+ )
+ set_data_parallel_group(dist.group.WORLD)
+ elif cfg.plugin == "zero2-seq":
+ plugin = ZeroSeqParallelPlugin(
+ sp_size=cfg.sp_size,
+ stage=2,
+ precision=cfg.dtype,
+ initial_scale=2**16,
+ max_norm=cfg.grad_clip,
+ )
+ set_sequence_parallel_group(plugin.sp_group)
+ set_data_parallel_group(plugin.dp_group)
+ else:
+ raise ValueError(f"Unknown plugin {cfg.plugin}")
+ booster = Booster(plugin=plugin)
+
+ # ======================================================
+ # 3. build dataset and dataloader
+ # ======================================================
+ dataset = DatasetFromCSV(
+ cfg.data_path,
+ # TODO: change transforms
+ transform=(
+ get_transforms_video(cfg.image_size[0])
+ if not cfg.use_image_transform
+ else get_transforms_image(cfg.image_size[0])
+ ),
+ num_frames=cfg.num_frames,
+ frame_interval=cfg.frame_interval,
+ root=cfg.root,
+ )
+
+ # TODO: use plugin's prepare dataloader
+ # a batch contains:
+ # {
+ # "video": torch.Tensor, # [B, C, T, H, W],
+ # "text": List[str],
+ # }
+ dataloader = prepare_dataloader(
+ dataset,
+ batch_size=cfg.batch_size,
+ num_workers=cfg.num_workers,
+ shuffle=True,
+ drop_last=True,
+ pin_memory=True,
+ process_group=get_data_parallel_group(),
+ )
+ logger.info(f"Dataset contains {len(dataset):,} videos ({cfg.data_path})")
+
+ total_batch_size = cfg.batch_size * dist.get_world_size() // cfg.sp_size
+ logger.info(f"Total batch size: {total_batch_size}")
+
+ # ======================================================
+ # 4. build model
+ # ======================================================
+ # 4.1. build model
+ vae = build_module(cfg.vae, MODELS)
+ vae_numel, vae_numel_trainable = get_model_numel(vae)
+ logger.info(
+ f"Trainable vae params: {format_numel_str(vae_numel_trainable)}, Total model params: {format_numel_str(vae_numel)}"
+ )
+
+
+ # 4.3. move to device
+ vae = vae.to(device, dtype)
+
+ # 4.5. setup optimizer
+ optimizer = HybridAdam(
+ filter(lambda p: p.requires_grad, vae.parameters()), lr=cfg.lr, weight_decay=0, adamw_mode=True
+ )
+ lr_scheduler = None
+
+ # 4.6. prepare for training
+ if cfg.grad_checkpoint:
+ set_grad_checkpoint(vae)
+ vae.train()
+
+
+ # =======================================================
+ # 5. boost model for distributed training with colossalai
+ # =======================================================
+ torch.set_default_dtype(dtype)
+ vae, optimizer, _, dataloader, lr_scheduler = booster.boost(
+ model=vae, optimizer=optimizer, lr_scheduler=lr_scheduler, dataloader=dataloader
+ )
+ torch.set_default_dtype(torch.float)
+ num_steps_per_epoch = len(dataloader)
+ logger.info("Boost vae for distributed training")
+
+ # =======================================================
+ # 6. training loop
+ # =======================================================
+ start_epoch = start_step = log_step = sampler_start_idx = 0
+ running_loss = 0.0
+
+ # TODO: allow resume training without ema
+
+
+ # 6.1. resume training
+ if cfg.load is not None:
+ logger.info("Loading checkpoint")
+ booster.load_model(vae, os.path.join(cfg.load, "model"))
+ booster.load_optimizer(optimizer, os.path.join(cfg.load, "optimizer"))
+ if lr_scheduler is not None:
+ booster.load_lr_scheduler(lr_scheduler, os.path.join(cfg.load, "lr_scheduler"))
+ running_states = load_json(os.path.join(cfg.load, "running_states.json"))
+ dist.barrier()
+ start_epoch, start_step, sampler_start_idx = running_states["epoch"], running_states["step"], running_states["sample_start_index"]
+ logger.info(f"Loaded checkpoint {cfg.load} at epoch {start_epoch} step {start_step}")
+ logger.info(f"Training for {cfg.epochs} epochs with {num_steps_per_epoch} steps per epoch")
+
+ dataloader.sampler.set_start_index(sampler_start_idx)
+
+ # 6.2. training loop
+ for epoch in range(start_epoch, cfg.epochs):
+ dataloader.sampler.set_epoch(epoch)
+ dataloader_iter = iter(dataloader)
+ logger.info(f"Beginning epoch {epoch}...")
+
+ with tqdm(
+ range(start_step, num_steps_per_epoch),
+ desc=f"Epoch {epoch}",
+ disable=not coordinator.is_master(),
+ total=num_steps_per_epoch,
+ initial=start_step,
+ ) as pbar:
+ for step in pbar:
+ batch = next(dataloader_iter)
+ x = batch["video"].to(device, dtype) # [B, C, T, H, W]
+
+ loss = vae.get_loss(x)
+ # Backward & update
+ booster.backward(loss=loss, optimizer=optimizer)
+ optimizer.step()
+ optimizer.zero_grad()
+
+ # Log loss values:
+ all_reduce_mean(loss)
+ running_loss += loss.item()
+ global_step = epoch * num_steps_per_epoch + step
+ log_step += 1
+
+ # Log to tensorboard
+ if coordinator.is_master() and (global_step + 1) % cfg.log_every == 0:
+ avg_loss = running_loss / log_step
+ pbar.set_postfix({"loss": avg_loss, "step": step, "global_step": global_step})
+ running_loss = 0
+ log_step = 0
+ writer.add_scalar("loss", loss.item(), global_step)
+ if cfg.wandb:
+ wandb.log(
+ {
+ "iter": global_step,
+ "num_samples": global_step * total_batch_size,
+ "epoch": epoch,
+ "loss": loss.item(),
+ "avg_loss": avg_loss,
+ },
+ step=global_step,
+ )
+
+ # Save checkpoint
+ if cfg.ckpt_every > 0 and (global_step + 1) % cfg.ckpt_every == 0:
+ save_dir = os.path.join(exp_dir, f"epoch{epoch}-global_step{global_step+1}")
+ os.makedirs(os.path.join(save_dir, "model"), exist_ok=True)
+
+ booster.save_model(vae, os.path.join(save_dir, "vae"), shard=True)
+ booster.save_optimizer(optimizer, os.path.join(save_dir, "optimizer"), shard=True, size_per_shard=4096)
+ if lr_scheduler is not None:
+ booster.save_lr_scheduler(lr_scheduler, os.path.join(save_dir, "lr_scheduler"))
+ running_states = {
+ "epoch": epoch,
+ "step": step+1,
+ "global_step": global_step+1,
+ "sample_start_index": (step+1) * cfg.batch_size,
+ }
+ if coordinator.is_master():
+ save_json(running_states, os.path.join(save_dir, "running_states.json"))
+ dist.barrier()
+ logger.info(
+ f"Saved checkpoint at epoch {epoch} step {step + 1} global_step {global_step + 1} to {exp_dir}"
+ )
+
+ # the continue epochs are not resumed, so we need to reset the sampler start index and start step
+ dataloader.sampler.set_start_index(0)
+ start_step = 0
+
+
+if __name__ == "__main__":
+ main()