Skip to content

Open-Sora: Democratizing Efficient Video Production for All

Python

[refactor] fix train warnings

zhengzangw31228fe9c842
diff --git a/configs/opensora-v1-2/inference/sample-ref.py b/configs/opensora-v1-2/inference/sample-ref.py
index 008650c..7593fb0 100644
--- a/configs/opensora-v1-2/inference/sample-ref.py
+++ b/configs/opensora-v1-2/inference/sample-ref.py
@@ -12,7 +12,7 @@ dtype = "bf16"
# Condition
prompt = [
- 'Drone view of waves crashing against the rugged cliffs along Big Sur\'s garay point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore. A small island with a lighthouse sits in the distance, and green shrubbery covers the cliff\'s edge. The steep drop from the road down to the beach is a dramatic feat, with the cliff\'s edges jutting out over the sea. This is a view that captures the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway.{"reference_path": "assets/images/condition/cliff.png", "mask_strategy": "0,0,0,0;0,0,0,1;0,0,0,2;0,0,0,3;0,0,0,4"}',
+ 'Drone view of waves crashing against the rugged cliffs along Big Sur\'s garay point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore. A small island with a lighthouse sits in the distance, and green shrubbery covers the cliff\'s edge. The steep drop from the road down to the beach is a dramatic feat, with the cliff\'s edges jutting out over the sea. This is a view that captures the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway.{"reference_path": "assets/images/condition/cliff.png", "mask_strategy": "0"}',
]
loop = 1
condition_frame_length = 4
diff --git a/opensora/schedulers/rf/__init__.py b/opensora/schedulers/rf/__init__.py
index 9c0e0f1..e9fb990 100644
--- a/opensora/schedulers/rf/__init__.py
+++ b/opensora/schedulers/rf/__init__.py
@@ -1,12 +1,9 @@
-from functools import partial
-
import torch
from tqdm import tqdm
from opensora.registry import SCHEDULERS
from .rectified_flow import RFlowScheduler, timestep_transform
-from ..iddpm.gaussian_diffusion import _extract_into_tensor
@SCHEDULERS.register_module("rflow")
@@ -66,12 +63,11 @@ class RFLOW:
if self.use_timestep_transform:
timesteps = [timestep_transform(t, additional_args, num_timesteps=self.num_timesteps) for t in timesteps]
-
progress_wrap = tqdm if progress else (lambda x: x)
for i, t in progress_wrap(enumerate(timesteps)):
if mask is not None:
if mask.shape[0] != z.shape[0]:
- mask = mask.repeat(2, 1)
+ mask = mask.repeat(2, 1)
mask_t = (mask * self.num_timesteps).to(torch.int)
x0 = z.clone()
x_noise = self.scheduler.add_noise(x0, torch.randn_like(x0), t)
diff --git a/opensora/utils/ckpt_utils.py b/opensora/utils/ckpt_utils.py
index d6206ae..4b97c08 100644
--- a/opensora/utils/ckpt_utils.py
+++ b/opensora/utils/ckpt_utils.py
@@ -1,6 +1,5 @@
import functools
import json
-import logging
import operator
import os
from typing import Tuple
@@ -269,27 +268,6 @@ def load(
)
-def create_logger(logging_dir):
- """
- Create a logger that writes to a log file and stdout.
- """
- if dist.get_rank() == 0: # real logger
- logging.basicConfig(
- level=logging.INFO,
- format="[\033[34m%(asctime)s\033[0m] %(message)s",
- datefmt="%Y-%m-%d %H:%M:%S",
- handlers=[
- logging.StreamHandler(),
- logging.FileHandler(f"{logging_dir}/log.txt"),
- ],
- )
- logger = logging.getLogger(__name__)
- else: # dummy logger (does nothing)
- logger = logging.getLogger(__name__)
- logger.addHandler(logging.NullHandler())
- return logger
-
-
def load_checkpoint(model, ckpt_path, save_as_pt=False, model_name="model"):
if ckpt_path.endswith(".pt") or ckpt_path.endswith(".pth"):
state_dict = find_model(ckpt_path, model=model)
diff --git a/opensora/utils/train_utils.py b/opensora/utils/train_utils.py
index d59aee2..77b9e35 100644
--- a/opensora/utils/train_utils.py
+++ b/opensora/utils/train_utils.py
@@ -1,3 +1,4 @@
+import logging
import math
import random
from collections import OrderedDict
@@ -160,3 +161,24 @@ class MaskGenerator:
masks.append(mask)
masks = torch.stack(masks, dim=0)
return masks
+
+
+def create_logger(logging_dir):
+ """
+ Create a logger that writes to a log file and stdout.
+ """
+ if dist.get_rank() == 0: # real logger
+ logging.basicConfig(
+ level=logging.INFO,
+ format="[\033[34m%(asctime)s\033[0m] %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ handlers=[
+ logging.StreamHandler(),
+ logging.FileHandler(f"{logging_dir}/log.txt"),
+ ],
+ )
+ logger = logging.getLogger(__name__)
+ else: # dummy logger (does nothing)
+ logger = logging.getLogger(__name__)
+ logger.addHandler(logging.NullHandler())
+ return logger
diff --git a/scripts/inference.py b/scripts/inference.py
index 98c3f1d..1cfb3c8 100644
--- a/scripts/inference.py
+++ b/scripts/inference.py
@@ -17,7 +17,7 @@ from opensora.utils.misc import to_torch_dtype
def main():
# ======================================================
- # 1. cfg and init distributed env
+ # 1. configs & runtime variables
# ======================================================
cfg = parse_configs(training=False)
verbose = cfg.get("verbose", 2)
diff --git a/scripts/inference_old.py b/scripts/inference_old.py
new file mode 100644
index 0000000..98c3f1d
--- /dev/null
+++ b/scripts/inference_old.py
@@ -0,0 +1,184 @@
+import os
+
+import colossalai
+import torch
+import torch.distributed as dist
+from colossalai.cluster import DistCoordinator
+from mmengine.runner import set_random_seed
+from tqdm import tqdm
+
+from opensora.acceleration.parallel_states import set_sequence_parallel_group
+from opensora.datasets import IMG_FPS, save_sample
+from opensora.models.text_encoder.t5 import text_preprocessing
+from opensora.registry import MODELS, SCHEDULERS, build_module
+from opensora.utils.config_utils import parse_configs
+from opensora.utils.misc import to_torch_dtype
+
+
+def main():
+ # ======================================================
+ # 1. cfg and init distributed env
+ # ======================================================
+ cfg = parse_configs(training=False)
+ verbose = cfg.get("verbose", 2)
+ print(cfg)
+
+ # init distributed
+ if os.environ.get("WORLD_SIZE", None):
+ use_dist = True
+ colossalai.launch_from_torch({})
+ coordinator = DistCoordinator()
+
+ if coordinator.world_size > 1:
+ set_sequence_parallel_group(dist.group.WORLD)
+ enable_sequence_parallelism = True
+ else:
+ enable_sequence_parallelism = False
+ else:
+ use_dist = False
+ enable_sequence_parallelism = False
+
+ # ======================================================
+ # 2. runtime variables
+ # ======================================================
+ torch.set_grad_enabled(False)
+ torch.backends.cuda.matmul.allow_tf32 = True
+ torch.backends.cudnn.allow_tf32 = True
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ dtype = to_torch_dtype(cfg.dtype)
+ set_random_seed(seed=cfg.seed)
+ prompts = cfg.prompt
+
+ # ======================================================
+ # 3. build model & load weights
+ # ======================================================
+ # 3.1. build model
+ input_size = (cfg.num_frames, *cfg.image_size)
+ vae = build_module(cfg.vae, MODELS)
+ latent_size = vae.get_latent_size(input_size)
+ text_encoder = build_module(cfg.text_encoder, MODELS, device=device) # T5 must be fp32
+
+ model = build_module(
+ cfg.model,
+ MODELS,
+ input_size=latent_size,
+ in_channels=vae.out_channels,
+ caption_channels=text_encoder.output_dim,
+ model_max_length=text_encoder.model_max_length,
+ enable_sequence_parallelism=enable_sequence_parallelism,
+ )
+ text_encoder.y_embedder = model.y_embedder # hack for classifier-free guidance
+
+ # 3.2. move to device & eval
+ vae = vae.to(device, dtype).eval()
+ model = model.to(device, dtype).eval()
+
+ # 3.3. build scheduler
+ scheduler = build_module(cfg.scheduler, SCHEDULERS)
+
+ # 3.4. support for multi-resolution
+ model_args = dict()
+ if cfg.multi_resolution == "PixArtMS":
+ image_size = cfg.image_size
+ hw = torch.tensor([image_size], device=device, dtype=dtype).repeat(cfg.batch_size, 1)
+ ar = torch.tensor([[image_size[0] / image_size[1]]], device=device, dtype=dtype).repeat(cfg.batch_size, 1)
+ model_args["data_info"] = dict(ar=ar, hw=hw)
+ elif cfg.multi_resolution == "STDiT2":
+ image_size = cfg.image_size
+ height = torch.tensor([image_size[0]], device=device, dtype=dtype).repeat(cfg.batch_size)
+ width = torch.tensor([image_size[1]], device=device, dtype=dtype).repeat(cfg.batch_size)
+ num_frames = torch.tensor([cfg.num_frames], device=device, dtype=dtype).repeat(cfg.batch_size)
+ ar = torch.tensor([image_size[0] / image_size[1]], device=device, dtype=dtype).repeat(cfg.batch_size)
+ if cfg.num_frames == 1:
+ cfg.fps = IMG_FPS
+ fps = torch.tensor([cfg.fps], device=device, dtype=dtype).repeat(cfg.batch_size)
+ model_args["height"] = height
+ model_args["width"] = width
+ model_args["num_frames"] = num_frames
+ model_args["ar"] = ar
+ model_args["fps"] = fps
+
+ # ======================================================
+ # 4. inference
+ # ======================================================
+ sample_idx = cfg.get("start_index", 0)
+ if cfg.sample_name is not None:
+ sample_name = cfg.sample_name
+ elif cfg.prompt_as_path:
+ sample_name = ""
+ else:
+ sample_name = "sample"
+ save_dir = cfg.save_dir
+ os.makedirs(save_dir, exist_ok=True)
+
+ # 4.1. batch generation
+ progress_wrap = tqdm if verbose == 1 else (lambda x: x)
+ for i in progress_wrap(range(0, len(prompts), cfg.batch_size)):
+ # 4.2 sample in hidden space
+ batch_prompts_raw = prompts[i : i + cfg.batch_size]
+ batch_prompts = [text_preprocessing(prompt) for prompt in batch_prompts_raw]
+ # handle the last batch
+ if len(batch_prompts_raw) < cfg.batch_size and cfg.multi_resolution == "STDiT2":
+ model_args["height"] = model_args["height"][: len(batch_prompts_raw)]
+ model_args["width"] = model_args["width"][: len(batch_prompts_raw)]
+ model_args["num_frames"] = model_args["num_frames"][: len(batch_prompts_raw)]
+ model_args["ar"] = model_args["ar"][: len(batch_prompts_raw)]
+ model_args["fps"] = model_args["fps"][: len(batch_prompts_raw)]
+
+ # 4.3. diffusion sampling
+ old_sample_idx = sample_idx
+ # generate multiple samples for each prompt
+ for k in range(cfg.num_sample):
+ sample_idx = old_sample_idx
+
+ # Skip if the sample already exists
+ # This is useful for resuming sampling VBench
+ if cfg.prompt_as_path:
+ skip = True
+ for batch_prompt in batch_prompts_raw:
+ path = os.path.join(save_dir, f"{sample_name}{batch_prompt}")
+ if cfg.num_sample != 1:
+ path = f"{path}-{k}"
+ path = f"{path}.mp4"
+ if not os.path.exists(path):
+ skip = False
+ break
+ if skip:
+ continue
+
+ # sampling
+ z = torch.randn(len(batch_prompts), vae.out_channels, *latent_size, device=device, dtype=dtype)
+ samples = scheduler.sample(
+ model,
+ text_encoder,
+ z=z,
+ prompts=batch_prompts,
+ device=device,
+ additional_args=model_args,
+ progress=verbose >= 2,
+ )
+ samples = vae.decode(samples.to(dtype), num_frames=cfg.num_frames)
+
+ # 4.4. save samples
+ if not use_dist or coordinator.is_master():
+ for idx, sample in enumerate(samples):
+ if verbose >= 2:
+ print(f"Prompt: {batch_prompts_raw[idx]}")
+ if cfg.prompt_as_path:
+ sample_name_suffix = batch_prompts_raw[idx]
+ else:
+ sample_name_suffix = f"_{sample_idx}"
+ save_path = os.path.join(save_dir, f"{sample_name}{sample_name_suffix}")
+ if cfg.num_sample != 1:
+ save_path = f"{save_path}-{k}"
+ save_sample(
+ sample,
+ fps=cfg.fps // cfg.frame_interval,
+ save_path=save_path,
+ verbose=verbose >= 2,
+ )
+ sample_idx += 1
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/train.py b/scripts/train.py
index 15e7fa4..2795c9c 100644
--- a/scripts/train.py
+++ b/scripts/train.py
@@ -16,7 +16,7 @@ from opensora.acceleration.checkpoint import set_grad_checkpoint
from opensora.acceleration.parallel_states import get_data_parallel_group
from opensora.datasets import prepare_dataloader, prepare_variable_dataloader
from opensora.registry import DATASETS, MODELS, SCHEDULERS, build_module
-from opensora.utils.ckpt_utils import create_logger, load, model_sharding, record_model_param_shape, save
+from opensora.utils.ckpt_utils import load, model_sharding, record_model_param_shape, save
from opensora.utils.config_utils import (
create_tensorboard_writer,
define_experiment_workspace,
@@ -24,14 +24,14 @@ from opensora.utils.config_utils import (
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 MaskGenerator, create_colossalai_plugin, update_ema
+from opensora.utils.train_utils import MaskGenerator, create_colossalai_plugin, create_logger, update_ema
DEFAULT_DATASET_NAME = "VideoTextDataset"
def main():
# ======================================================
- # 1. configs & runtime variables & colossalai launch
+ # 1. configs & runtime variables
# ======================================================
# == parse configs ==
cfg = parse_configs(training=True)
@@ -58,16 +58,14 @@ def main():
coordinator.block_all()
# == init logger, tensorboard & wandb ==
+ logger = create_logger(exp_dir)
if coordinator.is_master():
- logger = create_logger(exp_dir)
logger.info("Experiment directory created at %s", exp_dir)
logger.info("Training configuration:\n %s", pformat(cfg.to_dict()))
tb_writer = create_tensorboard_writer(exp_dir)
if cfg.get("wandb", False):
wandb.init(project="minisora", name=exp_name, config=cfg.to_dict())
- else:
- logger = create_logger(None)
# == init ColossalAI booster ==
plugin = create_colossalai_plugin(
diff --git a/scripts/train_vae.py b/scripts/train_vae.py
index add7f10..a878e62 100644
--- a/scripts/train_vae.py
+++ b/scripts/train_vae.py
@@ -18,7 +18,7 @@ from opensora.acceleration.parallel_states import get_data_parallel_group
from opensora.datasets import prepare_dataloader
from opensora.models.vae.losses import AdversarialLoss, DiscriminatorLoss, VAELoss
from opensora.registry import DATASETS, MODELS, build_module
-from opensora.utils.ckpt_utils import create_logger, load_json, save_json
+from opensora.utils.ckpt_utils import load_json, save_json
from opensora.utils.config_utils import (
create_tensorboard_writer,
define_experiment_workspace,
@@ -29,6 +29,7 @@ from opensora.utils.misc import all_reduce_mean, format_numel_str, get_model_num
from opensora.utils.train_utils import create_colossalai_plugin
DEFAULT_DATASET_NAME = "VideoTextDataset"
+from opensora.utils.train_utils import create_logger
def main():