Open-Sora: Democratizing Efficient Video Production for All
Python
update adaptation
Zangwei Zhengfd24a8c4f9d8
diff --git a/configs/opensora-v1-2/inference/xl-rf.py b/configs/opensora-v1-2/inference/xl-rf.pynew file mode 100644index 0000000..2192ae5--- /dev/null+++ b/configs/opensora-v1-2/inference/xl-rf.py@@ -0,0 +1,39 @@+num_frames = 1+fps = 1+image_size = (2560, 1536)+# image_size = (2048, 2048)+multi_resolution = "STDiT2"++model = dict(+ type="STDiT3-XL/2",+ from_pretrained="PixArt-Sigma-XL-2-2K-MS.pth",+ qk_norm=True,+ enable_flashattn=True,+ enable_layernorm_kernel=True,+)+vae = dict(+ type="VideoAutoencoderKL",+ micro_batch_size=4,+ from_pretrained="PixArt-alpha/pixart_sigma_sdxlvae_T5_diffusers",+ subfolder="vae",+ local_files_only=True,+)+text_encoder = dict(+ type="t5",+ from_pretrained="DeepFloyd/t5-v1_1-xxl",+ model_max_length=300,+ local_files_only=True,+)+scheduler = dict(+ type="rflow",+ use_discrete_timesteps=True,+ num_sampling_steps=50,+ cfg_scale=4.5,+)+dtype = "bf16"++# Others+batch_size = 1+seed = 42+prompt_path = "./assets/texts/t2i_sigma.txt"+save_dir = "./samples/samples/"diff --git a/configs/opensora-v1-2/inference/xl.py b/configs/opensora-v1-2/inference/xl.pyindex e700ea1..0e0d282 100644--- a/configs/opensora-v1-2/inference/xl.py+++ b/configs/opensora-v1-2/inference/xl.py@@ -7,6 +7,7 @@ multi_resolution = "STDiT2"model = dict(type="STDiT3-XL/2",from_pretrained="PixArt-Sigma-XL-2-2K-MS.pth",+ qk_norm=True,enable_flashattn=True,enable_layernorm_kernel=True,)diff --git a/configs/opensora-v1-2/train/adapt-rf.py b/configs/opensora-v1-2/train/adapt-rf.pynew file mode 100644index 0000000..2cfd00a--- /dev/null+++ b/configs/opensora-v1-2/train/adapt-rf.py@@ -0,0 +1,74 @@+# Define dataset+dataset = dict(+ type="VariableVideoTextDataset",+ transform_name="resize_crop",+)+bucket_config = {+ "144p": {1: (1.0, 64)},+ # ---+ "256": {1: (0.5, 48)},+ "240p": {1: (0.5, 48)},+ # ---+ "360p": {1: (0.5, 18)},+ "512": {1: (0.5, 18)},+ # ---+ "480p": {1: (0.5, 8)},+ # ---+ "720p": {1: (0.2, 4)},+ "1024": {1: (0.2, 4)},+ # ---+ "1080p": {1: (0.3, 2)},+ # ---+ "2048": {1: (1.0, 1)},+}++# Define acceleration+num_workers = 4+num_bucket_build_workers = 16+dtype = "bf16"+grad_checkpoint = False+plugin = "zero2"+sp_size = 1++# Define model+model = dict(+ type="STDiT3-XL/2",+ from_pretrained=None,+ qk_norm=True,+ enable_flashattn=True,+ enable_layernorm_kernel=True,+)+vae = dict(+ type="VideoAutoencoderKL",+ micro_batch_size=4,+ from_pretrained="PixArt-alpha/pixart_sigma_sdxlvae_T5_diffusers",+ subfolder="vae",+ local_files_only=True,+)+text_encoder = dict(+ type="t5",+ from_pretrained="DeepFloyd/t5-v1_1-xxl",+ model_max_length=300,+ shardformer=True,+ local_files_only=True,+)+scheduler = dict(+ type="rflow",+ use_discrete_timesteps=False,+ sample_method="logit-normal",+ use_timestep_transform=True,+)++# Others+seed = 42+outputs = "outputs"+wandb = False++epochs = 1000+log_every = 10+ckpt_every = 500+load = None++batch_size = 10 # only for logging+lr = 2e-5+grad_clip = 1.0diff --git a/configs/opensora-v1-2/train/adapt.py b/configs/opensora-v1-2/train/adapt.pyindex d785d16..7396f21 100644--- a/configs/opensora-v1-2/train/adapt.py+++ b/configs/opensora-v1-2/train/adapt.py@@ -19,7 +19,7 @@ bucket_config = {# ---"1080p": {1: (0.3, 2)},# ---- "2048": {1: (0.5, 1)},+ "2048": {1: (1.0, 1)},}# Define acceleration@@ -33,7 +33,7 @@ sp_size = 1# Define modelmodel = dict(type="STDiT3-XL/2",- from_pretrained="PixArt-Sigma-XL-2-2K-MS.pth",+ from_pretrained=None,qk_norm=True,enable_flashattn=True,enable_layernorm_kernel=True,diff --git a/configs/opensora-v1-2/train/pixart.py b/configs/opensora-v1-2/train/pixart.pydeleted file mode 100644index e69de29..0000000diff --git a/opensora/schedulers/iddpm/__init__.py b/opensora/schedulers/iddpm/__init__.pyindex 7a69927..26a856d 100644--- a/opensora/schedulers/iddpm/__init__.py+++ b/opensora/schedulers/iddpm/__init__.py@@ -47,7 +47,6 @@ class IDDPM(SpacedDiffusion):else gd.ModelVarType.LEARNED_RANGE),loss_type=loss_type,- # rescale_timesteps=rescale_timesteps,)self.cfg_scale = cfg_scalediff --git a/opensora/schedulers/iddpm/gaussian_diffusion.py b/opensora/schedulers/iddpm/gaussian_diffusion.pyindex 5aa20c7..4fae13f 100644--- a/opensora/schedulers/iddpm/gaussian_diffusion.py+++ b/opensora/schedulers/iddpm/gaussian_diffusion.py@@ -164,7 +164,13 @@ class GaussianDiffusion:"""def __init__(- self, *, betas: torch.Tensor, model_mean_type: str, model_var_type: str, loss_type: str, device: str = "cuda"+ self,+ *,+ betas: torch.Tensor,+ model_mean_type: str,+ model_var_type: str,+ loss_type: str,+ device: str = "cuda",):if device == "cuda":device = torch.device(f"cuda:{torch.cuda.current_device()}")@@ -728,18 +734,20 @@ class GaussianDiffusion:output = torch.where((t == 0), decoder_nll, kl)return {"output": output, "pred_xstart": out["pred_xstart"]}- def training_losses(self, model, x_start, t, model_kwargs=None, noise=None, mask=None, weights=None):+ def training_losses(self, model, x_start, model_kwargs=None, noise=None, mask=None, weights=None, t=None):"""Compute training losses for a single timestep.:param model: the model to evaluate loss on.:param x_start: the [N x C x ...] tensor of inputs.- :param t: a batch of timestep indices.:param model_kwargs: if not None, a dict of extra keyword arguments topass to the model. This can be used for conditioning.:param noise: if specified, the specific Gaussian noise to try to remove.:return: a dict with the key "loss" containing a tensor of shape [N].Some mean or variance settings may also have other keys."""+ # sample timestep+ t = torch.randint(0, self.num_timesteps, (x_start.shape[0],), device=x_start.device)+if model_kwargs is None:model_kwargs = {}if noise is None:diff --git a/opensora/schedulers/iddpm/speed.py b/opensora/schedulers/iddpm/speed.pyindex 04ff02c..7f4cb70 100644--- a/opensora/schedulers/iddpm/speed.py+++ b/opensora/schedulers/iddpm/speed.py@@ -67,7 +67,7 @@ class SpeeDiffusion(SpacedDiffusion):t = torch.cat([t, dual_t], dim=0)[:n]return t- def training_losses(self, model, x, t, *args, **kwargs): # pylint: disable=signature-differs+ def training_losses(self, model, x, *args, **kwargs): # pylint: disable=signature-differst = self.t_sample(x.shape[0], x.device)return super().training_losses(model, x, t, weights=self.weights, *args, **kwargs)diff --git a/opensora/schedulers/rf/__init__.py b/opensora/schedulers/rf/__init__.pyindex b6239de..3a3465c 100644--- a/opensora/schedulers/rf/__init__.py+++ b/opensora/schedulers/rf/__init__.py@@ -1,19 +1,36 @@-# should have property num_timesteps,-# method sample() training_losses()-import torch-from .rectified_flow import RFlowSchedulerfrom functools import partial+import torch+from opensora.registry import SCHEDULERS+from .rectified_flow import RFlowScheduler, timestep_transform++@SCHEDULERS.register_module("rflow")class RFLOW:- def __init__(self, num_sampling_steps = 10, num_timesteps = 1000, cfg_scale = 4.0):+ def __init__(+ self,+ num_sampling_steps=10,+ num_timesteps=1000,+ cfg_scale=4.0,+ use_discrete_timesteps=False,+ use_timestep_transform=False,+ **kwargs,+ ):self.num_sampling_steps = num_sampling_stepsself.num_timesteps = num_timestepsself.cfg_scale = cfg_scale+ self.use_discrete_timesteps = use_discrete_timesteps+ self.use_timestep_transform = use_timestep_transform- self.scheduler = RFlowScheduler(num_timesteps = num_timesteps, num_sampling_steps = num_sampling_steps)+ self.scheduler = RFlowScheduler(+ num_timesteps=num_timesteps,+ num_sampling_steps=num_sampling_steps,+ use_discrete_timesteps=use_discrete_timesteps,+ use_timestep_transform=use_timestep_transform,+ **kwargs,+ )def sample(self,@@ -24,8 +41,7 @@ class RFLOW:device,additional_args=None,mask=None,- guidance_scale = None,- # progress = True,+ guidance_scale=None,):assert mask is None, "mask is not supported in rectified flow inference yet"# if no specific guidance scale is provided, use the default scale when initializing the scheduler@@ -39,26 +55,29 @@ class RFLOW:if additional_args is not None:model_args.update(additional_args)- timesteps = [(1. - i/self.num_sampling_steps) * 1000. for i in range(self.num_sampling_steps)]+ timesteps = [(1.0 - i / self.num_sampling_steps) * 1000.0 for i in range(self.num_sampling_steps)]# convert float timesteps to most close int timesteps- timesteps = [int(round(t)) for t in timesteps]+ if self.use_discrete_timesteps:+ timesteps = [int(round(t)) for t in timesteps]++ if self.use_timestep_transform:+ timesteps = [timestep_transform(t, additional_args, scale=self.cfg_scale) for t in timesteps]for i, t in enumerate(timesteps):z_in = torch.cat([z, z], 0)- pred = model(z_in, torch.tensor([t]* z_in.shape[0], device = device), **model_args).chunk(2, dim = 1)[0]- pred_cond, pred_uncond = pred.chunk(2, dim = 0)+ pred = model(z_in, torch.tensor([t] * z_in.shape[0], device=device), **model_args).chunk(2, dim=1)[0]+ pred_cond, pred_uncond = pred.chunk(2, dim=0)v_pred = pred_uncond + guidance_scale * (pred_cond - pred_uncond)- dt = (timesteps[i] - timesteps[i+1])/self.num_timesteps if i < len(timesteps) - 1 else 1/self.num_timesteps+ dt = (+ (timesteps[i] - timesteps[i + 1]) / self.num_timesteps+ if i < len(timesteps) - 1+ else 1 / self.num_timesteps+ )z = z + v_pred * dtreturn z-- def training_losses(self, model, x_start, t, model_kwargs=None, noise = None, mask = None, weights = None):- return self.scheduler.training_losses(model, x_start, t, model_kwargs, noise, mask, weights)----\ No newline at end of file+ def training_losses(self, model, x_start, model_kwargs=None, noise=None, mask=None, weights=None):+ return self.scheduler.training_losses(model, x_start, model_kwargs, noise, mask, weights)diff --git a/opensora/schedulers/rf/rectified_flow.py b/opensora/schedulers/rf/rectified_flow.pyindex 05357ac..577254e 100644--- a/opensora/schedulers/rf/rectified_flow.py+++ b/opensora/schedulers/rf/rectified_flow.py@@ -1,30 +1,67 @@import torch-import numpy as np-from typing import Union-from einops import rearrange-from typing import List+from torch.distributions import LogisticNormal+from ..iddpm.gaussian_diffusion import _extract_into_tensor, mean_flat# some code are inspired by https://github.com/magic-research/piecewise-rectified-flow/blob/main/scripts/train_perflow.py# and https://github.com/magic-research/piecewise-rectified-flow/blob/main/src/scheduler_perflow.py+def timestep_transform(t, model_kwargs, base_resolution=512 * 512, base_num_frames=1, scale=1.0):+ resolution = model_kwargs["height"] * model_kwargs["width"]+ num_frames = model_kwargs["num_frames"]+ ratio = (resolution / base_resolution).sqrt() * (num_frames / base_num_frames).sqrt() * scale+ new_t = ratio * t / (1 + (ratio - 1) * t)+ return new_t++class RFlowScheduler:def __init__(self,- num_timesteps = 1000,- num_sampling_steps = 10,+ num_timesteps=1000,+ num_sampling_steps=10,+ use_discrete_timesteps=False,+ sample_method="uniform",+ loc=0.0,+ scale=1.0,+ use_timestep_transform=False,+ transform_scale=1.0,):self.num_timesteps = num_timestepsself.num_sampling_steps = num_sampling_steps-+ self.use_discrete_timesteps = use_discrete_timesteps- def training_losses(self, model, x_start, t, model_kwargs=None, noise = None, mask = None, weights = None):- '''- Compute training losses for a single timestep.+ # sample method+ assert sample_method in ["uniform", "logit-normal"]+ assert (+ sample_method == "uniform" or not use_discrete_timesteps+ ), "Only uniform sampling is supported for discrete timesteps"+ self.sample_method = sample_method+ if sample_method == "logit-normal":+ self.distribution = LogisticNormal(torch.tensor([loc]), torch.tensor([scale]))+ self.sample_t = lambda x: self.distribution.sample((x.shape[0],))[:, 0].to(x.device)++ # timestep transform+ self.use_timestep_transform = use_timestep_transform+ self.transform_scale = transform_scale++ def training_losses(self, model, x_start, model_kwargs=None, noise=None, mask=None, weights=None):+ """+ Compute training losses for a single timestep.Arguments format copied from opensora/schedulers/iddpm/gaussian_diffusion.py/training_lossesNote: t is int tensor and should be rescaled from [0, num_timesteps-1] to [1,0]- '''+ """+ if self.use_discrete_timesteps:+ t = torch.randint(0, self.num_timesteps, (x_start.shape[0],), device=x_start.device)+ elif self.sample_method == "uniform":+ t = torch.rand((x_start.shape[0],), device=x_start.device) * self.num_timesteps+ elif self.sample_method == "logit-normal":+ t = self.sample_t(x_start) * self.num_timesteps++ if self.use_timestep_transform:+ t = t / self.num_timesteps+ t = timestep_transform(t, model_kwargs, scale=self.transform_scale)+ t = t * self.num_timestepsif model_kwargs is None:model_kwargs = {}@@ -38,20 +75,18 @@ class RFlowScheduler:x_t0 = self.add_noise(x_start, noise, t0)x_t = torch.where(mask[:, None, :, None, None], x_t, x_t0)-terms = {}model_output = model(x_t, t, **model_kwargs)- velocity_pred = model_output.chunk(2, dim = 1)[0]+ velocity_pred = model_output.chunk(2, dim=1)[0]if weights is None:- loss = mean_flat((velocity_pred - (x_start - noise)).pow(2), mask = mask)+ loss = mean_flat((velocity_pred - (x_start - noise)).pow(2), mask=mask)else:weight = _extract_into_tensor(weights, t, x_start.shape)- loss = mean_flat(weight * (velocity_pred - (x_start - noise)).pow(2), mask = mask)- terms['loss'] = loss+ loss = mean_flat(weight * (velocity_pred - (x_start - noise)).pow(2), mask=mask)+ terms["loss"] = lossreturn terms-def add_noise(self,original_samples: torch.FloatTensor,@@ -61,8 +96,8 @@ class RFlowScheduler:"""compatible with diffusers add_noise()"""- timepoints = timesteps.float() / self.num_timesteps # [0, 999/1000]- timepoints = 1 - timepoints # [1,1/1000]+ timepoints = timesteps.float() / self.num_timesteps # [0, 999/1000]+ timepoints = 1 - timepoints # [1,1/1000]# timepoint (bsz) noise: (bsz, 4, frame, w ,h)# expand timepoint to noise shape@@ -70,7 +105,3 @@ class RFlowScheduler:timepoints = timepoints.repeat(1, noise.shape[1], noise.shape[2], noise.shape[3], noise.shape[4])return timepoints * original_samples + (1 - timepoints) * noise----\ No newline at end of filediff --git a/scripts/misc/search_bs.py b/scripts/misc/search_bs.pyindex d6789df..01d4d86 100644--- a/scripts/misc/search_bs.py+++ b/scripts/misc/search_bs.py@@ -434,8 +434,7 @@ def train(model_args[k] = v.to(device, dtype)# Diffusion- t = torch.randint(0, scheduler.num_timesteps, (x.shape[0],), device=device)- loss_dict = scheduler.training_losses(model, x, t, model_args, mask=mask)+ loss_dict = scheduler.training_losses(model, x, model_args, mask=mask)# Backward & updateloss = loss_dict["loss"].mean()diff --git a/scripts/train.py b/scripts/train.pyindex aed7b45..1c14fd7 100644--- a/scripts/train.py+++ b/scripts/train.py@@ -251,8 +251,7 @@ def main():model_args[k] = v.to(device, dtype)# Diffusion- t = torch.randint(0, scheduler.num_timesteps, (x.shape[0],), device=device)- loss_dict = scheduler.training_losses(model, x, t, model_args, mask=mask)+ loss_dict = scheduler.training_losses(model, x, model_args, mask=mask)# Backward & updateloss = loss_dict["loss"].mean()