# Kandinsky 5.0 Video

[Kandinsky 5.0](https://arxiv.org/abs/2511.14993) là một họ mô hình khuếch tán cho việc tạo Video & Ảnh.

Danh mục các mô hình tạo video nhẹ (2B tham số) của Kandinsky 5.0 Lite, xếp hạng #1 trong số các mô hình mã nguồn mở cùng phân khúc. Nó vượt trội hơn các mô hình lớn hơn và cung cấp khả năng hiểu các khái niệm tiếng Nga tốt nhất trong hệ sinh thái mã nguồn mở.

Dòng mô hình tạo video chất lượng cao cỡ lớn (19B tham số) của Kandinsky 5.0 Pro. Nó cung cấp khả năng tạo video chất lượng cao ở độ phân giải HD và nhiều định dạng tạo hơn như I2V.

Mô hình giới thiệu một số đổi mới chính:
- **Pipeline khuếch tán tiềm ẩn** với **Flow Matching** để cải thiện độ ổn định huấn luyện
- **Diffusion Transformer (DiT)** làm khung xương sinh chính với cross-attention đến text embeddings
- Mã hóa văn bản kép sử dụng **Qwen2.5-VL** và **CLIP** để hiểu văn bản toàn diện
- **HunyuanVideo 3D VAE** cho việc mã hóa và giải mã video hiệu quả
- **Cơ chế chú ý thưa** (NABLA) để xử lý chuỗi dài hiệu quả

Mã nguồn gốc có thể được tìm thấy tại [kandinskylab/Kandinsky-5](https://github.com/kandinskylab/Kandinsky-5).

> [!TIP]
> Xem tổ chức [Kandinsky Lab](https://huggingface.co/kandinskylab) trên Hub để tìm các checkpoint mô hình chính thức cho việc tạo video từ văn bản, bao gồm các biến thể được huấn luyện trước, SFT, no-CFG và distilled.

## Các Mô hình Có sẵn

Kandinsky 5.0 T2V Pro:

| model_id | Mô tả | Các trường hợp sử dụng |
|------------|-------------|-----------|
| **kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s-Diffusers** | Mô hình Text-to-Video Pro 5 giây | Tạo video từ văn bản chất lượng cao |
| **kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s-Diffusers** | Mô hình Image-to-Video Pro 5 giây | Tạo video từ hình ảnh chất lượng cao |

Kandinsky 5.0 T2V Lite:
| model_id | Mô tả | Các trường hợp sử dụng |
|------------|-------------|-----------|
| **kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers** | Mô hình Supervised Fine-Tuned trong 5 giây | Chất lượng sinh cao nhất |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-sft-10s-Diffusers** | Mô hình Supervised Fine-Tuned trong 10 giây | Chất lượng sinh cao nhất |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-5s-Diffusers** | 5 giây Classifier-Free Guidance đã được chưng cất | Suy luận nhanh gấp 2 lần |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-10s-Diffusers** | Classifier-Free Guidance được chưng cất trong 10 giây | Suy luận nhanh gấp 2 lần |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-5s-Diffusers** | 5 second Diffusion được chưng cất thành 16 bước | Suy luận nhanh hơn 6 lần, suy giảm chất lượng tối thiểu |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-10s-Diffusers** | Diffusion 10 giây được chưng cất thành 16 bước | Suy luận nhanh hơn 6 lần, suy giảm chất lượng tối thiểu |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-5s-Diffusers** | Mô hình Base được huấn luyện trước trong 5 giây | Nghiên cứu và tinh chỉnh |
| **kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-10s-Diffusers** | Mô hình Base được huấn luyện trước trong 10 giây | Nghiên cứu và tinh chỉnh |

## Ví dụ sử dụng

### Tạo video từ văn bản cơ bản

#### Pro
**⚠️ Cảnh báo!** tất cả các mô hình Pro nên được suy luận bằng 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)
```

### Mô hình 10 giây
**⚠️ Cảnh báo!** tất cả các mô hình 10 giây nên được sử dụng với Flex attention và biên dịch 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)
```

### Mô hình Diffusion Distilled
**⚠️ Cảnh báo!** tất cả các mô hình nocfg và diffusion distilled phải được suy luận mà không dùng 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)
```

### Tạo video từ ảnh cơ bản
**⚠️ Cảnh báo!** tất cả các mô hình Pro nên được suy luận bằng 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)
```

## Đánh giá song song Kandinsky 5.0 Pro

  
      
          
      
      
         
      

  
      
          So sánh với Veo 3
      
      
          So sánh với Veo 3 fast
      
  
      
          
      
      
          
      
  
      
          So sánh với chế độ Text-to-Video của Wan 2.2 A14B
      
      
          So sánh với chế độ Image-to-Video của Wan 2.2 A14B
      

## Đánh giá song song Kandinsky 5.0 Lite

Đánh giá dựa trên các prompt mở rộng từ [Movie Gen benchmark](https://github.com/facebookresearch/MovieGenBench), có sẵn trong cột expanded_prompt của tệp benchmark/moviegen_bench.csv.

  
      
          
      
      
          
      
  
      
          
      
      
          
      
  
      
          
      

## Đánh giá song song 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L131)

**Tham số:**

transformer (`Kandinsky5Transformer3DModel`) : Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/v0.43.0/vi/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo)) : Mô hình Variational Auto-Encoder [hunyuanvideo-community/HunyuanVideo (vae)](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) để mã hóa và giải mã video sang và từ các biểu diễn ẩn.

text_encoder (`Qwen2_5_VLForConditionalGeneration`) : Bộ mã hóa văn bản đóng băng [Qwen2.5-VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct).

tokenizer (`AutoProcessor`) : Bộ phân từ cho Qwen2.5-VL.

text_encoder_2 (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) được đóng băng, cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer cho CLIP.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một scheduler được sử dụng kết hợp với `transformer` để khử nhiễu các latents video đã được mã hóa.

Pipeline để tạo video từ văn bản sử dụng Kandinsky 5.0.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

#### __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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L680)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để định hướng việc tạo video. Nếu không được định nghĩa, hãy truyền `prompt_embeds` thay thế.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần tránh trong quá trình tạo video. Nếu không được định nghĩa, hãy truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale` < `1`).

height (`int`, mặc định là `512`) : Chiều cao của video được tạo ra, tính bằng pixel.

width (`int`, mặc định là `768`) : Độ rộng của video được tạo ra, tính bằng pixel.

num_frames (`int`, mặc định là `25`) : Số khung hình trong video được tạo ra.

num_inference_steps (`int`, mặc định là `50`) : Số bước khử nhiễu.

guidance_scale (`float`, mặc định là `5.0`) : Thang độ dẫn hướng (guidance scale) như được định nghĩa trong classifier-free guidance.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một torch generator để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước.

prompt_embeds_qwen (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản được tạo trước từ bộ mã hóa văn bản Qwen.

prompt_embeds_clip (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản được tạo trước từ bộ mã hóa văn bản CLIP.

negative_prompt_embeds_qwen (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm được tạo trước từ bộ mã hóa văn bản Qwen.

negative_prompt_embeds_clip (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm được tạo trước từ bộ mã hóa văn bản CLIP.

prompt_cu_seqlens (`torch.Tensor`, *tùy chọn*) : Độ dài chuỗi tích lũy cho các embedding prompt của Qwen, được sử dụng cho chú ý biến độ dài.

negative_prompt_cu_seqlens (`torch.Tensor`, *tùy chọn*) : Độ dài chuỗi tích lũy cho các embedding của prompt tiêu cực Qwen, được sử dụng cho chú ý có độ dài thay đổi.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của video được tạo.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có trả về một `KandinskyPipelineOutput` hay không.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *tuỳ chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu.

callback_on_step_end_tensor_inputs (`list`, *tùy chọn*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`.

max_sequence_length (`int`, mặc định là `512`) : Độ dài tối đa của chuỗi cho việc mã hóa văn bản.

**Trả về:** `~KandinskyPipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `KandinskyPipelineOutput` sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:

```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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L511)

**Tham số:**

prompt : Prompt đầu vào

negative_prompt : Prompt tiêu cực để điều hướng

height : Chiều cao video

width : Độ rộng video

prompt_embeds_qwen : Nhúng prompt Qwen đã tính trước

prompt_embeds_clip : Nhúng prompt CLIP đã tính trước

negative_prompt_embeds_qwen : Nhúng (embeddings) của prompt tiêu cực Qwen đã được tính trước

negative_prompt_embeds_clip : Nhúng (embeddings) của prompt tiêu cực CLIP đã được tính trước

prompt_cu_seqlens : Độ dài chuỗi tích lũy đã tính trước cho Qwen positive prompt

negative_prompt_cu_seqlens : Độ dài chuỗi tích lũy đã tính trước cho Qwen negative prompt

callback_on_step_end_tensor_inputs : Đầu vào tensor của Callback

**Lỗi:** ``ValueError``

- ``ValueError`` -- Nếu các đầu vào không hợp lệ

Xác thực các tham số đầu vào cho 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L418)

**Tham số:**

prompt (`str` hoặc `list[str]`) : Prompt cần được mã hóa.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là 512) : Độ dài tối đa của chuỗi cho việc mã hóa văn bản.

device (`torch.device`, *tùy chọn*) : Thiết bị Torch.

dtype (`torch.dtype`, *tùy chọn*) : Torch dtype.

**Trả về:** tuple[torch.Tensor, torch.Tensor, torch.Tensor]

- Qwen text embeddings có shape (batch_size * num_videos_per_prompt, sequence_length, embedding_dim)
- CLIP pooled embeddings có shape (batch_size * num_videos_per_prompt, clip_embedding_dim)
- Chiều dài chuỗi tích lũy (`cu_seqlens`) cho Qwen embeddings có shape (batch_size * num_videos_per_prompt + 1,)

Mã hóa một prompt duy nhất (tích cực hoặc tiêu cực) thành các trạng thái ẩn của text encoder.

Phương pháp này kết hợp các embedding từ cả hai bộ mã hóa văn bản Qwen2.5-VL và CLIP để tạo ra các biểu diễn văn bản toàn diện cho việc tạo video.

#### 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')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L229)

**Tham số:**

T (int) : Số lượng khung thời gian

H (int) : Chiều cao trong không gian tiềm ẩn

W (int) : Độ rộng trong không gian tiềm ẩn

wT (int) : Kích thước cửa sổ chú ý thời gian

wH (int) : Kích thước cửa sổ chú ý chiều cao

wW (int) : Kích thước cửa sổ chú ý

device (str) : Thiết bị để tạo tensor

**Trả về:** `torch.Tensor`

Mặt nạ chú ý thưa có hình dạng (T*H*W, T*H*W)

Tạo một mặt nạ chú ý thời gian thưa (STA) cho việc tạo video hiệu quả.

Phương pháp này tạo ra một mặt nạ (mask) giới hạn sự chú ý (attention) vào các khung hình và vị trí không gian lân cận, từ đó giảm độ phức tạp tính toán cho việc tạo video.

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

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L264)

**Tham số:**

sample (torch.Tensor) : Tensor mẫu đầu vào

device (torch.device) : Thiết bị để đặt các tensor

**Trả về:** `Dict`

Từ điển chứa các tham số chú ý thưa

Tạo các tham số chú ý thưa cho transformer dựa trên các kích thước mẫu.

Phương pháp này tính toán cấu hình chú ý thưa (sparse attention) cần thiết để xử lý video hiệu quả trong mô hình 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky.py#L597)

**Tham số:**

batch_size (int) : Số lượng video cần tạo

num_channels_latents (int) : Số lượng kênh trong không gian tiềm ẩn

height (int) : Chiều cao của video được tạo

width (int) : Độ rộng của video được tạo

num_frames (int) : Số khung hình trong video

dtype (torch.dtype) : Kiểu dữ liệu cho các biến ẩn

device (torch.device) : Thiết bị để tạo latents

generator (torch.Generator) : Bộ tạo số ngẫu nhiên

latents (torch.Tensor) : Các latents có sẵn để sử dụng

**Trả về:** `torch.Tensor`

Tensor latent đã được chuẩn bị

Chuẩn bị các biến tiềm ẩn ban đầu cho việc tạo video.

Phương pháp này tạo ra các latents nhiễu ngẫu nhiên hoặc sử dụng các latents được cung cấp làm điểm khởi đầu cho quá trình khử nhiễu.

## 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L128)

**Tham số:**

transformer (`Kandinsky5Transformer3DModel`) : Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/v0.43.0/vi/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo)) : Mô hình Variational Auto-Encoder [hunyuanvideo-community/HunyuanVideo (vae)](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) để mã hóa và giải mã video sang và từ các biểu diễn ẩn.

text_encoder (`Qwen2_5_VLForConditionalGeneration`) : Bộ mã hóa văn bản đóng băng [Qwen2.5-VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct).

tokenizer (`AutoProcessor`) : Bộ phân từ cho Qwen2.5-VL.

text_encoder_2 (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) được đóng băng, cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer cho CLIP.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một scheduler được sử dụng kết hợp với `transformer` để khử nhiễu các latents video đã được mã hóa.

Pipeline để tạo video từ hình ảnh sử dụng Kandinsky 5.0.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

#### __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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L748)

**Tham số:**

image (`PipelineImageInput`) : Ảnh đầu vào để điều kiện cho quá trình tạo. Phải là một ảnh, một danh sách các ảnh hoặc một `torch.Tensor`.

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để định hướng việc tạo video. Nếu không được định nghĩa, hãy truyền `prompt_embeds` thay thế.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần tránh trong quá trình tạo video. Nếu không được định nghĩa, hãy truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale` < `1`).

height (`int`, mặc định là `512`) : Chiều cao của video được tạo ra, tính bằng pixel.

width (`int`, mặc định là `768`) : Độ rộng của video được tạo ra, tính bằng pixel.

num_frames (`int`, mặc định là `121`) : Số khung hình trong video được tạo ra.

num_inference_steps (`int`, mặc định là `50`) : Số bước khử nhiễu.

guidance_scale (`float`, mặc định là `5.0`) : Thang độ dẫn hướng (guidance scale) như được định nghĩa trong classifier-free guidance.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một torch generator để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước.

prompt_embeds_qwen (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản Qwen đã được tạo trước.

prompt_embeds_clip (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản CLIP đã được tạo trước.

negative_prompt_embeds_qwen (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản âm của Qwen đã được tạo trước.

negative_prompt_embeds_clip (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản âm (negative text embeddings) của CLIP đã được tạo trước.

prompt_cu_seqlens (`torch.Tensor`, *tùy chọn*) : Độ dài chuỗi tích lũy đã tạo trước cho prompt tích cực của Qwen.

negative_prompt_cu_seqlens (`torch.Tensor`, *tùy chọn*) : Độ dài chuỗi tích lũy đã tạo trước cho prompt âm của Qwen.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của video được tạo.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có trả về một `KandinskyPipelineOutput` hay không.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *tuỳ chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu.

callback_on_step_end_tensor_inputs (`List`, *tùy chọn*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`.

max_sequence_length (`int`, mặc định là `512`) : Độ dài tối đa của chuỗi cho việc mã hóa văn bản.

**Trả về:** `~KandinskyPipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `KandinskyPipelineOutput` sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các video đã tạo.

Hàm gọi của pipeline để tạo video từ ảnh.

Ví dụ:

```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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L545)

**Tham số:**

prompt : Prompt đầu vào

negative_prompt : Prompt tiêu cực để điều hướng

image : Ảnh đầu vào để điều kiện

height : Chiều cao video

width : Độ rộng video

prompt_embeds_qwen : Nhúng prompt Qwen đã tính trước

prompt_embeds_clip : Nhúng prompt CLIP đã tính trước

negative_prompt_embeds_qwen : Nhúng (embeddings) của prompt tiêu cực Qwen đã được tính trước

negative_prompt_embeds_clip : Nhúng (embeddings) của prompt tiêu cực CLIP đã được tính trước

prompt_cu_seqlens : Độ dài chuỗi tích lũy đã tính trước cho Qwen positive prompt

negative_prompt_cu_seqlens : Độ dài chuỗi tích lũy đã tính trước cho Qwen negative prompt

callback_on_step_end_tensor_inputs : Đầu vào tensor của Callback

**Lỗi:** ``ValueError``

- ``ValueError`` -- Nếu các đầu vào không hợp lệ

Xác thực các tham số đầu vào cho 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L454)

**Tham số:**

prompt (`str` hoặc `list[str]`) : Prompt cần được mã hóa.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là 512) : Độ dài tối đa của chuỗi cho việc mã hóa văn bản.

device (`torch.device`, *tùy chọn*) : Thiết bị Torch.

dtype (`torch.dtype`, *tùy chọn*) : Torch dtype.

**Trả về:** tuple[torch.Tensor, torch.Tensor, torch.Tensor]

- Qwen text embeddings có shape (batch_size * num_videos_per_prompt, sequence_length, embedding_dim)
- CLIP pooled embeddings có shape (batch_size * num_videos_per_prompt, clip_embedding_dim)
- Chiều dài chuỗi tích lũy (`cu_seqlens`) cho Qwen embeddings có shape (batch_size * num_videos_per_prompt + 1,)

Mã hóa một prompt duy nhất (tích cực hoặc tiêu cực) thành các trạng thái ẩn của text encoder.

Phương pháp này kết hợp các embedding từ cả hai bộ mã hóa văn bản Qwen2.5-VL và CLIP để tạo ra các biểu diễn văn bản toàn diện cho việc tạo video.

#### 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')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L226)

**Tham số:**

T (int) : Số lượng khung thời gian

H (int) : Chiều cao trong không gian tiềm ẩn

W (int) : Độ rộng trong không gian tiềm ẩn

wT (int) : Kích thước cửa sổ chú ý thời gian

wH (int) : Kích thước cửa sổ chú ý chiều cao

wW (int) : Kích thước cửa sổ chú ý

device (str) : Thiết bị để tạo tensor

**Trả về:** `torch.Tensor`

Mặt nạ chú ý thưa có hình dạng (T*H*W, T*H*W)

Tạo một mặt nạ chú ý thời gian thưa (STA) cho việc tạo video hiệu quả.

Phương pháp này tạo ra một mặt nạ (mask) giới hạn sự chú ý (attention) vào các khung hình và vị trí không gian lân cận, từ đó giảm độ phức tạp tính toán cho việc tạo video.

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

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L261)

**Tham số:**

sample (torch.Tensor) : Tensor mẫu đầu vào

device (torch.device) : Thiết bị để đặt các tensor

**Trả về:** `Dict`

Từ điển chứa các tham số chú ý thưa

Tạo các tham số chú ý thưa cho transformer dựa trên các kích thước mẫu.

Phương pháp này tính toán cấu hình chú ý thưa (sparse attention) cần thiết để xử lý video hiệu quả trong mô hình 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2v.py#L636)

**Tham số:**

image (PipelineImageInput) : Ảnh đầu vào để điều kiện hóa quá trình tạo

batch_size (int) : Số lượng video cần tạo

num_channels_latents (int) : Số lượng kênh trong không gian tiềm ẩn

height (int) : Chiều cao của video được tạo

width (int) : Độ rộng của video được tạo

num_frames (int) : Số khung hình trong video

dtype (torch.dtype) : Kiểu dữ liệu cho các biến ẩn

device (torch.device) : Thiết bị để tạo latents

generator (torch.Generator) : Bộ tạo số ngẫu nhiên

latents (torch.Tensor) : Các latents có sẵn để sử dụng

**Trả về:** `torch.Tensor`

Tensor latent đã chuẩn bị với khung đầu tiên là ảnh đã mã hóa

Chuẩn bị các biến tiềm ẩn ban đầu cho việc tạo video từ hình ảnh.

Phương pháp này tạo ra các latent nhiễu ngẫu nhiên cho tất cả các khung hình ngoại trừ khung hình đầu tiên, khung hình này sẽ được thay thế bằng ảnh đầu vào đã được mã hóa.

## Trích dẫn
```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
}
```

