> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-ru/generaciya-video/stable-video-diffusion.md).

# Stable Video Diffusion

{% hint style="info" %}
**Доступны более новые альтернативы!** Рассмотрите [**FramePack**](/guides/guides_v2-ru/generaciya-video/framepack.md) (только 6 ГБ видеопамяти!), [**Wan2.1**](/guides/guides_v2-ru/generaciya-video/wan-video.md) (более высокое качество), или [**LTX-2**](/guides/guides_v2-ru/generaciya-video/ltx-video-2.md) (видео со встроенным звуком).
{% endhint %}

Создавайте видео из изображений с помощью модели SVD от Stability AI.

{% hint style="success" %}
Все примеры можно запускать на GPU-серверах, арендованных через [маркетплейс CLORE.AI](https://clore.ai/marketplace).
{% endhint %}

## Что такое Stable Video Diffusion?

SVD (Stable Video Diffusion) генерирует короткие видеоклипы из одного изображения:

* Выводы на 14 или 25 кадров
* Разрешение 576x1024
* Плавная генерация движения
* Веса с открытым исходным кодом

## Ресурсы

* **HuggingFace:** [stabilityai/stable-video-diffusion-img2vid-xt](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt)
* **GitHub:** [Stability-AI/generative-models](https://github.com/Stability-AI/generative-models)
* **Статья:** [Статья SVD](https://arxiv.org/abs/2311.15127)

## Требования к оборудованию

| Модель             | VRAM  | Рекомендуемый GPU |
| ------------------ | ----- | ----------------- |
| SVD (14 кадров)    | 16GB  | RTX 4090          |
| SVD-XT (25 кадров) | 24 ГБ | RTX 4090 / A100   |

## Быстрое развёртывание

**Docker-образ:**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
```

**Порты:**

```
22/tcp
7860/http
```

**Команда:**

```bash
pip install diffusers transformers accelerate && \\
pip install gradio && \\
python -c "
import gradio as gr
from diffusers import StableVideoDiffusionPipeline
from diffusers.utils import export_to_video
import torch

pipe = StableVideoDiffusionPipeline.from_pretrained(
    'stabilityai/stable-video-diffusion-img2vid-xt',
    torch_dtype=torch.float16,
    variant='fp16'
).to('cuda')

def generate(image, seed, fps):
    generator = torch.manual_seed(seed)
    frames = pipe(image, num_frames=25, generator=generator).frames[0]
    export_to_video(frames, 'output.mp4', fps=fps)
    return 'output.mp4'

gr.Interface(
    fn=generate,
    inputs=[gr.Image(type='pil'), gr.Number(value=42, label='Зерно'), gr.Slider(6, 30, value=7, label='FPS')],
    outputs=gr.Video(),
    title='Стабильная диффузия видео'
).launch(server_name='0.0.0.0', server_port=7860)
"
```

## Доступ к вашему сервису

После развертывания найдите свой `http_pub` URL в **Мои заказы**:

1. Перейдите на **Мои заказы** страницу
2. Нажмите на свой заказ
3. Найдите `http_pub` URL (например, `abc123.clorecloud.net`)

Используйте `https://YOUR_HTTP_PUB_URL` вместо `localhost` в примерах ниже.

## Установка

```bash
pip install diffusers transformers accelerate torch

# Для экспорта видео
pip install imageio[ffmpeg]
```

## Базовое использование

```python
import torch
from diffusers import StableVideoDiffusionPipeline
from diffusers.utils import load_image, export_to_video

# Загрузить пайплайн
pipe = StableVideoDiffusionPipeline.from_pretrained(
    "stabilityai/stable-video-diffusion-img2vid-xt",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

# Загрузить и изменить размер изображения
image = load_image("input.jpg")
image = image.resize((1024, 576))

# Сгенерировать видео
generator = torch.manual_seed(42)
frames = pipe(image, num_frames=25, generator=generator).frames[0]

# Сохранить видео
export_to_video(frames, "output.mp4", fps=7)
```

## SVD vs SVD-XT

| Функция      | SVD    | SVD-XT   |
| ------------ | ------ | -------- |
| Кадры        | 14     | 25       |
| Длительность | ≈2 сек | ≈3,5 сек |
| VRAM         | 16GB   | 24 ГБ    |
| Качество     | Хорошо | Лучше    |

## Оптимизация памяти

```python

# Включите attention с экономией памяти
pipe.enable_model_cpu_offload()

# Или используйте разбиение attention
pipe.enable_attention_slicing()

# Для очень малого объёма видеопамяти
pipe.enable_sequential_cpu_offload()
```

## Пакетная обработка

```python
import os
from pathlib import Path

input_dir = Path("./images")
output_dir = Path("./videos")
output_dir.mkdir(exist_ok=True)

for img_path in input_dir.glob("*.jpg"):
    image = load_image(str(img_path)).resize((1024, 576))
    frames = pipe(image, num_frames=25).frames[0]
    export_to_video(frames, str(output_dir / f"{img_path.stem}.mp4"), fps=7)
    print(f"Создано: {img_path.stem}.mp4")
```

## Интеграция с ComfyUI

SVD отлично работает в ComfyUI:

1. Установите ComfyUI
2. Скачайте модель SVD в `models/checkpoints/`
3. Используйте узлы SVD для рабочего процесса img2vid

## Устранение неполадок

{% hint style="danger" %}
**Не хватает памяти**
{% endhint %}

* Используйте `enable_model_cpu_offload()`
* Уменьшите `num_frames` до 14
* Используйте вариант fp16

### Видео слишком короткое

* Используйте SVD-XT (25 кадров) вместо SVD (14 кадров)
* Интерполируйте с помощью RIFE для более плавного результата

### Плохое качество движения

* Используйте изображения высокого качества
* Убедитесь, что изображение имеет размер 1024x576 (или 576x1024)
* Попробуйте другие seed-значения

### Ошибки CUDA

* Обновите PyTorch и diffusers
* Проверьте совместимость версии CUDA

## Оценка стоимости

Типичные цены на маркетплейсе CLORE.AI (по состоянию на 2024 год):

| GPU        | Почасовая ставка | Дневная ставка | 4-часовая сессия |
| ---------- | ---------------- | -------------- | ---------------- |
| RTX 3060   | \~$0.03          | \~$0.70        | \~$0.12          |
| RTX 3090   | \~$0.06          | \~$1.50        | \~$0.25          |
| RTX 4090   | \~$0.10          | \~$2.30        | \~$0.40          |
| A100 40 ГБ | \~$0.17          | \~$4.00        | \~$0.70          |
| A100 80 ГБ | \~$0.25          | \~$6.00        | \~$1.00          |

*Цены зависят от провайдера. Проверьте* [*маркетплейс CLORE.AI*](https://clore.ai/marketplace) *актуальные тарифы.*

## Дальнейшие шаги

* AnimateDiff — анимация изображений SD
* [Интерполяция RIFE](/guides/guides_v2-ru/obrabotka-video/rife-interpolation.md) - Увеличить FPS
* [Hunyuan Video](/guides/guides_v2-ru/generaciya-video/hunyuan-video.md) - генерация видео по тексту


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-ru/generaciya-video/stable-video-diffusion.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
