Skip to content

Open-Sora: Democratizing Efficient Video Production for All

Python

[feat] inference for rf

zhengzangw3a01cb440de3
diff --git a/configs/opensora-v1-1/inference/sample-ref.py b/configs/opensora-v1-1/inference/sample-ref.py
index c4c46a2..ae80774 100644
--- a/configs/opensora-v1-1/inference/sample-ref.py
+++ b/configs/opensora-v1-1/inference/sample-ref.py
@@ -7,9 +7,12 @@ multi_resolution = "STDiT2"
# Condition
prompt_path = None
prompt = [
- "A car driving on the ocean.",
- '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"}',
- "In an ornate, historical hall, a massive tidal wave peaks and begins to crash. Two surfers, seizing the moment, skillfully navigate the face of the wave.",
+ 'Drone view of waves crashing against the rugged cliffs along Big Sur\'s garay point beach. {"reference_path": "assets/images/condition/cliff.png", "mask_strategy": "0"}',
+ 'A breathtaking sunrise scene.{"reference_path": "assets/images/condition/sunset1.png","mask_strategy": "0"}',
+ 'A car driving on the ocean.{"reference_path": "https://cdn.openai.com/tmp/s/interp/d0.mp4","mask_strategy": "0,0,-8,0,8"}',
+ 'A snowy forest.{"reference_path": "https://cdn.pixabay.com/video/2021/04/25/72171-542991404_large.mp4","mask_strategy": "0,0,0,0,15,0.8"}',
+ 'A breathtaking sunrise scene.{"reference_path": "assets/images/condition/sunset1.png;assets/images/condition/sunset2.png","mask_strategy": "0;0,1,0,-1,1"}',
+ '|0|a white jeep equipped with a roof rack driving on a dirt road in a coniferous forest.|2|a white jeep equipped with a roof rack driving on a dirt road in the desert.|4|a white jeep equipped with a roof rack driving on a dirt road in a mountain.|6|A white jeep equipped with a roof rack driving on a dirt road in a city.|8|a white jeep equipped with a roof rack driving on a dirt road on the surface of a river.|10|a white jeep equipped with a roof rack driving on a dirt road under the lake.|12|a white jeep equipped with a roof rack flying into the sky.|14|a white jeep equipped with a roof rack driving in the universe. Earth is the background.{"reference_path": "https://cdn.openai.com/tmp/s/interp/d0.mp4", "mask_strategy": "0,0,0,0,15"}',
]
loop = 2
@@ -24,16 +27,6 @@ condition_frame_length = 4
# )
# See https://github.com/hpcaitech/Open-Sora/blob/main/docs/config.md#advanced-inference-config for more details
# See https://github.com/hpcaitech/Open-Sora/blob/main/docs/commands.md#inference-with-open-sora-11 for more examples
-mask_strategy = [
- "0,0,0,0,8,0.3",
- None,
- "0",
-]
-reference_path = [
- "https://cdn.openai.com/tmp/s/interp/d0.mp4",
- None,
- "assets/images/condition/wave.png",
-]
# Define model
model = dict(
diff --git a/configs/opensora-v1-2/inference/sample-ref.py b/configs/opensora-v1-2/inference/sample-ref.py
deleted file mode 100644
index 7593fb0..0000000
--- a/configs/opensora-v1-2/inference/sample-ref.py
+++ /dev/null
@@ -1,56 +0,0 @@
-image_size = (240, 426)
-num_frames = 34
-fps = 24
-frame_interval = 1
-
-prompt_path = None
-save_dir = "./samples/samples/"
-seed = 42
-batch_size = 1
-multi_resolution = "STDiT2"
-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"}',
-]
-loop = 1
-condition_frame_length = 4
-
-# Define model
-model = dict(
- type="STDiT3-XL/2",
- from_pretrained=None,
- qk_norm=True,
- enable_flash_attn=True,
- enable_layernorm_kernel=True,
-)
-vae = dict(
- type="VideoAutoencoderPipeline",
- from_pretrained="pretrained_models/vae-v3",
- micro_frame_size=17,
- vae_2d=dict(
- type="VideoAutoencoderKL",
- from_pretrained="PixArt-alpha/pixart_sigma_sdxlvae_T5_diffusers",
- subfolder="vae",
- micro_batch_size=4,
- local_files_only=True,
- ),
- vae_temporal=dict(
- type="VAE_Temporal_SD",
- from_pretrained=None,
- ),
-)
-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=False,
- use_timestep_transform=True,
- num_sampling_steps=30,
- cfg_scale=4.5,
-)
diff --git a/configs/opensora-v1-2/inference/sample.py b/configs/opensora-v1-2/inference/sample.py
index 65ccc1b..a4b592f 100644
--- a/configs/opensora-v1-2/inference/sample.py
+++ b/configs/opensora-v1-2/inference/sample.py
@@ -3,12 +3,24 @@ num_frames = 51
fps = 24
frame_interval = 1
-prompt_path = "./assets/texts/t2v_samples.txt"
+prompt_path = "./assets/texts/t2v_sora.txt"
+# == Uncomment the following line to use the prompt below ==
+# prompt = [
+# 'Drone view of waves crashing against the rugged cliffs along Big Sur\'s garay point beach. {"reference_path": "assets/images/condition/cliff.png", "mask_strategy": "0"}',
+# 'A breathtaking sunrise scene.{"reference_path": "assets/images/condition/sunset1.png","mask_strategy": "0"}',
+# 'A car driving on the ocean.{"reference_path": "https://cdn.openai.com/tmp/s/interp/d0.mp4","mask_strategy": "0,0,-8,0,8"}',
+# 'A snowy forest.{"reference_path": "https://cdn.pixabay.com/video/2021/04/25/72171-542991404_large.mp4","mask_strategy": "0,0,0,0,15,0.8"}',
+# 'A breathtaking sunrise scene.{"reference_path": "assets/images/condition/sunset1.png;assets/images/condition/sunset2.png","mask_strategy": "0;0,1,0,-1,1"}',
+# '|0|a white jeep equipped with a roof rack driving on a dirt road in a coniferous forest.|2|a white jeep equipped with a roof rack driving on a dirt road in the desert.|4|a white jeep equipped with a roof rack driving on a dirt road in a mountain.|6|A white jeep equipped with a roof rack driving on a dirt road in a city.|8|a white jeep equipped with a roof rack driving on a dirt road on the surface of a river.|10|a white jeep equipped with a roof rack driving on a dirt road under the lake.|12|a white jeep equipped with a roof rack flying into the sky.|14|a white jeep equipped with a roof rack driving in the universe. Earth is the background.{"reference_path": "https://cdn.openai.com/tmp/s/interp/d0.mp4", "mask_strategy": "0,0,0,0,15"}',
+# ]
+
save_dir = "./samples/samples/"
seed = 42
batch_size = 1
multi_resolution = "STDiT2"
dtype = "bf16"
+condition_frame_length = 5
+align = 5
model = dict(
type="STDiT3-XL/2",
@@ -19,8 +31,7 @@ model = dict(
)
vae = dict(
type="VideoAutoencoderPipeline",
- from_pretrained="pretrained_models/vae-v3",
- # scale=2.5,
+ from_pretrained="pretrained_models/vae-pipeline",
shift=(-0.10, 0.34, 0.27, 0.98),
scale=(3.85, 2.32, 2.33, 3.06),
micro_frame_size=17,
@@ -44,7 +55,6 @@ text_encoder = dict(
)
scheduler = dict(
type="rflow",
- use_discrete_timesteps=False,
use_timestep_transform=True,
num_sampling_steps=30,
cfg_scale=7.0,
diff --git a/configs/opensora-v1-2/train/adapt.py b/configs/opensora-v1-2/train/adapt.py
new file mode 100644
index 0000000..7088dfe
--- /dev/null
+++ b/configs/opensora-v1-2/train/adapt.py
@@ -0,0 +1,96 @@
+# Dataset settings
+dataset = dict(
+ type="VariableVideoTextDataset",
+ transform_name="resize_crop",
+)
+bucket_config = { # 2s/it
+ "144p": {1: (0.5, 48), 34: (1.0, 2), 51: (1.0, 4), 102: (1.0, 2), 204: (1.0, 1)},
+ # ---
+ "256": {1: (0.6, 20), 34: (0.5, 2), 51: (0.5, 1), 68: (0.5, 1), 136: (0.0, None)},
+ "240p": {1: (0.6, 20), 34: (0.5, 2), 51: (0.5, 1), 68: (0.5, 1), 136: (0.0, None)},
+ # ---
+ "360p": {1: (0.5, 8), 34: (0.2, 1), 102: (0.0, None)},
+ "512": {1: (0.5, 8), 34: (0.2, 1), 102: (0.0, None)},
+ # ---
+ "480p": {1: (0.2, 4), 17: (0.3, 1), 68: (0.0, None)},
+ # ---
+ "720p": {1: (0.1, 2)},
+ "1024": {1: (0.1, 2)},
+ # ---
+ "1080p": {1: (0.1, 1)},
+}
+grad_checkpoint = False
+
+# Acceleration settings
+num_workers = 8
+num_bucket_build_workers = 16
+dtype = "bf16"
+plugin = "zero2"
+
+# Model settings
+model = dict(
+ type="STDiT3-XL/2",
+ from_pretrained=None,
+ qk_norm=True,
+ enable_flash_attn=True,
+ enable_layernorm_kernel=True,
+)
+vae = dict(
+ type="VideoAutoencoderPipeline",
+ from_pretrained="pretrained_models/vae-pipeline",
+ shift=(-0.10, 0.34, 0.27, 0.98),
+ scale=(3.85, 2.32, 2.33, 3.06),
+ micro_frame_size=17,
+ vae_2d=dict(
+ type="VideoAutoencoderKL",
+ from_pretrained="PixArt-alpha/pixart_sigma_sdxlvae_T5_diffusers",
+ subfolder="vae",
+ micro_batch_size=4,
+ local_files_only=True,
+ ),
+ vae_temporal=dict(
+ type="VAE_Temporal_SD",
+ from_pretrained=None,
+ ),
+)
+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_timestep_transform=True,
+ sample_method="logit-normal",
+)
+
+# Mask settings
+mask_ratios = {
+ "random": 0.2,
+ "intepolate": 0.01,
+ "quarter_random": 0.01,
+ "quarter_head": 0.01,
+ "quarter_tail": 0.01,
+ "quarter_head_tail": 0.01,
+ "image_random": 0.05,
+ "image_head": 0.1,
+ "image_tail": 0.05,
+ "image_head_tail": 0.05,
+}
+
+# Log settings
+seed = 42
+outputs = "outputs"
+wandb = False
+epochs = 1000
+log_every = 10
+ckpt_every = 500
+
+# optimization settings
+load = None
+grad_clip = 1.0
+lr = 1e-4
+ema_decay = 0.99
+adam_eps = 1e-15
diff --git a/configs/opensora-v1-2/train/stage1-gc.py b/configs/opensora-v1-2/train/stage1-gc.py
deleted file mode 100644
index 001aa69..0000000
--- a/configs/opensora-v1-2/train/stage1-gc.py
+++ /dev/null
@@ -1,124 +0,0 @@
-# Dataset settings
-dataset = dict(
- type="VariableVideoTextDataset",
- transform_name="resize_crop",
- frame_interval=1,
-)
-
-# h800
-# bucket_config = { # 20s/it
-# "144p": {1: (1.0, 100), 51: (1.0, 30), 102: (1.0, 20), 204: (1.0, 8), 408: (1.0, 4)},
-# # ---
-# "256": {1: (0.5, 100), 51: (0.3, 24), 102: (0.3, 12), 204: (0.3, 4), 408: (0.3, 2)},
-# "240p": {1: (0.5, 100), 51: (0.3, 24), 102: (0.3, 12), 204: (0.3, 4), 408: (0.3, 2)},
-# # ---
-# "360p": {1: (0.5, 60), 51: (0.3, 12), 102: (0.3, 6), 204: (0.3, 2), 408: (0.3, 1)},
-# "512": {1: (0.5, 60), 51: (0.3, 12), 102: (0.3, 6), 204: (0.3, 2), 408: (0.3, 1)},
-# # ---
-# "480p": {1: (0.5, 40), 51: (0.3, 6), 102: (0.3, 3), 204: (0.3, 1), 408: (0.0, None)},
-# # ---
-# "720p": {1: (0.2, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
-# "1024": {1: (0.1, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
-# # ---
-# "1080p": {1: (0.1, 10)},
-# # ---
-# "2048": {1: (0.1, 5)},
-# }
-
-# webvid
-bucket_config = { # 20s/it
- "144p": {1: (1.0, 100), 51: (1.0, 30), 102: ((1.0, 0.33), 20), 204: ((1.0, 0.1), 8), 408: ((1.0, 0.1), 4)},
- # ---
- "256": {1: (0.4, 100), 51: (0.5, 24), 102: ((0.5, 0.33), 12), 204: ((0.5, 0.1), 4), 408: ((0.5, 0.1), 2)},
- "240p": {1: (0.3, 100), 51: (0.4, 24), 102: ((0.4, 0.33), 12), 204: ((0.4, 0.1), 4), 408: ((0.4, 0.1), 2)},
- # ---
- "360p": {1: (0.2, 60), 51: (0.15, 12), 102: ((0.15, 0.33), 6), 204: ((0.15, 0.1), 2), 408: ((0.15, 0.1), 1)},
- "512": {1: (0.1, 60), 51: (0.3, 12), 102: (0.3, 6), 204: (0.3, 2), 408: (0.3, 1)},
- # ---
- "480p": {1: (0.1, 40), 51: (0.3, 6), 102: (0.3, 3), 204: (0.3, 1), 408: (0.0, None)},
- # ---
- "720p": {1: (0.05, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
- "1024": {1: (0.05, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
- # ---
- "1080p": {1: (0.1, 10)},
- # ---
- "2048": {1: (0.1, 5)},
-}
-
-grad_checkpoint = True
-batch_size = None
-
-# Acceleration settings
-num_workers = 8
-num_bucket_build_workers = 16
-dtype = "bf16"
-plugin = "zero2"
-
-# Model settings
-model = dict(
- type="STDiT3-XL/2",
- from_pretrained=None,
- qk_norm=True,
- enable_flash_attn=True,
- enable_layernorm_kernel=True,
-)
-vae = dict(
- type="VideoAutoencoderPipeline",
- from_pretrained="pretrained_models/vae-pipeline",
- shift=(-0.10, 0.34, 0.27, 0.98),
- scale=(3.85, 2.32, 2.33, 3.06),
- micro_frame_size=17,
- vae_2d=dict(
- type="VideoAutoencoderKL",
- from_pretrained="PixArt-alpha/pixart_sigma_sdxlvae_T5_diffusers",
- subfolder="vae",
- micro_batch_size=4,
- local_files_only=True,
- ),
- vae_temporal=dict(
- type="VAE_Temporal_SD",
- from_pretrained=None,
- ),
-)
-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,
- use_timestep_transform=True,
- sample_method="logit-normal",
-)
-
-# Mask settings
-mask_ratios = {
- "random": 0.2,
- "intepolate": 0.01,
- "quarter_random": 0.01,
- "quarter_head": 0.01,
- "quarter_tail": 0.01,
- "quarter_head_tail": 0.01,
- "image_random": 0.05,
- "image_head": 0.1,
- "image_tail": 0.05,
- "image_head_tail": 0.05,
-}
-
-# Log settings
-seed = 42
-outputs = "outputs"
-wandb = False
-epochs = 1000
-log_every = 10
-ckpt_every = 500
-
-# optimization settings
-load = None
-grad_clip = 1.0
-lr = 2e-4
-ema_decay = 0.99
-adam_eps = 1e-15
diff --git a/configs/opensora-v1-2/train/stage1.py b/configs/opensora-v1-2/train/stage1.py
index e6e996e..531a485 100644
--- a/configs/opensora-v1-2/train/stage1.py
+++ b/configs/opensora-v1-2/train/stage1.py
@@ -2,26 +2,49 @@
dataset = dict(
type="VariableVideoTextDataset",
transform_name="resize_crop",
- frame_interval=1,
)
-bucket_config = { # 2s/it
- "144p": {1: (0.5, 48), 34: (1.0, 2), 51: (1.0, 4), 102: (1.0, 2), 204: (1.0, 1)},
+
+# h800
+# bucket_config = { # 20s/it
+# "144p": {1: (1.0, 100), 51: (1.0, 30), 102: (1.0, 20), 204: (1.0, 8), 408: (1.0, 4)},
+# # ---
+# "256": {1: (0.5, 100), 51: (0.3, 24), 102: (0.3, 12), 204: (0.3, 4), 408: (0.3, 2)},
+# "240p": {1: (0.5, 100), 51: (0.3, 24), 102: (0.3, 12), 204: (0.3, 4), 408: (0.3, 2)},
+# # ---
+# "360p": {1: (0.5, 60), 51: (0.3, 12), 102: (0.3, 6), 204: (0.3, 2), 408: (0.3, 1)},
+# "512": {1: (0.5, 60), 51: (0.3, 12), 102: (0.3, 6), 204: (0.3, 2), 408: (0.3, 1)},
+# # ---
+# "480p": {1: (0.5, 40), 51: (0.3, 6), 102: (0.3, 3), 204: (0.3, 1), 408: (0.0, None)},
+# # ---
+# "720p": {1: (0.2, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
+# "1024": {1: (0.1, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
+# # ---
+# "1080p": {1: (0.1, 10)},
+# # ---
+# "2048": {1: (0.1, 5)},
+# }
+
+# webvid
+bucket_config = { # 20s/it
+ "144p": {1: (1.0, 100), 51: (1.0, 30), 102: ((1.0, 0.33), 20), 204: ((1.0, 0.1), 8), 408: ((1.0, 0.1), 4)},
# ---
- "256": {1: (0.6, 20), 34: (0.5, 2), 51: (0.5, 1), 68: (0.5, 1), 136: (0.0, None)},
- "240p": {1: (0.6, 20), 34: (0.5, 2), 51: (0.5, 1), 68: (0.5, 1), 136: (0.0, None)},
+ "256": {1: (0.4, 100), 51: (0.5, 24), 102: ((0.5, 0.33), 12), 204: ((0.5, 0.1), 4), 408: ((0.5, 0.1), 2)},
+ "240p": {1: (0.3, 100), 51: (0.4, 24), 102: ((0.4, 0.33), 12), 204: ((0.4, 0.1), 4), 408: ((0.4, 0.1), 2)},
# ---
- "360p": {1: (0.5, 8), 34: (0.2, 1), 102: (0.0, None)},
- "512": {1: (0.5, 8), 34: (0.2, 1), 102: (0.0, None)},
+ "360p": {1: (0.2, 60), 51: (0.15, 12), 102: ((0.15, 0.33), 6), 204: ((0.15, 0.1), 2), 408: ((0.15, 0.1), 1)},
+ "512": {1: (0.1, 60), 51: (0.3, 12), 102: (0.3, 6), 204: (0.3, 2), 408: (0.3, 1)},
# ---
- "480p": {1: (0.2, 4), 17: (0.3, 1), 68: (0.0, None)},
+ "480p": {1: (0.1, 40), 51: (0.3, 6), 102: (0.3, 3), 204: (0.3, 1), 408: (0.0, None)},
# ---
- "720p": {1: (0.1, 2)},
- "1024": {1: (0.1, 2)},
+ "720p": {1: (0.05, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
+ "1024": {1: (0.05, 20), 51: (0.3, 2), 102: (0.3, 1), 204: (0.0, None)},
# ---
- "1080p": {1: (0.1, 1)},
+ "1080p": {1: (0.1, 10)},
+ # ---
+ "2048": {1: (0.1, 5)},
}
-grad_checkpoint = False # determine batch size
-batch_size = None
+
+grad_checkpoint = True
# Acceleration settings
num_workers = 8
@@ -39,7 +62,9 @@ model = dict(
)
vae = dict(
type="VideoAutoencoderPipeline",
- from_pretrained="pretrained_models/vae-v3",
+ from_pretrained="pretrained_models/vae-pipeline",
+ shift=(-0.10, 0.34, 0.27, 0.98),
+ scale=(3.85, 2.32, 2.33, 3.06),
micro_frame_size=17,
vae_2d=dict(
type="VideoAutoencoderKL",
@@ -62,7 +87,6 @@ text_encoder = dict(
)
scheduler = dict(
type="rflow",
- use_discrete_timesteps=False,
use_timestep_transform=True,
sample_method="logit-normal",
)
@@ -92,6 +116,6 @@ ckpt_every = 500
# optimization settings
load = None
grad_clip = 1.0
-lr = 1e-4
+lr = 2e-4
ema_decay = 0.99
adam_eps = 1e-15
diff --git a/opensora/models/stdit/stdit3.py b/opensora/models/stdit/stdit3.py
index 4bec074..14d5ad7 100644
--- a/opensora/models/stdit/stdit3.py
+++ b/opensora/models/stdit/stdit3.py
@@ -164,7 +164,7 @@ class STDiT3Config(PretrainedConfig):
drop_path=0.0,
caption_channels=4096,
model_max_length=300,
- qk_norm=False,
+ qk_norm=True,
enable_flash_attn=False,
enable_layernorm_kernel=False,
enable_sequence_parallelism=False,
diff --git a/opensora/schedulers/iddpm/gaussian_diffusion.py b/opensora/schedulers/iddpm/gaussian_diffusion.py
index 4fae13f..5b10823 100644
--- a/opensora/schedulers/iddpm/gaussian_diffusion.py
+++ b/opensora/schedulers/iddpm/gaussian_diffusion.py
@@ -424,6 +424,7 @@ class GaussianDiffusion:
) * _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape)
# active noise addition
+ # WARNING: this is a hacky implementation
mask_t_equall = (mask_t == t.unsqueeze(1))[:, None, :, None, None]
x = torch.where(mask_t_equall, x_noise, x0)
diff --git a/opensora/schedulers/rf/__init__.py b/opensora/schedulers/rf/__init__.py
index e9fb990..c4775b7 100644
--- a/opensora/schedulers/rf/__init__.py
+++ b/opensora/schedulers/rf/__init__.py
@@ -48,49 +48,52 @@ class RFLOW:
guidance_scale = self.cfg_scale
n = len(prompts)
+ # text encoding
model_args = text_encoder.encode(prompts)
y_null = text_encoder.null(n)
model_args["y"] = torch.cat([model_args["y"], y_null], 0)
if additional_args is not None:
model_args.update(additional_args)
+ # prepare timesteps
timesteps = [(1.0 - i / self.num_sampling_steps) * self.num_timesteps for i in range(self.num_sampling_steps)]
-
- # convert float timesteps to most close int timesteps
if self.use_discrete_timesteps:
timesteps = [int(round(t)) for t in timesteps]
-
+ timesteps = [torch.tensor([t] * z.shape[0], device=device) for t in timesteps]
if self.use_timestep_transform:
timesteps = [timestep_transform(t, additional_args, num_timesteps=self.num_timesteps) for t in timesteps]
+ if mask is not None:
+ noise_added = torch.zeros_like(mask, dtype=torch.bool)
+
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_t = (mask * self.num_timesteps).to(torch.int)
+ mask_t = mask * self.num_timesteps
x0 = z.clone()
x_noise = self.scheduler.add_noise(x0, torch.randn_like(x0), t)
- mask_t_equall = (mask_t == torch.floor(t.unsqueeze(1)).long())[:, None, :, None, None]
- z = torch.where(mask_t_equall, x_noise, x0)
- mask_t_upper = (mask_t > t.unsqueeze(1))[:, None, :, None, None]
- batch_size = z.shape[0]
- x_mask = mask_t_upper.reshape(batch_size, -1).to(torch.bool)
- model_args["x_mask"] = x_mask
+ mask_t_upper = mask_t >= t.unsqueeze(1)
+ model_args["x_mask"] = mask_t_upper.repeat(2, 1)
+
+ mask_add_noise = mask_t_upper & ~noise_added & (mask != 1)
+ noise_added = noise_added | mask_add_noise
+ z = torch.where(mask_add_noise[:, None, :, None, None], x_noise, x0)
+ # classifier-free guidance
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]
+ t = torch.cat([t, t], 0)
+ pred = model(z_in, t, **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)
+ # update z
dt = timesteps[i] - timesteps[i + 1] if i < len(timesteps) - 1 else timesteps[i]
dt = dt / self.num_timesteps
- z = z + v_pred * dt
+ z = z + v_pred * dt[:, None, None, None, None]
if mask is not None:
- mask_t_lower = (mask_t < t.unsqueeze(1))[:, None, :, None, None]
- z = torch.where(mask_t_lower, x0, z)
+ z = torch.where(mask_t_upper[:, None, :, None, None], z, x0)
return z
diff --git a/opensora/utils/config_utils.py b/opensora/utils/config_utils.py
index 8b61c83..e0177ed 100644
--- a/opensora/utils/config_utils.py
+++ b/opensora/utils/config_utils.py
@@ -4,7 +4,6 @@ import os
from glob import glob
from mmengine.config import Config
-from torch.utils.tensorboard import SummaryWriter
def parse_args(training=False):
@@ -25,6 +24,10 @@ def parse_args(training=False):
)
parser.add_argument("--batch-size", default=None, type=int, help="batch size")
parser.add_argument("--outputs", default=None, type=str, help="the dir to save model weights")
+ parser.add_argument("--flash-attn", default=None, action=argparse.BooleanOptionalAction, help="enable flash attn")
+ parser.add_argument(
+ "--layernorm-kernel", default=None, action=argparse.BooleanOptionalAction, help="enable layernorm kernel"
+ )
# ======================================================
# Inference
@@ -77,6 +80,12 @@ def merge_args(cfg, args, training=False):
if cfg.get("discriminator") is not None:
cfg.discriminator["from_pretrained"] = args.ckpt_path
args.ckpt_path = None
+ if args.flash_attn is not None:
+ cfg.model["enable_flash_attn"] = args.flash_attn
+ args.enable_flash_attn = None
+ if args.layernorm_kernel is not None:
+ cfg.model["enable_layernorm_kernel"] = args.layernorm_kernel
+ args.enable_layernorm_kernel = None
if args.data_path is not None:
cfg.dataset["data_path"] = args.data_path
args.data_path = None
@@ -98,12 +107,6 @@ def merge_args(cfg, args, training=False):
if v is not None:
cfg[k] = v
- if not training:
- if "reference_path" not in cfg:
- cfg["reference_path"] = None
- if "loop" not in cfg:
- cfg["loop"] = 1
-
return cfg
@@ -140,10 +143,3 @@ def define_experiment_workspace(cfg, get_last_workspace=False):
def save_training_config(cfg, experiment_dir):
with open(f"{experiment_dir}/config.txt", "w") as f:
json.dump(cfg, f, indent=4)
-
-
-def create_tensorboard_writer(exp_dir):
- tensorboard_dir = f"{exp_dir}/tensorboard"
- os.makedirs(tensorboard_dir, exist_ok=True)
- writer = SummaryWriter(tensorboard_dir)
- return writer
diff --git a/opensora/utils/inference_utils.py b/opensora/utils/inference_utils.py
index 48792b4..48b1312 100644
--- a/opensora/utils/inference_utils.py
+++ b/opensora/utils/inference_utils.py
@@ -1,8 +1,11 @@
+import json
import os
+import re
import torch
from opensora.datasets import IMG_FPS
+from opensora.datasets.utils import read_from_path
def prepare_multi_resolution_info(info_type, batch_size, image_size, num_frames, fps, device, dtype):
@@ -13,12 +16,12 @@ def prepare_multi_resolution_info(info_type, batch_size, image_size, num_frames,
ar = torch.tensor([[image_size[0] / image_size[1]]], device=device, dtype=dtype).repeat(batch_size, 1)
return dict(ar=ar, hw=hw)
elif info_type in ["STDiT2", "OpenSora"]:
+ fps = fps if num_frames > 1 else IMG_FPS
+ fps = torch.tensor([fps], device=device, dtype=dtype).repeat(batch_size)
height = torch.tensor([image_size[0]], device=device, dtype=dtype).repeat(batch_size)
width = torch.tensor([image_size[1]], device=device, dtype=dtype).repeat(batch_size)
num_frames = torch.tensor([num_frames], device=device, dtype=dtype).repeat(batch_size)
ar = torch.tensor([image_size[0] / image_size[1]], device=device, dtype=dtype).repeat(batch_size)
- fps = fps if num_frames > 1 else IMG_FPS
- fps = torch.tensor([fps], device=device, dtype=dtype).repeat(batch_size)
return dict(height=height, width=width, num_frames=num_frames, ar=ar, fps=fps)
else:
raise NotImplementedError
@@ -47,3 +50,124 @@ def get_save_path_name(
if num_sample != 1:
save_path = f"{save_path}-{k}"
return save_path
+
+
+def extract_json_from_prompts(prompts, reference, mask_strategy):
+ ret_prompts = []
+ for i, prompt in enumerate(prompts):
+ parts = re.split(r"(?=[{\[])", prompt)
+ assert len(parts) <= 2, f"Invalid prompt: {prompt}"
+ ret_prompts.append(parts[0])
+ if len(parts) > 1:
+ additional_info = json.loads(parts[1])
+ for key in additional_info:
+ assert key in ["reference_path", "mask_strategy"], f"Invalid key: {key}"
+ if key == "reference_path":
+ reference[i] = additional_info[key]
+ elif key == "mask_strategy":
+ mask_strategy[i] = additional_info[key]
+ return ret_prompts, reference, mask_strategy
+
+
+def collect_references_batch(reference_paths, vae, image_size):
+ refs_x = [] # refs_x: [batch, ref_num, C, T, H, W]
+ for reference_path in reference_paths:
+ if reference_path == "":
+ refs_x.append([])
+ continue
+ ref_path = reference_path.split(";")
+ ref = []
+ for r_path in ref_path:
+ r = read_from_path(r_path, image_size, transform_name="resize_crop")
+ r_x = vae.encode(r.unsqueeze(0).to(vae.device, vae.dtype))
+ r_x = r_x.squeeze(0)
+ ref.append(r_x)
+ refs_x.append(ref)
+ return refs_x
+
+
+def extract_prompts_loop(prompts, num_loop):
+ ret_prompts = []
+ for prompt in prompts:
+ if prompt.startswith("|0|"):
+ prompt_list = prompt.split("|")[1:]
+ text_list = []
+ for i in range(0, len(prompt_list), 2):
+ start_loop = int(prompt_list[i])
+ text = prompt_list[i + 1]
+ end_loop = int(prompt_list[i + 2]) if i + 2 < len(prompt_list) else num_loop
+ text_list.extend([text] * (end_loop - start_loop))
+ prompt = text_list[num_loop]
+ ret_prompts.append(prompt)
+ return ret_prompts
+
+
+MASK_DEFAULT = ["0", "0", "0", "0", "1", "0"]
+
+
+def parse_mask_strategy(mask_strategy):
+ mask_batch = []
+ if mask_strategy == "" or mask_strategy is None:
+ return mask_batch
+
+ mask_strategy = mask_strategy.split(";")
+ for mask in mask_strategy:
+ mask_group = mask.split(",")
+ num_group = len(mask_group)
+ assert num_group >= 1 and num_group <= 6, f"Invalid mask strategy: {mask}"
+ mask_group.extend(MASK_DEFAULT[num_group:])
+ for i in range(5):
+ mask_group[i] = int(mask_group[i])
+ mask_group[5] = float(mask_group[5])
+ mask_batch.append(mask_group)
+ return mask_batch
+
+
+def find_nearest_point(value, point, max_value):
+ t = value // point
+ if value % point > point / 2 and t < max_value // point - 1:
+ t += 1
+ return t * point
+
+
+def apply_mask_strategy(z, refs_x, mask_strategys, loop_i, align=None):
+ masks = []
+ for i, mask_strategy in enumerate(mask_strategys):
+ mask = torch.ones(z.shape[2], dtype=torch.float, device=z.device)
+ mask_strategy = parse_mask_strategy(mask_strategy)
+ for mst in mask_strategy:
+ loop_id, m_id, m_ref_start, m_target_start, m_length, edit_ratio = mst
+ if loop_id != loop_i:
+ continue
+ ref = refs_x[i][m_id]
+
+ if m_ref_start < 0:
+ # ref: [C, T, H, W]
+ m_ref_start = ref.shape[1] + m_ref_start
+ if m_target_start < 0:
+ # z: [B, C, T, H, W]
+ m_target_start = z.shape[2] + m_target_start
+ if align is not None:
+ m_ref_start = find_nearest_point(m_ref_start, align, ref.shape[1])
+ m_target_start = find_nearest_point(m_target_start, align, z.shape[2])
+ m_length = min(m_length, z.shape[2] - m_target_start, ref.shape[1] - m_ref_start)
+ z[i, :, m_target_start : m_target_start + m_length] = ref[:, m_ref_start : m_ref_start + m_length]
+ mask[m_target_start : m_target_start + m_length] = edit_ratio
+ masks.append(mask)
+ masks = torch.stack(masks)
+ return masks
+
+
+def append_generated(vae, generated_video, refs_x, mask_strategy, loop_i, condition_frame_length):
+ ref_x = vae.encode(generated_video)
+ for j, refs in enumerate(refs_x):
+ if refs is None:
+ refs_x[j] = [ref_x[j]]
+ else:
+ refs.append(ref_x[j])
+ if mask_strategy[j] is None:
+ mask_strategy[j] = ""
+ else:
+ mask_strategy[j] += ";"
+ mask_strategy[j] += f"{loop_i},{len(refs)-1},-{condition_frame_length},0,{condition_frame_length}"
+ return refs_x, mask_strategy
diff --git a/opensora/utils/misc.py b/opensora/utils/misc.py
index d191581..ea620a4 100644
--- a/opensora/utils/misc.py
+++ b/opensora/utils/misc.py
@@ -11,6 +11,7 @@ from typing import Tuple
import numpy as np
import torch
import torch.distributed as dist
+from torch.utils.tensorboard import SummaryWriter
# ======================================================
# Logging
@@ -63,6 +64,13 @@ def print_0(*args, **kwargs):
print(*args, **kwargs)
+def create_tensorboard_writer(exp_dir):
+ tensorboard_dir = f"{exp_dir}/tensorboard"
+ os.makedirs(tensorboard_dir, exist_ok=True)
+ writer = SummaryWriter(tensorboard_dir)
+ return writer
+
+
# ======================================================
# String
# ======================================================
diff --git a/scripts/inference.py b/scripts/inference.py
index 2887fce..03bf5e7 100644
--- a/scripts/inference.py
+++ b/scripts/inference.py
@@ -13,7 +13,16 @@ from opensora.datasets import 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.inference_utils import get_save_path_name, load_prompts, prepare_multi_resolution_info
+from opensora.utils.inference_utils import (
+ append_generated,
+ apply_mask_strategy,
+ collect_references_batch,
+ extract_json_from_prompts,
+ extract_prompts_loop,
+ get_save_path_name,
+ load_prompts,
+ prepare_multi_resolution_info,
+)
from opensora.utils.misc import all_exists, create_logger, is_distributed, is_main_process, to_torch_dtype
@@ -90,6 +99,12 @@ def main():
assert cfg.get("prompt_path", None) is not None, "Prompt or prompt_path must be provided"
prompts = load_prompts(cfg.prompt_path, start_idx, cfg.get("end_index", None))
+ # == prepare reference ==
+ reference_path = cfg.get("reference_path", [""] * len(prompts))
+ mask_strategy = cfg.get("mask_strategy", [""] * len(prompts))
+ assert len(reference_path) == len(prompts), "Length of reference must be the same as prompts"
+ assert len(mask_strategy) == len(prompts), "Length of mask_strategy must be the same as prompts"
+
# == prepare arguments ==
image_size = cfg.image_size
num_frames = cfg.num_frames
@@ -98,6 +113,9 @@ def main():
multi_resolution = cfg.get("multi_resolution", None)
batch_size = cfg.get("batch_size", 1)
num_sample = cfg.get("num_sample", 1)
+ loop = cfg.get("loop", 1)
+ condition_frame_length = cfg.get("condition_frame_length", 5)
+ align = cfg.get("align", None)
save_dir = cfg.save_dir
os.makedirs(save_dir, exist_ok=True)
@@ -107,8 +125,12 @@ def main():
# == Iter over all samples ==
for i in progress_wrap(range(0, len(prompts), batch_size)):
# == prepare batch prompts ==
- batch_prompts_raw = prompts[i : i + batch_size]
- batch_prompts = [text_preprocessing(prompt) for prompt in batch_prompts_raw]
+ batch_prompts = prompts[i : i + batch_size]
+ ms = mask_strategy[i : i + batch_size]
+ refs = reference_path[i : i + batch_size]
+
+ batch_prompts, refs, ms = extract_json_from_prompts(batch_prompts, refs, ms)
+ refs = collect_references_batch(refs, vae, image_size)
# == multi-resolution info ==
model_args = prepare_multi_resolution_info(
@@ -123,7 +145,7 @@ def main():
save_dir,
sample_name=sample_name,
sample_idx=start_idx + idx,
- prompt=batch_prompts_raw[idx],
+ prompt=batch_prompts[idx],
prompt_as_path=prompt_as_path,
num_sample=num_sample,
k=k,
@@ -136,34 +158,51 @@ def main():
if prompt_as_path and all_exists(save_paths):
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=num_frames)
+ # == Iter over loop generation ==
+ video_clips = []
+ for loop_i in range(loop):
+ batch_prompts_loop = extract_prompts_loop(batch_prompts, loop_i)
+ batch_prompts_cleaned = [text_preprocessing(prompt) for prompt in batch_prompts_loop]
+
+ # == loop ==
+ if loop_i > 0:
+ refs, ms = append_generated(vae, video_clips[-1], refs, ms, loop_i, condition_frame_length)
+
+ # == sampling ==
+ z = torch.randn(len(batch_prompts), vae.out_channels, *latent_size, device=device, dtype=dtype)
+ masks = apply_mask_strategy(z, refs, ms, loop_i, align=align)
+ samples = scheduler.sample(
+ model,
+ text_encoder,
+ z=z,
+ prompts=batch_prompts_cleaned,
+ device=device,
+ additional_args=model_args,
+ progress=verbose >= 2,
+ mask=masks,
+ )
+ samples = vae.decode(samples.to(dtype), num_frames=num_frames)
+ video_clips.append(samples)
# == save samples ==
if is_main_process():
- for idx, sample in enumerate(samples):
+ for idx, batch_prompt in enumerate(batch_prompts):
if verbose >= 2:
- logger.info("Prompt: %s", batch_prompts_raw[idx])
+ logger.info("Prompt: %s", batch_prompt)
save_path = save_paths[idx]
+ video = [video_clips[i][idx] for i in range(loop)]
+ for i in range(1, loop):
+ video[i] = video[i][:, condition_frame_length:]
+ video = torch.cat(video, dim=1)
save_sample(
- sample,
+ video,
fps=save_fps,
save_path=save_path,
verbose=verbose >= 2,
)
start_idx += len(batch_prompts)
logger.info("Inference finished.")
- logger.info("Saved samples to %s", save_dir)
+ logger.info("Saved %s samples to %s", start_idx, save_dir)
if __name__ == "__main__":
diff --git a/scripts/inference_long.py b/scripts/inference_long.py
deleted file mode 100644
index e185598..0000000
--- a/scripts/inference_long.py
+++ /dev/null
@@ -1,317 +0,0 @@
-import json
-import os
-import re
-
-import colossalai
-import torch
-import torch.distributed as dist
-from colossalai.cluster import DistCoordinator
-from mmengine.runner import set_random_seed
-
-from opensora.acceleration.parallel_states import set_sequence_parallel_group
-from opensora.datasets import IMG_FPS, save_sample
-from opensora.datasets.utils import read_from_path
-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 collect_references_batch(reference_paths, vae, image_size):
- refs_x = []
- for reference_path in reference_paths:
- if reference_path is None:
- refs_x.append([])
- continue
- ref_path = reference_path.split(";")
- ref = []
- for r_path in ref_path:
- r = read_from_path(r_path, image_size, transform_name="resize_crop")
- r_x = vae.encode(r.unsqueeze(0).to(vae.device, vae.dtype))
- r_x = r_x.squeeze(0)
- ref.append(r_x)
- refs_x.append(ref)
- # refs_x: [batch, ref_num, C, T, H, W]
- return refs_x
-
-
-def process_mask_strategy(mask_strategy):
- mask_batch = []
- mask_strategy = mask_strategy.split(";")
- for mask in mask_strategy:
- mask_group = mask.split(",")
- assert len(mask_group) >= 1 and len(mask_group) <= 6, f"Invalid mask strategy: {mask}"
- if len(mask_group) == 1:
- mask_group.extend(["0", "0", "0", "1", "0"])
- elif len(mask_group) == 2:
- mask_group.extend(["0", "0", "1", "0"])
- elif len(mask_group) == 3:
- mask_group.extend(["0", "1", "0"])
- elif len(mask_group) == 4:
- mask_group.extend(["1", "0"])
- elif len(mask_group) == 5:
- mask_group.append("0")
- mask_batch.append(mask_group)
- return mask_batch
-
-
-def apply_mask_strategy(z, refs_x, mask_strategys, loop_i):
- masks = []
- for i, mask_strategy in enumerate(mask_strategys):
- mask = torch.ones(z.shape[2], dtype=torch.float, device=z.device)
- if mask_strategy is None:
- masks.append(mask)
- continue
- mask_strategy = process_mask_strategy(mask_strategy)
- for mst in mask_strategy:
- loop_id, m_id, m_ref_start, m_target_start, m_length, edit_ratio = mst
- loop_id = int(loop_id)
- if loop_id != loop_i:
- continue
- m_id = int(m_id)
- m_ref_start = int(m_ref_start)
- m_length = int(m_length)
- m_target_start = int(m_target_start)
- edit_ratio = float(edit_ratio)
- ref = refs_x[i][m_id] # [C, T, H, W]
- if m_ref_start < 0:
- m_ref_start = ref.shape[1] + m_ref_start
- if m_target_start < 0:
- # z: [B, C, T, H, W]
- m_target_start = z.shape[2] + m_target_start
- z[i, :, m_target_start : m_target_start + m_length] = ref[:, m_ref_start : m_ref_start + m_length]
- mask[m_target_start : m_target_start + m_length] = edit_ratio
- masks.append(mask)
- masks = torch.stack(masks)
- return masks
-
-
-def process_prompts(prompts, num_loop):
- ret_prompts = []
- for prompt in prompts:
- if prompt.startswith("|0|"):
- prompt_list = prompt.split("|")[1:]
- text_list = []
- for i in range(0, len(prompt_list), 2):
- start_loop = int(prompt_list[i])
- text = prompt_list[i + 1]
- text = text_preprocessing(text)
- end_loop = int(prompt_list[i + 2]) if i + 2 < len(prompt_list) else num_loop
- text_list.extend([text] * (end_loop - start_loop))
- assert len(text_list) == num_loop, f"Prompt loop mismatch: {len(text_list)} != {num_loop}"
- ret_prompts.append(text_list)
- else:
- prompt = text_preprocessing(prompt)
- ret_prompts.append([prompt] * num_loop)
- return ret_prompts
-
-
-def extract_json_from_prompts(prompts):
- additional_infos = []
- ret_prompts = []
- for prompt in prompts:
- parts = re.split(r"(?=[{\[])", prompt)
- assert len(parts) <= 2, f"Invalid prompt: {prompt}"
- ret_prompts.append(parts[0])
- if len(parts) == 1:
- additional_infos.append({})
- else:
- additional_infos.append(json.loads(parts[1]))
- return ret_prompts, additional_infos
-
-
-def main():
- # ======================================================
- # 1. cfg and init distributed env
- # ======================================================
- cfg = parse_configs(training=False)
- 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
-
- # 3.5 reference
- if cfg.reference_path is not None:
- assert len(cfg.reference_path) == len(
- prompts
- ), f"Reference path mismatch: {len(cfg.reference_path)} != {len(prompts)}"
- assert len(cfg.reference_path) == len(
- cfg.mask_strategy
- ), f"Mask strategy mismatch: {len(cfg.mask_strategy)} != {len(prompts)}"
- else:
- cfg.reference_path = [None] * len(prompts)
- cfg.mask_strategy = [None] * len(prompts)
-
- # ======================================================
- # 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
- for i in range(0, len(prompts), cfg.batch_size):
- batch_prompts_raw = prompts[i : i + cfg.batch_size]
- batch_prompts_raw, additional_infos = extract_json_from_prompts(batch_prompts_raw)
- batch_prompts_loops = process_prompts(batch_prompts_raw, cfg.loop)
- # 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.2. load reference videos & images
- for j, info in enumerate(additional_infos):
- if "reference_path" in info:
- cfg.reference_path[i + j] = info["reference_path"]
- if "mask_strategy" in info:
- cfg.mask_strategy[i + j] = info["mask_strategy"]
- refs_x = collect_references_batch(cfg.reference_path[i : i + cfg.batch_size], vae, cfg.image_size)
- mask_strategy = cfg.mask_strategy[i : i + cfg.batch_size]
-
- # 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
- video_clips = []
-
- # 4.4. long video generation
- for loop_i in range(cfg.loop):
- # 4.4 sample in hidden space
- batch_prompts = [prompt[loop_i] for prompt in batch_prompts_loops]
-
- # 4.5. apply mask strategy
- masks = None
- # if cfg.reference_path is not None:
- if loop_i > 0:
- ref_x = vae.encode(video_clips[-1])
- for j, refs in enumerate(refs_x):
- if refs is None:
- refs_x[j] = [ref_x[j]]
- else:
- refs.append(ref_x[j])
- if mask_strategy[j] is None:
- mask_strategy[j] = ""
- else:
- mask_strategy[j] += ";"
- mask_strategy[
- j
- ] += f"{loop_i},{len(refs)-1},-{cfg.condition_frame_length},0,{cfg.condition_frame_length}"
-
- # sampling
- z = torch.randn(len(batch_prompts), vae.out_channels, *latent_size, device=device, dtype=dtype)
- masks = apply_mask_strategy(z, refs_x, mask_strategy, loop_i)
- samples = scheduler.sample(
- model,
- text_encoder,
- z=z,
- prompts=batch_prompts,
- device=device,
- additional_args=model_args,
- mask=masks, # scheduler must support mask
- )
- samples = vae.decode(samples.to(dtype), num_frames=cfg.num_frames)
- video_clips.append(samples)
-
- # 4.7. save video
- if loop_i == cfg.loop - 1:
- if not use_dist or coordinator.is_master():
- for idx in range(len(video_clips[0])):
- video_clips_i = [video_clips[0][idx]] + [
- video_clips[i][idx][:, cfg.condition_frame_length :] for i in range(1, cfg.loop)
- ]
- video = torch.cat(video_clips_i, dim=1)
- 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(video, fps=cfg.fps // cfg.frame_interval, save_path=save_path)
- sample_idx += 1
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/inference_old.py b/scripts/inference_old.py
deleted file mode 100644
index 98c3f1d..0000000
--- a/scripts/inference_old.py
+++ /dev/null
@@ -1,184 +0,0 @@
-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 e115b53..cc629cd 100644
--- a/scripts/train.py
+++ b/scripts/train.py
@@ -17,15 +17,11 @@ 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 load, model_gathering, model_sharding, record_model_param_shape, save
-from opensora.utils.config_utils import (
- create_tensorboard_writer,
- define_experiment_workspace,
- parse_configs,
- save_training_config,
-)
+from opensora.utils.config_utils import define_experiment_workspace, parse_configs, save_training_config
from opensora.utils.misc import (
all_reduce_mean,
create_logger,
+ create_tensorboard_writer,
format_numel_str,
get_model_numel,
requires_grad,
diff --git a/scripts/train_vae.py b/scripts/train_vae.py
index 5db369f..9c5cbec 100644
--- a/scripts/train_vae.py
+++ b/scripts/train_vae.py
@@ -19,13 +19,15 @@ 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 load, save
-from opensora.utils.config_utils import (
+from opensora.utils.config_utils import define_experiment_workspace, parse_configs, save_training_config
+from opensora.utils.misc import (
+ all_reduce_mean,
+ create_logger,
create_tensorboard_writer,
- define_experiment_workspace,
- parse_configs,
- save_training_config,
+ format_numel_str,
+ get_model_numel,
+ to_torch_dtype,
)
-from opensora.utils.misc import all_reduce_mean, create_logger, format_numel_str, get_model_numel, to_torch_dtype
from opensora.utils.train_utils import create_colossalai_plugin
DEFAULT_DATASET_NAME = "VideoTextDataset"