SkyReels-V2: Infinite-length Film Generative model
Python
fix huggingface load model && add peak VRAM description (#5)
Howe3e6371d4127f
diff --git a/.gitignore b/.gitignoreindex 0ec4713..d9a83d9 100644--- a/.gitignore+++ b/.gitignore@@ -6,7 +6,7 @@ results/*results/**.png*.jpg-# *.mp4+*.mp4*.log**.jsonscripts/transformer/*diff --git a/README.md b/README.mdindex 2dcf64b..dc68acd 100644--- a/README.md+++ b/README.md@@ -194,6 +194,7 @@ python3 generate_video_df.py \> - If you want to run the **image-to-video (I2V)** task, add `--image ${image_path}` to your command and it is also better to use **text-to-video (T2V)** prompt including the description of the first-frame image.> - You can use `--ar_step 5` to enable asynchronous inference. When asynchronous inference, `--causal_block_size 5` is recommanded.> - To reduce peak VRAM, lower the `--base_num_frames` for the same generative length `--num_frames`. This may slightly reduce video quality.+> - Generating a 540P video using the 1.3B model requires approximately 14.7GB peak VRAM, while the same resolution video using the 14B model demands around 51.2GB peak VRAM.- **Text To Video & Image To Video**@@ -212,6 +213,7 @@ python3 generate_video.py \```> **Note**:> - When using an **image-to-video (I2V)** model, you must provide an input image using the `--image ${image_path}` parameter. The `--guidance_scale 5.0` and `--shift 3.0` is recommanded for I2V model.+> - Generating a 540P video using the 1.3B model requires approximately 14.7GB peak VRAM, while the same resolution video using the 14B model demands around 43.4GB peak VRAM.- **Prompt Enhancer**diff --git a/generate_video.py b/generate_video.pyindex ccca27b..d527105 100644--- a/generate_video.py+++ b/generate_video.py@@ -1,6 +1,6 @@import argparse-import osimport gc+import osimport randomimport time@@ -8,13 +8,13 @@ import imageioimport torchfrom diffusers.utils import load_image+from skyreels_v2_infer.modules import download_modelfrom skyreels_v2_infer.pipelines import Image2VideoPipeline-from skyreels_v2_infer.pipelines import Text2VideoPipelinefrom skyreels_v2_infer.pipelines import PromptEnhancer+from skyreels_v2_infer.pipelines import Text2VideoPipelineMODEL_ID_CONFIG = {"text2video": [- "Skywork/SkyReels-V2-T2V-1.3B-540P","Skywork/SkyReels-V2-T2V-14B-540P","Skywork/SkyReels-V2-T2V-14B-720P",],@@ -30,7 +30,7 @@ if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("--outdir", type=str, default="video_out")- parser.add_argument("--model_id", type=str, default="Skywork/SkyReels-V2-T2V-1.3B-540P")+ parser.add_argument("--model_id", type=str, default="Skywork/SkyReels-V2-T2V-14B-540P")parser.add_argument("--resolution", type=str, choices=["540P", "720P"])parser.add_argument("--num_frames", type=int, default=97)parser.add_argument("--image", type=str, default=None)@@ -49,6 +49,9 @@ if __name__ == "__main__":parser.add_argument("--prompt_enhancer", action="store_true")args = parser.parse_args()+ args.model_id = download_model(args.model_id)+ print("model_id:", args.model_id)+assert (args.use_usp and args.seed is not None) or (not args.use_usp), "usp mode need seed"if args.seed == -1:random.seed(time.time())@@ -85,10 +88,10 @@ if __name__ == "__main__":prompt_input = args.promptif args.prompt_enhancer and args.image is None:- print(f'init prompt enhancer')+ print(f"init prompt enhancer")prompt_enhancer = PromptEnhancer()prompt_input = prompt_enhancer(prompt_input)- print(f'enhanced prompt: {prompt_input}')+ print(f"enhanced prompt: {prompt_input}")del prompt_enhancergc.collect()torch.cuda.empty_cache()@@ -105,11 +108,11 @@ if __name__ == "__main__":pipe = Image2VideoPipeline(model_path=args.model_id, dit_path=args.model_id, use_usp=args.use_usp, offload=args.offload)-+prompt_input = args.promptif args.prompt_enhancer and image is not None:prompt_input = prompt_enhancer(prompt_input)- print(f'enhanced prompt: {prompt_input}')+ print(f"enhanced prompt: {prompt_input}")kwargs = {"prompt": prompt_input,@@ -122,7 +125,7 @@ if __name__ == "__main__":"height": height,"width": width,}-+if image is not None:kwargs["image"] = load_image(args.image).convert("RGB")diff --git a/generate_video_df.py b/generate_video_df.pyindex 3fa2fe9..25aa052 100644--- a/generate_video_df.py+++ b/generate_video_df.py@@ -1,6 +1,6 @@import argparse-import osimport gc+import osimport randomimport time@@ -9,6 +9,7 @@ import torchfrom diffusers.utils import load_imagefrom skyreels_v2_infer import DiffusionForcingPipeline+from skyreels_v2_infer.modules import download_modelfrom skyreels_v2_infer.pipelines import PromptEnhancerif __name__ == "__main__":@@ -40,11 +41,14 @@ if __name__ == "__main__":parser.add_argument("--prompt_enhancer", action="store_true")args = parser.parse_args()+ args.model_id = download_model(args.model_id)+ print("model_id:", args.model_id)+assert (args.use_usp and args.seed is not None) or (not args.use_usp), "usp mode need seed"if args.seed == -1:random.seed(time.time())args.seed = int(random.randrange(4294967294))-+if args.resolution == "540P":height = 544width = 960@@ -93,10 +97,10 @@ if __name__ == "__main__":prompt_input = args.promptif args.prompt_enhancer and args.image is None:- print(f'init prompt enhancer')+ print(f"init prompt enhancer")prompt_enhancer = PromptEnhancer()prompt_input = prompt_enhancer(prompt_input)- print(f'enhanced prompt: {prompt_input}')+ print(f"enhanced prompt: {prompt_input}")del prompt_enhancergc.collect()torch.cuda.empty_cache()diff --git a/skyreels_v2_infer/modules/__init__.py b/skyreels_v2_infer/modules/__init__.pyindex ebbc5a5..5bc6afe 100644--- a/skyreels_v2_infer/modules/__init__.py+++ b/skyreels_v2_infer/modules/__init__.py@@ -1,3 +1,4 @@+import gcimport osimport torch@@ -9,28 +10,40 @@ from .transformer import WanModelfrom .vae import WanVAE+def download_model(model_id):+ if not os.path.exists(model_id):+ from huggingface_hub import snapshot_download++ model_id = snapshot_download(repo_id=model_id)+ return model_id++def get_vae(model_path, device="cuda", weight_dtype=torch.float32) -> WanVAE:vae = WanVAE(model_path).to(device).to(weight_dtype)vae.vae.requires_grad_(False)vae.vae.eval()+ gc.collect()+ torch.cuda.empty_cache()return vaedef get_transformer(model_path, device="cuda", weight_dtype=torch.bfloat16) -> WanModel:- """- load safetensor- """config_path = os.path.join(model_path, "config.json")transformer = WanModel.from_config(config_path).to(weight_dtype).to(device)- state_dict = {}+for file in os.listdir(model_path):if file.endswith(".safetensors"):file_path = os.path.join(model_path, file)- state_dict.update(load_file(file_path))- transformer.load_state_dict(state_dict, strict=False)+ state_dict = load_file(file_path)+ transformer.load_state_dict(state_dict, strict=False)+ del state_dict+ gc.collect()+ torch.cuda.empty_cache()+transformer.requires_grad_(False)transformer.eval()- transformer.to(device=device, dtype=weight_dtype)+ gc.collect()+ torch.cuda.empty_cache()return transformer@@ -40,6 +53,8 @@ def get_text_encoder(model_path, device="cuda", weight_dtype=torch.bfloat16) ->text_encoder = T5EncoderModel(checkpoint_path=t5_model, tokenizer_path=tokenizer_path).to(device).to(weight_dtype)text_encoder.requires_grad_(False)text_encoder.eval()+ gc.collect()+ torch.cuda.empty_cache()return text_encoder@@ -49,4 +64,6 @@ def get_image_encoder(model_path, device="cuda", weight_dtype=torch.bfloat16) ->image_enc = CLIPModel(checkpoint_path, tokenizer_path).to(weight_dtype).to(device)image_enc.requires_grad_(False)image_enc.eval()+ gc.collect()+ torch.cuda.empty_cache()return image_encdiff --git a/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.py b/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.pyindex 5230c80..c6f39ec 100644--- a/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.py+++ b/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.py@@ -218,6 +218,7 @@ class DiffusionForcingPipeline:negative_prompt_embeds = self.text_encoder.encode(negative_prompt).to(self.transformer.dtype)if self.offload:self.text_encoder.cpu()+ torch.cuda.empty_cache()self.scheduler.set_timesteps(num_inference_steps, device=prompt_embeds.device, shift=shift)init_timesteps = self.scheduler.timestepsdiff --git a/skyreels_v2_infer/pipelines/image2video_pipeline.py b/skyreels_v2_infer/pipelines/image2video_pipeline.pyindex ceef5dc..bb220db 100644--- a/skyreels_v2_infer/pipelines/image2video_pipeline.py+++ b/skyreels_v2_infer/pipelines/image2video_pipeline.py@@ -83,6 +83,7 @@ class Image2VideoPipeline:clip_context = self.clip.encode_video(img)if self.offload:self.clip.cpu()+ torch.cuda.empty_cache()# preprocessself.text_encoder.to(self.device)@@ -90,6 +91,7 @@ class Image2VideoPipeline:context_null = self.text_encoder.encode(negative_prompt).to(self.device)if self.offload:self.text_encoder.cpu()+ torch.cuda.empty_cache()latent = torch.randn(16, latent_length, latent_height, latent_width, dtype=torch.float32, generator=generator, device=self.devicediff --git a/skyreels_v2_infer/pipelines/text2video_pipeline.py b/skyreels_v2_infer/pipelines/text2video_pipeline.pyindex 1c085e9..05a1dd3 100644--- a/skyreels_v2_infer/pipelines/text2video_pipeline.py+++ b/skyreels_v2_infer/pipelines/text2video_pipeline.py@@ -1,4 +1,3 @@-import mathimport osfrom typing import Listfrom typing import Optional@@ -68,6 +67,7 @@ class Text2VideoPipeline:context_null = self.text_encoder.encode(negative_prompt).to(self.device)if self.offload:self.text_encoder.cpu()+ torch.cuda.empty_cache()latents = [torch.randn(