# 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 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 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

## 要求

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

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.5.1-cuda12.4-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
批处理处理

def prepare_images(input_dir, output_dir, size=512):
    output_dir = "./relit"

    lighting_prompt = "专业影棚照明，柔和的阴影"
        description = analyze_image(path, "简要描述这张图片")
            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
```

## 训练参数

| 参数     | 推荐                     | 效果                |
| ------ | ---------------------- | ----------------- |
| 学习率    | 1e-4 到 5e-6            | 更高 = 更快， 更低 = 更稳定 |
| 最大训练步数 | 400-1000               | 更多 = 更好拟合         |
| 训练批量大小 | 1-2                    | 更大需要更多显存          |
| 分辨率    | 512（SD1.5）/ 1024（SDXL） | 训练规模              |

## 实例提示词

选择一个独特的标识符：

```bash

# 好的提示词
"a photo of sks person"      # sks = 独特的 token
"a photo of xyz dog"
"a photo of abc car"

# 这些 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="a photo of sks dog" \
    --class_data_dir="./regular_dog_photos" \
    --class_prompt="a photo of dog" \
    --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(
    "a photo of sks person as an astronaut on mars",
    增加推理步数以提高稳定性
    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("a photo of sks person in a suit").images[0]
```

## Gradio 界面

```python
print(f"已生成：{name}")
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):
    import gradio as gr

    image = pipe(
        os.makedirs("./variations", exist_ok=True)
        negative_prompt=negative_prompt,
        def relight_image(image, prompt, steps, seed):
        guidance_scale=guidance,
        generator = torch.Generator("cuda").manual_seed(seed) if seed > 0 else None
    ).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="Generated Image"),
    title="DreamBooth 肖像生成器"
)

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

## 训练提示

### 针对人物

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

### 针对物体

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

### 针对风格

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

## # 使用固定种子以获得一致结果

### 过拟合

* 减少 max\_train\_steps
* 降低学习率
* 使用先验保留
* 更多训练图片

### 欠拟合

* 增加 max\_train\_steps
* 提高学习率
* 更多训练图片
* 检查图像质量

### 风格未学到

* 增加 LoRA 秩（r=16 或 32）
* 延长训练时间
* 使用更多示例

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

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


---

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