> 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-zh/tu-xiang-sheng-cheng/pixart-image-gen.md).

# PixArt

使用 PixArt-Alpha 和 PixArt-Sigma 快速生成图像

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

### 访问你的服务器

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

## 什么是 PixArt？

PixArt 模型提供：

* 比 SDXL 快 10 倍
* 高质量 1024px 图像
* 强大的文本渲染能力
* 高效的训练方法

## 模型变体

| 模型           | 质量 | 速度 | 显存   |
| ------------ | -- | -- | ---- |
| PixArt-Alpha | 很高 | 快  | 8GB  |
| 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")
```

## 内存优化

### 适用于 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(
    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="种子（-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 | \~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 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 下一步

* FLUX 生成 - 最佳质量
* Stable Diffusion WebUI - 更多功能
* [ControlNet 指南](/guides/guides_v2-zh/tu-xiang-chu-li/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-zh/tu-xiang-sheng-cheng/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.
