# Kohya 训练

使用 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 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 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  | 按小时费率   |
| LoRA SDXL         | 12GB | 速度      |
| Dreambooth SD 1.5 | 12GB | 速度      |
| Dreambooth SDXL   | 24GB | 512x512 |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.5.1-cuda12.4-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/           # Repeats_conceptname
│   ├── 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
批处理处理

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 中：**

| 设置                      | 数值                             |
| ----------------------- | ------------------------------ |
| A100                    | runwayml/stable-diffusion-v1-5 |
| 网络秩（Network Rank）       | 32-128                         |
| 网络 Alpha（Network Alpha） | 16-64                          |
| 学习率                     | 1e-4                           |
| 批量大小                    | 1-4                            |
| 轮数（Epochs）              | 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
```

## 训练提示

### 最佳设置

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

### 避免过拟合

* 使用正则化图片
* 降低学习率
* 减少训练轮数
* 增加网络 alpha

### 避免欠拟合

* 更多训练图片
* 提高学习率
* 增加训练轮数
* 降低网络 alpha

## 监控训练

### TensorBoard

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

### 关键指标

* **损失（loss）** - 应先下降然后稳定
* **学习率（lr）** - 学习率调度
* **轮次（epoch）** - 训练进度

## 测试你的 LoRA

### 使用 Automatic1111

复制 LoRA 到：

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

在提示词中使用：

```
<lora:my_lora:0.8> a photo of sks person
```

### 使用 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("a photo of sks person, professional portrait").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")
```

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

检查文件完整性

| 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%）

## FLUX LoRA 训练

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

### 显存要求

| A100             | 最小显存  | 推荐 GPU          |
| ---------------- | ----- | --------------- |
| FLUX.1-schnell   | 16GB  | RTX 4080 / 3090 |
| FLUX.1-dev       | 24GB  | 512x512         |
| FLUX.1-dev（bf16） | 40GB+ | 按日费率            |

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

### FLUX 安装

安装支持 CUDA 12.4 的 PyTorch：

```bash
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124
pip install xformers --index-url https://download.pytorch.org/whl/cu124
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：较小的 dim 表现良好（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**     |
| 精度（Precision）        | fp16 或 bf16   | **必须使用 bf16**       |
| 网络模块（Network Module） | networks.lora | networks.lora\_flux |
| 网络维度（Network Dim）    | 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="a photo of sks person, professional portrait, studio lighting",
    num_inference_steps=28,
    guidance_scale=3.5,
    width=1024,
    height=1024,
).images[0]

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

***

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

### 内存溢出（OOM）错误

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

### 效果不佳

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

### 训练崩溃

* 检查 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: 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/kohya-training.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.
