# Kandinsky 5.0 视频

[Kandinsky 5.0](https://arxiv.org/abs/2511.14993) 是一个用于视频和图像生成的扩散模型系列。

Kandinsky 5.0 Lite 系列轻量级视频生成模型（2B 参数），在同类开源模型中排名第一。其性能优于更大的模型，并且在开源生态系统中对俄语概念的理解能力最佳。

Kandinsky 5.0 Pro 系列包含大型高质量视频生成模型（19B 参数）。它支持 HD 高质量生成，并提供诸如 I2V 等更多生成格式。

该模型引入了几项关键创新：
- 采用 **Flow Matching** 的 **Latent diffusion pipeline**，以提升训练稳定性
- 以 **Diffusion Transformer (DiT)** 作为主要生成骨干网络，并通过交叉注意力机制与文本嵌入进行交互
- 使用 **Qwen2.5-VL** 和 **CLIP** 进行双重文本编码，以实现全面的文本理解
- 用于高效视频编码和解码的 **HunyuanVideo 3D VAE**
- 用于高效长序列处理的**稀疏注意力机制**（NABLA）

原始代码库可在 [kandinskylab/Kandinsky-5](https://github.com/kandinskylab/Kandinsky-5) 中找到。

> [!TIP]
> 在 Hub 上查看 [Kandinsky Lab](https://huggingface.co/kandinskylab) 组织，以获取用于文本到视频生成的官方模型检查点，包括预训练、SFT、无 CFG 和蒸馏变体。

## 可用模型

Kandinsky 5.0 T2V Pro：

| model_id | 描述 | 用例 |
|------------|-------------|-----------|
| **kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s-Diffusers** | 5 秒 Text-to-Video Pro 模型 | 高质量的文本到视频生成 |
| **kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s-Diffusers** | 5 秒 Image-to-Video Pro 模型 | 高质量图像到视频生成 |

Kandinsky 5.0 T2V Lite：
| model_id | 描述 | 用例 |
|------------|-------------|-----------|
| **kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers** | 5 秒监督微调模型 | 最高的生成质量 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-sft-10s-Diffusers** | 10 秒监督微调模型 | 最高的生成质量 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-5s-Diffusers** | 5 秒的 Classifier-Free Guidance 蒸馏 | 推理速度提升 2 倍 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-10s-Diffusers** | 10 秒的 Classifier-Free Guidance 蒸馏 | 推理速度提升 2 倍 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-5s-Diffusers** | 5 秒 Diffusion 蒸馏至 16 步 | 推理速度提升 6 倍，质量损失极小 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-10s-Diffusers** | 10 秒 Diffusion 蒸馏至 16 步 | 推理速度提升 6 倍，质量损失极小 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-5s-Diffusers** | 5 秒 Base 预训练模型 | 研究与微调 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-10s-Diffusers** | 10 秒 Base 预训练模型 | 研究与微调 |

## 使用示例

### 基础文本到视频生成

#### Pro
**⚠️ 警告！**所有 Pro 模型都应使用 pipeline.enable_model_cpu_offload() 进行推理
```python
import torch
from diffusers import Kandinsky5T2VPipeline
from diffusers.utils import export_to_video

# Load the pipeline
model_id = "kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s-Diffusers"
pipe = Kandinsky5T2VPipeline.from_pretrained(model_id, dtype=torch.bfloat16)

pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"
pipeline.transformer.set_attention_backend("flex")                            # <--- Set attention backend to Flex
pipeline.enable_model_cpu_offload()                                           # <--- Enable cpu offloading for single GPU inference
pipeline.transformer.compile(mode="max-autotune-no-cudagraphs", dynamic=True) # <--- Compile with max-autotune-no-cudagraphs

# Generate video
prompt = "A cat and a dog baking a cake together in a kitchen."
negative_prompt = "Static, 2D cartoon, cartoon, 2d animation, paintings, images, worst quality, low quality, ugly, deformed, walking backwards"

output = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    height=768,
    width=1024,
    num_frames=121,  # ~5 seconds at 24fps
    num_inference_steps=50,
    guidance_scale=5.0,
).frames[0]

export_to_video(output, "output.mp4", fps=24, quality=9)
```

#### Lite
```python
import torch
from diffusers import Kandinsky5T2VPipeline
from diffusers.utils import export_to_video

# Load the pipeline
model_id = "kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers"
pipe = Kandinsky5T2VPipeline.from_pretrained(model_id, dtype=torch.bfloat16)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Generate video
prompt = "A cat and a dog baking a cake together in a kitchen."
negative_prompt = "Static, 2D cartoon, cartoon, 2d animation, paintings, images, worst quality, low quality, ugly, deformed, walking backwards"

output = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    height=512,
    width=768,
    num_frames=121,  # ~5 seconds at 24fps
    num_inference_steps=50,
    guidance_scale=5.0,
).frames[0]

export_to_video(output, "output.mp4", fps=24, quality=9)
```

### 10 秒模型
**⚠️ 警告！**所有 10 秒模型都应配合 Flex attention 和 max-autotune-no-cudagraphs 编译使用：

```python
pipe = Kandinsky5T2VPipeline.from_pretrained(
    "kandinskylab/Kandinsky-5.0-T2V-Lite-sft-10s-Diffusers", 
    dtype=torch.bfloat16
)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

pipe.transformer.set_attention_backend(
    "flex"
)                                       # <--- Set attention backend to Flex
pipe.transformer.compile(
    mode="max-autotune-no-cudagraphs", 
    dynamic=True
)                                       # <--- Compile with max-autotune-no-cudagraphs

prompt = "A cat and a dog baking a cake together in a kitchen."
negative_prompt = "Static, 2D cartoon, cartoon, 2d animation, paintings, images, worst quality, low quality, ugly, deformed, walking backwards"

output = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    height=512,
    width=768,
    num_frames=241,
    num_inference_steps=50,
    guidance_scale=5.0,
).frames[0]

export_to_video(output, "output.mp4", fps=24, quality=9)
```

### Diffusion Distilled 模型
**⚠️ 警告！**所有 nocfg 和 diffusion distilled 模型都应使用无 CFG 的方式进行推理（```guidance_scale=1.0```）：

```python
model_id = "kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-5s-Diffusers"
pipe = Kandinsky5T2VPipeline.from_pretrained(model_id, dtype=torch.bfloat16)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

output = pipe(
    prompt="A beautiful sunset over mountains",
    num_inference_steps=16,  # <--- Model is distilled in 16 steps
    guidance_scale=1.0,      # <--- no CFG
).frames[0]

export_to_video(output, "output.mp4", fps=24, quality=9)
```

### 基础图像到视频生成
**⚠️ 警告！**所有 Pro 模型都应使用 pipeline.enable_model_cpu_offload() 进行推理
```python
import torch
from diffusers import Kandinsky5T2VPipeline
from diffusers.utils import export_to_video

# Load the pipeline
model_id = "kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s-Diffusers"
pipe = Kandinsky5T2VPipeline.from_pretrained(model_id, dtype=torch.bfloat16)

pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"
pipeline.transformer.set_attention_backend("flex")                            # <--- Set attention backend to Flex
pipeline.enable_model_cpu_offload()                                           # <--- Enable cpu offloading for single GPU inference
pipeline.transformer.compile(mode="max-autotune-no-cudagraphs", dynamic=True) # <--- Compile with max-autotune-no-cudagraphs

# Generate video
image = load_image(
    "https://huggingface.co/kandinsky-community/kandinsky-3/resolve/main/assets/title.jpg?download=true"
)
height = 896
width = 896
image = image.resize((width, height))

prompt = "An funny furry creture smiles happily and holds a sign that says 'Kandinsky'"
negative_prompt = ""

output = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    height=height,
    width=width,
    num_frames=121,  # ~5 seconds at 24fps
    num_inference_steps=50,
    guidance_scale=5.0,
).frames[0]

export_to_video(output, "output.mp4", fps=24, quality=9)
```

## Kandinsky 5.0 Pro 并排评估

  
      
          
      
      
         
      

  
      
          与 Veo 3 的对比
      
      
          与 Veo 3 fast 的对比
      
  
      
          
      
      
          
      
  
      
          与 Wan 2.2 A14B 文本到视频模式的比较
      
      
          与 Wan 2.2 A14B 图生视频模式的对比
      

## Kandinsky 5.0 Lite 并排评估

评估基于 [Movie Gen benchmark](https://github.com/facebookresearch/MovieGenBench) 中扩展后的提示词，这些提示词位于 benchmark/moviegen_bench.csv 文件的 expanded_prompt 列中。

  
      
          
      
      
          
      
  
      
          
      
      
          
      
  
      
          
      

## Kandinsky 5.0 Lite Distill 并排评估

  
      
          
      
      
          
      

## Kandinsky5T2VPipeline[[diffusers.Kandinsky5T2VPipeline]]

#### diffusers.Kandinsky5T2VPipeline[[diffusers.Kandinsky5T2VPipeline]]

```python
diffusers.Kandinsky5T2VPipeline(transformer: Kandinsky5Transformer3DModel, vae: AutoencoderKLHunyuanVideo, text_encoder: Qwen2_5_VLForConditionalGeneration, tokenizer: Qwen2VLProcessor, text_encoder_2: CLIPTextModel, tokenizer_2: CLIPTokenizer, scheduler: FlowMatchEulerDiscreteScheduler)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L131)

**参数：**

transformer (`Kandinsky5Transformer3DModel`)：用于对编码后的视频潜在变量进行去噪的条件 Transformer。

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo))：变分自编码器模型，用于将 [hunyuanvideo-community/HunyuanVideo (vae)](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) 的视频编码为潜在表示，并从潜在表示解码回视频。

text_encoder (`Qwen2_5_VLForConditionalGeneration`)：冻结的文本编码器 [Qwen2.5-VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct)。

tokenizer (`AutoProcessor`)：Qwen2.5-VL 的 Tokenizer。

text_encoder_2 (`CLIPTextModel`)：冻结的 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

tokenizer_2 (`CLIPTokenizer`)：CLIP 的 Tokenizer。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的视频潜变量进行去噪的调度器。

使用 Kandinsky 5.0 进行文本到视频生成的 Pipeline。

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

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 512, width: int = 768, num_frames: int = 121, 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_qwen: typing.Optional[torch.Tensor] = None, prompt_embeds_clip: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_qwen: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_clip: typing.Optional[torch.Tensor] = None, prompt_cu_seqlens: typing.Optional[torch.Tensor] = None, negative_prompt_cu_seqlens: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, 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/kandinsky5/pipeline_kandinsky.py#L680)

**参数：**

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

negative_prompt (`str` 或 `list[str]`，*可选*)：视频生成过程中需要避免的提示词。如果未定义，请改为传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale` < `1`）时将被忽略。

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

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

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

num_inference_steps (`int`，默认为 `50`)：去噪步数。

guidance_scale (`float`，默认为 `5.0`) : 无分类器引导中定义的引导比例。

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

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 torch 生成器。

latents (`torch.Tensor`，*可选*)：预生成的带噪潜在变量。

prompt_embeds_qwen (`torch.Tensor`, *可选*) : 由 Qwen 文本编码器预生成的文本嵌入。

prompt_embeds_clip (`torch.Tensor`, *可选*) : 由 CLIP 文本编码器预生成的文本嵌入。

negative_prompt_embeds_qwen (`torch.Tensor`, *可选*) : 由 Qwen 文本编码器预生成的负样本文本嵌入。

negative_prompt_embeds_clip (`torch.Tensor`, *可选*) : 由 CLIP 文本编码器预生成的负样本文本嵌入。

prompt_cu_seqlens (`torch.Tensor`, *可选*) : Qwen 提示嵌入的累积序列长度，用于变长注意力。

negative_prompt_cu_seqlens (`torch.Tensor`, *可选*) : Qwen 负提示嵌入的累积序列长度，用于变长注意力。

output_type (`str`，*可选*，默认为 `"pil"`)：生成视频的输出格式。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `KandinskyPipelineOutput`。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：在每个去噪步骤结束时调用的函数。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。

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

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

如果 `return_dict` 为 `True`，则返回 `KandinskyPipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表。

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

示例：

```python
>>> import torch
>>> from diffusers import Kandinsky5T2VPipeline
>>> from diffusers.utils import export_to_video

>>> # Available models:
>>> # kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-5s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-5s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-5s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-sft-10s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-10s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-10s-Diffusers
>>> # kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-10s-Diffusers

>>> model_id = "kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers"
>>> pipe = Kandinsky5T2VPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe = pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen."
>>> negative_prompt = "Static, 2D cartoon, cartoon, 2d animation, paintings, images, worst quality, low quality, ugly, deformed, walking backwards"

>>> output = pipe(
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     height=512,
...     width=768,
...     num_frames=121,
...     num_inference_steps=50,
...     guidance_scale=5.0,
... ).frames[0]

>>> export_to_video(output, "output.mp4", fps=24, quality=9)
```

#### check_inputs[[diffusers.Kandinsky5T2VPipeline.check_inputs]]

```python
check_inputs(prompt, negative_prompt, height, width, prompt_embeds_qwen = None, prompt_embeds_clip = None, negative_prompt_embeds_qwen = None, negative_prompt_embeds_clip = None, prompt_cu_seqlens = None, negative_prompt_cu_seqlens = None, callback_on_step_end_tensor_inputs = None, max_sequence_length = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L511)

**参数：**

prompt : 输入提示

negative_prompt : 用于引导的负面提示

height : 视频高度

width : 视频宽度

prompt_embeds_qwen : 预计算的 Qwen 提示嵌入

prompt_embeds_clip : 预计算的 CLIP 提示嵌入

negative_prompt_embeds_qwen : 预计算的 Qwen 负面提示嵌入

negative_prompt_embeds_clip : 预计算的 CLIP 负提示嵌入

prompt_cu_seqlens : Qwen 正向提示的预计算累积序列长度

negative_prompt_cu_seqlens : Qwen 负面提示的预计算累积序列长度

callback_on_step_end_tensor_inputs : 回调张量输入

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

- ``ValueError`` -- 如果输入无效

验证 pipeline 的输入参数。

#### encode_prompt[[diffusers.Kandinsky5T2VPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_videos_per_prompt: int = 1, max_sequence_length: int = 512, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

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

**参数：**

prompt (`str` 或 `list[str]`) : 要编码的提示词。

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

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

device (`torch.device`，*可选*)：Torch 设备。

dtype (`torch.dtype`，*可选*)：Torch 数据类型。

**返回：** tuple[torch.Tensor, torch.Tensor, torch.Tensor]

- 形状为 (batch_size * num_videos_per_prompt, sequence_length, embedding_dim) 的 Qwen 文本嵌入
- 形状为 (batch_size * num_videos_per_prompt, clip_embedding_dim) 的 CLIP 池化嵌入
- Qwen 嵌入的累积序列长度（`cu_seqlens`），形状为 (batch_size * num_videos_per_prompt + 1,)

将单个提示（正向或负向）编码为文本编码器的隐藏状态。

该方法结合了 Qwen2.5-VL 和 CLIP 文本编码器的嵌入，以创建用于视频生成的全面文本表示。

#### fast_sta_nabla[[diffusers.Kandinsky5T2VPipeline.fast_sta_nabla]]

```python
fast_sta_nabla(T: int, H: int, W: int, wT: int = 3, wH: int = 3, wW: int = 3, device = 'cuda')
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L229)

**参数：**

T (int)：时间帧的数量

H (int)：潜在空间中的高度

W (int)：潜在空间中的宽度

wT (int)：时间注意力窗口大小

wH (int)：高度注意力窗口大小

wW (int)：宽度注意力窗口大小

device (str) : 创建张量所在的设备

**返回：** `torch.Tensor`

形状为 (T*H*W, T*H*W) 的稀疏注意力掩码

创建稀疏时间注意力（STA）掩码，以实现高效的视频生成。

此方法生成一个掩码，将注意力限制在邻近的帧和空间位置上，从而降低视频生成的计算复杂度。

#### get_sparse_params[[diffusers.Kandinsky5T2VPipeline.get_sparse_params]]

```python
get_sparse_params(sample, device)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L264)

**参数：**

sample (torch.Tensor) ：输入样本张量

device (torch.device)：用于放置张量的设备

**返回：** `Dict`

包含稀疏注意力参数的字典

根据样本维度为 Transformer 生成稀疏注意力参数。

此方法计算 Transformer 模型中高效视频处理所需的稀疏注意力配置。

#### prepare_latents[[diffusers.Kandinsky5T2VPipeline.prepare_latents]]

```python
prepare_latents(batch_size: int, num_channels_latents: int = 16, height: int = 480, width: int = 832, num_frames: int = 81, dtype: typing.Optional[torch.dtype] = None, device: typing.Optional[torch.device] = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L597)

**参数：**

batch_size (int)：要生成的视频数量

num_channels_latents (int)：潜在空间中的通道数

height (int)：生成视频的高度

width (int)：生成视频的宽度

num_frames (int)：视频中的帧数

dtype (torch.dtype) ：潜变量的数据类型

device (torch.device)：用于创建潜在向量的设备

generator (torch.Generator)：随机数生成器

latents (torch.Tensor)：要使用的现有潜在变量

**返回：** `torch.Tensor`

准备好的潜在张量

为视频生成准备初始潜在变量。

此方法会创建随机噪声潜变量，或使用提供的潜变量作为去噪过程的起点。

## Kandinsky5I2VPipeline[[diffusers.Kandinsky5I2VPipeline]]

#### diffusers.Kandinsky5I2VPipeline[[diffusers.Kandinsky5I2VPipeline]]

```python
diffusers.Kandinsky5I2VPipeline(transformer: Kandinsky5Transformer3DModel, vae: AutoencoderKLHunyuanVideo, text_encoder: Qwen2_5_VLForConditionalGeneration, tokenizer: Qwen2VLProcessor, text_encoder_2: CLIPTextModel, tokenizer_2: CLIPTokenizer, scheduler: FlowMatchEulerDiscreteScheduler)
```

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

**参数：**

transformer (`Kandinsky5Transformer3DModel`)：用于对编码后的视频潜在变量进行去噪的条件 Transformer。

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo))：变分自编码器模型，用于将 [hunyuanvideo-community/HunyuanVideo (vae)](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) 的视频编码为潜在表示，并从潜在表示解码回视频。

text_encoder (`Qwen2_5_VLForConditionalGeneration`)：冻结的文本编码器 [Qwen2.5-VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct)。

tokenizer (`AutoProcessor`)：Qwen2.5-VL 的 Tokenizer。

text_encoder_2 (`CLIPTextModel`)：冻结的 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

tokenizer_2 (`CLIPTokenizer`)：CLIP 的 Tokenizer。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的视频潜变量进行去噪的调度器。

使用 Kandinsky 5.0 进行图像到视频生成的 Pipeline。

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

#### __调用__[[diffusers.Kandinsky5I2VPipeline.__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 = None, height: int = 512, width: int = 768, num_frames: int = 121, 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_qwen: typing.Optional[torch.Tensor] = None, prompt_embeds_clip: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_qwen: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_clip: typing.Optional[torch.Tensor] = None, prompt_cu_seqlens: typing.Optional[torch.Tensor] = None, negative_prompt_cu_seqlens: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int, NoneType], diffusers.callbacks.PipelineCallback | diffusers.callbacks.MultiPipelineCallbacks]] = 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/kandinsky5/pipeline_kandinsky_i2v.py#L748)

**参数：**

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

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

negative_prompt (`str` 或 `list[str]`，*可选*)：视频生成过程中需要避免的提示词。如果未定义，请改为传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale` < `1`）时将被忽略。

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

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

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

num_inference_steps (`int`，默认为 `50`)：去噪步数。

guidance_scale (`float`，默认为 `5.0`) : 无分类器引导中定义的引导比例。

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

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 torch 生成器。

latents (`torch.Tensor`，*可选*)：预生成的带噪潜在变量。

prompt_embeds_qwen (`torch.Tensor`, *可选*) : 预生成的 Qwen 文本嵌入。

prompt_embeds_clip (`torch.Tensor`, *可选*) : 预生成的 CLIP 文本嵌入。

negative_prompt_embeds_qwen (`torch.Tensor`, *可选*) : 预生成的 Qwen 负文本嵌入。

negative_prompt_embeds_clip (`torch.Tensor`, *可选*) : 预生成的 CLIP 负文本嵌入。

prompt_cu_seqlens (`torch.Tensor`, *可选*) : 为 Qwen 正向提示词预生成的累积序列长度。

negative_prompt_cu_seqlens (`torch.Tensor`, *可选*) : 为 Qwen 负面提示词预生成的累积序列长度。

output_type (`str`，*可选*，默认为 `"pil"`)：生成视频的输出格式。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `KandinskyPipelineOutput`。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：在每个去噪步骤结束时调用的函数。

callback_on_step_end_tensor_inputs (`List`，*可选*)：`callback_on_step_end` 函数的张量输入列表。

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

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

如果 `return_dict` 为 `True`，则返回 `KandinskyPipelineOutput`；否则返回一个 `tuple`，其中第一个元素是包含生成视频的列表。

用于图像到视频生成的 pipeline 的调用函数。

示例：

```python
>>> import torch
>>> from diffusers import Kandinsky5I2VPipeline
>>> from diffusers.utils import export_to_video, load_image

>>> # Available models:
>>> # kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s-Diffusers

>>> model_id = "kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s-Diffusers"
>>> pipe = Kandinsky5I2VPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe = pipe.to("cuda")

>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
... )
>>> prompt = "An astronaut floating in space with Earth in the background, cinematic shot"
>>> negative_prompt = "Static, 2D cartoon, cartoon, 2d animation, paintings, images, worst quality, low quality, ugly, deformed, walking backwards"

>>> output = pipe(
...     image=image,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     height=512,
...     width=768,
...     num_frames=121,
...     num_inference_steps=50,
...     guidance_scale=5.0,
... ).frames[0]

>>> export_to_video(output, "output.mp4", fps=24, quality=9)
```

#### check_inputs[[diffusers.Kandinsky5I2VPipeline.check_inputs]]

```python
check_inputs(prompt, negative_prompt, image, height, width, prompt_embeds_qwen = None, prompt_embeds_clip = None, negative_prompt_embeds_qwen = None, negative_prompt_embeds_clip = None, prompt_cu_seqlens = None, negative_prompt_cu_seqlens = None, callback_on_step_end_tensor_inputs = None, max_sequence_length = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L545)

**参数：**

prompt : 输入提示

negative_prompt : 用于引导的负面提示

image : 用于条件控制的输入图像

height : 视频高度

width : 视频宽度

prompt_embeds_qwen : 预计算的 Qwen 提示嵌入

prompt_embeds_clip : 预计算的 CLIP 提示嵌入

negative_prompt_embeds_qwen : 预计算的 Qwen 负面提示嵌入

negative_prompt_embeds_clip : 预计算的 CLIP 负提示嵌入

prompt_cu_seqlens : Qwen 正向提示的预计算累积序列长度

negative_prompt_cu_seqlens : Qwen 负面提示的预计算累积序列长度

callback_on_step_end_tensor_inputs : 回调张量输入

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

- ``ValueError`` -- 如果输入无效

验证 pipeline 的输入参数。

#### encode_prompt[[diffusers.Kandinsky5I2VPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_videos_per_prompt: int = 1, max_sequence_length: int = 512, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L454)

**参数：**

prompt (`str` 或 `list[str]`) : 要编码的提示词。

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

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

device (`torch.device`，*可选*)：Torch 设备。

dtype (`torch.dtype`，*可选*)：Torch 数据类型。

**返回：** tuple[torch.Tensor, torch.Tensor, torch.Tensor]

- 形状为 (batch_size * num_videos_per_prompt, sequence_length, embedding_dim) 的 Qwen 文本嵌入
- 形状为 (batch_size * num_videos_per_prompt, clip_embedding_dim) 的 CLIP 池化嵌入
- Qwen 嵌入的累积序列长度（`cu_seqlens`），形状为 (batch_size * num_videos_per_prompt + 1,)

将单个提示（正向或负向）编码为文本编码器的隐藏状态。

该方法结合了 Qwen2.5-VL 和 CLIP 文本编码器的嵌入，以创建用于视频生成的全面文本表示。

#### fast_sta_nabla[[diffusers.Kandinsky5I2VPipeline.fast_sta_nabla]]

```python
fast_sta_nabla(T: int, H: int, W: int, wT: int = 3, wH: int = 3, wW: int = 3, device = 'cuda')
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L226)

**参数：**

T (int)：时间帧的数量

H (int)：潜在空间中的高度

W (int)：潜在空间中的宽度

wT (int)：时间注意力窗口大小

wH (int)：高度注意力窗口大小

wW (int)：宽度注意力窗口大小

device (str) : 创建张量所在的设备

**返回：** `torch.Tensor`

形状为 (T*H*W, T*H*W) 的稀疏注意力掩码

创建稀疏时间注意力（STA）掩码，以实现高效的视频生成。

此方法生成一个掩码，将注意力限制在邻近的帧和空间位置上，从而降低视频生成的计算复杂度。

#### get_sparse_params[[diffusers.Kandinsky5I2VPipeline.get_sparse_params]]

```python
get_sparse_params(sample, device)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L261)

**参数：**

sample (torch.Tensor) ：输入样本张量

device (torch.device)：用于放置张量的设备

**返回：** `Dict`

包含稀疏注意力参数的字典

根据样本维度为 Transformer 生成稀疏注意力参数。

此方法计算 Transformer 模型中高效视频处理所需的稀疏注意力配置。

#### prepare_latents[[diffusers.Kandinsky5I2VPipeline.prepare_latents]]

```python
prepare_latents(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], batch_size: int, num_channels_latents: int = 16, height: int = 480, width: int = 832, num_frames: int = 81, dtype: typing.Optional[torch.dtype] = None, device: typing.Optional[torch.device] = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L636)

**参数：**

image (PipelineImageInput)：用于条件生成的输入图像

batch_size (int)：要生成的视频数量

num_channels_latents (int)：潜在空间中的通道数

height (int)：生成视频的高度

width (int)：生成视频的宽度

num_frames (int)：视频中的帧数

dtype (torch.dtype) ：潜变量的数据类型

device (torch.device)：用于创建潜在向量的设备

generator (torch.Generator)：随机数生成器

latents (torch.Tensor)：要使用的现有潜在变量

**返回：** `torch.Tensor`

以编码图像作为第一帧的预准备潜在张量

为图像到视频生成准备初始潜在变量。

此方法为除第一帧之外的所有帧创建随机噪声潜变量，第一帧则被替换为编码后的输入图像。

## 引用
```bibtex
@misc{kandinsky2025,
    author = {Alexander Belykh and Alexander Varlamov and Alexey Letunovskiy and Anastasia Aliaskina and Anastasia Maltseva and Anastasiia Kargapoltseva and Andrey Shutkin and Anna Averchenkova and Anna Dmitrienko and Bulat Akhmatov and Denis Dimitrov and Denis Koposov and Denis Parkhomenko and Dmitrii and Ilya Vasiliev and Ivan Kirillov and Julia Agafonova and Kirill Chernyshev and Kormilitsyn Semen and Lev Novitskiy and Maria Kovaleva and Mikhail Mamaev and Mikhailov and Nikita Kiselev and Nikita Osterov and Nikolai Gerasimenko and Nikolai Vaulin and Olga Kim and Olga Vdovchenko and Polina Gavrilova and Polina Mikhailova and Tatiana Nikulina and Viacheslav Vasilev and Vladimir Arkhipkin and Vladimir Korviakov and Vladimir Polovnikov and Yury Kolabushin},
    title = {Kandinsky 5.0: A family of diffusion models for Video & Image generation},
    howpublished = {\url{https://github.com/kandinskylab/Kandinsky-5}},
    year = 2025
}
```

