> 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 Marketplace](https://clore.ai/marketplace).
{% endhint %}

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

1. Посетите [CLORE.AI Marketplace](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
* Качественные изображения 1024px
* Сильная отрисовка текста
* Эффективные методы обучения

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

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

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

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

```
pytorch/pytorch:2.5.1-cuda12.4-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="a beautiful sunset over mountains",
    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ГБ видеопамяти

```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="Подсказка (Prompt)", 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="Width"),
        gr.Slider(512, 1024, value=1024, step=64, label="Height"),
        gr.Number(value=-1, label="Seed (-1 для случайного)")
    ],
    outputs=gr.Image(label="Generated Image"),
    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 | \~3s            |
| PixArt-Sigma | RTX 3090 | \~5 с           |
| SDXL         | RTX 3090 | \~15с           |
| PixArt-Alpha | RTX 4090 | \~2s            |
| PixArt-Sigma | RTX 4090 | \~3s            |

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

| Случай использования | Шаги  | Направление |
| -------------------- | ----- | ----------- |
| Предпросмотр         | 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 40GB | \~$0.17          | \~$4.00        | \~$0.70       |
| A100 80GB | \~$0.25          | \~$6.00        | \~$1.00       |

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

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

* Используйте **Spot** рынок для гибких рабочих нагрузок (часто на 30–50% дешевле)
* Платите с помощью **CLORE** токенов
* Сравнивайте цены у разных провайдеров

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

* FLUX Generation - Лучшее качество
* 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.
