> 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/kohya-training.md).

# Kohya 训练

在 Clore.ai 上使用 Kohya 训练 Stable Diffusion 的 LoRA 和 DreamBooth

使用 Kohya 的训练器训练 Stable Diffusion 的 LoRA、Dreambooth 和完整微调。

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

## 什么是 Kohya？

Kohya\_ss 是一个训练工具包，适用于：

* **LoRA** - 轻量级适配器（最受欢迎）
* **Dreambooth** - 主体/风格训练
* **完整微调** - 完整模型训练
* **LyCORIS** - 高级 LoRA 变体

## 需求

| 训练类型              | 最低显存 | 推荐       |
| ----------------- | ---- | -------- |
| LoRA SD 1.5       | 6GB  | RTX 3060 |
| LoRA SDXL         | 12GB | RTX 3090 |
| Dreambooth SD 1.5 | 12GB | RTX 3090 |
| Dreambooth SDXL   | 24GB | RTX 4090 |

## 快速部署

**Docker 镜像：**

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

**端口：**

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

**命令：**

```bash
apt-get update && apt-get install -y git libgl1 libglib2.0-0 && \\
cd /workspace && \
git clone https://github.com/bmaltais/kohya_ss.git && \
cd kohya_ss && \
pip install -r requirements.txt && \
pip install xformers && \
python kohya_gui.py --listen 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` 在下面的示例中。

## 使用 Web UI

1. 访问地址： `http://<proxy>:<port>`
2. 选择训练类型（LoRA、Dreambooth 等）
3. 配置设置
4. 开始训练

## 数据集准备

### 文件夹结构

```
/workspace/dataset/
├── 10_mysubject/           # 重复次数_概念名称
│   ├── image1.png
│   ├── image1.txt          # 标注文件
│   ├── image2.png
│   └── image2.txt
└── 10_regularization/      # 可选的正则化图像
    ├── reg1.png
    └── reg1.txt
```

### 图像要求

* **分辨率：** 512x512（SD 1.5）或 1024x1024（SDXL）
* **格式：** PNG 或 JPG
* **数量：** LoRA 需要 10-50 张图像
* **质量：** 清晰、光线充足、角度多样

### 标注文件

创建 `.txt` 与图像同名的文件：

**myimage.txt：**

```
一张 sks 人物的照片，专业肖像，棚拍灯光，高质量
```

### 自动标注

使用 BLIP 自动生成标注：

```python
from transformers import BlipProcessor, BlipForConditionalGeneration
from PIL import Image
import os

processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cuda")

for img_file in os.listdir("./images"):
    if img_file.endswith(('.png', '.jpg')):
        image = Image.open(f"./images/{img_file}")
        inputs = processor(image, return_tensors="pt").to("cuda")
        output = model.generate(**inputs, max_new_tokens=50)
        caption = processor.decode(output[0], skip_special_tokens=True)

        txt_file = img_file.rsplit('.', 1)[0] + '.txt'
        with open(f"./images/{txt_file}", 'w') as f:
            f.write(caption)
```

## LoRA 训练（SD 1.5）

### 配置

**在 Kohya UI 中：**

| 设置       | 数值                             |
| -------- | ------------------------------ |
| 模型       | runwayml/stable-diffusion-v1-5 |
| 网络秩      | 32-128                         |
| 网络 Alpha | 16-64                          |
| 学习率      | 1e-4                           |
| 批大小      | 1-4                            |
| 轮数       | 10-20                          |
| 优化器      | AdamW8bit                      |

### 命令行训练

```bash
accelerate launch --num_cpu_threads_per_process=2 train_network.py \
    --pretrained_model_name_or_path="runwayml/stable-diffusion-v1-5" \
    --train_data_dir="/workspace/dataset" \
    --output_dir="/workspace/output" \
    --output_name="my_lora" \
    --resolution=512 \
    --train_batch_size=1 \
    --max_train_epochs=10 \
    --learning_rate=1e-4 \
    --network_module=networks.lora \
    --network_dim=32 \
    --network_alpha=16 \
    --mixed_precision=fp16 \
    --save_precision=fp16 \
    --optimizer_type=AdamW8bit \
    --lr_scheduler=cosine \
    --cache_latents \
    --xformers \
    --save_every_n_epochs=2
```

## LoRA 训练（SDXL）

```bash
accelerate launch train_network.py \
    --pretrained_model_name_or_path="stabilityai/stable-diffusion-xl-base-1.0" \
    --train_data_dir="/workspace/dataset" \
    --output_dir="/workspace/output" \
    --output_name="my_sdxl_lora" \
    --resolution=1024 \
    --train_batch_size=1 \
    --max_train_epochs=10 \
    --learning_rate=1e-4 \
    --network_module=networks.lora \
    --network_dim=32 \
    --network_alpha=16 \
    --mixed_precision=bf16 \
    --save_precision=fp16 \
    --optimizer_type=Adafactor \
    --cache_latents \
    --xformers \
    --save_every_n_epochs=2
```

## Dreambooth 训练

### 主体训练

```bash
accelerate launch train_dreambooth.py \
    --pretrained_model_name_or_path="runwayml/stable-diffusion-v1-5" \
    --instance_data_dir="/workspace/dataset/instance" \
    --class_data_dir="/workspace/dataset/class" \
    --output_dir="/workspace/output" \
    --instance_prompt="a photo of sks person" \
    --class_prompt="a photo of person" \
    --with_prior_preservation \
    --prior_loss_weight=1.0 \
    --num_class_images=200 \
    --resolution=512 \
    --train_batch_size=1 \
    --learning_rate=2e-6 \
    --max_train_steps=1000 \
    --mixed_precision=fp16 \
    --gradient_checkpointing
```

### 风格训练

```bash
accelerate launch train_dreambooth.py \
    --pretrained_model_name_or_path="runwayml/stable-diffusion-v1-5" \
    --instance_data_dir="/workspace/dataset/style" \
    --output_dir="/workspace/output" \
    --instance_prompt="painting in the style of xyz" \
    --resolution=512 \
    --train_batch_size=1 \
    --learning_rate=5e-6 \
    --max_train_steps=2000 \
    --mixed_precision=fp16
```

## 训练技巧

### 最佳设置

| 参数       | 人物/角色  | 风格    | 物体    |
| -------- | ------ | ----- | ----- |
| 网络秩      | 64-128 | 32-64 | 32    |
| 网络 Alpha | 32-64  | 16-32 | 16    |
| 学习率      | 1e-4   | 5e-5  | 1e-4  |
| 轮数       | 15-25  | 10-15 | 10-15 |

### 避免过拟合

* 使用正则化图像
* 降低学习率
* 减少轮次
* 提高网络 alpha

### 避免欠拟合

* 更多训练图像
* 更高学习率
* 更多轮次
* 降低网络 alpha

## 监控训练

### TensorBoard

```bash
tensorboard --logdir /workspace/output/logs --port 6006 --bind_all
```

### 关键指标

* **loss** - 应该下降然后稳定
* **lr** - 学习率调度
* **轮次** - 训练进度

## 测试你的 LoRA

### 使用 Automatic1111

将 LoRA 复制到：

```
stable-diffusion-webui/models/Lora/my_lora.safetensors
```

在提示词中使用：

```
<lora:my_lora:0.8> 一张 sks 人物的照片
```

### 使用 ComfyUI

加载 LoRA 节点并连接到模型。

### 使用 Diffusers

```python
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("/workspace/output/my_lora.safetensors")

image = pipe("一张 sks 人物的照片，专业肖像").images[0]
```

## 高级训练

### LyCORIS（LoHa、LoKR）

```bash
accelerate launch train_network.py \
    --network_module=lycoris.kohya \
    --network_args "algo=loha" "conv_dim=4" "conv_alpha=2" \
    ...
```

### 文本反演

```bash
accelerate launch train_textual_inversion.py \
    --pretrained_model_name_or_path="runwayml/stable-diffusion-v1-5" \
    --train_data_dir="/workspace/dataset" \
    --learnable_property="style" \
    --placeholder_token="<my-style>" \
    --initializer_token="art" \
    --resolution=512 \
    --train_batch_size=1 \
    --max_train_steps=3000 \
    --learning_rate=5e-4
```

## 保存与导出

### 下载训练好的模型

```bash
scp -P <port> root@<proxy>:/workspace/output/my_lora.safetensors ./
```

### 转换格式

```python

# SafeTensors 转 PyTorch
from safetensors.torch import load_file, save_file
import torch

state_dict = load_file("model.safetensors")
torch.save(state_dict, "model.pt")
```

## 成本估算

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

## FLUX LoRA 训练

为 FLUX.1-dev 和 FLUX.1-schnell 训练 LoRA 适配器——新一代扩散 Transformer 模型，质量更高。

### 显存要求

| 模型                | 最低显存  | 推荐 GPU          |
| ----------------- | ----- | --------------- |
| FLUX.1-schnell    | 16GB  | RTX 4080 / 3090 |
| FLUX.1-dev        | 24GB  | RTX 4090        |
| FLUX.1-dev (bf16) | 40GB+ | A100 40GB       |

> **注意：** FLUX 使用 DiT（Diffusion Transformer）架构——其训练动态与 SD 1.5 / SDXL 有显著不同。

### FLUX 安装

安装支持 CUDA 12.8 的 PyTorch：

```bash
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128
pip install xformers --index-url https://download.pytorch.org/whl/cu128
pip install -r requirements.txt
pip install accelerate sentencepiece protobuf
```

### FLUX LoRA 配置（flux\_lora.toml）

```toml
[general]
shuffle_caption = false
caption_extension = ".txt"
keep_tokens = 1

[datasets]
[[datasets.subsets]]
image_dir = "/workspace/dataset/train"
caption_extension = ".txt"
num_repeats = 5
resolution = [512, 512]

[training]
pretrained_model_name_or_path = "black-forest-labs/FLUX.1-dev"
output_dir = "/workspace/output"
output_name = "my_flux_lora"

# FLUX 特定：使用 bf16（不是 fp16——FLUX 需要 bf16）
mixed_precision = "bf16"
save_precision = "bf16"
full_bf16 = true

train_batch_size = 1
max_train_epochs = 20
gradient_checkpointing = true
gradient_accumulation_steps = 4

# FLUX LoRA 参数——学习率要低于 SDXL！
learning_rate = 1e-4
lr_scheduler = "cosine_with_restarts"
lr_warmup_steps = 100

# 网络配置
network_module = "networks.lora_flux"
network_dim = 16           # FLUX：更小的维度效果很好（16-64）
network_alpha = 16         # 设为与 network_dim 相同

# FLUX 特定选项
t5xxl_max_token_length = 512
apply_t5_attn_mask = true

# 优化器——Adafactor 在 FLUX 上表现很好
optimizer_type = "adafactor"
optimizer_args = ["scale_parameter=False", "relative_step=False", "warmup_init=False"]

# 节省显存
cache_latents = true
cache_latents_to_disk = true
cache_text_encoder_outputs = true
cache_text_encoder_outputs_to_disk = true

# 训练期间采样（可选预览）
sample_every_n_epochs = 5
sample_prompts = "/workspace/sample_prompts.txt"
```

### FLUX LoRA 训练命令

```bash
# 单 GPU
accelerate launch train_network.py \
    --config_file flux_lora.toml \
    --network_module networks.lora_flux \
    --network_dim 16 \
    --network_alpha 16 \
    --mixed_precision bf16 \\
    --full_bf16

# 使用显式参数（无 toml）
accelerate launch train_network.py \
    --pretrained_model_name_or_path "black-forest-labs/FLUX.1-dev" \
    --train_data_dir "/workspace/dataset" \
    --output_dir "/workspace/output" \
    --output_name "my_flux_lora" \
    --network_module networks.lora_flux \
    --network_dim 16 \
    --network_alpha 16 \
    --learning_rate 1e-4 \
    --max_train_epochs 20 \
    --train_batch_size 1 \
    --gradient_accumulation_steps 4 \
    --mixed_precision bf16 \\
    --full_bf16 \
    --optimizer_type adafactor \
    --cache_latents \
    --cache_text_encoder_outputs \
    --t5xxl_max_token_length 512 \
    --apply_t5_attn_mask \
    --save_every_n_epochs 5
```

### FLUX 与 SDXL：主要区别

| 参数   | SDXL          | FLUX.1              |
| ---- | ------------- | ------------------- |
| 学习率  | 1e-3 到 1e-4   | **1e-4 到 5e-5**     |
| 精度   | fp16 或 bf16   | **必须使用 bf16**       |
| 网络模块 | networks.lora | networks.lora\_flux |
| 网络维度 | 32–128        | 8–64（更小）            |
| 优化器  | AdamW8bit     | Adafactor           |
| 最低显存 | 12GB          | 16–24GB             |
| 架构   | U-Net         | DiT（Transformer）    |

### FLUX 学习率指南

```toml
# 保守（更安全，过拟合风险更低）
learning_rate = 5e-5

# 标准（良好的起点）
learning_rate = 1e-4

# 激进（表达能力更强，但有伪影风险）
learning_rate = 2e-4
```

> **提示：** FLUX 对学习率比 SDXL 更敏感。起始值设为 `1e-4` 并降低到 `5e-5` 如果你看到质量问题。对于 SDXL， `1e-3` 很常见——FLUX 请避免使用。

### 测试 FLUX LoRA

```python
import torch
from diffusers import FluxPipeline

pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    torch_dtype=torch.bfloat16,
).to("cuda")

# 加载你训练好的 LoRA
pipe.load_lora_weights("/workspace/output/my_flux_lora.safetensors")

image = pipe(
    prompt="一张 sks 人物的照片，专业肖像，棚拍灯光",
    num_inference_steps=28,
    guidance_scale=3.5,
    width=1024,
    height=1024,
).images[0]

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

***

## 故障排查

### 显存溢出错误

* 将批次大小降为 1
* 启用梯度检查点
* 使用 8 位优化器
* 降低分辨率

### 结果不佳

* 更多/更好的训练图像
* 调整学习率
* 检查标注是否与图像匹配
* 尝试不同的网络秩

### 训练崩溃

* 检查 CUDA 版本
* 更新 xformers
* 减小批量大小
* 检查磁盘空间

### FLUX 特定问题

* **“不支持 bf16”** — 使用 A 系列（Ampere 及以上）或 RTX 30/40 系列 GPU
* **FLUX.1-dev 上出现 OOM** — 切换到 FLUX.1-schnell（需要 16GB）或启用 `cache_text_encoder_outputs`
* **模糊结果** — 增加 `network_dim` 到 32–64，将学习率降低到 `5e-5`
* **NaN 损失** — 禁用 `full_bf16`，检查你的数据集中是否有损坏的图像


---

# 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/kohya-training.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.
