> 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/sdxl-turbo.md).

# SDXL Turbo 与 LCM

在 Clore.ai 上使用 SDXL Turbo 和 LCM 通过 1-4 步生成图像

使用 SDXL Turbo 和潜在一致性模型，在 CLORE.AI GPU 上以 1-4 步生成图像。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 为什么选择 SDXL Turbo / LCM？

* **实时速度** - 以 1-4 步生成图像，而不是 30-50 步
* **相同质量** - 以少 10 倍的步骤数达到与完整 SDXL 相当的效果
* **交互式** - 速度足以支持实时应用
* **低显存占用** - 高效的内存使用
* **兼容 LoRA** - 可与现有的 SDXL LoRA 一起使用

## 模型变体

| 模型              | 步数  | 速度  | 质量 | 显存   |
| --------------- | --- | --- | -- | ---- |
| SDXL Turbo      | 1-4 | 最快  | 好  | 8GB  |
| SDXL Lightning  | 2-8 | 非常快 | 很高 | 8GB  |
| LCM-SDXL        | 4-8 | 快   | 很高 | 8GB  |
| LCM-LoRA + SDXL | 4-8 | 快   | 优秀 | 10GB |
| SD Turbo (1.5)  | 1-4 | 最快  | 好  | 4GB  |

## 在 CLORE.AI 上快速部署

**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
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    'stabilityai/sdxl-turbo',
    torch_dtype=torch.float16,
    variant='fp16'
).to('cuda')

def generate(prompt, steps, seed):
    generator = torch.Generator('cuda').manual_seed(seed) if seed > 0 else None
    image = pipe(prompt, num_inference_steps=steps, guidance_scale=0.0, generator=generator).images[0]
    return image

gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label='提示词'),
        gr.Slider(1, 4, value=1, step=1, label='步数'),
        gr.Number(value=-1, label='种子')
    ],
    outputs=gr.Image(),
    title='SDXL Turbo - 实时生成'
).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` 在下面的示例中。

## 硬件要求

| 模型             | 最低 GPU        | 推荐       |
| -------------- | ------------- | -------- |
| SD Turbo       | RTX 3060 8GB  | RTX 3070 |
| SDXL Turbo     | RTX 3070 8GB  | RTX 3080 |
| SDXL Lightning | RTX 3070 8GB  | RTX 3090 |
| LCM-SDXL       | RTX 3080 10GB | RTX 4090 |

## 安装

```bash
pip install diffusers transformers accelerate torch
```

## SDXL Turbo

### 基础用法

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

# 1 步生成！
image = pipe(
    prompt="一只穿着精致意大利牧师长袍的电影感小浣熊",
    num_inference_steps=1,
    guidance_scale=0.0  # Turbo 不使用 CFG
).images[0]

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

### 最佳设置

```python
# 1 步 - 最快，质量不错
image = pipe(prompt, num_inference_steps=1, guidance_scale=0.0).images[0]

# 2 步 - 更好的细节
image = pipe(prompt, num_inference_steps=2, guidance_scale=0.0).images[0]

# 4 步 - Turbo 的最佳质量
image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
```

## SDXL Lightning

### 2 步生成

```python
import torch
from diffusers import StableDiffusionXLPipeline, EulerDiscreteScheduler
from huggingface_hub import hf_hub_download

base = "stabilityai/stable-diffusion-xl-base-1.0"
repo = "ByteDance/SDXL-Lightning"
ckpt = "sdxl_lightning_2step_unet.safetensors"

# 加载基础模型
pipe = StableDiffusionXLPipeline.from_pretrained(
    base,
    torch_dtype=torch.float16,
    variant="fp16"
).to("cuda")

# 加载 lightning unet
pipe.unet.load_state_dict(
    torch.load(hf_hub_download(repo, ckpt), map_location="cuda")
)

# 配置调度器
pipe.scheduler = EulerDiscreteScheduler.from_config(
    pipe.scheduler.config,
    timestep_spacing="trailing"
)

# 以 2 步生成
image = pipe(
    "一个在花园中微笑的女孩",
    num_inference_steps=2,
    guidance_scale=0.0
).images[0]

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

### 4 步（更高质量）

```python
ckpt = "sdxl_lightning_4step_unet.safetensors"
# ... 相同设置 ...

image = pipe(
    prompt,
    num_inference_steps=4,
    guidance_scale=0.0
).images[0]
```

## LCM-LoRA

可与任何 SDXL 模型一起使用，实现快速生成：

```python
import torch
from diffusers import DiffusionPipeline, LCMScheduler

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

# 加载 LCM-LoRA
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")

# 设置 LCM 调度器
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

# 以 4 步生成
image = pipe(
    "宇航员在丛林中，冷色调，柔和色彩，细节丰富，8k",
    num_inference_steps=4,
    guidance_scale=1.0  # LCM 使用较低的 CFG
).images[0]

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

### 使用自定义 LoRA

```python
# 加载基础模型 + LCM-LoRA + 风格 LoRA
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl", adapter_name="lcm")
pipe.load_lora_weights("your-style-lora", adapter_name="style")

# 合并适配器
pipe.set_adapters(["lcm", "style"], adapter_weights=[1.0, 0.8])

image = pipe(prompt, num_inference_steps=4, guidance_scale=1.5).images[0]
```

## SD Turbo (SD 1.5)

适用于更低显存需求：

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sd-turbo",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

image = pipe(
    "一只猫的照片",
    num_inference_steps=1,
    guidance_scale=0.0
).images[0]
```

## 图生图

### SDXL Turbo 图生图

```python
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image

pipe = AutoPipelineForImage2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

init_image = load_image("input.jpg").resize((512, 512))

image = pipe(
    prompt="猫巫师，甘道夫，指环王，细节丰富，奇幻风",
    image=init_image,
    num_inference_steps=2,
    strength=0.5,
    guidance_scale=0.0
).images[0]
```

## 批量生成

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16
).to("cuda")

prompts = [
    "群山上的日落",
    "夜晚的未来城市",
    "花园里的一只可爱机器人",
    "迷雾中的古老神庙"
]

# 批量生成
images = pipe(
    prompts,
    num_inference_steps=1,
    guidance_scale=0.0
).images

for i, img in enumerate(images):
    img.save(f"batch_{i}.png")
```

## 实时流式生成

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

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16
).to("cuda")

def generate_realtime(prompt):
    if not prompt:
        return None
    image = pipe(
        prompt,
        num_inference_steps=1,
        guidance_scale=0.0,
        width=512,
        height=512
    ).images[0]
    return image

demo = gr.Interface(
    fn=generate_realtime,
    inputs=gr.Textbox(label="提示词"),
    outputs=gr.Image(label="生成结果"),
    live=True,  # 输入时即时更新
    title="实时 SDXL Turbo"
)

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

## 性能对比

| 模型             | 步数 | 分辨率       | RTX 3090 | RTX 4090 | A100   |
| -------------- | -- | --------- | -------- | -------- | ------ |
| SDXL（基础版）      | 30 | 1024x1024 | 8s       | 5s       | 4 秒    |
| SDXL Turbo     | 1  | 512x512   | 0.3秒     | 0.2 秒    | 0.15 秒 |
| SDXL Turbo     | 4  | 512x512   | 0.8秒     | 0.5秒     | 0.4 秒  |
| SDXL Lightning | 2  | 1024x1024 | 0.8秒     | 0.5秒     | 0.4 秒  |
| SDXL Lightning | 4  | 1024x1024 | 1.2秒     | 0.8秒     | 0.6 秒  |
| LCM-SDXL       | 4  | 1024x1024 | 1.5 秒    | 1.0 秒    | 0.7 秒  |

## 质量对比

| 方面    | SDXL 30 步 | Turbo 4 步 | Lightning 4 步 |
| ----- | --------- | --------- | ------------- |
| 详情    | 优秀        | 好         | 很高            |
| 文本渲染  | 好         | 较差        | 较差            |
| 面部    | 很高        | 好         | 好             |
| 一致性   | 优秀        | 好         | 很高            |
| 风格多样性 | 优秀        | 好         | 很高            |

## 何时使用哪种

| 使用场景       | 推荐             | 步数  |
| ---------- | -------------- | --- |
| 实时预览       | SDXL Turbo     | 1   |
| 交互式应用      | SDXL Turbo     | 1-2 |
| 快速迭代       | SDXL Lightning | 2-4 |
| 使用自定义 LoRA | LCM-LoRA       | 4-8 |
| 最高质量       | SDXL Lightning | 8   |
| 低显存占用      | SD Turbo       | 1-2 |

## 成本估算

CLORE.AI 市场的典型费率：

| GPU           | 小时费率    | 每小时图像数（1 步） |
| ------------- | ------- | ----------- |
| RTX 3060 12GB | \~$0.03 | \~3,000     |
| RTX 3090 24GB | \~$0.06 | \~8,000     |
| RTX 4090 24GB | \~$0.10 | \~12,000    |
| A100 40GB     | \~$0.17 | \~15,000    |

*价格会有所不同。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

## 故障排查

### 模糊结果

* SDXL Turbo 原生输出 512x512
* 使用 SDXL Lightning 生成 1024x1024
* 添加放大后处理

### guidance\_scale 错误

```python
# SDXL Turbo：始终使用 0.0
image = pipe(prompt, guidance_scale=0.0).images[0]

# LCM：使用 1.0-2.0
image = pipe(prompt, guidance_scale=1.5).images[0]

# Lightning：使用 0.0
image = pipe(prompt, guidance_scale=0.0).images[0]
```

### LoRA 不起作用

```python
# 对于 LCM-LoRA，必须使用 LCMScheduler
from diffusers import LCMScheduler

pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
```

### 内存不足

```python
# 启用内存优化
pipe.enable_model_cpu_offload()
pipe.enable_vae_slicing()

# 或使用更小的模型
# 使用 SD Turbo 代替 SDXL Turbo
```

## 下一步

* [FLUX.1](/guides/guides_v2-zh/tu-xiang-sheng-cheng/flux.md) - 最高质量生成
* [Stable Diffusion WebUI](/guides/guides_v2-zh/tu-xiang-sheng-cheng/stable-diffusion-webui.md) - 完整 UI
* [ComfyUI](/guides/guides_v2-zh/tu-xiang-sheng-cheng/comfyui.md) - 基于节点的工作流
* [Real-ESRGAN](/guides/guides_v2-zh/tu-xiang-chu-li/real-esrgan-upscaling.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/sdxl-turbo.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.
