> 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-izobrazhenii/pixart-image-gen.md).

# PixArt

Быстро создавайте изображения с PixArt-Alpha и PixArt-Sigma.

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

## Аренда на CLORE.AI

1. Перейдите на [маркетплейс CLORE.AI](https://clore.ai/marketplace)
2. Отфильтруйте по типу GPU, объёму VRAM и цене
3. Выберите **On-Demand** (фиксированная ставка) или **Spot** (цена ставки)
4. Настройте свой заказ:
   * Выберите Docker-образ
   * Установите порты (TCP для SSH, HTTP для веб-интерфейсов)
   * При необходимости добавьте переменные окружения
   * Введите команду запуска
5. Выберите способ оплаты: **CLORE**, **BTC**, или **USDT/USDC**
6. Создайте заказ и дождитесь развертывания

### Получите доступ к своему серверу

* Найдите данные для подключения в **Мои заказы**
* Веб-интерфейсы: используйте URL HTTP-порта
* SSH: `ssh -p <port> root@<proxy-address>`

## Что такое PixArt?

Модели PixArt предлагают:

* В 10 раз быстрее, чем SDXL
* Высококачественные изображения 1024 px
* Отличное отображение текста
* Эффективные методы обучения

## Варианты модели

| Модель       | Качество    | Скорость | VRAM |
| ------------ | ----------- | -------- | ---- |
| PixArt-Alpha | Отлично     | Быстро   | 8 ГБ |
| PixArt-Sigma | Лучше всего | Средне   | 12GB |

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

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

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

**Порты:**

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

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

```bash
pip install diffusers transformers accelerate gradio && \\
python -c "
import gradio as gr
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained('PixArt-alpha/PixArt-XL-2-1024-MS', torch_dtype=torch.float16)
pipe.to('cuda')

def generate(prompt, steps):
    image = pipe(prompt, num_inference_steps=steps).images[0]
    return image

demo = gr.Interface(fn=generate, inputs=[gr.Textbox(), gr.Slider(10, 50, 20)], outputs=gr.Image(), title='PixArt')
demo.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
```

## PixArt-Alpha

### Базовая генерация

```python
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
)
pipe.to("cuda")

prompt = "Кот-космонавт, парящий в космосе, Земля на заднем плане, фотореалистично"

image = pipe(
    prompt=prompt,
    num_inference_steps=20,
    guidance_scale=4.5
).images[0]

image.save("output.png")
```

### Параметры генерации

```python
image = pipe(
    prompt="красивый закат над горами",
    negative_prompt="размыто, низкое качество",
    num_inference_steps=20,      # Качество (10-50)
    guidance_scale=4.5,          # Соответствие запросу (3-7)
    height=1024,
    width=1024,
    generator=torch.Generator("cuda").manual_seed(42)
).images[0]
```

## PixArt-Sigma

Версия более высокого качества:

```python
from diffusers import PixArtSigmaPipeline
import torch

pipe = PixArtSigmaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
    torch_dtype=torch.float16
)
pipe.to("cuda")
pipe.enable_model_cpu_offload()

image = pipe(
    prompt="профессиональная фотография красного спортивного автомобиля",
    num_inference_steps=30,
    guidance_scale=4.5
).images[0]

image.save("sigma_output.png")
```

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

### Для 8 ГБ VRAM

```python
pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
)

# Выгрузка на CPU
pipe.enable_model_cpu_offload()

# Последовательная выгрузка на CPU (более агрессивная)

# pipe.enable_sequential_cpu_offload()
```

### Включить нарезку VAE

```python
pipe.enable_vae_slicing()
pipe.enable_vae_tiling()
```

## Пакетная генерация

```python
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
).to("cuda")

prompts = [
    "киберпанк-город ночью",
    "мирный японский сад",
    "фэнтезийный замок на утесе",
    "подводный коралловый риф"
]

for i, prompt in enumerate(prompts):
    image = pipe(prompt, num_inference_steps=20).images[0]
    image.save(f"output_{i:03d}.png")
    print(f"Сгенерировано: {prompt[:50]}...")
```

## Разные разрешения

```python

# Поддерживаемые разрешения
resolutions = [
    (512, 512),
    (768, 768),
    (1024, 1024),
    (1024, 512),   # Альбомная ориентация
    (512, 1024),   # Портретная ориентация
    (768, 1024),
    (1024, 768),
]

for w, h in resolutions:
    image = pipe(
        prompt="красивый пейзаж",
        width=w,
        height=h,
        num_inference_steps=20
    ).images[0]

    image.save(f"output_{w}x{h}.png")
```

## Отображение текста

PixArt отлично справляется с текстом на изображениях:

```python
prompt = """
Винтажный киноплакат с названием "COSMIC ADVENTURE" жирными буквами,
с космическим кораблем и планетами, в ретро-стиле 1950-х годов
"""

image = pipe(
    prompt=prompt,
    num_inference_steps=30,
    guidance_scale=5.0
).images[0]
```

## Интерфейс Gradio

```python
import gradio as gr
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
).to("cuda")

def generate(prompt, negative_prompt, steps, guidance, width, height, seed):
    generator = torch.Generator("cuda").manual_seed(seed) if seed > 0 else None

    image = pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_inference_steps=steps,
        guidance_scale=guidance,
        width=width,
        height=height,
        generator=generator
    ).images[0]

    return image

demo = gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label="Запрос", lines=3),
        gr.Textbox(label="Негативный запрос"),
        gr.Slider(10, 50, value=20, step=1, label="Шаги"),
        gr.Slider(1, 10, value=4.5, step=0.5, label="Сила соответствия"),
        gr.Slider(512, 1024, value=1024, step=64, label="Ширина"),
        gr.Slider(512, 1024, value=1024, step=64, label="Высота"),
        gr.Number(value=-1, label="Seed (-1 для случайного)" )
    ],
    outputs=gr.Image(label="Сгенерированное изображение"),
    title="Генератор изображений PixArt"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## API-сервер

```python
from fastapi import FastAPI
from fastapi.responses import Response
from diffusers import PixArtAlphaPipeline
import torch
import io

app = FastAPI()

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
).to("cuda")

@app.post("/generate")
async def generate(
    prompt: str,
    negative_prompt: str = "",
    steps: int = 20,
    guidance: float = 4.5,
    width: int = 1024,
    height: int = 1024
):
    image = pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_inference_steps=steps,
        guidance_scale=guidance,
        width=width,
        height=height
    ).images[0]

    buffer = io.BytesIO()
    image.save(buffer, format="PNG")
    return Response(content=buffer.getvalue(), media_type="image/png")

# Запуск: uvicorn server:app --host 0.0.0.0 --port 8000
```

## Сравнение производительности

| Модель       | GPU      | Время 1024x1024 |
| ------------ | -------- | --------------- |
| PixArt-Alpha | RTX 3090 | \~3 с           |
| PixArt-Sigma | RTX 3090 | \~5 с           |
| SDXL         | RTX 3090 | \~15с           |
| PixArt-Alpha | RTX 4090 | \~2 с           |
| PixArt-Sigma | RTX 4090 | \~3 с           |

## Настройки качества

| Сценарий использования | Шаги  | Сила соответствия |
| ---------------------- | ----- | ----------------- |
| Предпросмотр           | 10-15 | 4.0               |
| Стандартный            | 20    | 4.5               |
| Высокое качество       | 30-40 | 5.0               |

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

### Недостаточно памяти

```python

# Включить выгрузку
pipe.enable_model_cpu_offload()

# Или используйте меньшее разрешение
width, height = 768, 768
```

### Низкое качество

* Увеличьте число шагов (25-40)
* Настройте шкалу соответствия
* Более подробные запросы

### Медленная генерация

* Используйте PixArt-Alpha (быстрее)
* Уменьшите число шагов
* Более низкое разрешение

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

Типичные цены на маркетплейсе 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) *актуальные тарифы.*

**Сэкономьте деньги:**

* Используйте **Spot** рынок для прерываемых задач — примерно треть серверов оценивает spot-цены ниже on-demand (медиана \~13% скидки), остальные совпадают с ними
* Платите **CLORE** токенами
* Сравните цены у разных провайдеров

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

* Генерация FLUX — лучшее качество
* Stable Diffusion WebUI — больше возможностей
* [Руководство по ControlNet](/guides/guides_v2-ru/obrabotka-izobrazhenii/controlnet-advanced.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-izobrazhenii/pixart-image-gen.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.
