Skip to content

SkyReels-V2: Infinite-length Film Generative model

Python

support video extension and start/end frame control

wangwei2eee067ff29a
diff --git a/.gitignore b/.gitignore
index d9a83d9..ce11adc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,4 +16,5 @@ scripts/.gradio/*
# *.csv
*.jsonl
out/*
-model/
\ No newline at end of file
+model/
+run.sh
\ No newline at end of file
diff --git a/README.md b/README.md
index dd2a88e..3f3656d 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,7 @@ Welcome to the **SkyReels V2** repository! Here, you'll find the model weights a
## 🔥🔥🔥 News!!
+* May 16, 2025: 🔥 We support video extension and experimental features for start/end frame control.
* Apr 24, 2025: 🔥 We release the 720P models, [SkyReels-V2-DF-14B-720P](https://huggingface.co/Skywork/SkyReels-V2-DF-14B-720P) and [SkyReels-V2-I2V-14B-720P](https://huggingface.co/Skywork/SkyReels-V2-I2V-14B-720P). The former facilitates infinite-length autoregressive video generation, and the latter focuses on Image2Video synthesis.
* Apr 21, 2025: 👋 We release the inference code and model weights of [SkyReels-V2](https://huggingface.co/collections/Skywork/skyreels-v2-6801b1b93df627d441d0d0d9) Series Models and the video captioning model [SkyCaptioner-V1](https://huggingface.co/Skywork/SkyCaptioner-V1) .
* Apr 3, 2025: 🔥 We also release [SkyReels-A2](https://github.com/SkyworkAI/SkyReels-A2). This is an open-sourced controllable video generation framework capable of assembling arbitrary visual elements.
@@ -288,6 +289,8 @@ Below are the key parameters you can customize for video generation:
| --overlap_history | 17 | Number of frames to overlap for smooth transitions in long videos |
| --addnoise_condition | 20 | Improves consistency in long video generation |
| --causal_block_size | 5 | Recommended when using asynchronous inference (--ar_step > 0) |
+--video_path | | Path to input video for video extension |
+--end_image | | Path to input image for end frame control |
#### Multi-GPU inference using xDiT USP
diff --git a/generate_video_df.py b/generate_video_df.py
index aa49782..9931439 100644
--- a/generate_video_df.py
+++ b/generate_video_df.py
@@ -11,16 +11,27 @@ from diffusers.utils import load_image
from skyreels_v2_infer import DiffusionForcingPipeline
from skyreels_v2_infer.modules import download_model
from skyreels_v2_infer.pipelines import PromptEnhancer
-from skyreels_v2_infer.pipelines import resizecrop
+from skyreels_v2_infer.pipelines.image2video_pipeline import resizecrop
+from moviepy.editor import VideoFileClip
+
+
+def get_video_num_frames_moviepy(video_path):
+ with VideoFileClip(video_path) as clip:
+ num_frames = 0
+ for _ in clip.iter_frames():
+ num_frames += 1
+ return clip.size, num_frames
-if __name__ == "__main__":
+if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--outdir", type=str, default="diffusion_forcing")
parser.add_argument("--model_id", type=str, default="Skywork/SkyReels-V2-DF-1.3B-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)
+ parser.add_argument("--end_image", type=str, default=None)
+ parser.add_argument("--video_path", type=str, default='')
parser.add_argument("--ar_step", type=int, default=0)
parser.add_argument("--causal_attention", action="store_true")
parser.add_argument("--causal_block_size", type=int, default=1)
@@ -45,13 +56,11 @@ if __name__ == "__main__":
"--teacache_thresh",
type=float,
default=0.2,
- help="Higher speedup will cause to worse quality -- 0.1 for 2.0x speedup -- 0.2 for 3.0x speedup",
- )
+ help="Higher speedup will cause to worse quality -- 0.1 for 2.0x speedup -- 0.2 for 3.0x speedup")
parser.add_argument(
"--use_ret_steps",
action="store_true",
- help="Using Retention Steps will result in faster generation speed and better generation quality.",
- )
+ help="Using Retention Steps will result in faster generation speed and better generation quality.")
args = parser.parse_args()
args.model_id = download_model(args.model_id)
@@ -85,22 +94,14 @@ if __name__ == "__main__":
guidance_scale = args.guidance_scale
shift = args.shift
- if args.image:
- args.image = load_image(args.image)
- image_width, image_height = args.image.size
- if image_height > image_width:
- height, width = width, height
- args.image = resizecrop(args.image, height, width)
- image = args.image.convert("RGB") if args.image else None
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
save_dir = os.path.join("result", args.outdir)
os.makedirs(save_dir, exist_ok=True)
local_rank = 0
if args.use_usp:
- assert (
- not args.prompt_enhancer
- ), "`--prompt_enhancer` is not allowed if using `--use_usp`. We recommend running the skyreels_v2_infer/pipelines/prompt_enhancer.py script first to generate enhanced prompt before enabling the `--use_usp` parameter."
+ assert not args.prompt_enhancer, "`--prompt_enhancer` is not allowed if using `--use_usp`. We recommend running the skyreels_v2_infer/pipelines/prompt_enhancer.py script first to generate enhanced prompt before enabling the `--use_usp` parameter."
from xfuser.core.distributed import initialize_model_parallel, init_distributed_environment
import torch.distributed as dist
@@ -138,32 +139,31 @@ if __name__ == "__main__":
if args.causal_attention:
pipe.transformer.set_ar_attention(args.causal_block_size)
-
+
if args.teacache:
if args.ar_step > 0:
- num_steps = (
- args.inference_steps
- + (((args.base_num_frames - 1) // 4 + 1) // args.causal_block_size - 1) * args.ar_step
- )
- print("num_steps:", num_steps)
+ num_steps = args.inference_steps + (((args.base_num_frames - 1) // 4 + 1) // args.causal_block_size - 1) * args.ar_step
+ print('num_steps:', num_steps)
else:
num_steps = args.inference_steps
- pipe.transformer.initialize_teacache(
- enable_teacache=True,
- num_steps=num_steps,
- teacache_thresh=args.teacache_thresh,
- use_ret_steps=args.use_ret_steps,
- ckpt_dir=args.model_id,
- )
+ pipe.transformer.initialize_teacache(enable_teacache=True, num_steps=num_steps,
+ teacache_thresh=args.teacache_thresh, use_ret_steps=args.use_ret_steps,
+ ckpt_dir=args.model_id)
print(f"prompt:{prompt_input}")
print(f"guidance_scale:{guidance_scale}")
- with torch.cuda.amp.autocast(dtype=pipe.transformer.dtype), torch.no_grad():
- video_frames = pipe(
+ if os.path.exists(args.video_path):
+ (v_width, v_height), input_num_frames = get_video_num_frames_moviepy(args.video_path)
+ assert input_num_frames >= args.overlap_history, "The input video is too short."
+
+ if v_height > v_width:
+ width, heigth = height, width
+
+ video_frames = pipe.extend_video(
prompt=prompt_input,
negative_prompt=negative_prompt,
- image=image,
+ prefix_video_path=args.video_path,
height=height,
width=width,
num_frames=num_frames,
@@ -178,6 +178,40 @@ if __name__ == "__main__":
causal_block_size=args.causal_block_size,
fps=fps,
)[0]
+ else:
+ if args.image:
+ args.image = load_image(args.image)
+ image_width, image_height = args.image.size
+ if image_height > image_width:
+ height, width = width, height
+ args.image = resizecrop(args.image, height, width)
+ if args.end_image:
+ args.end_image = load_image(args.end_image)
+ args.end_image = resizecrop(args.end_image, height, width)
+
+ image = args.image.convert("RGB") if args.image else None
+ end_image = args.end_image.convert("RGB") if args.end_image else None
+
+ with torch.cuda.amp.autocast(dtype=pipe.transformer.dtype), torch.no_grad():
+ video_frames = pipe(
+ prompt=prompt_input,
+ negative_prompt=negative_prompt,
+ image=image,
+ end_image=end_image,
+ height=height,
+ width=width,
+ num_frames=num_frames,
+ num_inference_steps=args.inference_steps,
+ shift=shift,
+ guidance_scale=guidance_scale,
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
+ overlap_history=args.overlap_history,
+ addnoise_condition=args.addnoise_condition,
+ base_num_frames=args.base_num_frames,
+ ar_step=args.ar_step,
+ causal_block_size=args.causal_block_size,
+ fps=fps,
+ )[0]
if local_rank == 0:
current_time = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
diff --git a/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.py b/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.py
index b27f1d8..f16f532 100644
--- a/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.py
+++ b/skyreels_v2_infer/pipelines/diffusion_forcing_pipeline.py
@@ -11,6 +11,8 @@ from diffusers.image_processor import PipelineImageInput
from diffusers.utils.torch_utils import randn_tensor
from diffusers.video_processor import VideoProcessor
from tqdm import tqdm
+import decord
+from decord import VideoReader
from ..modules import get_text_encoder
from ..modules import get_transformer
@@ -18,6 +20,8 @@ from ..modules import get_vae
from ..scheduler.fm_solvers_unipc import FlowUniPCMultistepScheduler
+
+
class DiffusionForcingPipeline:
"""
A pipeline for diffusion-based video generation tasks.
@@ -180,12 +184,205 @@ class DiffusionForcingPipeline:
return step_matrix, step_index, step_update_mask, valid_interval
+ def get_video_as_tensor(self, video_path, width, height):
+ """
+ Loads a video from the given path and returns it as a tensor with proper channel ordering.
+ Args:
+ video_path (str): Path to the video file
+ Returns:
+ torch.Tensor: Video tensor in [C, T, H, W] format (channels first)
+ """
+
+ # Set Decord to use CPU for video decoding
+ decord.bridge.set_bridge('torch')
+
+ # Load video
+ vr = VideoReader(video_path, width=width, height=height)
+ total_frames = len(vr)
+
+ # Read all frames
+ video_frames = vr.get_batch(list(range(total_frames)))
+
+ # Convert from [T, H, W, C] to [C, T, H, W] format
+ video_tensor = video_frames.permute(0, 3, 1, 2).float()
+
+ return video_tensor
+
+ @torch.no_grad()
+ def extend_video(
+ self,
+ prompt: Union[str, List[str]],
+ negative_prompt: Union[str, List[str]] = "",
+ prefix_video_path: List[torch.Tensor] = None,
+ height: int = 480,
+ width: int = 832,
+ num_frames: int = 97,
+ num_inference_steps: int = 50,
+ shift: float = 1.0,
+ guidance_scale: float = 5.0,
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
+ overlap_history: int = None,
+ addnoise_condition: int = 0,
+ base_num_frames: int = 97,
+ ar_step: int = 5,
+ causal_block_size: int = None,
+ fps: int = 24,
+ ):
+ latent_height = height // 8
+ latent_width = width // 8
+ latent_length = (num_frames - 1) // 4 + 1
+
+ self._guidance_scale = guidance_scale
+
+ i2v_extra_kwrags = {}
+ prefix_video = None
+ predix_video_latent_length = 0
+
+ self.text_encoder.to(self.device)
+ prompt_embeds = self.text_encoder.encode(prompt).to(self.transformer.dtype)
+ if self.do_classifier_free_guidance:
+ 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.timesteps
+ if causal_block_size is None:
+ causal_block_size = self.transformer.num_frame_per_block
+ fps_embeds = [fps] * prompt_embeds.shape[0]
+ fps_embeds = [0 if i == 16 else 1 for i in fps_embeds]
+ transformer_dtype = self.transformer.dtype
+ # with torch.cuda.amp.autocast(dtype=self.transformer.dtype), torch.no_grad():
+
+ prefix_video = self.get_video_as_tensor(prefix_video_path, width, height)
+ prefix_frame = torch.tensor(prefix_video, device=self.device)
+ start_video = (prefix_frame.float() / (255.0 / 2.0)) - 1.0
+ start_video = start_video.transpose(0, 1)
+
+ # long video generation
+ base_num_frames = (base_num_frames - 1) // 4 + 1 if base_num_frames is not None else latent_length
+ overlap_history_frames = (overlap_history - 1) // 4 + 1
+ n_iter = 1 + (latent_length - base_num_frames - 1) // (base_num_frames - overlap_history_frames) + 1
+ print(f"n_iter:{n_iter}")
+ output_video = start_video.cpu()
+ for i in range(n_iter):
+ prefix_video = output_video[:, -overlap_history:].to(prompt_embeds.device)
+ prefix_video = [self.vae.encode(prefix_video.unsqueeze(0))[0]] # [(c, f, h, w)]
+ if prefix_video[0].shape[1] % causal_block_size != 0:
+ truncate_len = prefix_video[0].shape[1] % causal_block_size
+ print("the length of prefix video is truncated for the casual block size alignment.")
+ prefix_video[0] = prefix_video[0][:, : prefix_video[0].shape[1] - truncate_len]
+ predix_video_latent_length = prefix_video[0].shape[1]
+ finished_frame_num = i * (base_num_frames - overlap_history_frames) + overlap_history_frames
+ left_frame_num = latent_length - finished_frame_num
+ base_num_frames_iter = min(left_frame_num + overlap_history_frames, base_num_frames)
+ if ar_step > 0 and self.transformer.enable_teacache:
+ num_steps = num_inference_steps + ((base_num_frames_iter - overlap_history_frames) // causal_block_size - 1) * ar_step
+ self.transformer.num_steps = num_steps
+
+ latent_shape = [16, base_num_frames_iter, latent_height, latent_width]
+ latents = self.prepare_latents(
+ latent_shape, dtype=transformer_dtype, device=prompt_embeds.device, generator=generator
+ )
+ latents = [latents]
+ if prefix_video is not None:
+ latents[0][:, :predix_video_latent_length] = prefix_video[0].to(transformer_dtype)
+ step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
+ base_num_frames_iter,
+ init_timesteps,
+ base_num_frames_iter,
+ ar_step,
+ predix_video_latent_length,
+ causal_block_size,
+ )
+ sample_schedulers = []
+ for _ in range(base_num_frames_iter):
+ sample_scheduler = FlowUniPCMultistepScheduler(
+ num_train_timesteps=1000, shift=1, use_dynamic_shifting=False
+ )
+ sample_scheduler.set_timesteps(num_inference_steps, device=prompt_embeds.device, shift=shift)
+ sample_schedulers.append(sample_scheduler)
+ sample_schedulers_counter = [0] * base_num_frames_iter
+ self.transformer.to(self.device)
+ for i, timestep_i in enumerate(tqdm(step_matrix)):
+ update_mask_i = step_update_mask[i]
+ valid_interval_i = valid_interval[i]
+ valid_interval_start, valid_interval_end = valid_interval_i
+ timestep = timestep_i[None, valid_interval_start:valid_interval_end].clone()
+ latent_model_input = [latents[0][:, valid_interval_start:valid_interval_end, :, :].clone()]
+ if addnoise_condition > 0 and valid_interval_start < predix_video_latent_length:
+ noise_factor = 0.001 * addnoise_condition
+ timestep_for_noised_condition = addnoise_condition
+ latent_model_input[0][:, valid_interval_start:predix_video_latent_length] = (
+ latent_model_input[0][:, valid_interval_start:predix_video_latent_length]
+ * (1.0 - noise_factor)
+ + torch.randn_like(
+ latent_model_input[0][:, valid_interval_start:predix_video_latent_length]
+ )
+ * noise_factor
+ )
+ timestep[:, valid_interval_start:predix_video_latent_length] = timestep_for_noised_condition
+ if not self.do_classifier_free_guidance:
+ noise_pred = self.transformer(
+ torch.stack([latent_model_input[0]]),
+ t=timestep,
+ context=prompt_embeds,
+ fps=fps_embeds,
+ **i2v_extra_kwrags,
+ )[0]
+ else:
+ noise_pred_cond = self.transformer(
+ torch.stack([latent_model_input[0]]),
+ t=timestep,
+ context=prompt_embeds,
+ fps=fps_embeds,
+ **i2v_extra_kwrags,
+ )[0]
+ noise_pred_uncond = self.transformer(
+ torch.stack([latent_model_input[0]]),
+ t=timestep,
+ context=negative_prompt_embeds,
+ fps=fps_embeds,
+ **i2v_extra_kwrags,
+ )[0]
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
+ for idx in range(valid_interval_start, valid_interval_end):
+ if update_mask_i[idx].item():
+ latents[0][:, idx] = sample_schedulers[idx].step(
+ noise_pred[:, idx - valid_interval_start],
+ timestep_i[idx],
+ latents[0][:, idx],
+ return_dict=False,
+ generator=generator,
+ )[0]
+ sample_schedulers_counter[idx] += 1
+ if self.offload:
+ self.transformer.cpu()
+ torch.cuda.empty_cache()
+ x0 = latents[0].unsqueeze(0)
+ videos = [self.vae.decode(x0)[0]]
+ if output_video is None:
+ output_video = videos[0].clamp(-1, 1).cpu() # c, f, h, w
+ else:
+ output_video = torch.cat(
+ [output_video, videos[0][:, overlap_history:].clamp(-1, 1).cpu()], 1
+ ) # c, f, h, w
+ output_video = [(output_video / 2 + 0.5).clamp(0, 1)]
+ output_video = [video for video in output_video]
+ output_video = [video.permute(1, 2, 3, 0) * 255 for video in output_video]
+ output_video = [video.cpu().numpy().astype(np.uint8) for video in output_video]
+
+ return output_video
+
+
@torch.no_grad()
def __call__(
self,
prompt: Union[str, List[str]],
negative_prompt: Union[str, List[str]] = "",
image: PipelineImageInput = None,
+ end_image: PipelineImageInput = None,
height: int = 480,
width: int = 832,
num_frames: int = 97,
@@ -209,8 +406,14 @@ class DiffusionForcingPipeline:
i2v_extra_kwrags = {}
prefix_video = None
predix_video_latent_length = 0
+ end_video = None
+ end_video_latent_length = 0
+
if image:
prefix_video, predix_video_latent_length = self.encode_image(image, height, width, num_frames)
+
+ if end_image:
+ end_video, end_video_latent_length = self.encode_image(end_image, height, width, num_frames)
self.text_encoder.to(self.device)
prompt_embeds = self.text_encoder.encode(prompt).to(self.transformer.dtype)
@@ -237,10 +440,24 @@ class DiffusionForcingPipeline:
latents = [latents]
if prefix_video is not None:
latents[0][:, :predix_video_latent_length] = prefix_video[0].to(transformer_dtype)
+
+ if end_video is not None:
+ latents[0] = torch.cat([latents[0], end_video[0].to(transformer_dtype)], dim=1)
+
+ base_num_frames = num_frames
base_num_frames = (base_num_frames - 1) // 4 + 1 if base_num_frames is not None else latent_length
+ if end_video is not None:
+ base_num_frames += end_video_latent_length
+ latent_length += end_video_latent_length
+
+
step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
latent_length, init_timesteps, base_num_frames, ar_step, predix_video_latent_length, causal_block_size
)
+ if end_video is not None:
+ step_matrix[:, -end_video_latent_length:] = 0
+ step_update_mask[:, -end_video_latent_length:] = False
+
sample_schedulers = []
for _ in range(latent_length):
sample_scheduler = FlowUniPCMultistepScheduler(
@@ -303,6 +520,9 @@ class DiffusionForcingPipeline:
self.transformer.cpu()
torch.cuda.empty_cache()
x0 = latents[0].unsqueeze(0)
+ if end_video is not None:
+ x0 = latents[0][:, :-end_video_latent_length].unsqueeze(0)
+
videos = self.vae.decode(x0)
videos = (videos / 2 + 0.5).clamp(0, 1)
videos = [video for video in videos]
@@ -340,6 +560,11 @@ class DiffusionForcingPipeline:
latents = [latents]
if prefix_video is not None:
latents[0][:, :predix_video_latent_length] = prefix_video[0].to(transformer_dtype)
+
+ if end_video is not None and i == n_iter - 1:
+ base_num_frames_iter += end_video_latent_length
+ latents[0] = torch.cat([latents[0], end_video[0].to(transformer_dtype)], dim=1)
+
step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
base_num_frames_iter,
init_timesteps,
@@ -348,6 +573,10 @@ class DiffusionForcingPipeline:
predix_video_latent_length,
causal_block_size,
)
+ if end_video is not None and i == n_iter - 1:
+ step_matrix[:, -end_video_latent_length:] = 0
+ step_update_mask[:, -end_video_latent_length:] = False
+
sample_schedulers = []
for _ in range(base_num_frames_iter):
sample_scheduler = FlowUniPCMultistepScheduler(
@@ -413,6 +642,9 @@ class DiffusionForcingPipeline:
self.transformer.cpu()
torch.cuda.empty_cache()
x0 = latents[0].unsqueeze(0)
+ if end_video is not None and i == n_iter - 1:
+ x0 = latents[0][:, :-end_video_latent_length].unsqueeze(0)
+
videos = [self.vae.decode(x0)[0]]
if output_video is None:
output_video = videos[0].clamp(-1, 1).cpu() # c, f, h, w