> 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 Stable Diffusion, um Bilder bestimmter Motive zu erzeugen.

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

## Mieten auf CLORE.AI

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

### Zugriff auf Ihren Server

* Verbindungsdetails finden Sie in **Meine Bestellungen**
* Webschnittstellen: Verwenden Sie die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Was ist DreamBooth?

DreamBooth feinjustiert SD anhand deiner Bilder:

* Auf 5–20 Bildern trainieren
* Neue Bilder deines Motivs erzeugen
* Jeder Stil oder Kontext
* Funktioniert mit SD 1.5 und SDXL

## Anforderungen

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

## Schnelle Bereitstellung

**Docker-Image:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
```

**Ports:**

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

**Befehl:**

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

## Zugriff auf Ihren Dienst

Nach der Bereitstellung finden Sie Ihre `http_pub` URL in **Meine Bestellungen**:

1. Gehen Sie zur **Meine Bestellungen** Seite
2. Klicken Sie auf Ihre Bestellung
3. Finden Sie die `http_pub` URL (z. B., `abc123.clorecloud.net`)

Verwenden Sie `https://IHRE_HTTP_PUB_URL` anstelle von `localhost` in den Beispielen unten.

## 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. Hintergründe bei Bedarf 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))

            # Größe ändern
            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 zum 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

# Anforderungen 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                                  |
| ------------------ | ------------------------- | --------------------------------------- |
| Lernrate           | 1e-4 bis 5e-6             | Höher = schneller, niedriger = stabiler |
| max\_train\_steps  | 400-1000                  | Mehr = besserer Fit                     |
| train\_batch\_size | 1-2                       | Höher benötigt mehr VRAM                |
| Auflösung          | 512 (SD1.5) / 1024 (SDXL) | Trainingsgröße                          |

## Instanz-Prompt

Wähle eine eindeutige Kennung:

```bash

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

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

## Mit Klassen-Erhaltung

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

## Verwendung des trainierten Modells

### 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="Negativ-Prompt", value="verschwommen, hässlich"),
        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="Erzeugtes Bild"),
    title="DreamBooth Portrait-Generator"
)

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

## Trainingstipps

### Für Personen

* Verwende verschiedene Winkel (Frontal, Seite, 3/4)
* Verschiedene Lichtverhältnisse
* Verschiedene Ausdrücke
* Klare, hochauflösende Fotos

### Für Objekte

* Mehrere Winkel
* Verschiedene Hintergründe
* Konstante Beleuchtung
* Keine Verdeckung

### Für Stile

* 10–20 Beispielbilder
* Konsistenter künstlerischer Stil
* Verschiedene Motive in diesem Stil

## Fehlerbehebung

### Überanpassung

* max\_train\_steps reduzieren
* Lernrate verringern
* Prior-Preservation verwenden
* Mehr Trainingsbilder

### Unteranpassung

* max\_train\_steps erhöhen
* Lernrate 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

## Kostenabschätzung

Typische CLORE.AI-Marktplatztarife (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           |

*Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *auf aktuelle Preise.*

**Geld sparen:**

* Verwenden Sie **Spot** Markt für flexible Workloads (oft 30–50% günstiger)
* Bezahlen mit **CLORE** Token
* Preise bei verschiedenen Anbietern vergleichen

## Nächste Schritte

* [Kohya Training](/guides/guides_v2-de/training/kohya-training.md) - Fortgeschrittenes Training
* Stable Diffusion WebUI - Modelle verwenden
* [LoRA-Finetuning](/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:

```
GET https://docs.clore.ai/guides/guides_v2-de/training/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.
