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

# LLaMA-Factory

LLaMA-Factory ist das umfangreichste Open-Source-Fine-Tuning-Framework und unterstützt über 100 Sprachmodelle, einschließlich aller LLaMA-Varianten, Qwen, Mistral, Phi, Falcon, ChatGLM und mehr. Es bietet LoRA, QLoRA, vollständiges Fine-Tuning, RLHF, DPO und PPO — alles über eine intuitive Weboberfläche (LLaMA Board) oder die CLI. Die On-Demand-GPU-Server von CLORE.AI machen es zur perfekten Plattform, um Fine-Tuning-Jobs zu starten, und das zu einem Bruchteil der Kosten von Cloud-Anbietern.

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

## Serveranforderungen

| Parameter  | Minimum          | Empfohlen      |
| ---------- | ---------------- | -------------- |
| RAM        | 16 GB            | 32 GB+         |
| VRAM       | 8 GB (QLoRA)     | 24 GB+         |
| Festplatte | 50 GB            | 200 GB+        |
| GPU        | NVIDIA RTX 2080+ | A100, RTX 4090 |

{% hint style="info" %}
**Die Trainingsmethode bestimmt die GPU-Anforderungen:**

* **QLoRA (4-bit)**: 8 GB VRAM für 7B-Modelle, 16 GB für 13B
* **LoRA (float16)**: 16 GB VRAM für 7B-Modelle, 40 GB für 13B
* **Vollständiges Fine-Tuning**: \~14 GB VRAM pro 7B-Parameter (+ Optimizer-Zustände)
* Multi-GPU (DeepSpeed/FSDP) skaliert über beliebig viele GPUs
  {% endhint %}

## Schnelle Bereitstellung auf CLORE.AI

**Docker-Image:** `hiyouga/llamafactory:latest`

**Ports:** `22/tcp`, `7860/http`

**Umgebungsvariablen:**

| Variable               | Beispiel    | Beschreibung                             |
| ---------------------- | ----------- | ---------------------------------------- |
| `HF_TOKEN`             | `hf_xxx...` | HuggingFace-Token für gesperrte Modelle  |
| `WANDB_API_KEY`        | `xxx...`    | Weights & Biases für Experiment-Tracking |
| `CUDA_VISIBLE_DEVICES` | `0,1`       | Zu verwendende GPUs                      |

## Schritt-für-Schritt-Einrichtung

### 1. Mieten Sie einen GPU-Server auf CLORE.AI

Besuchen Sie [CLORE.AI Marketplace](https://clore.ai/marketplace) und wählen Sie basierend auf Ihrer Aufgabe:

| Aufgabe    | VRAM     | Empfohlene GPU     |
| ---------- | -------- | ------------------ |
| QLoRA 7B   | 8 GB     | RTX 3070/2080      |
| QLoRA 13B  | 16 GB    | RTX 3090/A4000     |
| LoRA 7B    | 16 GB    | RTX 3090/A4000     |
| LoRA 13B   | 40 GB    | A6000/A100 40GB    |
| Full FT 7B | 80 GB    | A100 80GB          |
| Multi-GPU  | Variiert | 2–8× beliebige GPU |

### 2. SSH auf Ihren Server

```bash
ssh -p <PORT> root@<SERVER_IP>
```

### 3. Arbeitsverzeichnisse erstellen

```bash
mkdir -p /root/llamafactory/{data,models,output,saves}
```

### 4. Docker-Image ziehen

```bash
docker pull hiyouga/llamafactory:latest
```

### 5. LLaMA-Factory starten

**Starten mit Web-UI (LLaMA Board):**

```bash
docker run -d \
  --name llamafactory \
  --gpus all \
  -p 7860:7860 \
  -v /root/llamafactory/data:/app/LLaMA-Factory/data \
  -v /root/llamafactory/models:/root/.cache/huggingface \
  -v /root/llamafactory/output:/app/LLaMA-Factory/output \
  -v /root/llamafactory/saves:/app/LLaMA-Factory/saves \
  -e HF_TOKEN=hf_your_token_here \
  hiyouga/llamafactory:latest \
  llamafactory-cli webui
```

**Mit Weights & Biases-Tracking:**

```bash
docker run -d \
  --name llamafactory \
  --gpus all \
  -p 7860:7860 \
  -v /root/llamafactory/data:/app/LLaMA-Factory/data \
  -v /root/llamafactory/models:/root/.cache/huggingface \
  -v /root/llamafactory/output:/app/LLaMA-Factory/output \
  -v /root/llamafactory/saves:/app/LLaMA-Factory/saves \
  -e HF_TOKEN=hf_your_token_here \
  -e WANDB_API_KEY=your_wandb_key \
  hiyouga/llamafactory:latest \
  llamafactory-cli webui
```

**Multi-GPU mit DeepSpeed (4 GPUs):**

```bash
docker run -d \
  --name llamafactory \
  --gpus all \
  --shm-size 16g \
  --ipc host \
  -p 7860:7860 \
  -v /root/llamafactory/data:/app/LLaMA-Factory/data \
  -v /root/llamafactory/models:/root/.cache/huggingface \
  -v /root/llamafactory/output:/app/LLaMA-Factory/output \
  -e CUDA_VISIBLE_DEVICES=0,1,2,3 \
  hiyouga/llamafactory:latest \
  bash -c "llamafactory-cli webui"
```

### 6. Auf die Weboberfläche zugreifen

Logs prüfen und die URL abrufen:

```bash
docker logs -f llamafactory
```

Ihre CLORE.AI http\_pub-URL für Port 7860:

```
https://<order-id>-7860.clore.ai/
```

***

## Beispielanwendungen

### Beispiel 1: LoRA-Fine-Tuning über Web-UI (LLaMA Board)

1. Öffnen Sie das LLaMA Board unter Ihrer CLORE.AI-URL
2. Gehen Sie zu **Train** Tab
3. Konfigurieren:
   * **Modellname**: `LLaMA-3` → `Meta-Llama-3-8B-Instruct`
   * **Trainingsphase**: `Supervised Fine-Tuning`
   * **Datensatz**: Wählen Sie Ihren Datensatz (oder laden Sie einen eigenen hoch)
   * **Fine-Tuning-Methode**: `lora`
   * **LoRA-Rang**: `8` (höher = mehr trainierte Parameter)
   * **Lernrate**: `1e-4`
   * **Epochen**: `3`
   * **Ausgabeverzeichnis**: `llama3-finetuned`
4. Klicken Sie **Start** um das Training zu beginnen
5. Überwachen Sie Loss-Kurven im **Loss** Diagramm

### Beispiel 2: CLI-basiertes QLoRA-Fine-Tuning

Bereiten Sie eine Trainingskonfigurations-YAML vor:

```bash
docker exec -it llamafactory bash

cat > /app/LLaMA-Factory/configs/qlora_mistral.yaml << 'EOF'
### Modell
model_name_or_path: mistralai/Mistral-7B-Instruct-v0.3

### Methode
stage: sft
do_train: true
finetuning_type: lora
lora_target: all
lora_rank: 16
lora_alpha: 32
lora_dropout: 0.05

### Datensatz
dataset: alpaca_en
template: mistral
cutoff_len: 2048
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16

### Ausgabe
output_dir: saves/mistral-qlora
logging_steps: 10
save_steps: 500
plot_loss: true
overwrite_output_dir: true

### Training
per_device_train_batch_size: 2
gradient_accumulation_steps: 8
learning_rate: 0.0001
num_train_epochs: 3.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
fp16: true

### Quantisierung
quantization_method: bitsandbytes
quantization_bit: 4
EOF

# Training ausführen
llamafactory-cli train /app/LLaMA-Factory/configs/qlora_mistral.yaml
```

### Beispiel 3: Eigenen Datensatz hochladen

Erstellen Sie einen eigenen Datensatz im Alpaca-Format:

```bash
# Datensatzdatei erstellen
cat > /root/llamafactory/data/my_dataset.json << 'EOF'
[
  {
    "instruction": "Sie sind ein Kundendienstmitarbeiter für ein Technologieunternehmen. Antworten Sie hilfreich.",
    "input": "Mein Laptop lässt sich nach dem Update nicht mehr einschalten. Was soll ich tun?",
    "output": "Ich verstehe, wie frustrierend das sein kann. Lassen Sie uns Schritt für Schritt Fehler beheben:\n\n1. **Halten Sie die Einschalttaste 10 Sekunden lang gedrückt**, um einen erzwungenen Shutdown durchzuführen\n2. **Trennen Sie das Netzkabel** und entfernen Sie die Batterie, falls entfernbar, warten Sie 30 Sekunden\n3. **Schließen Sie die Stromversorgung wieder an** und versuchen Sie, das Gerät einzuschalten\n4. Wenn weiterhin keine Reaktion, drücken Sie während des Starts **F8/F11**, um den Wiederherstellungsmodus aufzurufen\n\nMöchten Sie, dass ich Sie durch einen dieser Schritte im Detail führe?"
  },
  {
    "instruction": "Sie sind ein Kundendienstmitarbeiter für ein Technologieunternehmen.",
    "input": "Wie setze ich mein Passwort zurück?",
    "output": "Das Zurücksetzen Ihres Passworts ist einfach! So geht's:\n\n1. Gehen Sie zur Anmeldeseite und klicken Sie auf **'Passwort vergessen'**\n2. Geben Sie Ihre **registrierte E-Mail-Adresse** ein\n3. Überprüfen Sie Ihre E-Mails auf einen Reset-Link (auch Spam-Ordner prüfen)\n4. Klicken Sie auf den Link und **erstellen Sie ein neues Passwort**\n\nDer Reset-Link ist 24 Stunden gültig. Wenn Sie die E-Mail nicht innerhalb von 5 Minuten erhalten, kontaktieren Sie unser Support-Team."
  }
]
EOF

# Datensatz in dataset_info.json registrieren
docker exec -it llamafactory bash -c "
cat >> /app/LLaMA-Factory/data/dataset_info.json << 'EOF2'
,
\"my_dataset\": {
  \"file_name\": \"/root/llamafactory/data/my_dataset.json\"
}
EOF2
"
```

Wählen Sie dann `my_dataset` im Dataset-Dropdown des LLaMA Boards.

### Beispiel 4: DPO (Direct Preference Optimization)

```yaml
### configs/dpo_llama.yaml

model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct

### Methode - DPO
stage: dpo
do_train: true
finetuning_type: lora
lora_rank: 8

### DPO-spezifisch
pref_beta: 0.1
pref_loss: sigmoid  # sigmoid, hinge, ipo

### Datensatz (muss Präferenzformat haben)
dataset: dpo_en_demo
template: llama3
cutoff_len: 2048

### Ausgabe
output_dir: saves/llama3-dpo
logging_steps: 10
save_steps: 100

### Training
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
learning_rate: 5e-5
num_train_epochs: 1.0
fp16: true
```

```bash
docker exec -it llamafactory bash -c "llamafactory-cli train /configs/dpo_llama.yaml"
```

### Beispiel 5: Inferenz mit dem feinabgestimmten Modell

Testen Sie Ihr Modell nach dem Training:

```bash
docker exec -it llamafactory bash

# Interaktiver Chat
llamafactory-cli chat \
  --model_name_or_path mistralai/Mistral-7B-Instruct-v0.3 \
  --adapter_name_or_path /app/LLaMA-Factory/saves/mistral-qlora \
  --template mistral \
  --finetuning_type lora
```

Oder exportieren Sie das gemergte Modell:

```bash
llamafactory-cli export \
  --model_name_or_path mistralai/Mistral-7B-Instruct-v0.3 \
  --adapter_name_or_path /app/LLaMA-Factory/saves/mistral-qlora \
  --template mistral \
  --finetuning_type lora \
  --export_dir /app/LLaMA-Factory/output/mistral-merged \
  --export_size 4 \
  --export_legacy_format false
```

***

## Konfiguration

### Wichtige Trainingsparameter

| Parameter                     | Typischer Wert | Beschreibung                              |
| ----------------------------- | -------------- | ----------------------------------------- |
| `lora_rank`                   | 8–64           | LoRA-Rang (höher = ausdrucksstärker)      |
| `lora_alpha`                  | 2× Rang        | LoRA-Alpha-Skalierung                     |
| `lora_dropout`                | 0.0–0.1        | Dropout für LoRA-Schichten                |
| `lora_target`                 | `all`          | Auf welche Schichten LoRA angewendet wird |
| `learning_rate`               | `1e-4`         | Anfangslernrate                           |
| `num_train_epochs`            | 1–5            | Trainings-Epochen                         |
| `per_device_train_batch_size` | 1–4            | Batch-Größe pro GPU                       |
| `gradient_accumulation_steps` | 4–16           | Effektiver Batch-Multiplikator            |
| `cutoff_len`                  | 1024–4096      | Maximale Sequenzlänge                     |
| `quantization_bit`            | 4 oder 8       | QLoRA-Quantisierungsbits                  |
| `warmup_ratio`                | 0.05–0.1       | LR-Warmup-Anteil                          |
| `lr_scheduler_type`           | `cosine`       | LR-Schedule                               |

### Unterstützte Fine-Tuning-Methoden

| Methode              | Speichernutzung | Qualität | Wann verwenden             |
| -------------------- | --------------- | -------- | -------------------------- |
| `full`               | Sehr hoch       | Beste    | Unbegrenzter VRAM          |
| `freeze`             | Mittel          | Gut      | Basis-Schichten einfrieren |
| `lora`               | Niedrig         | Sehr gut | Standardwahl               |
| `qlora` (lora+quant) | Am niedrigsten  | Gut      | Begrenzter VRAM            |

### Multi-GPU DeepSpeed-Training

Für Training auf mehreren GPUs starten Sie mit `torchrun`:

```bash
docker exec -it llamafactory bash -c "
FORCE_TORCHRUN=1 NNODES=1 RANK=0 MASTER_ADDR=127.0.0.1 MASTER_PORT=29500 \
llamafactory-cli train configs/qlora_mistral.yaml \
  --deepspeed examples/deepspeed/ds_z3_config.json
"
```

***

## Leistungs-Tipps

### 1. Optimale QLoRA-Einstellungen nach GPU

**8 GB VRAM (RTX 3070):**

```yaml
quantization_bit: 4
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
cutoff_len: 1024
```

**24 GB VRAM (RTX 3090/4090):**

```yaml
quantization_bit: 4  # Verwenden Sie weiterhin QLoRA für größere Batch-Größen
per_device_train_batch_size: 4
gradient_accumulation_steps: 4
cutoff_len: 2048
```

**80 GB VRAM (A100):**

```yaml
# Keine Quantisierung nötig — LoRA direkt verwenden
finetuning_type: lora
per_device_train_batch_size: 8
gradient_accumulation_steps: 2
cutoff_len: 4096
fp16: true
```

### 2. Flash Attention 2 für längere Kontexte

```yaml
flash_attn: fa2  # Erfordert Ampere+ GPU
```

Dies ermöglicht Training mit 2× längeren Sequenzen bei gleichem VRAM.

### 3. Gradient Checkpointing

Spart VRAM auf Kosten von \~20% langsamerem Training:

```yaml
gradient_checkpointing: true
```

### 4. Wählen Sie das richtige LoRA-Ziel

```yaml
lora_target: all  # Alle linearen Schichten (Standard, beste Qualität)
# oder
lora_target: q_proj,v_proj  # Minimal, am schnellsten, geringere Qualität
```

### 5. Obere Schichten einfrieren für schnelle Anpassung

```yaml
finetuning_type: freeze
freeze_trainable_layers: 2   # Nur die obersten 2 Schichten trainieren
freeze_trainable_modules: all
```

Viel schneller als vollständiges LoRA für einfache Aufgabenanpassungen.

### 6. Mit TensorBoard überwachen

```bash
# In einem separaten Terminal
docker exec -it llamafactory bash -c "
tensorboard --logdir /app/LLaMA-Factory/saves --host 0.0.0.0 --port 6006
"
```

Fügen Sie Port 6006 zu Ihrer CLORE.AI-Bestellung hinzu, um auf TensorBoard zuzugreifen.

***

## Fehlerbehebung

### Problem: "CUDA out of memory" während des Trainings

1. Batch-Größe reduzieren: `per_device_train_batch_size: 1`
2. Gradient Checkpointing aktivieren: `gradient_checkpointing: true`
3. Kontextlänge reduzieren: `cutoff_len: 512`
4. Verwenden Sie QLoRA (4-bit): `quantization_bit: 4`
5. LoRA-Rang reduzieren: `lora_rank: 4`

### Problem: Trainingsverlust sinkt nicht

* Überprüfen Sie die Lernrate — versuchen Sie `5e-5` oder `2e-4`
* Stellen Sie sicher, dass das Datensatzformat zur Vorlage passt
* Erhöhen `lora_rank` (8→16→32)
* Prüfen Sie, dass `lora_target: all` gesetzt ist

### Problem: Langsame Trainingsgeschwindigkeit

```bash
# GPU-Auslastung im Container prüfen
docker exec -it llamafactory bash -c "watch -n 1 nvidia-smi"
```

Wenn die GPU < 80% ausgelastet ist:

* Batch-Größe erhöhen
* Verwenden Sie Flash Attention: `flash_attn: fa2`
* Entfernen Sie `gradient_checkpointing` falls VRAM es zulässt

### Problem: Modell nicht in der Web-UI gefunden

```bash
# Vorab in das Cache-Volume herunterladen
docker exec -it llamafactory bash -c "
huggingface-cli download mistralai/Mistral-7B-Instruct-v0.3
"
```

Aktualisieren Sie dann die Modellliste im LLaMA Board.

### Problem: Fehler im Datensatzformat

Alle Datensatzformate müssen der `dataset_info.json` Spezifikation entsprechen:

```bash
# Datensatz validieren
docker exec -it llamafactory python3 -c "
import json
with open('/app/LLaMA-Factory/data/my_dataset.json') as f:
    data = json.load(f)
print(f'Dataset has {len(data)} samples')
print('First sample keys:', list(data[0].keys()))
"
```

### Problem: WebUI-Port nicht erreichbar

Stellen Sie sicher, dass LLaMA-Factory den Gradio-Server gestartet hat:

```bash
docker logs llamafactory 2>&1 | grep -E "Running on|Error|Traceback"
```

Fügen Sie `--share` Flag für eine öffentliche Gradio-URL als Alternative.

***

## Links

* [GitHub](https://github.com/hiyouga/LLaMA-Factory)
* [Dokumentation](https://llamafactory.readthedocs.io)
* [Docker Hub (hiyouga)](https://hub.docker.com/r/hiyouga/llamafactory)
* [Unterstützte Modelle](https://github.com/hiyouga/LLaMA-Factory?tab=readme-ov-file#supported-models)
* [Datensatzformat](https://github.com/hiyouga/LLaMA-Factory/blob/main/data/README.md)
* [CLORE.AI Marketplace](https://clore.ai/marketplace)

***

## Clore.ai GPU-Empfehlungen

| Anwendungsfall       | Empfohlene GPU  | Geschätzte Kosten auf Clore.ai |
| -------------------- | --------------- | ------------------------------ |
| Entwicklung/Tests    | RTX 3090 (24GB) | \~$0.12/gpu/hr                 |
| Fine-Tuning (7B–13B) | RTX 4090 (24GB) | \~$0.70/gpu/hr                 |
| Große Modelle (70B+) | A100 80GB       | \~$1.20/gpu/hr                 |
| Multi-GPU-Training   | 2–4× A100 80GB  | \~$2.40–$4.80/hr               |

> 💡 Alle Beispiele in diesem Leitfaden können bereitgestellt werden auf [Clore.ai](https://clore.ai/marketplace) GPU-Servern. Durchsuchen Sie verfügbare GPUs und mieten Sie stundenweise — keine Verpflichtungen, voller Root-Zugriff.


---

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