# Stable Diffusion WebUI

在 CLORE.AI GPU 上最受欢迎的 Stable Diffusion 网页界面。

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

## 服务器要求

| 参数       | 最低       | 推荐     |
| -------- | -------- | ------ |
| 内存 (RAM) | 16GB     | 32GB+  |
| 显存       | 8GB      | 12GB+  |
| 网络       | 500Mbps  | 1Gbps+ |
| 启动时间     | 10-20 分钟 | -      |

{% hint style="warning" %}
**启动时间：** 首次启动会安装 Python 依赖并下载基础模型（根据网络速度需 10-20 分钟）。此期间出现 HTTP 502 是正常的。
{% endhint %}

## 为什么选择 SD WebUI？

* **功能丰富** - txt2img、img2img、修复（inpainting）、扩展画布（outpainting）
* **扩展** - 大量插件生态系统
* **用户友好** - 直观的网页界面
* **文档完善** - 庞大的社区支持

> 📚 另见： [如何在云 GPU 上运行 Stable Diffusion](https://blog.clore.ai/how-to-run-stable-diffusion-cloud-gpu/)

## 在 CLORE.AI 上快速部署

**Docker 镜像：**

```
universonic/stable-diffusion-webui:latest
```

**端口：**

```
22/tcp
8080/http
```

**命令：**

```bash
./webui.sh --listen --xformers
```

### 验证是否正常工作

部署后，找到你的 `http_pub` URL 在 **我的订单 (My Orders)**:

```bash
# 检查 UI 是否可访问（首次运行可能需 10-20 分钟）
curl https://your-http-pub.clorecloud.net/
```

{% hint style="info" %}
如果 HTTP 502 超过 20 分钟，请检查：

1. 服务器有 16GB+ 内存
2. 服务器有 8GB+ 显存 (VRAM)
3. 网络速度足以下载依赖项
   {% endhint %}

## 访问你的服务

部署在 CLORE.AI 上时，通过以下方式访问 SD WebUI `http_pub` URL：

* **网页界面：** `https://your-http-pub.clorecloud.net/`
* **API（如果启用）：** `https://your-http-pub.clorecloud.net/sdapi/v1/`

{% hint style="info" %}
全部 `localhost:7860` 下面的示例在通过 SSH 连接时可用。若需外部访问，请将其替换为你的 `https://your-http-pub.clorecloud.net/` URL。
{% endhint %}

## 安装

### 使用 Docker（推荐）

```bash
docker run -d --gpus all \
    -p 8080:8080 \
    -v sd-webui-data:/app/stable-diffusion-webui \
    universonic/stable-diffusion-webui:latest
```

### 手动安装

```bash
# 安装依赖
sudo apt install python3.10 python3.10-venv git wget

# 克隆仓库
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
cd stable-diffusion-webui

# 运行（会自动安装所有内容）
./webui.sh --listen --xformers
```

## 目录结构

```
stable-diffusion-webui/
├── models/
│   ├── Stable-diffusion/   # 主要模型 (.safetensors)
│   ├── Lora/               # LoRA 模型
│   ├── VAE/                # VAE 模型
│   ├── ControlNet/         # ControlNet 模型
│   └── ESRGAN/             # 放大器（Upscalers）
├── embeddings/             # 文本反演（Textual inversions）
├── extensions/             # 已安装的扩展
├── outputs/                # 生成的图像
└── scripts/                # 自定义脚本
```

## 下载模型

### 检查点

```bash
cd models/Stable-diffusion

# SD 1.5
wget https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned.safetensors

# SDXL
wget https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors

# Realistic Vision（真实感）
wget "https://civitai.com/api/download/models/245598" -O realisticVision_v60B1.safetensors

# DreamShaper（艺术风）
wget "https://civitai.com/api/download/models/351306" -O dreamshaper_8.safetensors
```

### VAE（更佳色彩）

```bash
cd models/VAE

# SD 1.5 VAE
wget https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.safetensors

# SDXL VAE
wget https://huggingface.co/stabilityai/sdxl-vae/resolve/main/sdxl_vae.safetensors
```

## 基本用法

### txt2img（文本到图像）

1. 从下拉菜单选择模型
2. 在正向提示 (positive prompt) 中输入：你想要的内容
3. 在负向提示 (negative prompt) 中输入：要避免的内容
4. 设置尺寸（SD1.5 使用 512x512，SDXL 使用 1024x1024）
5. 点击生成

### img2img（图像到图像）

1. 转到 img2img 选项卡
2. 上传源图像
3. 输入描述所需更改的提示
4. 调整 **去噪强度** (0.3-0.8)
5. 生成

### 修复（Inpainting）

1. 转到 img2img → Inpaint
2. 上传图像
3. 在要更改的区域上绘制掩码
4. 为被掩盖区域输入提示
5. 生成

## 必要设置

### 生成设置

| 设置                 | SD 1.5          | SDXL            |
| ------------------ | --------------- | --------------- |
| 宽度                 | 512             | 1024            |
| 高度                 | 512             | 1024            |
| 步数 (Steps)         | 20-30           | 20-40           |
| CFG 缩放 (CFG Scale) | 7               | 5-7             |
| 采样器 (Sampler)      | DPM++ 2M Karras | DPM++ 2M Karras |

### 命令行参数

```bash
./webui.sh \
    --listen \              # 允许外部访问
    --port 7860 \           # 端口号
    --xformers \            # 内存优化
    --enable-insecure-extension-access \  # 允许扩展
    --api \                 # 启用 API
    --no-half-vae           # 修复黑图像问题
```

### 针对低显存

```bash
./webui.sh \
    --listen \
    --medvram \           # 6-8GB 显存
    # 或
    --lowvram \           # 4GB 显存
    --xformers
```

## 流行扩展

### 必备

| 扩展                        | 用途               |
| ------------------------- | ---------------- |
| ControlNet                | 引导生成             |
| ADetailer                 | 自动修复人脸/手部        |
| Ultimate SD Upscale       | 更好的放大效果          |
| sd-webui-segment-anything | 分割（Segmentation） |
| Regional Prompter         | 多区域提示            |

### 安装扩展

1. 转到 **扩展** 选项卡
2. 点击 **可用**
3. 点击 **从加载 (Load from)**
4. 搜索并安装
5. 应用并重启界面

或手动：

```bash
cd extensions
git clone https://github.com/Mikubill/sd-webui-controlnet.git
```

## ControlNet

### 安装

```bash
# 安装扩展
cd extensions
git clone https://github.com/Mikubill/sd-webui-controlnet.git

# 下载模型
cd ../models/ControlNet
wget https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_canny.pth
wget https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_openpose.pth
wget https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11f1p_sd15_depth.pth
```

### 使用方法

1. 展开 ControlNet 部分
2. 上传控制图像
3. 选择预处理器（Canny、OpenPose 等）
4. 选择与预处理器匹配的模型
5. 生成

## API 使用

通过以下方式启用 `--api` 标志，然后：

```python
import requests
import base64

# 对于外部访问，请使用你的 http_pub URL：
API_URL = "https://your-http-pub.clorecloud.net"
# 或通过 SSH： API_URL = "http://localhost:7860"

def txt2img(prompt, negative="", steps=20, width=512, height=512):
    response = requests.post(
        f"{API_URL}/sdapi/v1/txt2img",
        json={
            "prompt": prompt,
            "negative_prompt": negative,
            "steps": steps,
            "width": width,
            "height": height,
        }
    )
    return base64.b64decode(response.json()["images"][0])

# 生成并保存
image_data = txt2img("A beautiful sunset over mountains")
with open("output.png", "wb") as f:
    f.write(image_data)
```

### img2img API

```python
import base64

def img2img(prompt, image_path, denoising=0.5):
    with open(image_path, "rb") as f:
        image_b64 = base64.b64encode(f.read()).decode()

    response = requests.post(
        f"{API_URL}/sdapi/v1/img2img",
        json={
            "prompt": prompt,
            "init_images": [image_b64],
            "denoising_strength": denoising,
            "steps": 30,
        }
    )
    return base64.b64decode(response.json()["images"][0])
```

## 提示词撰写

### 基本结构

```
[主体], [风格], [细节], [光照], [质量标签]
```

### 示例提示词

```
# 人像
一位年轻女子的肖像，专业摄影，
柔和光线，浅景深，8k 超高清，
高度细节化，照片级真实感

# 风景
日落时分壮丽的山地风光，戏剧性云层，
黄金时段光线，国家地理风格，
8k 壁纸，高度细节化

# 二次元 / 动漫
1girl，银发，蓝眼睛，校服，
樱花，春天，杰作，最佳质量
```

### 负向提示词

```
# 通用
低分辨率、解剖结构差、手部差、文字、错误、
缺失手指、裁剪、最差质量、低质量、
jpeg 压缩痕迹、签名、水印、模糊

# 对于真实感
卡通、动漫、插画、绘画、素描、
3D 渲染、CGI
```

## 性能优化建议

1. **启用 xFormers** - 显著的速度提升
2. **使用 VAE** - 更好的色彩表现
3. **批量大小设为 1** - 适用于显存有限的情况
4. **高分辨率修复（Hires Fix）** - 先生成小图，然后放大
5. **ADetailer** - 自动修复人脸

## GPU 要求

| 模型              | 最低显存 (VRAM) | 推荐显存 | 最低内存 (RAM) |
| --------------- | ----------- | ---- | ---------- |
| SD 1.5          | 4GB         | 8GB  | 16GB       |
| SD 2.1          | 6GB         | 8GB  | 16GB       |
| SDXL            | 8GB         | 12GB | 16GB       |
| 使用 ControlNet 时 | +2GB        | +4GB | 16GB       |

## GPU 预设

### RTX 3060 12GB（预算）

```bash
# 启动命令
./webui.sh --medvram --xformers

# 推荐的 settings.json：
# - SD 1.5：512x512，batch 4，20-30 步
# - SDXL：768x768，batch 1，20 步
# - 在设置中启用 VAE 平铺（tiling）
# - 对人脸使用 ADetailer
```

**最佳模型：** SD 1.5、DreamShaper、RealisticVision

### RTX 3090 24GB（最优）

```bash
# 启动命令
./webui.sh --xformers

# 推荐设置：
# - SD 1.5：512x512，batch 8，30 步
# - SDXL：1024x1024，batch 2，30 步
# - ControlNet + SD 1.5 配合良好
# - Hires 修复到 2x 有效
```

**最佳模型：** SDXL、Juggernaut、RealVisXL

### RTX 4090 24GB（性能）

```bash
# 启动命令
./webui.sh --xformers --opt-sdp-attention

# 推荐设置：
# - SD 1.5：512x512，batch 16，30 步
# - SDXL：1024x1024，batch 4，40 步
# - 多个 ControlNet 同时使用
# - Hires 修复到 4x
```

**最佳模型：** SDXL、Pony Diffusion、任何高分辨率模型

### A100 40GB/80GB（生产）

```bash
# 启动命令
./webui.sh --opt-sdp-attention --no-half-vae

# 推荐设置：
# - SDXL：1024x1024，batch 8+，50 步
# - 多个 ControlNet + IP-Adapter
# - Hires 修复到 4096x4096
# - 使用 AnimateDiff 生成视频
```

**最佳适用：** 适合批量生成、复杂工作流、视频

## 费用估算

典型 CLORE.AI 市场费率：

| GPU      | 显存   | 价格/天       | SD1.5 速度 | SDXL 速度 |
| -------- | ---- | ---------- | -------- | ------- |
| RTX 3060 | 12GB | $0.15–0.30 | 约 4 秒    | 约 12 秒  |
| RTX 3090 | 24GB | $0.30–1.00 | 约 2 秒    | 约 6 秒   |
| RTX 4090 | 24GB | $0.50–2.00 | 约 1 秒    | 约 3 秒   |
| A100     | 40GB | $1.50–3.00 | 约 0.5 秒  | 约 2 秒   |

*价格以美元/天计。费率随供应商而异——请检查* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

## 故障排除

### 长时间出现 HTTP 502

1. **检查内存（RAM）：** 服务器必须有 16GB+ 内存
2. **检查显存（VRAM）：** SDXL 需要至少 8GB
3. **依赖项正在安装：** 首次运行需要 10-20 分钟
4. **网络缓慢：** 低带宽会导致更长的启动时间

### 黑图像问题

```bash
# 添加到启动参数
--no-half-vae
```

### 内存不足 (OOM)

```bash
# 使用优化
--medvram
--xformers
```

### 扩展未加载

```bash
--enable-insecure-extension-access
```

### 生成缓慢

1. 启用 xFormers
2. 减小图像尺寸
3. 降低步数（20 步通常足够）

## 下一步

* [ComfyUI](https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-sheng-cheng/comfyui) - 更高级的工作流
* [FLUX.1](https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-sheng-cheng/flux) - 最新模型
* [ControlNet](https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-chu-li/controlnet-advanced) - 引导生成
* [LoRA 训练](https://docs.clore.ai/guides/guides_v2-zh/xun-lian/kohya-training) - 定制模型


---

# 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/stable-diffusion-webui.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.
