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

# Kohya-Training

Trainiere LoRA und DreamBooth für Stable Diffusion mit Kohya auf Clore.ai

Trainiere LoRA, Dreambooth und vollständige Feinabstimmungen für Stable Diffusion mit Kohyas Trainer.

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die gemietet wurden über [CLORE.AI-Marktplatz](https://clore.ai/marketplace).
{% endhint %}

## Mieten auf CLORE.AI

1. Besuchen [CLORE.AI-Marktplatz](https://clore.ai/marketplace)
2. Filtern nach GPU-Typ, VRAM und Preis
3. Wähle **On-Demand** (Festpreis) oder **Spot** (Gebotspreis)
4. Konfiguriere deine Bestellung:
   * Docker-Image auswählen
   * Ports festlegen (TCP für SSH, HTTP für Web-UIs)
   * Bei Bedarf Umgebungsvariablen hinzufügen
   * Startbefehl eingeben
5. Zahlung auswählen: **CLORE**, **BTC**, oder **USDT/USDC**
6. Bestellung erstellen und auf die Bereitstellung warten

### Greife auf deinen Server zu

* Verbindungsdetails finden in **Meine Bestellungen**
* Web-Oberflächen: Verwende die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Was ist Kohya?

Kohya\_ss ist ein Trainingstoolkit für:

* **LoRA** - Leichte Adapter (am beliebtesten)
* **Dreambooth** - Subjekt-/Stiltraining
* **Vollständiges Fine-Tuning** - Komplettes Modelltraining
* **LyCORIS** - Erweiterte LoRA-Varianten

## Anforderungen

| Trainingsart      | Min. VRAM | Empfohlen |
| ----------------- | --------- | --------- |
| LoRA SD 1.5       | 6 GB      | RTX 3060  |
| LoRA SDXL         | 12 GB     | RTX 3090  |
| Dreambooth SD 1.5 | 12 GB     | RTX 3090  |
| Dreambooth SDXL   | 24 GB     | RTX 4090  |

## Schnell bereitstellen

**Docker-Image:**

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

**Ports:**

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

**Befehl:**

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

## Auf deinen Dienst zugreifen

Nach der Bereitstellung findest du deine `http_pub` URL in **Meine Bestellungen**:

1. Gehe zu **Meine Bestellungen** Seite
2. Klicke auf deine Bestellung
3. Finde die `http_pub` URL (z. B. `abc123.clorecloud.net`)

Verwende `https://YOUR_HTTP_PUB_URL` anstelle von `localhost` in den folgenden Beispielen.

## Verwendung der Web-UI

1. Zugriff unter `http://<proxy>:<port>`
2. Trainingsart auswählen (LoRA, Dreambooth usw.)
3. Einstellungen konfigurieren
4. Training starten

## Datensatzvorbereitung

### Ordnerstruktur

```
/workspace/dataset/
├── 10_mysubject/           # Wiederholungen_conceptname
│   ├── image1.png
│   ├── image1.txt          # Beschriftungsdatei
│   ├── image2.png
│   └── image2.txt
└── 10_regularization/      # Optionale Regularisierungsbilder
    ├── reg1.png
    └── reg1.txt
```

### Bildanforderungen

* **Auflösung:** 512x512 (SD 1.5) oder 1024x1024 (SDXL)
* **Format:** PNG oder JPG
* **Menge:** 10–50 Bilder für LoRA
* **Qualität:** Klare, gut beleuchtete, verschiedene Blickwinkel

### Beschriftungsdateien

Erstelle `.txt` Datei mit demselben Namen wie das Bild:

**myimage.txt:**

```
ein Foto einer sks-Person, professionelles Porträt, Studiobeleuchtung, hohe Qualität
```

### Automatische Beschriftung

Verwende BLIP für automatische Beschriftungen:

```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-Training (SD 1.5)

### Konfiguration

**In der Kohya-UI:**

| Einstellung    | Wert                           |
| -------------- | ------------------------------ |
| Modell         | runwayml/stable-diffusion-v1-5 |
| Netzwerk-Rang  | 32-128                         |
| Netzwerk-Alpha | 16-64                          |
| Lernrate       | 1e-4                           |
| Batchgröße     | 1-4                            |
| Epochen        | 10-20                          |
| Optimierer     | AdamW8bit                      |

### Training per Kommandozeile

```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-Training (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-Training

### Subjekttraining

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

### Stiltraining

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

## Trainingstipps

### Optimale Einstellungen

| Parameter      | Person/Charakter | Stil  | Objekt |
| -------------- | ---------------- | ----- | ------ |
| Netzwerk-Rang  | 64-128           | 32-64 | 32     |
| Netzwerk-Alpha | 32-64            | 16-32 | 16     |
| Lernrate       | 1e-4             | 5e-5  | 1e-4   |
| Epochen        | 15-25            | 10-15 | 10-15  |

### Überanpassung vermeiden

* Verwende Regularisierungsbilder
* Niedrigere Lernrate
* Weniger Epochen
* Erhöhe Netzwerk-Alpha

### Unteranpassung vermeiden

* Mehr Trainingsbilder
* Höhere Lernrate
* Mehr Epochen
* Niedrigeres Netzwerk-Alpha

## Training überwachen

### TensorBoard

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

### Wichtige Metriken

* **Verlust** - Sollte abnehmen und sich dann stabilisieren
* **Lernrate** - Lernratenplan
* **Epoche** - Trainingsfortschritt

## Dein LoRA testen

### Mit Automatic1111

LoRA kopieren nach:

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

Im Prompt verwenden:

```
<lora:my_lora:0.8> ein Foto einer sks-Person
```

### Mit ComfyUI

Lade den LoRA-Knoten und verbinde ihn mit dem Modell.

### Mit 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]
```

## Erweitertes Training

### LyCORIS (LoHa, LoKR)

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

### Textuelle Inversion

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

## Speichern & Exportieren

### Trainiertes Modell herunterladen

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

### Formate konvertieren

```python

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

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

## Kostenschätzung

Übliche CLORE.AI-Marktplatzpreise (Stand 2024):

| GPU       | Stundensatz | Tagessatz | 4-Stunden-Sitzung |
| --------- | ----------- | --------- | ----------------- |
| 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           |

*Die Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI-Marktplatz*](https://clore.ai/marketplace) *für aktuelle Preise.*

**Geld sparen:**

* Nutzen Sie den **Spot** Markt für unterbrechbare Arbeit — etwa ein Drittel der Server bietet Spot-Preise unter dem On-Demand-Preis (Median ca. 13 % Rabatt), der Rest ist gleichauf
* Bezahlen Sie mit **CLORE** Tokens
* Vergleichen Sie Preise zwischen verschiedenen Anbietern

## FLUX-LoRA-Training

Trainiere LoRA-Adapter für FLUX.1-dev und FLUX.1-schnell — die neueste Generation von Diffusion-Transformer-Modellen mit überlegener Qualität.

### VRAM-Anforderungen

| Modell            | Min. VRAM | Empfohlene GPU  |
| ----------------- | --------- | --------------- |
| FLUX.1-schnell    | 16 GB     | RTX 4080 / 3090 |
| FLUX.1-dev        | 24 GB     | RTX 4090        |
| FLUX.1-dev (bf16) | 40GB+     | A100 40GB       |

> **Hinweis:** FLUX verwendet die DiT-(Diffusion Transformer)-Architektur — die Trainingsdynamik unterscheidet sich deutlich von SD 1.5 / SDXL.

### Installation für FLUX

Installiere PyTorch mit Unterstützung für CUDA 12.8:

```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-Konfiguration (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-spezifisch: bf16 verwenden (NICHT fp16 — FLUX erfordert 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-Parameter — niedrigere LR als bei SDXL!
learning_rate = 1e-4
lr_scheduler = "cosine_with_restarts"
lr_warmup_steps = 100

# Netzwerkkonfiguration
network_module = "networks.lora_flux"
network_dim = 16           # FLUX: kleinere Dim funktioniert gut (16-64)
network_alpha = 16         # Auf denselben Wert wie network_dim setzen

# FLUX-spezifische Optionen
t5xxl_max_token_length = 512
apply_t5_attn_mask = true

# Optimierer — Adafactor funktioniert gut für FLUX
optimizer_type = "adafactor"
optimizer_args = ["scale_parameter=False", "relative_step=False", "warmup_init=False"]

# Speicher sparen
cache_latents = true
cache_latents_to_disk = true
cache_text_encoder_outputs = true
cache_text_encoder_outputs_to_disk = true

# Sampling während des Trainings (optionale Vorschau)
sample_every_n_epochs = 5
sample_prompts = "/workspace/sample_prompts.txt"
```

### FLUX-LoRA-Trainingsbefehl

```bash
# Einzelne 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

# Mit expliziten Parametern (kein 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 vs. SDXL: Wichtige Unterschiede

| Parameter     | SDXL           | FLUX.1                |
| ------------- | -------------- | --------------------- |
| Lernrate      | 1e-3 bis 1e-4  | **1e-4 bis 5e-5**     |
| Präzision     | fp16 oder bf16 | **bf16 ERFORDERLICH** |
| Netzwerkmodul | networks.lora  | networks.lora\_flux   |
| Netzwerk-Dim  | 32–128         | 8–64 (kleiner)        |
| Optimierer    | AdamW8bit      | Adafactor             |
| Min. VRAM     | 12 GB          | 16–24GB               |
| Architektur   | U-Net          | DiT (Transformer)     |

### Lernratenleitfaden für FLUX

```toml
# Konservativ (sicherer, geringere Gefahr der Überanpassung)
learning_rate = 5e-5

# Standard (guter Ausgangspunkt)
learning_rate = 1e-4

# Aggressiv (ausdrucksstärker, Risiko von Artefakten)
learning_rate = 2e-4
```

> **Tipp:** FLUX reagiert empfindlicher auf die Lernrate als SDXL. Beginne bei `1e-4` und reduziere auf `5e-5` wenn du Qualitätsprobleme siehst. Für SDXL, `1e-3` ist üblich — vermeide das für FLUX.

### FLUX-LoRA testen

```python
import torch
from diffusers import FluxPipeline

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

# Lade dein trainiertes 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")
```

***

## Fehlerbehebung

### OOM-Fehler

* Reduziere die Batchgröße auf 1
* Gradient Checkpointing aktivieren
* Verwende 8-Bit-Optimizer
* Niedrigere Auflösung

### Schlechte Ergebnisse

* Mehr/bessere Trainingsbilder
* Lernrate anpassen
* Überprüfe, ob die Beschriftungen zu den Bildern passen
* Versuche einen anderen Netzwerk-Rang

### Training stürzt ab

* CUDA-Version prüfen
* xformers aktualisieren
* Batch-Größe reduzieren
* Festplattenspeicher prüfen

### FLUX-spezifische Probleme

* **„bf16 wird nicht unterstützt“** — Verwenden Sie GPUs der A-Serie (Ampere+) oder der RTX-30/40-Serie
* **OOM bei FLUX.1-dev** — Wechseln Sie zu FLUX.1-schnell (benötigt 16 GB) oder aktivieren Sie `cache_text_encoder_outputs`
* **Unscharfe Ergebnisse** — Erhöhen `network_dim` auf 32–64, Lernrate senken auf `5e-5`
* **NaN-Loss** — Deaktivieren `full_bf16`, prüfen Sie Ihr Datenset auf beschädigte Bilder


---

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