> 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/xun-lian/dreambooth.md).

# DreamBooth

在 Clore.ai GPU 上使用 DreamBooth 训练自定义图像模型

训练 Stable Diffusion 生成特定对象的图像。

{% 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>`

## 什么是 DreamBooth？

DreamBooth 会在你的图像上对 SD 进行微调：

* 使用 5-20 张图像训练
* 生成你的对象的新图像
* 任何风格或场景
* 适用于 SD 1.5 和 SDXL

## 需求

| 模型            | 显存   | 训练时间     |
| ------------- | ---- | -------- |
| SD 1.5        | 12GB | 15-30 分钟 |
| SDXL          | 24GB | 30-60 分钟 |
| SD 1.5 + LoRA | 8GB  | 10-20 分钟 |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
```

**端口：**

```
22/tcp
7860/http
```

**命令：**

```bash
pip install diffusers transformers accelerate bitsandbytes && \
pip install xformers peft && \
python dreambooth_train.py
```

## 访问你的服务

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

1. 前往 **我的订单** 页面
2. 点击你的订单
3. 找到 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 替代 `localhost` 在下面的示例中。

## 安装

```bash
pip install diffusers transformers accelerate
pip install bitsandbytes xformers peft
```

## 准备训练数据

1. 收集 5-20 张你的对象图像
2. 裁剪到人脸/对象
3. 调整大小为 512x512（SDXL 则为 1024x1024）
4. 如有需要，移除背景

```python
from PIL import Image
import os

def prepare_images(input_dir, output_dir, size=512):
    os.makedirs(output_dir, exist_ok=True)

    for filename in os.listdir(input_dir):
        if filename.endswith(('.jpg', '.png', '.jpeg')):
            img = Image.open(os.path.join(input_dir, filename))
            img = img.convert('RGB')

            # 居中裁剪为正方形
            min_dim = min(img.size)
            left = (img.width - min_dim) // 2
            top = (img.height - min_dim) // 2
            img = img.crop((left, top, left + min_dim, top + min_dim))

            # 调整大小
            img = img.resize((size, size), Image.LANCZOS)
            img.save(os.path.join(output_dir, filename))

prepare_images("./raw_photos", "./training_data")
```

## 带 LoRA 的 DreamBooth（推荐）

内存高效训练：

```python
from diffusers import StableDiffusionPipeline, DDPMScheduler
from diffusers.loaders import LoraLoaderMixin
import torch

# 训练脚本
from accelerate import Accelerator
from diffusers import AutoencoderKL, UNet2DConditionModel
from transformers import CLIPTextModel, CLIPTokenizer
from peft import LoraConfig, get_peft_model

# 加载模型
model_id = "runwayml/stable-diffusion-v1-5"
tokenizer = CLIPTokenizer.from_pretrained(model_id, subfolder="tokenizer")
text_encoder = CLIPTextModel.from_pretrained(model_id, subfolder="text_encoder")
vae = AutoencoderKL.from_pretrained(model_id, subfolder="vae")
unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")

# 向 UNet 添加 LoRA
lora_config = LoraConfig(
    r=8,
    lora_alpha=32,
    target_modules=["to_q", "to_k", "to_v", "to_out.0"],
    lora_dropout=0.1,
)

unet = get_peft_model(unet, lora_config)
```

## 使用 diffusers 训练脚本

```bash

# 克隆训练脚本
git clone https://github.com/huggingface/diffusers
cd diffusers/examples/dreambooth

# 安装依赖
pip install -r requirements.txt

# 使用 LoRA 训练
accelerate launch train_dreambooth_lora.py \
    --pretrained_model_name_or_path="runwayml/stable-diffusion-v1-5" \
    --instance_data_dir="./training_data" \
    --instance_prompt="a photo of sks person" \
    --output_dir="./dreambooth_model" \
    --resolution=512 \
    --train_batch_size=1 \
    --gradient_accumulation_steps=1 \
    --learning_rate=1e-4 \
    --lr_scheduler="constant" \
    --lr_warmup_steps=0 \
    --max_train_steps=500 \
    --seed=42
```

## 训练参数

| 参数                 | 推荐                     | 效果               |
| ------------------ | ---------------------- | ---------------- |
| learning\_rate     | 1e-4 到 5e-6            | 更高 = 更快，更低 = 更稳定 |
| max\_train\_steps  | 400-1000               | 更多 = 更好拟合        |
| train\_batch\_size | 1-2                    | 更高需要更多 VRAM      |
| 分辨率                | 512（SD1.5）/ 1024（SDXL） | 训练尺寸             |

## 实例提示词

选择一个独特标识符：

```bash

# 好的提示词
"一张 sks 人物的照片"      # sks = 独特 token
"一张 xyz 狗的照片"
"一张 abc 汽车的照片"

# 这个 token（sks、xyz、abc）应该是罕见的
```

## 带类别保持

防止过拟合：

```bash
accelerate launch train_dreambooth_lora.py \
    --pretrained_model_name_or_path="runwayml/stable-diffusion-v1-5" \
    --instance_data_dir="./my_dog_photos" \
    --instance_prompt="一张 sks 狗的照片" \
    --class_data_dir="./regular_dog_photos" \
    --class_prompt="一张狗的照片" \
    --with_prior_preservation \
    --prior_loss_weight=1.0 \
    --num_class_images=200 \
    --output_dir="./dreambooth_dog" \
    --max_train_steps=800
```

## SDXL DreamBooth

```bash
accelerate launch train_dreambooth_lora_sdxl.py \
    --pretrained_model_name_or_path="stabilityai/stable-diffusion-xl-base-1.0" \
    --instance_data_dir="./training_data" \
    --instance_prompt="a photo of sks person" \
    --output_dir="./dreambooth_sdxl" \
    --resolution=1024 \
    --train_batch_size=1 \
    --gradient_accumulation_steps=4 \
    --learning_rate=1e-4 \
    --max_train_steps=500 \
    --mixed_precision="fp16"
```

## 使用已训练模型

### 加载 LoRA

```python
from diffusers import StableDiffusionPipeline
import torch

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16
).to("cuda")

# 加载你训练好的 LoRA
pipe.load_lora_weights("./dreambooth_model")

# 生成
image = pipe(
    "一张 sks 人物穿着宇航员服在火星上的照片"，
    num_inference_steps=30,
    guidance_scale=7.5
).images[0]

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

### 完整微调

```python
pipe = StableDiffusionPipeline.from_pretrained(
    "./dreambooth_model",
    torch_dtype=torch.float16
).to("cuda")

image = pipe("一张 sks 人物穿着西装的照片").images[0]
```

## Gradio 界面

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

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16
).to("cuda")

pipe.load_lora_weights("./dreambooth_model")

def generate(prompt, negative_prompt, steps, guidance, 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,
        generator=generator
    ).images[0]

    return image

demo = gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label="提示词（为你的对象使用 'sks'）"),
        gr.Textbox(label="负面提示词", value="模糊，丑陋"),
        gr.Slider(20, 50, value=30, step=1, label="步数"),
        gr.Slider(5, 15, value=7.5, step=0.5, label="引导强度"),
        gr.Number(value=-1, label="种子")
    ],
    outputs=gr.Image(label="生成的图像"),
    title="DreamBooth 肖像生成器"
)

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

## 训练技巧

### 适用于人物

* 使用多种角度（正面、侧面、3/4 角）
* 不同的光照条件
* 各种表情
* 清晰、高分辨率照片

### 适用于物体

* 多个角度
* 不同背景
* 一致的光照
* 无遮挡

### 适用于风格

* 10-20 张示例图像
* 一致的艺术风格
* 该风格下的各种对象

## 故障排查

### 过拟合

* 降低 max\_train\_steps
* 降低 learning\_rate
* 使用先验保持
* 更多训练图像

### 欠拟合

* 增加 max\_train\_steps
* 提高 learning\_rate
* 更多训练图像
* 检查图像质量

### 风格未学到

* 提高 LoRA rank（r=16 或 32）
* 训练更久
* 使用更多示例

## 成本估算

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** 代币支付
* 比较不同提供商的价格

## 下一步

* [Kohya 训练](/guides/guides_v2-zh/xun-lian/kohya-training.md) - 高级训练
* Stable Diffusion WebUI - 使用模型
* [LoRA 微调](/guides/guides_v2-zh/xun-lian/kohya-training.md) - LLM 训练


---

# 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/xun-lian/dreambooth.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.
