> 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/sd-webui-forge.md).

# SD WebUI Forge

在 Clore.ai GPU 上部署具有优化 VRAM 管理和 FLUX 支持的 Stable Diffusion WebUI Forge

SD WebUI Forge 是经典 AUTOMATIC1111 Stable Diffusion WebUI 的一个优化分支，由 lllyasviel 团队开发。它在显存管理方面显著更好（可在 4 GB GPU 上运行 SDXL），原生支持 FLUX 模型，生成速度更快，并且与所有 A1111 扩展和模型完全向后兼容。CLORE.AI 灵活的 GPU 市场让你可以为 Forge 选择最合适的 GPU——从入门级显卡到顶级 A100。

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

## 服务器要求

| 参数  | 最低                   | 推荐                 |
| --- | -------------------- | ------------------ |
| 内存  | 8 GB                 | 16 GB+             |
| 显存  | 4 GB                 | 12 GB+             |
| 磁盘  | 30 GB                | 200 GB+            |
| GPU | NVIDIA GTX 1650 4GB+ | RTX 3090, RTX 4090 |

{% hint style="info" %}
Forge 的核心优势是显存优化器：它最少只需 4 GB 显存就能运行 SDXL（但速度较慢）。对于 FLUX 模型，12 GB 显存是实际最低要求，而要获得完整质量和速度则需要 24 GB。
{% endhint %}

## 在 CLORE.AI 上快速部署

**Docker 镜像：** `nykk3/stable-diffusion-webui-forge:latest`

**端口：** `22/tcp`, `7860/http`

**环境变量：**

| 变量                 | 示例                     | 描述            |
| ------------------ | ---------------------- | ------------- |
| `CLI_ARGS`         | `--xformers --medvram` | 额外 CLI 参数     |
| `COMMANDLINE_ARGS` | `--api --listen`       | 替代 CLI 参数环境变量 |

## 逐步设置

### 1. 在 CLORE.AI 上租用 GPU 服务器

前往 [CLORE.AI 市场](https://clore.ai/marketplace):

* **入门级 SD1.5**：GTX 1660/2060（6 GB）——足以应对 512/768 像素
* **可运行 SDXL**：RTX 3080/3090（10–24 GB）
* **可运行 FLUX**：RTX 4090/A6000（24+ GB）
* **最高质量**：用于批量生成的 A100 80GB

### 2. SSH 登录到你的服务器

```bash
ssh -p <PORT> root@<SERVER_IP>
```

### 3. 创建存储目录

```bash
mkdir -p /root/sd-forge/{models,outputs,extensions,configs}
mkdir -p /root/sd-forge/models/{Stable-diffusion,VAE,Lora,ControlNet,embeddings,ESRGAN}
```

### 4. 拉取并运行 SD WebUI Forge

**标准启动：**

```bash
docker run -d \\
  --name sd-forge \
  --gpus all \\
  -p 7860:7860 \
  -v /root/sd-forge/models:/app/stable-diffusion-webui/models \
  -v /root/sd-forge/outputs:/app/stable-diffusion-webui/outputs \
  -v /root/sd-forge/extensions:/app/stable-diffusion-webui/extensions \
  nykk3/stable-diffusion-webui-forge:latest
```

**启用 API 并添加额外性能标志：**

```bash
docker run -d \\
  --name sd-forge \
  --gpus all \\
  -p 7860:7860 \
  -v /root/sd-forge/models:/app/stable-diffusion-webui/models \
  -v /root/sd-forge/outputs:/app/stable-diffusion-webui/outputs \
  -v /root/sd-forge/extensions:/app/stable-diffusion-webui/extensions \
  -e CLI_ARGS="--api --xformers --enable-insecure-extension-access" \
  nykk3/stable-diffusion-webui-forge:latest
```

**低显存模式（4-6 GB GPU）：**

```bash
docker run -d \\
  --name sd-forge \
  --gpus all \\
  -p 7860:7860 \
  -v /root/sd-forge/models:/app/stable-diffusion-webui/models \
  -v /root/sd-forge/outputs:/app/stable-diffusion-webui/outputs \
  -e CLI_ARGS="--api --medvram-sdxl --opt-sdp-attention" \
  nykk3/stable-diffusion-webui-forge:latest
```

**最高性能（24+ GB 显存）：**

```bash
docker run -d \\
  --name sd-forge \
  --gpus all \\
  -p 7860:7860 \
  -v /root/sd-forge/models:/app/stable-diffusion-webui/models \
  -v /root/sd-forge/outputs:/app/stable-diffusion-webui/outputs \
  -e CLI_ARGS="--api --xformers --no-half-vae" \
  nykk3/stable-diffusion-webui-forge:latest
```

### 5. 监控启动过程

```bash
docker logs -f sd-forge
```

请留意：

```
正在本地 URL 上运行：  http://0.0.0.0:7860
```

首次运行时启动通常需要 2–5 分钟。

### 6. 访问网页界面

你的 CLORE.AI 用于端口 7860 的 http\_pub URL：

```
https://<order-id>-7860.clore.ai/
```

### 7. 添加模型

**方法 1：在网页界面中通过 CivitAI 下载**

* 前往 **扩展 → 已安装 → 模型** （某些版本）
* 或者在设置中使用 URL 下载器

**方法 2：直接在服务器上下载**

```bash
# 下载 SDXL 基础模型
cd /root/sd-forge/models/Stable-diffusion
wget -O "sd_xl_base_1.0.safetensors" \
  "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors"

# 下载 FLUX.1-schnell（快速 FLUX 模型）
wget -O "flux1-schnell.safetensors" \
  "https://huggingface.co/black-forest-labs/FLUX.1-schnell/resolve/main/flux1-schnell.safetensors"
```

**方法 3：HuggingFace CLI**

```bash
docker exec -it sd-forge bash -c "
pip install huggingface_hub
huggingface-cli download stabilityai/stable-diffusion-xl-base-1.0 \
  sd_xl_base_1.0.safetensors \
  --local-dir /app/stable-diffusion-webui/models/Stable-diffusion/
"
```

***

## 使用示例

### 示例 1：通过网页界面文生图

1. 在你的 CLORE.AI URL 中打开 Forge 界面
2. 从 **Checkpoint** 下拉菜单
3. 输入提示词： `"cinematic portrait of a warrior, golden hour, 8k photography"`
4. 设置负面提示词： `"blurry, low resolution, watermark, ugly"`
5. 设置宽度/高度： `1024x1024` 对于 SDXL， `512x768` 对于 SD1.5
6. 设置步数：20–30，CFG：7
7. 点击 **生成**

### 示例 2：FLUX 生成

FLUX 模型的工作方式不同——不使用负面提示词，质量更高：

1. 选择 FLUX 检查点（flux1-dev.safetensors）
2. 在 **Forge**，选择合适的 **Unet** 以及 **VAE** 如果是单独文件
3. 输入提示词（无需负面提示词）：

   ```
   夕阳下令人惊叹的风景，群山倒映在清澈如镜的湖中，
   写实风格，超高细节，专业摄影
   ```
4. 步数：20，CFG：1.0（FLUX 使用更低的 CFG）
5. 采样器： `Euler` 或 `DPM++ 2M`

### 示例 3：ControlNet 引导生成

1. 安装 ControlNet 扩展（如果尚未预装）：
   * 前往 **扩展 → 可用 → 从**
   * 搜索“ControlNet”并安装
2. 将 ControlNet 模型下载到 `/root/sd-forge/models/ControlNet/`
3. 在 txt2img 中展开 **ControlNet** 部分
4. 上传参考图像（姿势、深度、canny 边缘）
5. 选择与参考类型匹配的预处理器和模型
6. 生成——输出会遵循参考结构

### 示例 4：API 用法

使用 `--api` 标志，Forge 会暴露一个 REST API：

```python
import requests
import base64
import io
from PIL import Image

BASE_URL = "http://localhost:7860"  # 或 CLORE.AI 的 http_pub URL

# 文生图
payload = {
    "prompt": "a serene Japanese garden with cherry blossoms, watercolor style",
    "negative_prompt": "ugly, blurry, low quality",
    "steps": 25,
    "cfg_scale": 7,
    "width": 1024,
    "height": 1024,
    "sampler_name": "DPM++ 2M",
    "batch_size": 1,
}

response = requests.post(f"{BASE_URL}/sdapi/v1/txt2img", json=payload)
result = response.json()

# 保存图片
for i, img_b64 in enumerate(result["images"]):
    img_data = base64.b64decode(img_b64)
    img = Image.open(io.BytesIO(img_data))
    img.save(f"output_{i}.png")
    print(f"已保存 output_{i}.png")
```

### 示例 5：批量生成脚本

```python
import requests
import base64
import io
from PIL import Image
import os

BASE_URL = "http://localhost:7860"

prompts = [
    ("cyberpunk city at night, neon lights, rain", "cyberpunk"),
    ("ancient forest, mystical fog, fantasy art", "fantasy"),
    ("minimalist logo design, geometric shapes, white background", "logo"),
    ("portrait of an elderly sailor, weathered face, oil painting", "portrait"),
]

os.makedirs("batch_output", exist_ok=True)

for prompt_text, filename in prompts:
    print(f"正在生成：{filename}...")
    response = requests.post(
        f"{BASE_URL}/sdapi/v1/txt2img",
        json={
            "prompt": prompt_text,
            "negative_prompt": "low quality, blurry, watermark",
            "steps": 25,
            "cfg_scale": 7,
            "width": 1024,
            "height": 1024,
        },
    )
    
    if response.status_code == 200:
        img_b64 = response.json()["images"][0]
        img = Image.open(io.BytesIO(base64.b64decode(img_b64)))
        img.save(f"batch_output/{filename}.png")
        print(f"  已保存 batch_output/{filename}.png")
    else:
        print(f"  错误：{response.status_code}")
```

***

## 配置

### 关键 CLI 参数

| 参数                                   | 描述                         |
| ------------------------------------ | -------------------------- |
| `--api`                              | 启用 REST API                |
| `--listen`                           | 监听所有接口（CLORE.AI 需要）        |
| `--port 7860`                        | 更改端口                       |
| `--xformers`                         | 启用 xFormers 注意力机制（更快，显存更少） |
| `--medvram`                          | 中等显存模式（6GB 上运行 SD1.5）      |
| `--medvram-sdxl`                     | SDXL 的中等显存模式（8GB 上运行 SDXL） |
| `--lowvram`                          | 低显存模式（非常慢，适用于任何 GPU）       |
| `--no-half`                          | 使用 float32（更多显存，更稳定）       |
| `--no-half-vae`                      | 将 VAE 保持为 float32（防止黑图）    |
| `--opt-sdp-attention`                | PyTorch 缩放点积注意力            |
| `--enable-insecure-extension-access` | 允许安装扩展                     |
| `--skip-version-check`               | 跳过 Python/torch 版本检查       |

### Forge 特定设置

Forge 会在 **Forge** 面板中添加：

* **Forge Unet**：选择优化后端（默认、bnb 等）
* **Diffusers Torch 编译**：启用后生成速度可提高 20-30%（首次运行会编译）
* **GPU 权重**：在 GPU 与 CPU 之间保留多少

***

## 性能提示

### 1. 使用 xFormers 减少 20-30% 显存占用

```bash
--xformers
```

会自动在大多数 GPU 上提升性能。

### 2. Forge 的显存优化器

Forge 的显存管理自动优于 A1111。只需使用 `--medvram-sdxl` 标志在 8-12 GB GPU 上运行 SDXL，并让它处理其余部分。

### 3. 启用 Torch 编译（Ampere+）

在 UI 的 Forge 选项卡中，启用 **Diffusers Torch 编译**。第一次生成需要 2-3 分钟进行编译，但后续生成会快 20-30%。

### 4. 最佳步数/采样器组合

| 目标   | 采样器                | 步数    | CFG |
| ---- | ------------------ | ----- | --- |
| 速度   | `DPM++ SDE Karras` | 15-20 | 7   |
| 质量   | `DPM++ 2M Karras`  | 25-35 | 7   |
| 艺术风格 | `Euler a`          | 20-30 | 5-7 |
| FLUX | `Euler`            | 20    | 1   |

### 5. 对 2K+ 分辨率使用 Tile VAE

对于超高分辨率（2048×2048+），启用 **分块 VAE** 以防止 VAE OOM 错误。

### 6. 使用 API 本地批量生成

不要在 UI 中一次生成一张，而是使用带有 `batch_size` 的 API，以获得更高吞吐量：

```python
payload = {
    "prompt": "...",
    "batch_size": 4,  # 一次生成 4 张图像
    "n_iter": 2,      # 运行 2 次迭代 = 共 8 张图像
}
```

***

## 故障排查

### 问题：黑图或绿图

VAE 精度问题。添加标志：

```bash
--no-half-vae
```

或者使用 `sdxl-vae-fp16-fix.safetensors` VAE。

### 问题：“CUDA out of memory”

请按以下顺序尝试：

1. `--medvram-sdxl` （用于 SDXL）
2. `--medvram` （用于 SD1.5）
3. 降低图像分辨率
4. `--lowvram` （最后手段，非常慢）

### 问题：扩展未加载

```bash
# 允许扩展访问
-e CLI_ARGS="--enable-insecure-extension-access"
```

然后在 UI 的扩展选项卡中安装。

### 问题：启动时间太长

首次运行时属于正常情况——会计算 PyTorch 和模型哈希。后续启动会更快。

```bash
docker logs -f sd-forge  # 查看进度
```

### 问题：无法在浏览器中访问 UI

确保 Forge 进程绑定到 `0.0.0.0`:

* 在 `--listen` 加入到 CLI\_ARGS 中
* 确认 7860 端口已在你的 CLORE.AI 订单端口列表中

### 问题：模型没有显示在下拉菜单中

在放入 `.safetensors` 文件到正确文件夹后，点击 **🔄 刷新** 按钮，位于 Checkpoint 下拉菜单旁边。

***

## 链接

* [GitHub（Forge）](https://github.com/lllyasviel/stable-diffusion-webui-forge)
* [GitHub（A1111 基础版）](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
* [Docker Hub（nykk3）](https://hub.docker.com/r/nykk3/stable-diffusion-webui-forge)
* [CivitAI（模型）](https://civitai.com)
* [FLUX 模型](https://huggingface.co/black-forest-labs)
* [CLORE.AI 市场](https://clore.ai/marketplace)

***

## Clore.ai GPU 推荐

| 使用场景  | 推荐 GPU         | Clore.ai 预计成本                     |
| ----- | -------------- | --------------------------------- |
| 开发/测试 | RTX 3090（24GB） | $0.07–0.21/gpu/hr                 |
| 生产环境  | RTX 4090（24GB） | $0.14–0.42/gpu/hr                 |
| 大规模   | A100 80GB      | [裸机](https://clore.ai/bare-metal) |

> 💡 本指南中的所有示例都可以部署在 [Clore.ai](https://clore.ai/marketplace) GPU 服务器上。浏览可用 GPU 并按小时租用——无需承诺，拥有完整 root 访问权限。


---

# 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/sd-webui-forge.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.
