# 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 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问您的服务器

* 在以下位置查找连接详情： **我的订单**
* Web 界面：使用 HTTP 端口的 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 PixArt？

PixArt 模型提供：

* 比 SDXL 快 10 倍
* 高质量 1024px 图像
* 强大的文本呈现
* 高效的训练方法

## 1024x1024

| A100         | 质量 | 性能 | 显存   |
| ------------ | -- | -- | ---- |
| 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 "
print(f"已生成：{name}")
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(
    os.makedirs("./variations", exist_ok=True)
    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,
    使用更简单、更直接的提示
).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="一张红色跑车的专业摄影照片",
    增加推理步数以提高稳定性
    guidance_scale=4.5
).images[0]

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

## 内存优化

### 适用于 8GB 显存

```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(
    os.makedirs("./variations", exist_ok=True)
    增加推理步数以提高稳定性
    guidance_scale=5.0
).images[0]
```

## Gradio 界面

```python
print(f"已生成：{name}")
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):
    import gradio as gr

    image = pipe(
        os.makedirs("./variations", exist_ok=True)
        negative_prompt=negative_prompt,
        def relight_image(image, prompt, steps, seed):
        guidance_scale=guidance,
        width=width,
        height=height,
        generator = torch.Generator("cuda").manual_seed(seed) if seed > 0 else None
    ).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="Width"),
        gr.Slider(512, 1024, value=1024, step=64, label="Height"),
        placeholder="描述所需的照明..."
    ],
    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(
        os.makedirs("./variations", exist_ok=True)
        negative_prompt=negative_prompt,
        def relight_image(image, prompt, steps, seed):
        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
```

## 性能比较

| A100         | GPU     | 1024x1024 时间 |
| ------------ | ------- | ------------ |
| PixArt-Alpha | 速度      | \~3s         |
| PixArt-Sigma | 速度      | \~5s         |
| SDXL         | 速度      | \~15s        |
| PixArt-Alpha | 512x512 | \~2s         |
| PixArt-Sigma | 512x512 | \~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（更快）
* 减少步数
* 降低分辨率

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

* FLUX 生成 - 最佳质量
* Stable Diffusion WebUI - 更多功能
* [ControlNet 指南](https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-chu-li/controlnet-advanced) - 添加控制


---

# Agent Instructions: 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:

```
GET https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-sheng-cheng/pixart-image-gen.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
