# Kandinsky 5.0 Video

[Kandinsky 5.0](https://arxiv.org/abs/2511.14993)は、動画および画像の生成のための拡散モデルのファミリーです。

Kandinsky 5.0 Lite は、2B パラメータの軽量な動画生成モデルのラインナップです。オープンソースモデルの中で同クラスで 1 位にランクインしています。より大規模なモデルを上回る性能を発揮し、オープンソースエコシステムの中でロシア語の概念に対する理解度が最も優れています。

Kandinsky 5.0 Proは、大規模で高品質な動画生成モデル（19Bパラメータ）のラインナップです。HDでの高品質な生成や、I2Vなどより多くの生成フォーマットに対応しています。

このモデルには、いくつかの重要な革新が導入されています。
- **潜在拡散パイプライン**と**Flow Matching**による訓練安定性の向上
- **Diffusion Transformer (DiT)**を主要な生成バックボーンとし、テキスト埋め込みへのクロスアテンションを使用
- **Qwen2.5-VL**と**CLIP**を用いたデュアルテキストエンコーディングによる包括的なテキスト理解
- 効率的な動画エンコードおよびデコードのための**HunyuanVideo 3D VAE**
- **スパースアテンション機構**（NABLA）による効率的な長シーケンス処理

元のコードベースは[kandinskylab/Kandinsky-5](https://github.com/kandinskylab/Kandinsky-5)で確認できます。

> [!TIP]
> テキストから動画への変換用の公式モデルチェックポイント（事前学習済み、SFT、no-CFG、蒸留済みバリアントを含む）については、Hub上の[Kandinsky Lab](https://huggingface.co/kandinskylab)組織を確認してください。

## 利用可能なモデル

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秒で学習したSupervised Fine-Tunedモデル | 最高品質の生成 |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-sft-10s-Diffusers** | 10秒で学習したSupervised Fine-Tunedモデル | 最高品質の生成 |
| **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 ベンチマーク](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/ja/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo)) : [hunyuanvideo-community/HunyuanVideo (vae)](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) の Variational Auto-Encoder モデル。動画を潜在表現にエンコードし、潜在表現からデコードするために使用します。

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/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`と組み合わせて、エンコードされた動画の潜在変数（latents）のノイズ除去に使用するスケジューラー。

Kandinsky 5.0 を使用したテキストから動画への生成を行う Pipeline。

このモデルは [DiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。すべてのパイプラインに実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

#### __call__[[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 を使用していない場合（`guidance_scale` < `1`）は無視されます。

height (`int`、デフォルトは`512`) : 生成される動画のピクセル単位の縦幅。

width (`int`、デフォルトは`768`) : 生成される動画の幅（ピクセル単位）。

num_frames (`int`、デフォルトは`25`) : 生成される動画のフレーム数です。

num_inference_steps (`int`、デフォルトは`50`) : デノイジングのステップ数。

guidance_scale (`float`、デフォルトは`5.0`) : classifier-free guidance で定義されるガイダンススケール。

num_videos_per_prompt (`int`、*optional*、デフォルトは 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`` -- 入力が無効な場合

パイプラインの入力パラメータを検証します。

#### 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`、*optional*、デフォルトは 1) : プロンプトごとに生成する動画の数。

max_sequence_length (`int`、*optional*、デフォルトは 512) : テキストエンコーディングの最大シーケンス長。

device (`torch.device`、*任意*) : Torch デバイス。

dtype (`torch.dtype`、*任意*) : Torch の dtype。

**戻り値:** 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/ja/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo)) : [hunyuanvideo-community/HunyuanVideo (vae)](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) の Variational Auto-Encoder モデル。動画を潜在表現にエンコードし、潜在表現からデコードするために使用します。

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/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`と組み合わせて、エンコードされた動画の潜在変数（latents）のノイズ除去に使用するスケジューラー。

Kandinsky 5.0 を使用した画像から動画への生成を行う Pipeline。

このモデルは [DiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。すべてのパイプラインに実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

#### __call__[[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 を使用していない場合（`guidance_scale` < `1`）は無視されます。

height (`int`、デフォルトは`512`) : 生成される動画のピクセル単位の縦幅。

width (`int`、デフォルトは`768`) : 生成される動画の幅（ピクセル単位）。

num_frames (`int`、デフォルトは`121`) : 生成される動画のフレーム数。

num_inference_steps (`int`、デフォルトは`50`) : デノイジングのステップ数。

guidance_scale (`float`、デフォルトは`5.0`) : classifier-free guidance で定義されるガイダンススケール。

num_videos_per_prompt (`int`、*optional*、デフォルトは 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`` -- 入力が無効な場合

パイプラインの入力パラメータを検証します。

#### 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`、*optional*、デフォルトは 1) : プロンプトごとに生成する動画の数。

max_sequence_length (`int`、*optional*、デフォルトは 512) : テキストエンコーディングの最大シーケンス長。

device (`torch.device`、*任意*) : Torch デバイス。

dtype (`torch.dtype`、*任意*) : Torch の dtype。

**戻り値:** 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
}
```

