#
# 根据 Apache 许可证 2.0 版本（“许可证”）授权
# 您只能在遵守许可证的情况下使用本文件。
# 您可以在以下位置获取许可证副本
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或双方书面同意，软件
# 根据许可证分发，本软件按“原样”
# 不附带任何明示或暗示的保证或条件。
# 请参阅许可证中关于权限的具体语言
# 许可证下的限制。-->

  
    
      
    
  

# SkyReels-V2：无限长度电影生成模型

来自 Skywork AI 的 SkyReels 团队的 [SkyReels-V2](https://huggingface.co/papers/2504.13074)。

*视频生成领域的最新进展主要由扩散模型和自回归框架推动，但在协调提示词遵循度、视觉质量、运动动态和时长方面仍存在关键挑战：为提升时序视觉质量而牺牲运动动态、为优先保证分辨率而将视频时长限制在 5-10 秒，以及由于通用多模态大语言模型（MLLM）无法解读镜头构图、演员表情和镜头运动等电影语法，导致缺乏镜头感知的生成能力。这些相互交织的局限性阻碍了逼真的长视频合成和专业电影风格的生成。为了解决这些局限性，我们提出了 SkyReels-V2，一个无限长度的电影生成模型，该模型协同运用了多模态大语言模型（MLLM）、多阶段预训练、强化学习和扩散强制框架。首先，我们设计了一种综合的视频结构表示，结合了多模态 LLM 的通用描述和子专家模型的详细镜头语言。在人工标注的辅助下，我们随后训练了一个统一的视频描述器，命名为 SkyCaptioner-V1，以高效地标注视频数据。其次，我们为基础视频生成建立了渐进式分辨率预训练，随后进行四阶段的后训练增强：初始的概念平衡监督微调（SFT）提升了基线质量；使用人工标注和合成失真数据进行针对运动的强化学习（RL）训练，以解决动态伪影问题；我们采用非递减噪声调度的扩散强制框架，在高效的搜索空间中实现长视频合成；最终的高质量 SFT 进一步提升了视觉保真度。所有代码和模型均可在 [this https URL](https://github.com/SkyworkAI/SkyReels-V2) 获取。*

您可以在 [Skywork](https://huggingface.co/collections/Skywork/skyreels-v2-6801b1b93df627d441d0d0d9) 组织下找到所有原始的 SkyReels-V2 检查点。

以下 SkyReels-V2 模型在 Diffusers 中受支持：
- [SkyReels-V2 DF 1.3B - 540P](https://huggingface.co/Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers)
- [SkyReels-V2 DF 14B - 540P](https://huggingface.co/Skywork/SkyReels-V2-DF-14B-540P-Diffusers)
- [SkyReels-V2 DF 14B - 720P](https://huggingface.co/Skywork/SkyReels-V2-DF-14B-720P-Diffusers)
- [SkyReels-V2 T2V 14B - 540P](https://huggingface.co/Skywork/SkyReels-V2-T2V-14B-540P-Diffusers)
- [SkyReels-V2 T2V 14B - 720P](https://huggingface.co/Skywork/SkyReels-V2-T2V-14B-720P-Diffusers)
- [SkyReels-V2 I2V 1.3B - 540P](https://huggingface.co/Skywork/SkyReels-V2-I2V-1.3B-540P-Diffusers)
- [SkyReels-V2 I2V 14B - 540P](https://huggingface.co/Skywork/SkyReels-V2-I2V-14B-540P-Diffusers)
- [SkyReels-V2 I2V 14B - 720P](https://huggingface.co/Skywork/SkyReels-V2-I2V-14B-720P-Diffusers)

该模型由 [M. Tolga Cangöz](https://github.com/tolgacangoz) 贡献。

> [!TIP]
> 点击右侧边栏中的 SkyReles-V2 模型，以查看更多视频生成示例。

### _可视化_演示

以下示例包含以下参数：

- `base_num_frames=97`
- `num_frames=97`
- `num_inference_steps=30`
- `ar_step=5`
- `causal_block_size=5`

当 `vae_scale_factor_temporal=4` 时，预期会有 `5` 个块，每个块包含 `5` 帧，计算方式如下：

`num_latent_frames: (97-1)//vae_scale_factor_temporal+1 = 25 frames -> 5 blocks of 5 frames each`

潜在空间中的最大上下文长度通过 `base_num_latent_frames` 计算得出：

`base_num_latent_frames = (97-1)//vae_scale_factor_temporal+1 = 25 -> 25//5 = 5 blocks`

异步处理时间线：
```text
┌─────────────────────────────────────────────────────────────────┐
│ Steps:    1    6   11   16   21   26   31   36   41   46   50   │
│ Block 1: [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]                       │
│ Block 2:      [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]                  │
│ Block 3:           [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]             │
│ Block 4:                [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]        │
│ Block 5:                     [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]   │
└─────────────────────────────────────────────────────────────────┘
```

对于长视频（`num_frames` > `base_num_frames`）：`base_num_frames` 充当处理长视频时的“滑动窗口大小”。

示例：`257` 帧视频，`base_num_frames=97`，`overlap_history=17`
```text
┌──── Iteration 1 (frames 1-97) ────┐
│ Processing window: 97 frames      │ → 5 blocks,
│ Generates: frames 1-97            │   async processing
└───────────────────────────────────┘
            ┌────── Iteration 2 (frames 81-177) ──────┐
            │ Processing window: 97 frames            │
            │ Overlap: 17 frames (81-97) from prev    │ → 5 blocks,
            │ Generates: frames 98-177                │   async processing
            └─────────────────────────────────────────┘
                        ┌────── Iteration 3 (frames 161-257) ──────┐
                        │ Processing window: 97 frames             │
                        │ Overlap: 17 frames (161-177) from prev   │ → 5 blocks,
                        │ Generates: frames 178-257                │   async processing
                        └──────────────────────────────────────────┘
```

每次迭代都会独立运行异步处理，并拥有自己的 `5` 个块。`base_num_frames` 控制：
1. 内存使用量（窗口越大 = 显存占用越多）
2. 模型上下文长度（必须与训练约束相匹配）
3. 每次迭代的块数（`base_num_latent_frames // causal_block_size`）

每个块需要 `30` 步来完成去噪。第 N 个块从第 `1 + (N-1) x ar_step` 步开始。总步数：`30 + (5-1) x 5 = 50` 步

同步模式（`ar_step=0`）会同时处理所有块/帧：
```text
┌──────────────────────────────────────────────┐
│ Steps:       1            ...            30  │
│ All blocks: [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■] │
└──────────────────────────────────────────────┘
```
总步数：`30` 步

异步处理中步长矩阵构建的示例：给定参数：(`num_inference_steps=30, flow_shift=8, num_frames=97, ar_step=5, causal_block_size=5`)
```
- num_latent_frames = (97 frames - 1) // (4 temporal downsampling) + 1 = 25
- step_template = [999, 995, 991, 986, 980, 975, 969, 963, 956, 948,
                   941, 932, 922, 912, 901, 888, 874, 859, 841, 822,
                   799, 773, 743, 708, 666, 615, 551, 470, 363, 216]
```

该算法会创建一个 `50x25` 的 `step_matrix`，其中：
```
- Row 1:  [999×5, 999×5, 999×5, 999×5, 999×5]
- Row 2:  [995×5, 999×5, 999×5, 999×5, 999×5]
- Row 3:  [991×5, 999×5, 999×5, 999×5, 999×5]
- ...
- Row 7:  [969×5, 995×5, 999×5, 999×5, 999×5]
- ...
- Row 21: [799×5, 888×5, 941×5, 975×5, 999×5]
- ...
- Row 35: [  0×5, 216×5, 666×5, 822×5, 901×5]
- ...
- Row 42: [  0×5,   0×5,   0×5, 551×5, 773×5]
- ...
- Row 50: [  0×5,   0×5,   0×5,   0×5, 216×5]
```

`6` 行的详细分析：
```
- step_matrix[5]:      [ 975×5,  999×5,   999×5,   999×5,   999×5]
- step_index[5]:       [   6×5,    1×5,     0×5,     0×5,     0×5]
- step_update_mask[5]: [True×5, True×5, False×5, False×5, False×5]
- valid_interval[5]:   (0, 25)
```

关键模式：块 `i` 比块 `i-1` 恰好滞后 `ar_step=5` 个时间步，从而形成错位的“diffusion forcing”效果，即后续块以更早、更干净的块作为条件。

### 文本到视频生成

下面的示例演示了如何从文本生成视频。

有关各种内存节省技术的详细信息，请参阅 [减少内存使用](../../optimization/memory) 指南。

来自原始仓库：
>您可以使用 --ar_step 5 来启用异步推理。在异步推理时，建议设置 --causal_block_size 5，而在同步生成时则不应设置该参数……异步推理需要更多的步骤来扩散整个序列，这意味着它比同步模式更慢。在我们的实验中，异步推理可能会提升指令遵循和视觉一致性方面的表现。

```py
import torch
from diffusers import AutoModel, SkyReelsV2DiffusionForcingPipeline, UniPCMultistepScheduler
from diffusers.utils import export_to_video

model_id = "Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers"
vae = AutoModel.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)

pipeline = SkyReelsV2DiffusionForcingPipeline.from_pretrained(
    model_id,
    vae=vae,
    dtype=torch.bfloat16,
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"
flow_shift = 8.0  # 8.0 for T2V, 5.0 for I2V
pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config, flow_shift=flow_shift)

prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."

output = pipeline(
    prompt=prompt,
    num_inference_steps=30,
    height=544,  # 720 for 720P
    width=960,   # 1280 for 720P
    num_frames=97,
    base_num_frames=97,  # 121 for 720P
    ar_step=5,  # Controls asynchronous inference (0 for synchronous mode)
    causal_block_size=5,  # Number of frames in each block for asynchronous processing
    overlap_history=None,  # Number of frames to overlap for smooth transitions in long videos; 17 for long video generations
    addnoise_condition=20,  # Improves consistency in long video generation
).frames[0]
export_to_video(output, "video.mp4", fps=24, quality=8)
```

### 首尾帧到视频生成

下面的示例演示了如何使用图像到视频流水线，根据文本描述、起始帧和结束帧生成视频。

```python
import numpy as np
import torch
import torchvision.transforms.functional as TF
from diffusers import AutoencoderKLWan, SkyReelsV2DiffusionForcingImageToVideoPipeline, UniPCMultistepScheduler
from diffusers.utils import export_to_video, load_image

model_id = "Skywork/SkyReels-V2-DF-1.3B-720P-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipeline = SkyReelsV2DiffusionForcingImageToVideoPipeline.from_pretrained(
    model_id, vae=vae, dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"
flow_shift = 5.0  # 8.0 for T2V, 5.0 for I2V
pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config, flow_shift=flow_shift)

first_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png")
last_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png")

def aspect_ratio_resize(image, pipeline, max_area=720 * 1280):
    aspect_ratio = image.height / image.width
    mod_value = pipeline.vae_scale_factor_spatial * pipeline.transformer.config.patch_size[1]
    height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
    width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
    image = image.resize((width, height))
    return image, height, width

def center_crop_resize(image, height, width):
    # Calculate resize ratio to match first frame dimensions
    resize_ratio = max(width / image.width, height / image.height)

    # Resize the image
    width = round(image.width * resize_ratio)
    height = round(image.height * resize_ratio)
    size = [width, height]
    image = TF.center_crop(image, size)

    return image, height, width

first_frame, height, width = aspect_ratio_resize(first_frame, pipeline)
if last_frame.size != first_frame.size:
    last_frame, _, _ = center_crop_resize(last_frame, height, width)

prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."

output = pipeline(
    image=first_frame, last_image=last_frame, prompt=prompt, height=height, width=width, guidance_scale=5.0
).frames[0]
export_to_video(output, "video.mp4", fps=24, quality=8)
```

### 视频到视频生成

`SkyReelsV2DiffusionForcingVideoToVideoPipeline` 用于延长给定的视频。

```python
import numpy as np
import torch
import torchvision.transforms.functional as TF
from diffusers import AutoencoderKLWan, SkyReelsV2DiffusionForcingVideoToVideoPipeline, UniPCMultistepScheduler
from diffusers.utils import export_to_video, load_video

model_id = "Skywork/SkyReels-V2-DF-1.3B-720P-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipeline = SkyReelsV2DiffusionForcingVideoToVideoPipeline.from_pretrained(
    model_id, vae=vae, dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"
flow_shift = 5.0  # 8.0 for T2V, 5.0 for I2V
pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config, flow_shift=flow_shift)

video = load_video("input_video.mp4")

prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."

output = pipeline(
    video=video, prompt=prompt, height=720, width=1280, guidance_scale=5.0, overlap_history=17,
    num_inference_steps=30, num_frames=257, base_num_frames=121#, ar_step=5, causal_block_size=5,
).frames[0]
export_to_video(output, "video.mp4", fps=24, quality=8)
# Total frames will be the number of frames of the given video + 257
```

## 备注

- SkyReels-V2 支持通过 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.SkyReelsV2LoraLoaderMixin.load_lora_weights) 加载 LoRA。

`SkyReelsV2Pipeline` 和 `SkyReelsV2ImageToVideoPipeline` 也可在不应用 Diffusion Forcing 框架的情况下使用。

## SkyReelsV2DiffusionForcingPipeline[[diffusers.SkyReelsV2DiffusionForcingPipeline]]

#### diffusers.SkyReelsV2DiffusionForcingPipeline[[diffusers.SkyReelsV2DiffusionForcingPipeline]]

```python
diffusers.SkyReelsV2DiffusionForcingPipeline(tokenizer: AutoTokenizer, text_encoder: transformers.models.t5.modeling_t5.T5EncoderModel | transformers.models.umt5.modeling_umt5.UMT5EncoderModel, transformer: SkyReelsV2Transformer3DModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py#L128)

**参数：**

tokenizer (`AutoTokenizer`)：来自 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer) 的 Tokenizer，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

text_encoder （`UMT5EncoderModel`）：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

transformer ([SkyReelsV2Transformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/skyreels_v2_transformer_3d#diffusers.SkyReelsV2Transformer3DModel))：用于对编码后的图像潜在变量进行去噪的条件 Transformer。

scheduler ([UniPCMultistepScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/unipc#diffusers.UniPCMultistepScheduler))：一种调度器，需与 `transformer` 配合使用，以对编码后的图像潜变量进行去噪。

vae ([AutoencoderKLWan](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

使用 SkyReels-V2 和扩散强制（diffusion forcing）进行文本到视频（t2v）生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有 pipeline 实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

#### __调用__[[diffusers.SkyReelsV2DiffusionForcingPipeline.__call__]]

```python
__call__(prompt: str | list[str], negative_prompt: str | list[str] = None, height: int = 544, width: int = 960, num_frames: int = 97, num_inference_steps: int = 50, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, overlap_history: int | None = None, addnoise_condition: float = 0, base_num_frames: int = 97, ar_step: int = 0, causal_block_size: int | None = None, fps: int = 24)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py#L598)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

height (`int`，默认为 `544`)：生成视频的高度。

width (`int`，默认为 `960`)：生成视频的宽度。

num_frames (`int`，默认为 `97`)：生成视频的帧数。

num_inference_steps (`int`，默认为 `50`)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

guidance_scale (`float`，默认值为 `6.0`) : 如 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，通常以牺牲图像质量为代价。（**T2V 为 6.0**，**I2V 为 5.0**）

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

latents (`torch.Tensor`, *可选*) : 从高斯分布中采样的预生成噪声潜变量，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，则使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `negative_prompt` 输入参数生成文本嵌入。

output_type (`str`，*可选*，默认为 `"np"`)：生成图像的输出格式。在 `PIL.Image` 和 `np.array` 之间选择。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `SkyReelsV2PipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认为 `512`)：提示词的最大序列长度。

overlap_history (`int`，*可选*，默认为 `None`)：长视频中用于实现平滑过渡的重叠帧数。如果为 `None`，则流水线假定处于短视频生成模式，不应用任何重叠。建议设置为 17 或 37。

addnoise_condition (`float`，*可选*，默认值为 `0`)：用于通过在干净的条件中添加一些噪声来帮助平滑长视频生成。噪声过大同样会导致不一致。推荐值为 20，可以尝试更大的值，但建议不要超过 50。

base_num_frames (`int`，*可选*，默认值为 `97`)：97 或 121 | 基础帧数（**540P 为 97**，**720P 为 121**）

ar_step (`int`, *可选*，默认为 `0`)：控制异步推理（0 表示同步模式）。您可以设置 `ar_step=5` 以启用异步推理。在异步推理时，建议设置 `causal_block_size=5`，而在同步生成时不应设置该参数。异步推理需要更多步骤来扩散整个序列，这意味着它比同步模式更慢。在我们的实验中，异步推理可能会提升指令遵循和视觉一致性方面的表现。

causal_block_size (`int`，*可选*，默认为 `None`)：每个块/分块中的帧数。在使用异步推理（当 ar_step > 0）时建议使用。

fps (`int`，*可选*，默认为 `24`)：生成视频的帧率

**返回：** `~SkyReelsV2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `SkyReelsV2PipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成的 pipeline 的调用函数。

示例：
```py
>>> import torch
>>> from diffusers import (
...     SkyReelsV2DiffusionForcingPipeline,
...     UniPCMultistepScheduler,
...     AutoencoderKLWan,
... )
>>> from diffusers.utils import export_to_video

>>> # Load the pipeline
>>> # Available models:
>>> # - Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-DF-14B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-DF-14B-720P-Diffusers
>>> vae = AutoencoderKLWan.from_pretrained(
...     "Skywork/SkyReels-V2-DF-14B-720P-Diffusers",
...     subfolder="vae",
...     torch_dtype=torch.float32,
... )
>>> pipe = SkyReelsV2DiffusionForcingPipeline.from_pretrained(
...     "Skywork/SkyReels-V2-DF-14B-720P-Diffusers",
...     vae=vae,
...     torch_dtype=torch.bfloat16,
... )
>>> flow_shift = 8.0  # 8.0 for T2V, 5.0 for I2V
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe = pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."

>>> output = pipe(
...     prompt=prompt,
...     num_inference_steps=30,
...     height=544,
...     width=960,
...     guidance_scale=6.0,  # 6.0 for T2V, 5.0 for I2V
...     num_frames=97,
...     ar_step=5,  # Controls asynchronous inference (0 for synchronous mode)
...     causal_block_size=5,  # Number of frames processed together in a causal block
...     overlap_history=None,  # Number of frames to overlap for smooth transitions in long videos
...     addnoise_condition=20,  # Improves consistency in long video generation
... ).frames[0]
>>> export_to_video(output, "video.mp4", fps=24, quality=8)
```

#### encode_prompt[[diffusers.SkyReelsV2DiffusionForcingPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py#L219)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

#### generate_timestep_matrix[[diffusers.SkyReelsV2DiffusionForcingPipeline.generate_timestep_matrix]]

```python
generate_timestep_matrix(num_latent_frames: int, step_template: Tensor, base_num_latent_frames: int, ar_step: int = 5, num_pre_ready: int = 0, causal_block_size: int = 1, shrink_interval_with_mask: bool = False)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py#L418)

**参数：**

num_latent_frames (int) : 要生成的潜在帧总数

step_template (torch.Tensor) ：基础时间步调度（例如，[1000, 800, 600, ..., 0]）

base_num_latent_frames (int)：模型在单次前向传播中可处理的最大帧数

ar_step (int, optional) : 时间滞后自回归步长。0 = 同步，>0 = 异步。默认值为 5。

num_pre_ready (int, 可选) : 已去噪的帧数（例如，在 video2video 任务中来自前缀的帧数）。默认为 0。

causal_block_size (int, 可选) : 作为因果块处理的帧数。默认为 1。

shrink_interval_with_mask (bool, optional) : 是否优化处理间隔。默认为 False。

**返回：** `tuple containing`

- step_matrix (torch.Tensor): 每次迭代中每帧的时间步矩阵。形状：[num_iterations, num_latent_frames]
- step_index (torch.Tensor): 用于时间步查找的索引矩阵。形状: [num_iterations, num_latent_frames]
- step_update_mask (torch.Tensor): 布尔掩码，指示要更新哪些帧。形状：[num_iterations, num_latent_frames]
- valid_interval (list[tuple])：每次迭代的 (start, end) 区间列表

**引发：** ``ValueError``

- ``ValueError`` -- 如果 ar_step 对于给定的配置来说太小

该函数实现了核心的扩散强制（diffusion forcing）算法，用于在时间帧之间创建协调的去噪调度。它支持同步和异步两种生成模式：

**同步模式**（ar_step=0, causal_block_size=1）：
- 在每个时间步，所有帧同时去噪
- 每一帧都遵循相同的去噪轨迹：[1000, 800, 600, ..., 0]
- 更简单，但对于长视频可能具有较低的时间一致性

**异步模式**（ar_step>0，causal_block_size>1）：
- 帧被分组为因果块，并按块/分块进行处理
- 每个块以交错模式进行去噪，从而形成“去噪波”。
- 较早的块去噪程度更高，较晚的块则滞后 ar_step 个时间步
- 创建更强的时间依赖性和更好的一致性

## SkyReelsV2DiffusionForcingImageToVideoPipeline[[diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline]]

#### diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline[[diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline]]

```python
diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline(tokenizer: AutoTokenizer, text_encoder: transformers.models.t5.modeling_t5.T5EncoderModel | transformers.models.umt5.modeling_umt5.UMT5EncoderModel, transformer: SkyReelsV2Transformer3DModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py#L133)

**参数：**

tokenizer (`AutoTokenizer`)：来自 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer) 的 Tokenizer，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

text_encoder （`UMT5EncoderModel`）：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

transformer ([SkyReelsV2Transformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/skyreels_v2_transformer_3d#diffusers.SkyReelsV2Transformer3DModel))：用于对编码后的图像潜在变量进行去噪的条件 Transformer。

scheduler ([UniPCMultistepScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/unipc#diffusers.UniPCMultistepScheduler))：一种调度器，需与 `transformer` 配合使用，以对编码后的图像潜变量进行去噪。

vae ([AutoencoderKLWan](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

使用 SkyReels-V2 和扩散强制（diffusion forcing）进行图像到视频（i2v）生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有 pipeline 实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

#### __调用__[[diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 544, width: int = 960, num_frames: int = 97, num_inference_steps: int = 50, guidance_scale: float = 5.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, image_embeds: typing.Optional[torch.Tensor] = None, last_image: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, overlap_history: int | None = None, addnoise_condition: float = 0, base_num_frames: int = 97, ar_step: int = 0, causal_block_size: int | None = None, fps: int = 24)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py#L644)

**参数：**

image (`PipelineImageInput`)：用于条件生成的输入图像。必须是一张图像、一个图像列表或一个 `torch.Tensor`。

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

height (`int`，默认为 `544`)：生成视频的高度。

width (`int`，默认为 `960`)：生成视频的宽度。

num_frames (`int`，默认为 `97`)：生成视频的帧数。

num_inference_steps (`int`，默认为 `50`)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

guidance_scale (`float`，默认为 `5.0`) : 如 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，通常以牺牲图像质量为代价。（**T2V 为 6.0**，**I2V 为 5.0**）

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

latents (`torch.Tensor`, *可选*) : 从高斯分布中采样的预生成噪声潜变量，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，则使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `negative_prompt` 输入参数生成文本嵌入。

image_embeds (`torch.Tensor`, *可选*) : 预生成的图像嵌入。可用于轻松调整图像输入（加权）。如果未提供，则从 `image` 输入参数生成图像嵌入。

last_image (`torch.Tensor`, *可选*) : 预生成的图像嵌入。可用于轻松调整图像输入（加权）。如果未提供，则从 `image` 输入参数生成图像嵌入。

output_type (`str`，*可选*，默认为 `"np"`)：生成图像的输出格式。在 `PIL.Image` 和 `np.array` 之间选择。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `SkyReelsV2PipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认为 `512`)：提示词的最大序列长度。

overlap_history (`int`，*可选*，默认为 `None`)：长视频中用于实现平滑过渡的重叠帧数。如果为 `None`，则流水线假定处于短视频生成模式，不应用任何重叠。建议设置为 17 或 37。

addnoise_condition (`float`，*可选*，默认值为 `0`)：用于通过在干净的条件中添加一些噪声来帮助平滑长视频生成。噪声过大同样会导致不一致。推荐值为 20，可以尝试更大的值，但建议不要超过 50。

base_num_frames (`int`，*可选*，默认值为 `97`)：97 或 121 | 基础帧数（**540P 为 97**，**720P 为 121**）

ar_step (`int`, *可选*，默认为 `0`)：控制异步推理（0 表示同步模式）。您可以设置 `ar_step=5` 以启用异步推理。在异步推理时，建议设置 `causal_block_size=5`，而在同步生成时不应设置该参数。异步推理需要更多步骤来扩散整个序列，这意味着它比同步模式更慢。在我们的实验中，异步推理可能会提升指令遵循和视觉一致性方面的表现。

causal_block_size (`int`，*可选*，默认为 `None`)：每个块/分块中的帧数。在使用异步推理（当 ar_step > 0）时建议使用。

fps (`int`，*可选*，默认为 `24`)：生成视频的帧率

**返回：** `~SkyReelsV2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `SkyReelsV2PipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成的 pipeline 的调用函数。

示例：
```py
>>> import torch
>>> from diffusers import (
...     SkyReelsV2DiffusionForcingImageToVideoPipeline,
...     UniPCMultistepScheduler,
...     AutoencoderKLWan,
... )
>>> from diffusers.utils import export_to_video
>>> from PIL import Image

>>> # Load the pipeline
>>> # Available models:
>>> # - Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-DF-14B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-DF-14B-720P-Diffusers
>>> vae = AutoencoderKLWan.from_pretrained(
...     "Skywork/SkyReels-V2-DF-14B-720P-Diffusers",
...     subfolder="vae",
...     torch_dtype=torch.float32,
... )
>>> pipe = SkyReelsV2DiffusionForcingImageToVideoPipeline.from_pretrained(
...     "Skywork/SkyReels-V2-DF-14B-720P-Diffusers",
...     vae=vae,
...     torch_dtype=torch.bfloat16,
... )
>>> flow_shift = 5.0  # 8.0 for T2V, 5.0 for I2V
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe = pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
>>> image = Image.open("path/to/image.png")

>>> output = pipe(
...     image=image,
...     prompt=prompt,
...     num_inference_steps=50,
...     height=544,
...     width=960,
...     guidance_scale=5.0,  # 6.0 for T2V, 5.0 for I2V
...     num_frames=97,
...     ar_step=0,  # Controls asynchronous inference (0 for synchronous mode)
...     overlap_history=None,  # Number of frames to overlap for smooth transitions in long videos
...     addnoise_condition=20,  # Improves consistency in long video generation
... ).frames[0]
>>> export_to_video(output, "video.mp4", fps=24, quality=8)
```

#### encode_prompt[[diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py#L224)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

#### generate_timestep_matrix[[diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline.generate_timestep_matrix]]

```python
generate_timestep_matrix(num_latent_frames: int, step_template: Tensor, base_num_latent_frames: int, ar_step: int = 5, num_pre_ready: int = 0, causal_block_size: int = 1, shrink_interval_with_mask: bool = False)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py#L464)

**参数：**

num_latent_frames (int) : 要生成的潜在帧总数

step_template (torch.Tensor) ：基础时间步调度（例如，[1000, 800, 600, ..., 0]）

base_num_latent_frames (int)：模型在单次前向传播中可处理的最大帧数

ar_step (int, optional) : 时间滞后自回归步长。0 = 同步，>0 = 异步。默认值为 5。

num_pre_ready (int, 可选) : 已去噪的帧数（例如，在 video2video 任务中来自前缀的帧数）。默认为 0。

causal_block_size (int, 可选) : 作为因果块处理的帧数。默认为 1。

shrink_interval_with_mask (bool, optional) : 是否优化处理间隔。默认为 False。

**返回：** `tuple containing`

- step_matrix (torch.Tensor): 每次迭代中每帧的时间步矩阵。形状：[num_iterations, num_latent_frames]
- step_index (torch.Tensor): 用于时间步查找的索引矩阵。形状: [num_iterations, num_latent_frames]
- step_update_mask (torch.Tensor): 布尔掩码，指示要更新哪些帧。形状：[num_iterations, num_latent_frames]
- valid_interval (list[tuple])：每次迭代的 (start, end) 区间列表

**引发：** ``ValueError``

- ``ValueError`` -- 如果 ar_step 对于给定的配置来说太小

该函数实现了核心的扩散强制（diffusion forcing）算法，用于在时间帧之间创建协调的去噪调度。它支持同步和异步两种生成模式：

**同步模式**（ar_step=0, causal_block_size=1）：
- 在每个时间步，所有帧同时去噪
- 每一帧都遵循相同的去噪轨迹：[1000, 800, 600, ..., 0]
- 更简单，但对于长视频可能具有较低的时间一致性

**异步模式**（ar_step>0，causal_block_size>1）：
- 帧被分组为因果块，并按块/分块进行处理
- 每个块以交错模式进行去噪，从而形成“去噪波”。
- 较早的块去噪程度更高，较晚的块则滞后 ar_step 个时间步
- 创建更强的时间依赖性和更好的一致性

## SkyReelsV2DiffusionForcingVideoToVideoPipeline[[diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline]]

#### diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline[[diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline]]

```python
diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline(tokenizer: AutoTokenizer, text_encoder: transformers.models.t5.modeling_t5.T5EncoderModel | transformers.models.umt5.modeling_umt5.UMT5EncoderModel, transformer: SkyReelsV2Transformer3DModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py#L189)

**参数：**

tokenizer (`AutoTokenizer`)：来自 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer) 的 Tokenizer，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

text_encoder （`UMT5EncoderModel`）：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

transformer ([SkyReelsV2Transformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/skyreels_v2_transformer_3d#diffusers.SkyReelsV2Transformer3DModel))：用于对编码后的图像潜在变量进行去噪的条件 Transformer。

scheduler ([UniPCMultistepScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/unipc#diffusers.UniPCMultistepScheduler))：一种调度器，需与 `transformer` 配合使用，以对编码后的图像潜变量进行去噪。

vae ([AutoencoderKLWan](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

使用 SkyReels-V2 和扩散强制（diffusion forcing）进行视频到视频（v2v）生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有 pipeline 实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

#### __调用__[[diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline.__call__]]

```python
__call__(video: list[PIL.Image.Image], prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 544, width: int = 960, num_frames: int = 120, num_inference_steps: int = 50, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, overlap_history: int | None = None, addnoise_condition: float = 0, base_num_frames: int = 97, ar_step: int = 0, causal_block_size: int | None = None, fps: int = 24)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py#L684)

**参数：**

video (`list[Image.Image]`) : 用于引导视频生成的视频。

prompt (`str` 或 `list[str]`，*可选*)：用于引导视频生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导视频生成的负面提示词或提示词列表。如果未定义，则必须传入 `negative_prompt_embeds`。在未使用引导时（即 `guidance_scale` 小于 `1` 时）将被忽略。

height (`int`，默认为 `544`)：生成视频的高度。

width (`int`，默认为 `960`)：生成视频的宽度。

num_frames (`int`，默认为 `120`)：生成视频的帧数。

num_inference_steps (`int`，默认为 `50`)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

guidance_scale (`float`，默认值为 `6.0`) : 如 [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，通常以牺牲图像质量为代价。（**T2V 为 6.0**，**I2V 为 5.0**）

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

latents (`torch.Tensor`, *可选*) : 从高斯分布中采样的预生成噪声潜变量，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，则使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `negative_prompt` 输入参数生成文本嵌入。

output_type (`str`，*可选*，默认为 `"np"`)：生成图像的输出格式。在 `PIL.Image` 和 `np.array` 之间选择。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `SkyReelsV2PipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认为 `512`)：提示词的最大序列长度。

overlap_history (`int`，*可选*，默认为 `None`)：长视频中用于实现平滑过渡的重叠帧数。如果为 `None`，则流水线假定处于短视频生成模式，不应用任何重叠。建议设置为 17 或 37。

addnoise_condition (`float`，*可选*，默认值为 `0`)：用于通过在干净的条件中添加一些噪声来帮助平滑长视频生成。噪声过大同样会导致不一致。推荐值为 20，可以尝试更大的值，但建议不要超过 50。

base_num_frames (`int`，*可选*，默认值为 `97`)：97 或 121 | 基础帧数（**540P 为 97**，**720P 为 121**）

ar_step (`int`, *可选*，默认为 `0`)：控制异步推理（0 表示同步模式）。您可以设置 `ar_step=5` 以启用异步推理。在异步推理时，建议设置 `causal_block_size=5`，而在同步生成时不应设置该参数。异步推理需要更多步骤来扩散整个序列，这意味着它比同步模式更慢。在我们的实验中，异步推理可能会提升指令遵循和视觉一致性方面的表现。

causal_block_size (`int`，*可选*，默认为 `None`)：每个块/分块中的帧数。在使用异步推理（当 ar_step > 0）时建议使用。

fps (`int`，*可选*，默认为 `24`)：生成视频的帧率

**返回：** `~SkyReelsV2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `SkyReelsV2PipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成的 pipeline 的调用函数。

示例：
```py
>>> import torch
>>> from diffusers import (
...     SkyReelsV2DiffusionForcingVideoToVideoPipeline,
...     UniPCMultistepScheduler,
...     AutoencoderKLWan,
... )
>>> from diffusers.utils import export_to_video

>>> # Load the pipeline
>>> # Available models:
>>> # - Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-DF-14B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-DF-14B-720P-Diffusers
>>> vae = AutoencoderKLWan.from_pretrained(
...     "Skywork/SkyReels-V2-DF-14B-720P-Diffusers",
...     subfolder="vae",
...     torch_dtype=torch.float32,
... )
>>> pipe = SkyReelsV2DiffusionForcingVideoToVideoPipeline.from_pretrained(
...     "Skywork/SkyReels-V2-DF-14B-720P-Diffusers",
...     vae=vae,
...     torch_dtype=torch.bfloat16,
... )
>>> flow_shift = 8.0  # 8.0 for T2V, 5.0 for I2V
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe = pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."

>>> output = pipe(
...     prompt=prompt,
...     num_inference_steps=50,
...     height=544,
...     width=960,
...     guidance_scale=6.0,  # 6.0 for T2V, 5.0 for I2V
...     num_frames=97,
...     ar_step=0,  # Controls asynchronous inference (0 for synchronous mode)
...     overlap_history=None,  # Number of frames to overlap for smooth transitions in long videos
...     addnoise_condition=20,  # Improves consistency in long video generation
... ).frames[0]
>>> export_to_video(output, "video.mp4", fps=24, quality=8)
```

#### encode_prompt[[diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py#L280)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

#### generate_timestep_matrix[[diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline.generate_timestep_matrix]]

```python
generate_timestep_matrix(num_latent_frames: int, step_template: Tensor, base_num_latent_frames: int, ar_step: int = 5, num_pre_ready: int = 0, causal_block_size: int = 1, shrink_interval_with_mask: bool = False)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py#L504)

**参数：**

num_latent_frames (int) : 要生成的潜在帧总数

step_template (torch.Tensor) ：基础时间步调度（例如，[1000, 800, 600, ..., 0]）

base_num_latent_frames (int)：模型在单次前向传播中可处理的最大帧数

ar_step (int, optional) : 时间滞后自回归步长。0 = 同步，>0 = 异步。默认值为 5。

num_pre_ready (int, 可选) : 已去噪的帧数（例如，在 video2video 任务中来自前缀的帧数）。默认为 0。

causal_block_size (int, 可选) : 作为因果块处理的帧数。默认为 1。

shrink_interval_with_mask (bool, optional) : 是否优化处理间隔。默认为 False。

**返回：** `tuple containing`

- step_matrix (torch.Tensor): 每次迭代中每帧的时间步矩阵。形状：[num_iterations, num_latent_frames]
- step_index (torch.Tensor): 用于时间步查找的索引矩阵。形状: [num_iterations, num_latent_frames]
- step_update_mask (torch.Tensor): 布尔掩码，指示要更新哪些帧。形状：[num_iterations, num_latent_frames]
- valid_interval (list[tuple])：每次迭代的 (start, end) 区间列表

**引发：** ``ValueError``

- ``ValueError`` -- 如果 ar_step 对于给定的配置来说太小

该函数实现了核心的扩散强制（diffusion forcing）算法，用于在时间帧之间创建协调的去噪调度。它支持同步和异步两种生成模式：

**同步模式**（ar_step=0, causal_block_size=1）：
- 在每个时间步，所有帧同时去噪
- 每一帧都遵循相同的去噪轨迹：[1000, 800, 600, ..., 0]
- 更简单，但对于长视频可能具有较低的时间一致性

**异步模式**（ar_step>0，causal_block_size>1）：
- 帧被分组为因果块，并按块/分块进行处理
- 每个块以交错模式进行去噪，从而形成“去噪波”。
- 较早的块去噪程度更高，较晚的块则滞后 ar_step 个时间步
- 创建更强的时间依赖性和更好的一致性

## SkyReelsV2Pipeline[[diffusers.SkyReelsV2Pipeline]]

#### diffusers.SkyReelsV2Pipeline[[diffusers.SkyReelsV2Pipeline]]

```python
diffusers.SkyReelsV2Pipeline(tokenizer: AutoTokenizer, text_encoder: transformers.models.t5.modeling_t5.T5EncoderModel | transformers.models.umt5.modeling_umt5.UMT5EncoderModel, transformer: SkyReelsV2Transformer3DModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py#L107)

**参数：**

tokenizer (`T5Tokenizer`)：来自 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer) 的分词器，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

text_encoder (`T5EncoderModel`)：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

transformer ([SkyReelsV2Transformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/skyreels_v2_transformer_3d#diffusers.SkyReelsV2Transformer3DModel))：用于对输入潜变量进行去噪的条件 Transformer。

scheduler ([UniPCMultistepScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/unipc#diffusers.UniPCMultistepScheduler))：一种调度器，需与 `transformer` 配合使用，以对编码后的图像潜变量进行去噪。

vae ([AutoencoderKLWan](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

使用 SkyReels-V2 进行文本到视频（t2v）生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

#### __调用__[[diffusers.SkyReelsV2Pipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 544, width: int = 960, num_frames: int = 97, num_inference_steps: int = 50, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py#L377)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale < 1`）时将被忽略。

height (`int`，默认为 `544`)：生成图像的高度（以像素为单位）。

width (`int`，默认为 `960`)：生成图像的宽度（以像素为单位）。

num_frames (`int`，默认为 `97`)：生成视频的帧数。

num_inference_steps (`int`，默认为 `50`)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

guidance_scale (`float`，默认值为 `6.0`) : 如 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

latents (`torch.Tensor`, *可选*) : 从高斯分布中采样的预生成噪声潜变量，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，则使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，`negative_prompt_embeds` 将从 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"np"`)：生成图像的输出格式。在 `PIL.Image` 和 `np.array` 之间选择。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `SkyReelsV2PipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认值为 `512`)：文本编码器的最大序列长度。

**返回：** `~SkyReelsV2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `SkyReelsV2PipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成的 pipeline 的调用函数。

示例：
```py
>>> import torch
>>> from diffusers import (
...     SkyReelsV2Pipeline,
...     UniPCMultistepScheduler,
...     AutoencoderKLWan,
... )
>>> from diffusers.utils import export_to_video

>>> # Load the pipeline
>>> # Available models:
>>> # - Skywork/SkyReels-V2-T2V-14B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-T2V-14B-720P-Diffusers
>>> vae = AutoencoderKLWan.from_pretrained(
...     "Skywork/SkyReels-V2-T2V-14B-720P-Diffusers",
...     subfolder="vae",
...     torch_dtype=torch.float32,
... )
>>> pipe = SkyReelsV2Pipeline.from_pretrained(
...     "Skywork/SkyReels-V2-T2V-14B-720P-Diffusers",
...     vae=vae,
...     torch_dtype=torch.bfloat16,
... )
>>> flow_shift = 8.0  # 8.0 for T2V, 5.0 for I2V
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe = pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."

>>> output = pipe(
...     prompt=prompt,
...     num_inference_steps=50,
...     height=544,
...     width=960,
...     guidance_scale=6.0,  # 6.0 for T2V, 5.0 for I2V
...     num_frames=97,
... ).frames[0]
>>> export_to_video(output, "video.mp4", fps=24, quality=8)
```

#### encode_prompt[[diffusers.SkyReelsV2Pipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py#L198)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

## SkyReelsV2ImageToVideoPipeline[[diffusers.SkyReelsV2ImageToVideoPipeline]]

#### diffusers.SkyReelsV2ImageToVideoPipeline[[diffusers.SkyReelsV2ImageToVideoPipeline]]

```python
diffusers.SkyReelsV2ImageToVideoPipeline(tokenizer: AutoTokenizer, text_encoder: transformers.models.t5.modeling_t5.T5EncoderModel | transformers.models.umt5.modeling_umt5.UMT5EncoderModel, image_encoder: CLIPVisionModelWithProjection, image_processor: CLIPProcessor, transformer: SkyReelsV2Transformer3DModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py#L127)

**参数：**

tokenizer (`T5Tokenizer`)：来自 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer) 的分词器，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

text_encoder (`T5EncoderModel`)：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 变体。

image_encoder (`CLIPVisionModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModelWithProjection)，具体为 [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large) 变体。

transformer ([SkyReelsV2Transformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/skyreels_v2_transformer_3d#diffusers.SkyReelsV2Transformer3DModel))：用于对输入潜变量进行去噪的条件 Transformer。

scheduler ([UniPCMultistepScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/unipc#diffusers.UniPCMultistepScheduler))：一种调度器，需与 `transformer` 配合使用，以对编码后的图像潜变量进行去噪。

vae ([AutoencoderKLWan](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，以及从潜在表示解码为视频。

使用 SkyReels-V2 进行图像到视频（i2v）生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

#### __调用__[[diffusers.SkyReelsV2ImageToVideoPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 544, width: int = 960, num_frames: int = 97, num_inference_steps: int = 50, guidance_scale: float = 5.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, image_embeds: typing.Optional[torch.Tensor] = None, last_image: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py#L479)

**参数：**

image (`PipelineImageInput`)：用于条件生成的输入图像。必须是一张图像、一个图像列表或一个 `torch.Tensor`。

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

height (`int`，默认为 `544`)：生成视频的高度。

width (`int`，默认为 `960`)：生成视频的宽度。

num_frames (`int`，默认为 `97`)：生成视频的帧数。

num_inference_steps (`int`，默认为 `50`)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

guidance_scale (`float`，默认为 `5.0`) : 如 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，通常以牺牲图像质量为代价。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

latents (`torch.Tensor`, *可选*) : 从高斯分布中采样的预生成噪声潜变量，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，则使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `negative_prompt` 输入参数生成文本嵌入。

image_embeds (`torch.Tensor`, *可选*) : 预生成的图像嵌入。可用于轻松调整图像输入（加权）。如果未提供，则从 `image` 输入参数生成图像嵌入。

last_image (`torch.Tensor`, *可选*) : 用于图像到视频条件控制的可选最后一帧图像，用于锚定生成视频的结尾。

output_type (`str`，*可选*，默认为 `"np"`)：生成图像的输出格式。在 `PIL.Image` 和 `np.array` 之间选择。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `WanPipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认为 `512`)：提示词的最大序列长度。

**返回：** `~SkyReelsV2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `SkyReelsV2PipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成的 pipeline 的调用函数。

示例：
```py
>>> import torch
>>> from diffusers import (
...     SkyReelsV2ImageToVideoPipeline,
...     UniPCMultistepScheduler,
...     AutoencoderKLWan,
... )
>>> from diffusers.utils import export_to_video
>>> from PIL import Image

>>> # Load the pipeline
>>> # Available models:
>>> # - Skywork/SkyReels-V2-I2V-1.3B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-I2V-14B-540P-Diffusers
>>> # - Skywork/SkyReels-V2-I2V-14B-720P-Diffusers
>>> vae = AutoencoderKLWan.from_pretrained(
...     "Skywork/SkyReels-V2-I2V-14B-720P-Diffusers",
...     subfolder="vae",
...     torch_dtype=torch.float32,
... )
>>> pipe = SkyReelsV2ImageToVideoPipeline.from_pretrained(
...     "Skywork/SkyReels-V2-I2V-14B-720P-Diffusers",
...     vae=vae,
...     torch_dtype=torch.bfloat16,
... )
>>> flow_shift = 5.0  # 8.0 for T2V, 5.0 for I2V
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe = pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
>>> image = Image.open("path/to/image.png")

>>> output = pipe(
...     image=image,
...     prompt=prompt,
...     num_inference_steps=50,
...     height=544,
...     width=960,
...     guidance_scale=5.0,  # 6.0 for T2V, 5.0 for I2V
...     num_frames=97,
... ).frames[0]
>>> export_to_video(output, "video.mp4", fps=24, quality=8)
```

#### encode_prompt[[diffusers.SkyReelsV2ImageToVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py#L241)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

## SkyReelsV2PipelineOutput[[diffusers.pipelines.skyreels_v2.pipeline_output.SkyReelsV2PipelineOutput]]

#### diffusers.pipelines.skyreels_v2.pipeline_output.SkyReelsV2PipelineOutput[[diffusers.pipelines.skyreels_v2.pipeline_output.SkyReelsV2PipelineOutput]]

```python
diffusers.pipelines.skyreels_v2.pipeline_output.SkyReelsV2PipelineOutput(frames: Tensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/skyreels_v2/pipeline_output.py#L9)

**参数：**

frames (`torch.Tensor`、`np.ndarray` 或 list[list[PIL.Image.Image]]) : 视频输出列表 - 它可以是一个长度为 `batch_size,` 的嵌套列表，其中每个子列表包含长度为 `num_frames.` 的去噪 PIL 图像序列。它也可以是一个形状为 `(batch_size, num_frames, channels, height, width)` 的 NumPy 数组或 Torch 张量。

SkyReelsV2 流水线的输出类。

