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

# DreamBooth

Trainiere benutzerdefinierte Bildmodelle mit DreamBooth auf Clore.ai-GPUs

Trainiere Stable Diffusion, um Bilder bestimmter Motive zu erzeugen.

{% 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 DreamBooth?

DreamBooth feinabstimmt SD anhand deiner Bilder:

* Mit 5-20 Bildern trainieren
* Neue Bilder deines Motivs generieren
* Beliebiger Stil oder Kontext
* Funktioniert mit SD 1.5 und SDXL

## Anforderungen

| Modell        | VRAM  | Trainingszeit |
| ------------- | ----- | ------------- |
| SD 1.5        | 12 GB | 15-30 Min.    |
| SDXL          | 24 GB | 30-60 Min.    |
| SD 1.5 + LoRA | 8 GB  | 10-20 Min.    |

## Schnell bereitstellen

**Docker-Image:**

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

**Ports:**

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

**Befehl:**

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

## 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.

## Installation

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

## Trainingsdaten vorbereiten

1. Sammle 5-20 Bilder deines Motivs
2. Auf Gesicht/Motiv zuschneiden
3. Auf 512x512 skalieren (oder 1024x1024 für SDXL)
4. Bei Bedarf Hintergründe entfernen

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

            # Zentriert auf Quadrat zuschneiden
            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))

            # Skalieren
            img = img.resize((size, size), Image.LANCZOS)
            img.save(os.path.join(output_dir, filename))

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

## DreamBooth mit LoRA (empfohlen)

Speichereffizientes Training:

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

# Trainingsskript
from accelerate import Accelerator
from diffusers import AutoencoderKL, UNet2DConditionModel
from transformers import CLIPTextModel, CLIPTokenizer
from peft import LoraConfig, get_peft_model

# Modelle laden
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")

# LoRA zu UNet hinzufügen
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)
```

## Verwendung des diffusers-Trainingsskripts

```bash

# Trainingsskripte klonen
git clone https://github.com/huggingface/diffusers
cd diffusers/examples/dreambooth

# Abhängigkeiten installieren
pip install -r requirements.txt

# Mit LoRA trainieren
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
```

## Trainingsparameter

| Parameter          | Empfohlen                 | Effekt                                  |
| ------------------ | ------------------------- | --------------------------------------- |
| learning\_rate     | 1e-4 bis 5e-6             | Höher = schneller, niedriger = stabiler |
| max\_train\_steps  | 400-1000                  | Mehr = bessere Anpassung                |
| train\_batch\_size | 1-2                       | Höher benötigt mehr VRAM                |
| resolution         | 512 (SD1.5) / 1024 (SDXL) | Trainingsgröße                          |

## Instanz-Prompt

Wähle einen eindeutigen Bezeichner:

```bash

# Gute Prompts
"a photo of sks person"      # sks = eindeutiges Token
"a photo of xyz dog"
"a photo of abc car"

# Das Token (sks, xyz, abc) sollte selten sein
```

## Mit Klassenerhalt

Überanpassung verhindern:

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

## Trainiertes Modell verwenden

### LoRA laden

```python
from diffusers import StableDiffusionPipeline
import torch

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

# Lade dein trainiertes LoRA
pipe.load_lora_weights("./dreambooth_model")

# Generieren
image = pipe(
    "a photo of sks person as an astronaut on mars",
    num_inference_steps=30,
    guidance_scale=7.5
).images[0]

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

### Vollständiges Fine-Tuning

```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-Oberfläche

```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="Prompt (verwende 'sks' für dein Motiv)"),
        gr.Textbox(label="Negativer Prompt", value="blurry, ugly"),
        gr.Slider(20, 50, value=30, step=1, label="Schritte"),
        gr.Slider(5, 15, value=7.5, step=0.5, label="Guidance"),
        gr.Number(value=-1, label="Seed")
    ],
    outputs=gr.Image(label="Generiertes Bild"),
    title="DreamBooth-Porträtgenerator"
)

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

## Trainingstipps

### Für Personen

* Verwende verschiedene Blickwinkel (frontal, seitlich, 3/4)
* Unterschiedliche Lichtverhältnisse
* Verschiedene Gesichtsausdrücke
* Klare Fotos in hoher Auflösung

### Für Objekte

* Mehrere Blickwinkel
* Unterschiedliche Hintergründe
* Konsistente Beleuchtung
* Keine Verdeckung

### Für Stile

* 10-20 Beispielbilder
* Einheitlicher künstlerischer Stil
* Verschiedene Motive in diesem Stil

## Fehlerbehebung

### Überanpassung

* max\_train\_steps reduzieren
* learning\_rate senken
* Vorab-Erhalt verwenden
* Mehr Trainingsbilder

### Unteranpassung

* max\_train\_steps erhöhen
* learning\_rate erhöhen
* Mehr Trainingsbilder
* Bildqualität prüfen

### Stil nicht gelernt

* LoRA-Rang erhöhen (r=16 oder 32)
* Länger trainieren
* Mehr Beispiele verwenden

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

## Nächste Schritte

* [Kohya-Training](/guides/guides_v2-de/training/kohya-training.md) - Fortgeschrittenes Training
* Stable Diffusion WebUI - Modelle verwenden
* [LoRA-Fine-Tuning](/guides/guides_v2-de/training/kohya-training.md) - LLM-Training


---

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